From d6ec24ae5d04e62e4de9a7a193975a37b3cf79c8 Mon Sep 17 00:00:00 2001 From: Camden Dixie O'Brien Date: Sat, 18 Oct 2025 17:43:22 +0100 Subject: [PATCH] Add restart and handle quitting with callback --- game.c | 6 ++++++ input.c | 25 +++++++++++++++++++++---- input.h | 4 +++- main.c | 12 +++++++++++- 4 files changed, 41 insertions(+), 6 deletions(-) diff --git a/game.c b/game.c index 440a5ff..38c680c 100644 --- a/game.c +++ b/game.c @@ -153,6 +153,11 @@ static unsigned ship_entity_id; static unsigned ship_shape_id; static unsigned fire_shape_id; +static void restart() +{ + game_init(aspect); +} + static entity_t *add_entity(unsigned *id_out) { const unsigned id = entity_count++; @@ -451,6 +456,7 @@ static void handle_collisions(const collision_t *collisions, unsigned count) void game_init(float _aspect) { input_on_shoot(shoot); + input_on_restart(restart); aspect = _aspect; dead = false; diff --git a/input.c b/input.c index 318b5c7..47b4e18 100644 --- a/input.c +++ b/input.c @@ -15,15 +15,14 @@ enum { input_state_t input; static int input_fd; + +static input_callback_t restart; +static input_callback_t quit; static input_callback_t shoot; static void key_press(int key) { switch (key) { - case KEY_Q: - input.quit = true; - break; - case KEY_UP: ++input.thrust; break; @@ -35,6 +34,14 @@ static void key_press(int key) --input.spin; break; + case KEY_Q: + if (quit != nullptr) + quit(); + break; + case KEY_R: + if (restart != nullptr) + restart(); + break; case KEY_SPACE: if (shoot != nullptr) shoot(); @@ -88,6 +95,16 @@ void input_on_shoot(input_callback_t cb) shoot = cb; } +void input_on_restart(input_callback_t cb) +{ + restart = cb; +} + +void input_on_quit(input_callback_t cb) +{ + quit = cb; +} + void input_handle() { struct input_event ev; diff --git a/input.h b/input.h index 8f524b3..7347bae 100644 --- a/input.h +++ b/input.h @@ -6,7 +6,6 @@ typedef void (*input_callback_t)(); typedef struct { int spin; int thrust; - bool quit; } input_state_t; extern input_state_t input; @@ -15,6 +14,9 @@ int input_init(); void input_cleanup(); void input_on_shoot(input_callback_t cb); +void input_on_restart(input_callback_t cb); +void input_on_quit(input_callback_t cb); + void input_handle(); #endif diff --git a/main.c b/main.c index d23a669..9a773e0 100644 --- a/main.c +++ b/main.c @@ -8,6 +8,13 @@ #define MAX(a, b) ((a) < (b) ? (b) : (a)) +static bool run; + +static void quit() +{ + run = false; +} + int main() { const int input_fd = input_init(); @@ -15,6 +22,8 @@ int main() rng_init(); game_init(renderer_params.aspect); + input_on_quit(quit); + renderer_clear(); renderer_swap(); @@ -22,7 +31,8 @@ int main() const int max_fd = MAX(input_fd, drm_fd); fd_set set; - while (!input.quit) { + run = true; + while (run) { FD_ZERO(&set); FD_SET(input_fd, &set); FD_SET(drm_fd, &set);