// This program bounces multiple balls at once #include #include #include #include #include #define XDIM 600 // x dimension of table #define YDIM 400 // y dimension of table #define BALL_RADIUS 20 // ball radius #define TABLE_COLOR COLOR(0,50,0) // color of table #define N_BALLS 100 // function prototypes void initialize_screen(); void initialize_ball(double &ball_loc_x, double &ball_loc_y, double &ball_direction, double &ball_velocity); void update_ball_loc(double &ball_loc_x, double &ball_loc_y, double &ball_direction, double ball_velocity); void update_screen(int old_ball_screen_x, int old_ball_screen_y, int new_ball_screen_x, int new_ball_screen_y, int ball_color); int random_in_range(int lower, int upper); int main () { int i; double ball_loc_x[N_BALLS]; // ball x coordinate in screen units double ball_loc_y[N_BALLS]; // ball y coordinate in screen units double ball_direction[N_BALLS]; // ball angle in radians double ball_velocity[N_BALLS]; // ball velocity in screen units double old_ball_loc_x; double old_ball_loc_y; initialize_screen(); for (i=0; i= XDIM - BALL_RADIUS) || (ball_loc_x + delta_x < BALL_RADIUS)) ball_direction = 3.14159 - ball_direction; else ball_loc_x += delta_x; // check whether ball has hit upper or lower wall if ((ball_loc_y + delta_y >= YDIM - BALL_RADIUS) || (ball_loc_y + delta_y < BALL_RADIUS)) ball_direction = -ball_direction; else ball_loc_y += delta_y; } /************************************ update_screen **************************/ void update_screen(int old_ball_screen_x, int old_ball_screen_y, int new_ball_screen_x, int new_ball_screen_y, int ball_color) { // check to see if ball has moved on screen if (old_ball_screen_x != new_ball_screen_x || old_ball_screen_y != new_ball_screen_y) { // erase ball in old location setfillstyle(SOLID_FILL, TABLE_COLOR); setcolor(TABLE_COLOR); fillellipse(old_ball_screen_x, old_ball_screen_y, BALL_RADIUS, BALL_RADIUS); // draw ball in new location setfillstyle(SOLID_FILL, ball_color); setcolor(ball_color); fillellipse(new_ball_screen_x, new_ball_screen_y, BALL_RADIUS, BALL_RADIUS); } } /************************************ random_in_range ************************/ // Generate a random number in the integer range [lower, upper] int random_in_range(int lower, int upper) { static int first_time = 1; if (first_time) { srand(time(0)); first_time = 0; } return (lower + rand()%(upper-lower+1)); }