From 0b18de256368f90628e93045987a045163354a93 Mon Sep 17 00:00:00 2001 From: Aadhavan Srinivasan Date: Thu, 14 Dec 2023 12:59:27 -0500 Subject: [PATCH] Added ball, and basic ball bouncing physics --- pong.c | 37 ++++++++++++++++++++++++++++++------- 1 file changed, 30 insertions(+), 7 deletions(-) diff --git a/pong.c b/pong.c index 787cd70..97c0d90 100644 --- a/pong.c +++ b/pong.c @@ -33,21 +33,26 @@ int main(int argc, char** argv) { ALLEGRO_COLOR white = al_map_rgba(255,255,255,255); ALLEGRO_EVENT event; bool running = true; - bool key_down_1 = false; - bool key_down_2 = false; - float width = 25; + float width = 25; // Width and height of paddles float height = 150; - float start_x_1 = 10; + float start_x_1 = 10; // Top-left coordinates of first paddle float start_y_1 = 10; - float start_x_2 = WIN_WIDTH - 10 - width; + float start_x_2 = WIN_WIDTH - 10 - width; // Top-left coordinates of second paddle float start_y_2 = 10; - float velocity_1 = 0; - float velocity_2 = 0; + float velocity_1 = 0; // Vertical velocity of first paddle + float velocity_2 = 0; // Vertical velocity of second paddle + + float circ_x = WIN_WIDTH / 2; // Center coordinates of ball + float circ_y = WIN_HEIGHT / 2; + float circ_rad = 10; // Radius of ball + float circ_vel_x = 5; // Horizontal velocity of ball + float circ_vel_y = 0; // Vertical velocity of ball al_clear_to_color(black); al_draw_filled_rectangle(start_x_1, start_y_1, start_x_1 + width, start_y_1 + height, white); al_draw_filled_rectangle(start_x_2, start_y_2, start_x_2 + width, start_y_2 + height, white); + al_draw_filled_circle(circ_x, circ_y, circ_rad, white); al_flip_display(); while (running) { @@ -96,11 +101,29 @@ int main(int argc, char** argv) { } al_clear_to_color(black); + + // Update positions ((velocity_1 < 0 && start_y_1 > 0) || (velocity_1 > 0 && start_y_1 + height < WIN_HEIGHT)) && (start_y_1 += velocity_1); ((velocity_2 < 0 && start_y_2 > 0) || (velocity_2 > 0 && start_y_2 + height < WIN_HEIGHT)) && (start_y_2 += velocity_2); + circ_x += circ_vel_x; + circ_y += circ_vel_y; + + //Redraw shapes al_draw_filled_rectangle(start_x_1, start_y_1, start_x_1 + width, start_y_1 + height + velocity_1, white); al_draw_filled_rectangle(start_x_2, start_y_2, start_x_2 + width, start_y_2 + height + velocity_2, white); + al_draw_filled_circle(circ_x, circ_y, circ_rad, white); al_flip_display(); + + if (circ_x + circ_rad >= WIN_WIDTH - 10 - width) { // FOR PADDLE 2: If the circle has reached the point where the paddle would be... + if (circ_y > start_y_2 && circ_y < start_y_2 + height) { // If the circle is touching the paddle... + circ_vel_x = -circ_vel_x; + } + } else if (circ_x - circ_rad <= 10 + width) { // FOR PADDLE 1 + if (circ_y > start_y_1 && circ_y < start_y_1 + height) { + circ_vel_x =- circ_vel_x; + } + } + } // Clean up