]> git.lizzy.rs Git - dungeon_game.git/blob - plugins/game/game.c
Modularize input
[dungeon_game.git] / plugins / game / game.c
1 #include <stdio.h>
2 #include <stdbool.h>
3 #include <stdlib.h>
4 #include <stddef.h>
5 #include <unistd.h>
6 #include <assert.h>
7 #include <ctype.h>
8 #include <time.h>
9 #include <signal.h>
10 #include <termios.h>
11 #include <sys/ioctl.h>
12 #include <math.h>
13 #include <pthread.h>
14 #include "game.h"
15
16 bool running = true;
17 double damage_overlay = 0.0;
18
19 int score = 0;
20
21 struct color black = {0, 0, 0};
22
23 struct material wall;
24 struct material air;
25 struct material outside;
26
27 struct node map[MAP_WIDTH][MAP_HEIGHT];
28
29 struct entity player;
30 struct list *entities = & (struct list) {
31         .element = &player,
32         .next = NULL,
33 };
34
35 struct entity *entity_collision_map[MAP_WIDTH][MAP_HEIGHT] = {{NULL}};
36
37 struct list *air_functions = NULL;
38
39 struct input_handler *input_handlers[256] = {NULL};
40
41 void quit()
42 {
43         running = false;
44 }
45
46 struct color get_color(const char *str)
47 {
48         unsigned int r, g, b;
49         sscanf(str, "#%2x%2x%2x", &r, &g, &b);
50         return (struct color) {r, g, b};
51 }
52
53 bool is_outside(int x, int y)
54 {
55         return x >= MAP_WIDTH || x < 0 || y >= MAP_HEIGHT || y < 0;
56 }
57
58 struct node get_node(int x, int y)
59 {
60         return is_outside(x, y) ? (struct node) {&outside} : map[x][y];
61 }
62
63 bool is_solid(int x, int y)
64 {
65         return get_node(x, y).material->solid;
66 }
67
68 bool move(struct entity *entity, int xoff, int yoff)
69 {
70         int x, y;
71
72         x = entity->x + xoff;
73         y = entity->y + yoff;
74
75         if (is_solid(x, y)) {
76                 if (entity->on_collide)
77                         entity->on_collide(entity, x, y);
78                 return false;
79         } else if (entity->collide_with_entities && entity_collision_map[x][y]) {
80                 if (entity->on_collide_with_entity)
81                         entity->on_collide_with_entity(entity, entity_collision_map[x][y]);
82                 return false;
83         } else {
84                 entity_collision_map[entity->x][entity->y] = NULL;
85                 entity->x = x;
86                 entity->y = y;
87                 entity_collision_map[entity->x][entity->y] = entity;
88                 return true;
89         }
90 }
91
92 void spawn(struct entity def, int x, int y)
93 {
94         if (is_outside(x, y))
95                 return;
96
97         if (def.collide_with_entities && entity_collision_map[x][y])
98                 return;
99
100         def.x = x;
101         def.y = y;
102
103         struct entity *entity = malloc(sizeof(struct entity));
104         *entity = def;
105
106         add_element(entities, entity);
107
108         if (entity->collide_with_entities)
109                 entity_collision_map[x][y] = entity;
110
111         if (entity->on_spawn)
112                 entity->on_spawn(entity);
113 }
114
115 void add_health(struct entity *entity, int health)
116 {
117         bool was_alive = entity->health > 0;
118
119         entity->health += health;
120
121         if (health < 0 && entity->on_damage)
122                 entity->on_damage(entity, -health);
123
124         if (entity->health > entity->max_health)
125                 entity->health = entity->max_health;
126         else if (entity->health <= 0 && was_alive && entity->on_death)
127                 entity->on_death(entity);
128 }
129
130 void add_score(int s)
131 {
132         score += s;
133 }
134
135 bool player_dead()
136 {
137         return player.health <= 0;
138 }
139
140 struct list *add_element(struct list *list, void *element)
141 {
142         struct list **ptr;
143
144         for (ptr = &list; *ptr != NULL; ptr = &(*ptr)->next)
145                 ;
146
147         *ptr = malloc(sizeof(struct list));
148         (*ptr)->element = element;
149         (*ptr)->next = NULL;
150
151         return list;
152 }
153
154 void register_air_function(struct generator_function func)
155 {
156         struct generator_function *buf = malloc(sizeof(struct generator_function));
157         *buf = func;
158
159         air_functions = add_element(air_functions, buf);
160 }
161
162 void register_input_handler(unsigned char c, struct input_handler handler)
163 {
164         if (input_handlers[c])
165                 return;
166
167         struct input_handler *buf = malloc(sizeof(struct input_handler));
168         *buf = handler;
169
170         input_handlers[c] = buf;
171 }
172
173 /* Player */
174
175 static void player_death(struct entity *self)
176 {
177         self->texture = "☠ ";
178 }
179
180 static void player_damage(struct entity *self, int damage)
181 {
182         damage_overlay = (double) damage * 0.5;
183 }
184
185 /* Mapgen */
186
187 static bool check_direction(int x, int y, int dir)
188 {
189         if (dir % 2 == 0)
190                 return is_solid(x, y + 1) && is_solid(x, y - 1) && (is_solid(x + 1, y) || rand() % 3 > 1) && (is_solid(x - 1, y) || rand() % 3 > 1);
191         else
192                 return is_solid(x + 1, y) && is_solid(x - 1, y) && (is_solid(x, y + 1) || rand() % 3 > 1) && (is_solid(x, y - 1) || rand() % 3 > 1);
193 }
194
195 static void generate_corridor(int lx, int ly, int ldir, bool off)
196 {
197         if (is_outside(lx, ly))
198                 return;
199
200         /*
201         if (off && rand() % 100 == 0)
202                 return;
203         */
204
205         map[lx][ly] = (struct node) {&air};
206
207         for (struct list *ptr = air_functions; ptr != NULL; ptr = ptr->next) {
208                 struct generator_function *func = ptr->element;
209
210                 if (! func->chance || rand() % func->chance == 0) {
211                         func->callback(lx, ly);
212                 }
213         }
214
215         int x, y, dir;
216         int ret = (ldir + 2) % 4;
217         int limit = 50;
218
219         do {
220                 x = lx;
221                 y = ly;
222
223                 if (rand() % 3 > 1)
224                         dir = ldir;
225                 else
226                         dir = rand() % 4;
227
228                 switch (dir) {
229                         case 0:
230                                 x++;
231                                 break;
232                         case 1:
233                                 y++;
234                                 break;
235                         case 2:
236                                 x--;
237                                 break;
238                         case 3:
239                                 y--;
240                                 break;
241                 }
242
243         } while (dir == ret || (! check_direction(x, y, dir) && --limit));
244
245         if (limit)
246                 generate_corridor(x, y, dir, off);
247
248         if (rand() % 20 == 0)
249                 generate_corridor(lx, ly, ldir, true);
250 }
251
252 static void generate_corridor_random(int x, int y)
253 {
254         int dir = rand() % 4;
255
256         generate_corridor(x, y, dir, false);
257         generate_corridor(x, y, (dir + 2) % 4, false);
258 }
259
260 /* Rendering */
261
262 void set_color(struct color color, bool bg)
263 {
264         printf("\e[%u;2;%u;%u;%um", bg ? 48 : 38, color.r, color.g, color.b);
265 }
266
267 void light_color(struct color *color, double light)
268 {
269         color->r *= light;
270         color->g *= light;
271         color->b *= light;
272 }
273
274 void mix_color(struct color *color, struct color other, double ratio)
275 {
276         double ratio_total = ratio + 1;
277
278         color->r = (color->r + other.r * ratio) / ratio_total;
279         color->g = (color->g + other.g * ratio) / ratio_total;
280         color->b = (color->b + other.b * ratio) / ratio_total;
281 }
282
283 static bool render_color(struct color color, double light, bool bg)
284 {
285         if (light <= 0.0) {
286                 set_color(black, bg);
287                 return false;
288         } else {
289                 if (damage_overlay > 0.0)
290                         mix_color(&color, get_color("#F20000"), damage_overlay * 2.0);
291
292                 light_color(&color, light);
293
294                 set_color(color, bg);
295                 return true;
296         }
297 }
298
299 static void render(render_entity_list entity_list)
300 {
301         printf("\e[2J\e[0;0H");
302
303         struct winsize ws;
304         ioctl(STDIN_FILENO, TIOCGWINSZ, &ws);
305
306         int cols = ws.ws_col / 2 - LIGHT * 2;
307         int rows = ws.ws_row / 2 - LIGHT;
308
309         int cols_left = ws.ws_col - cols - (LIGHT * 2 + 1) * 2;
310         int rows_left = ws.ws_row - rows - (LIGHT * 2 + 1);
311
312         set_color(black, true);
313
314         for (int i = 0; i < rows; i++)
315                 for (int i = 0; i < ws.ws_col; i++)
316                         printf(" ");
317
318         for (int y = -LIGHT; y <= LIGHT; y++) {
319                 for (int i = 0; i < cols; i++)
320                         printf(" ");
321
322                 for (int x = -LIGHT; x <= LIGHT; x++) {
323                         int map_x, map_y;
324
325                         map_x = x + player.x;
326                         map_y = y + player.y;
327
328                         struct node node = get_node(map_x, map_y);
329
330                         double dist = sqrt(x * x + y * y);
331                         double light = 1.0 - (double) dist / (double) LIGHT;
332
333                         render_color(node.material->color, light, true);
334
335                         struct entity *entity = entity_list[x + LIGHT][y + LIGHT];
336
337                         if (entity && render_color(entity->color, light, false))
338                                 printf("%s", entity->texture);
339                         else
340                                 printf("  ");
341                 }
342
343                 set_color(black, true);
344
345                 for (int i = 0; i < cols_left; i++)
346                         printf(" ");
347         }
348
349         for (int i = 0; i < rows_left + 1; i++)
350                 for (int i = 0; i < ws.ws_col; i++)
351                         printf(" ");
352
353         printf("\e[0;0H\e[39m");
354
355         printf("\e[32m\e[3mScore:\e[23m %d\e[39m", score);
356
357         printf("\e[0;0");
358
359         for (int i = 0; i < rows; i++)
360                 printf("\n");
361
362         printf("\t\e[1mInventory\e[22m\n\n");
363         printf("\t0x\t\e[3mNothing\e[23m\n");
364
365         printf("\e[0;0H");
366
367         for (int i = 0; i < ws.ws_row - 2; i++)
368                 printf("\n");
369
370         int hearts_cols = ws.ws_col / 2 - player.max_health;
371
372         for (int i = 0; i < hearts_cols; i++)
373                 printf(" ");
374
375         set_color((struct color) {255, 0, 0}, false);
376
377         for (int i = 0; i < player.max_health; i++) {
378                 if (i >= player.health)
379                         set_color(get_color("#5A5A5A"), false);
380                 printf("\u2665 ");
381         }
382
383         printf("\e[39m\n");
384 }
385
386 /* Input */
387
388 static void handle_input(unsigned char c)
389 {
390         struct input_handler *handler = input_handlers[c];
391
392         if (handler && (handler->run_if_dead || ! player_dead()))
393                 handler->callback();
394 }
395
396 /* Multithreading */
397
398 static void handle_interrupt(int signal)
399 {
400         (void) signal;
401
402         running = false;
403 }
404
405 static void *input_thread(void *unused)
406 {
407         (void) unused;
408
409         while (running)
410                 handle_input(tolower(fgetc(stdin)));
411
412         return NULL;
413 }
414
415 /* Main Game */
416
417 __attribute__ ((constructor)) static void init()
418 {
419         wall = (struct material) {
420                 .solid = true,
421                 .color = get_color("#5B2F00"),
422         };
423
424         air = (struct material) {
425                 .solid = false,
426                 .color = get_color("#FFE027"),
427         };
428
429         outside = (struct material) {
430                 .solid = true,
431                 .color = black,
432         };
433
434         player = (struct entity) {
435                 .name = "player",
436                 .x = MAP_WIDTH / 2,
437                 .y = MAP_HEIGHT / 2,
438                 .color = get_color("#00FFFF"),
439                 .texture = "🙂",
440                 .remove = false,
441                 .meta = NULL,
442                 .health = 10,
443                 .max_health = 10,
444                 .collide_with_entities = true,
445
446                 .on_step = NULL,
447                 .on_collide = NULL,
448                 .on_collide_with_entity = NULL,
449                 .on_spawn = NULL,
450                 .on_remove = NULL,
451                 .on_death = &player_death,
452                 .on_damage = &player_damage,
453         };
454
455         entity_collision_map[player.x][player.y] = &player;
456
457         for (int x = 0; x < MAP_WIDTH; x++)
458                 for (int y = 0; y < MAP_HEIGHT; y++)
459                         map[x][y] = (struct node) {&wall};
460
461         register_input_handler('q', (struct input_handler) {
462                 .run_if_dead = true,
463                 .callback = &quit,
464         });
465 }
466
467 void game()
468 {
469         srand(time(0));
470
471         struct sigaction sa;
472         sa.sa_handler = &handle_interrupt;
473         sigaction(SIGINT, &sa, NULL);
474
475         generate_corridor_random(player.x, player.y);
476
477         for (int i = 0; i < 50; i++)
478                 generate_corridor_random(rand() % MAP_WIDTH, rand() % MAP_HEIGHT);
479
480         struct termios oldtio, newtio;
481         tcgetattr(STDIN_FILENO, &oldtio);
482         newtio = oldtio;
483         newtio.c_lflag &= ~(ICANON | ECHO);
484         tcsetattr(STDIN_FILENO, TCSANOW, &newtio);
485
486         printf("\e[?1049h\e[?25l");
487
488         pthread_t input_thread_id;
489         pthread_create(&input_thread_id, NULL, &input_thread, NULL);
490
491         struct timespec ts, ts_old;
492         clock_gettime(CLOCK_REALTIME, &ts_old);
493
494         while (running) {
495                 clock_gettime(CLOCK_REALTIME, &ts);
496                 double dtime = (double) (ts.tv_sec - ts_old.tv_sec) + (double) (ts.tv_nsec - ts_old.tv_nsec) / 1000000000.0;
497                 ts_old = ts;
498
499                 bool dead = player_dead();
500
501                 if (! dead && damage_overlay > 0.0)
502                         damage_overlay -= dtime;
503
504                 render_entity_list render_list = {{NULL}};
505
506                 for (struct list **ptr = &entities; *ptr != NULL; ) {
507                         struct entity *entity = (*ptr)->element;
508
509                         if (entity->remove) {
510                                 assert(entity != &player);
511                                 struct list *next = (*ptr)->next;
512
513                                 if (entity->on_remove)
514                                         entity->on_remove(entity);
515
516                                 if (entity->meta)
517                                         free(entity->meta);
518
519                                 free(entity);
520                                 free(*ptr);
521
522                                 *ptr = next;
523                                 continue;
524                         }
525
526                         int dx, dy;
527
528                         dx = entity->x - player.x;
529                         dy = entity->y - player.y;
530
531                         bool visible = abs(dx) <= LIGHT && abs(dy) <= LIGHT;
532
533                         if (visible)
534                                 render_list[dx + LIGHT][dy + LIGHT] = entity;
535
536                         if (! dead && entity->on_step)
537                                 entity->on_step(entity, (struct entity_step_data) {
538                                         .dtime = dtime,
539                                         .visible = visible,
540                                         .dx = dx,
541                                         .dy = dy,
542                                 });
543
544                         ptr = &(*ptr)->next;
545                 }
546
547                 render(render_list);
548
549                 // there is no such thing as glfwSwapBuffers, so we just wait 1 / 60 seconds to prevent artifacts
550                 usleep(1000000 / 60);
551         }
552
553         printf("\e[?1049l\e[?25h");
554         tcsetattr(STDIN_FILENO, TCSANOW, &oldtio);
555 }
556
557 /* Use later */
558
559 /*
560 get_box_char(is_solid(x, y - 1), is_solid(x, y + 1), is_solid(x - 1, y), is_solid(x + 1, y));
561
562 const char *get_box_char(bool up, bool down, bool left, bool right)
563 {
564         if (left && right && ! up && ! down)
565                 return "\u2501\u2501";
566         else if (up && down && ! right && ! left)
567                 return "\u2503 ";
568         else if (down && right && ! up && ! left)
569                 return "\u250F\u2501";
570         else if (down && left && ! up && ! right)
571                 return "\u2513 ";
572         else if (up && right && ! down && ! left)
573                 return "\u2517\u2501";
574         else if (up && left && ! down && ! right)
575                 return "\u251B ";
576         else if (up && down && right && ! left)
577                 return "\u2523\u2501";
578         else if (up && down && left && ! right)
579                 return "\u252B ";
580         else if (down && left && right && ! up)
581                 return "\u2533\u2501";
582         else if (up && left && right && ! down)
583                 return "\u253B\u2501";
584         else if (up && down && left && right)
585                 return "\u254b\u2501";
586         else if (left && ! up && ! down && ! right)
587                 return "\u2578 ";
588         else if (up && ! down && ! left && ! right)
589                 return "\u2579 ";
590         else if (right && ! up && ! down && ! left)
591                 return "\u257A\u2501";
592         else if (down && ! up && ! left && ! right)
593                 return "\u257B ";
594         else if (! up && ! down && ! left && ! right)
595                 return "\u25AA ";
596         else
597                 return "??";
598 }
599 */