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