From 729f7045e31100244c66d6b775254f7b56e33983 Mon Sep 17 00:00:00 2001 From: Justine Tunney Date: Fri, 22 Nov 2024 08:52:49 -0800 Subject: [PATCH] Cleanup terminal on ^C in asteroids game --- examples/asteroids.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/examples/asteroids.c b/examples/asteroids.c index 4cd2afd1a..d9537936c 100644 --- a/examples/asteroids.c +++ b/examples/asteroids.c @@ -12,6 +12,7 @@ #include #include #include +#include #include #include @@ -38,6 +39,7 @@ GameObject bullets[MAX_BULLETS]; int score = 0; time_t startTime; int isGameOver = 0; +int shouldExit = 0; int finalTime = 0; // To store final time at game over char display[SCREEN_HEIGHT][SCREEN_WIDTH]; @@ -298,8 +300,13 @@ void restoreTerminal(struct termios *old_tio) { tcsetattr(STDIN_FILENO, TCSANOW, old_tio); } +void onSignal(int sig) { + shouldExit = 1; +} + // Main game loop int main() { + signal(SIGINT, onSignal); // Capture ^C srand(time(NULL)); // Seed the random number generator initGame(); // Initialize the game state @@ -308,7 +315,7 @@ int main() { printf("\033[?25l"); // Hide the cursor - while (1) { + while (!shouldExit) { if (isKeyHit()) { char input = getchar(); if (input == 27) { // ESC key