/* Draw a character that you can move around on the screen ** Type a lowercase 'q' to exit */ #include /* for exit() */ #include /* for printf() */ #include /* for ncurses */ #include /* for usleep() */ #include /* for handling SIGTERM */ /* Function prototypes */ static void finish(int sig); static void nextFrame(void); static void drawFrame(void); int main(void) { int run=1; /* Boolean on/off flag, default on */ int c=0; /* Character for input. Curses uses ints for chars */ int xpos=40, ypos=11; /* X and Y positions of the actor */ signal(SIGINT, finish); /* run finish() on sig INT */ initscr(); /* ncurses won't do anything without this */ nonl(); /* Allows detection of return key; Not needed here */ noecho(); /* Don't print what you type back onto the screen */ keypad(stdscr,TRUE); /* Allow input from arrow keys */ drawFrame(); /* Run my drawFrame function */ mvaddch(ypos,xpos,'O'); /* Draw the actor on the screen */ /* Note that curses uses (Y,X) rather than (X,Y) */ while(run){ c=getch(); /* Input a character. Curses uses ints */ mvaddch(ypos,xpos,' '); /* Blank out the actor's position */ if(c=='q') run=0; /* Quit on 'q' as input */ else /* Redraw the actor on other input */ if(c== (KEY_DOWN) || c=='j') mvaddch(++ypos,xpos,'O'); else if(c==(KEY_RIGHT) || c=='l') mvaddch(ypos,++xpos,'O'); else if(c==(KEY_LEFT) || c=='h') mvaddch(ypos,--xpos,'O'); else if(c==(KEY_UP) || c=='k') mvaddch(--ypos,xpos,'O'); else mvaddch(xpos,ypos,'?'); refresh(); /* Nothing shows up on screen without this */ } finish(0); return 0; } static void finish(int sig) { endwin(); /* Keeps you from having to reset your terminal */ exit(0); } static void nextFrame(void) { refresh(); /* Draw stuff on the screen */ usleep(1024*16); /* Sleep 1/64th of a second */ } /* Draw an 80x21 char frame */ static void drawFrame(void){ int i=0, j=0; /* Loop counters */ /* Draw the top and left sides of the frame */ while(j<80){ mvaddch(0,j++,'#'); if(!(j%4)) mvaddch(++i,0,'#'); nextFrame(); } i=j=0; /* Draw the right and bottom sides of the frame */ while(j<80){ mvaddch(20,++j,'#'); if(!(j%4)) mvaddch(++i,79,'#'); nextFrame(); } }