//------------------------------------------------------------------- // 2dimwalk.cpp // // This program enhances our 'randwalk.cpp' demo by showing a // two-dimensional walk, with barriers above and below, where // a molecule can move left or right, and up or down, or else // can remain stationary in either or both of the dimensions. // // to compile: $ g++ 2dimewalk.cpp -o 2dimwalk // to execute: $ ./2dimwalk // // 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 printf( "\e[H\e[J" ); // clear the screen printf( "\e[?25l" ); // hide the cursor fflush( stdout ); // draw the horizontal barriers printf( "\e[12;0H" ); for (int k = 0; k < 80; k++) printf( "-" ); printf( "\e[18;0H" ); for (int k = 0; k < 80; k++) printf( "-" ); fflush( stdout ); // seed the random number generator srandom( time( 0 ) ); // initialize the simulation int row = 15, col = 40; printf( "\e[%d;%dH%c", row, col, 'o' ); fflush( stdout ); // exhibit the two-dimensional random walk for (int i = 0; i < 100; i++) { usleep( 125000 ); // 125 milliseconds printf( "\e[%d;%dH%c", row, col, ' ' ); fflush( stdout ); int x = random() % 3; int y = random() % 3; switch ( x ) { case 0: ++col; break; case 1: --col; break; } switch ( y ) { case 0: ++row; break; case 1: --row; break; } if ( row == 12 ) ++row; if ( row == 18 ) --row; if ( col == 1 ) ++col; if ( col == 79 ) --col; printf( "\e[%d;%dH%c", row, col, 'o' ); fflush( stdout ); } // prepare the cursor for program exit printf( "\e[24;0H" ); // move cursor to bottom of screen printf( "\e[?25h" ); // show the cursor fflush( stdout ); }