//------------------------------------------------------------------- // randwalk.cpp // // This program exhibits a simple "random walk" animation that // shows a molecule moving left or right with equal liklihood. // // compile using: $ g++ randwalk.cpp -o randwalk // execute using: $ ./randwalk // // programmer: ALLAN CRUSE // written on: 25 JAN 2011 //------------------------------------------------------------------- #include // for printf() #include // for random() #include // for usleep() #include // for time() int main( int argc, char **argv ) { // prepare a blank screen with the cursor hidden printf( "\e[H\e[J" ); // clear the screen printf( "\e[?25l" ); // hide the cursor fflush( stdout ); // seed the random number generator srandom( time( 0 ) ); // initialize the annimation int row = 12, col = 40; printf( "\e[%d;%dH%c", row, col, 'o' ); fflush( stdout ); // perform the random walk for (int i = 0; i < 100; i++) { usleep( 200000 ); // delay 200 milliseconds printf( "\e[%d;%dH%c", row, col, ' ' ); fflush( stdout ); int x = random() % 2; if ( x > 0 ) ++col; else --col; printf( "\e[%d;%dH%c", row, col, 'o' ); fflush( stdout ); } // prepare cursor for exit and restore its visibility printf( "\e[24;0H" ); // move cursor to bottom of screen printf( "\e[?25h" ); // show the cursor fflush( stdout ); }