bounce1d.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /* bounce1d.c
  2. * purpose animation with user controlled speed and direction
  3. * note the handler does the animation
  4. * the main program reads keyboard input
  5. * compile cc bounce1d.c set_ticker.c -lcurses -o bounce1d
  6. */
  7. #include <stdio.h>
  8. #include <curses.h>
  9. #include <signal.h>
  10. /* some global settings main and the handler use */
  11. #define MESSAGE "hello"
  12. #define BLANK " "
  13. int row; /* current row */
  14. int col; /* current column */
  15. int dir; /* where we are going */
  16. int main()
  17. {
  18. int delay; /* bigger => slower */
  19. int ndelay; /* new delay */
  20. int c; /* user input */
  21. void move_msg(int); /* handler for timer */
  22. initscr();
  23. crmode();
  24. noecho();
  25. clear();
  26. row = 10; /* start here */
  27. col = 0;
  28. dir = 1; /* add 1 to row number */
  29. delay = 200; /* 200ms = 0.2 seconds */
  30. move(row,col); /* get into position */
  31. addstr(MESSAGE); /* draw message */
  32. signal(SIGALRM, move_msg );
  33. set_ticker( delay );
  34. while(1)
  35. {
  36. ndelay = 0;
  37. c = getch();
  38. if ( c == 'Q' ) break;
  39. if ( c == ' ' ) dir = -dir;
  40. if ( c == 'f' && delay > 2 ) ndelay = delay/2;
  41. if ( c == 's' ) ndelay = delay * 2 ;
  42. if ( ndelay > 0 )
  43. set_ticker( delay = ndelay );
  44. }
  45. endwin();
  46. return 0;
  47. }
  48. void move_msg(int signum)
  49. {
  50. signal(SIGALRM, move_msg); /* reset, just in case */
  51. move( row, col );
  52. addstr( BLANK );
  53. col += dir; /* move to new column */
  54. move( row, col ); /* then set cursor */
  55. addstr( MESSAGE ); /* redo message */
  56. refresh(); /* and show it */
  57. /*
  58. * now handle borders
  59. */
  60. if ( dir == -1 && col <= 0 )
  61. dir = 1;
  62. else if ( dir == 1 && col+strlen(MESSAGE) >= COLS )
  63. dir = -1;
  64. }