From 65ba1edac573cbc321bb4a22068becf1f1bd9b67 Mon Sep 17 00:00:00 2001 From: Armaan Bhojwani Date: Sat, 15 May 2021 18:33:55 -0400 Subject: [PATCH] Cleanup logic and fix slide bug Accidentally screwed up the git history, so this is one massive commit --- pong.c | 56 +++++++++++++++++++++++++++++++------------------------- 1 file changed, 31 insertions(+), 25 deletions(-) diff --git a/pong.c b/pong.c index 83d3647..717b1ae 100644 --- a/pong.c +++ b/pong.c @@ -12,18 +12,26 @@ die(int code) exit(code); } +int +randslope(void) +{ + const int low = 2; + const int high = 10; + return (rand() % (high - low + 1)) + low; +} + int main(void) { + srand((unsigned int)time(NULL)); int x, y, aoff = 0, boff = 0; int max_y, max_x; int max_y_new = 0, max_x_new = 0; int pad_h = 5; int a_score = 0, b_score = 0; - int slope_x = 8; - int slope_y = 1; + int slope_x = randslope(); int index_dir = 1; int direction = 1; - double speed = 0.015; + double speed = 0.02; struct timeval start, stop; // Initialize curses @@ -34,7 +42,7 @@ main(void) { getmaxyx(stdscr, max_y, max_x); --max_x; --max_y; - int index = (max_y/2)*(slope_x/slope_y); + int index = slope_x*max_y/2; x = max_x/2; gettimeofday(&start, NULL); @@ -98,35 +106,33 @@ main(void) { index += index_dir; mvprintw(y, x, " "); x += direction; - y = slope_y * index / slope_x; + y = index / slope_x; mvprintw(y, x, "o"); } - // Check if touching paddle or edges - if (x >= max_x - 1) { - if (y >= boff && y <= boff + pad_h) { - direction *= -1; - x += direction; + if ((x >= max_x - 1 && y >= boff && y <= boff + pad_h) || + (x <= 1 && y >= aoff && y <= aoff + pad_h)) { + // Ball hits paddle + direction *= -1; + x += direction; + speed *= 0.9; + } else if (x >= max_x - 1 || x <= 1) { + // Ball goes out of bounds + if (x <=1) { + b_score += 1; } else { a_score += 1; - x = max_x/2; - index = (max_y/2)*(slope_x/slope_y); - speed /= 0.8; - sleep(1); - } - } else if (x <= 1) { - if (y >= aoff && y <= aoff + pad_h) { - direction *= -1; - x += direction; - } else { - b_score += 1; - x = max_x/2; - index = (max_y/2)*(slope_x/slope_y); - speed /= 0.8; - sleep(1); } + x = max_x/2; + index = slope_x*max_y/2; + slope_x = randslope(); + speed = 0.02; + sleep(1); } else if (y == 0 || y == max_y) { + // Ball hits top or bottom wall index_dir *= -1; + mvprintw(y, x, " "); + y = max_y - 1; } } } -- 2.39.2