Add restart and handle quitting with callback

This commit is contained in:
Camden Dixie O'Brien
2025-10-15 13:13:44 +01:00
parent db1fc63652
commit a3486b47c7
4 changed files with 41 additions and 6 deletions

6
game.c
View File

@@ -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;

25
input.c
View File

@@ -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;

View File

@@ -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

12
main.c
View File

@@ -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);