Wednesday, February 4, 2009

Interesting C Program - 25

Hi all,
I am here with a really interesting c program that I have developed today. It is a text based paint program. It uses ncurses library. Here goes the program.


/*
------------TEXT BASED PAINT PROGRAM--------------
*/
#include "stdio.h"
#include "stdlib.h"
#include "curses.h"
int rmax,cmax;
int crow,ccol;
char drawchar = ' ';
void moveup(void);
void movedown(void);
void moveleft(void);
void moveright(void);
void delcurrent(void);
void bckspace(void);
void delup(void);
void toggledraw(void);
int main()
{
WINDOW *scrn;
char key;
//----------------------------------------
printf("\n-----------------------------\n");
printf("\n Welcome to TextPaint\n");
printf("\n w - move up\n");
printf("\n a - move left\n");
printf("\n s - move down\n");
printf("\n d - move right\n");
printf("\n r - remove current character\n");
printf("\n b - remove character in the left\n");
printf("\n v - remove character in the top\n");
printf("\n t - toggle between moving and drawing\n");
printf("\n-----------------------------\n");
printf("\n Press ENTER Key to Continue\n");
getchar();
scrn = initscr();
cbreak();
noecho();
getmaxyx(scrn,rmax,cmax);
clear();
refresh();
crow = 0;
ccol = 0;
//----------------------------------------
while(1)
{
key = getch();
switch(key)
{
case 'w':
moveup();
break;
case 'a':
moveleft();
break;
case 's':
movedown();
break;
case 'd':
moveright();
break;
case 'r':
delcurrent();
break;
case 'b':
bckspace();
break;
case 'v':
delup();
break;
case 't':
toggledraw();
break;
default:
endwin();
printf("!!!You Have Come out of TextPaint!!!\n");
return 0;
break;
}
}

endwin();

return 0;
}

void moveup(void)
{
crow--;
if(crow<0)
{
crow = rmax;
}
move(crow,ccol);
delch();
insch(drawchar);
refresh();
}
void movedown(void)
{
crow++;
if(crow>rmax)
crow = 0;
move(crow,ccol);
delch();
insch(drawchar);
refresh();
}
void moveleft(void)
{
ccol--;
if(ccol<0)
ccol = cmax;
move(crow,ccol);
delch();
insch(drawchar);
refresh();
}
void moveright(void)
{
ccol++;
if(ccol>cmax)
ccol = 0;
move(crow,ccol);
delch();
insch(drawchar);
refresh();
}
void delcurrent(void)
{
move(crow,ccol);
delch();
//insch(' ');
refresh();
}
void bckspace(void)
{
ccol--;
if(ccol<0)
ccol = cmax;
move(crow,ccol);
delch();
refresh();
}
void delup(void)
{
crow--;
if(crow<0)
crow = rmax;
move(crow,ccol);
delch();
refresh();
}
void toggledraw(void)
{
static int i;
i++;
if(i%2)
drawchar = '-';
else
drawchar = ' ';
}

Search Google

Books that I refer to...

  • The Complete Reference C, Fourth Edition
  • The C Programming Language