]> git.lizzy.rs Git - dungeon_game.git/blobdiff - plugins/game/game.c
Only use entity color if use_color = true
[dungeon_game.git] / plugins / game / game.c
index c6ca4f81f3874dccdd1e946864e6d34d3ee0e874..9fcf7ea6c0191237fec9683d19161f2edd6a6cf6 100644 (file)
@@ -1,24 +1,19 @@
 #include <stdio.h>
-#include <stdbool.h>
 #include <stdlib.h>
-#include <stddef.h>
 #include <unistd.h>
 #include <assert.h>
 #include <ctype.h>
 #include <time.h>
 #include <signal.h>
 #include <termios.h>
-#include <sys/ioctl.h>
 #include <math.h>
 #include <pthread.h>
+#include <string.h>
 #include "game.h"
 
-bool running = true;
-double damage_overlay = 0.0;
+/* Shared variables */
 
-int score = 0;
-
-struct color black = {0, 0, 0};
+struct color black = {0};
 
 struct material wall;
 struct material air;
@@ -26,20 +21,25 @@ struct material outside;
 
 struct node map[MAP_WIDTH][MAP_HEIGHT];
 
-struct entity player;
 struct list *entities = & (struct list) {
        .element = &player,
        .next = NULL,
 };
 
+/* Private variables */
+
 struct entity *entity_collision_map[MAP_WIDTH][MAP_HEIGHT] = {{NULL}};
 
-struct list *air_functions = NULL;
+static bool running = true;
+static double damage_overlay = 0.0;
+static struct color damage_overlay_color;
 
-void quit()
-{
-       running = false;
-}
+static struct list *air_functions = NULL;
+static struct input_handler *input_handlers[256] = {NULL};
+static struct entity *render_entities[LIGHT * 2 + 1][LIGHT * 2 + 1];
+static struct list *render_components = NULL;
+
+/* Helper functions */
 
 struct color get_color(const char *str)
 {
@@ -48,21 +48,138 @@ struct color get_color(const char *str)
        return (struct color) {r, g, b};
 }
 
-bool is_outside(int x, int y)
+void set_color(struct color color, bool bg)
 {
-       return x >= MAP_WIDTH || x < 0 || y >= MAP_HEIGHT || y < 0;
+       printf("\e[%u;2;%u;%u;%um", bg ? 48 : 38, color.r, color.g, color.b);
+}
+
+void light_color(struct color *color, double light)
+{
+       color->r *= light;
+       color->g *= light;
+       color->b *= light;
+}
+
+void mix_color(struct color *color, struct color other, double ratio)
+{
+       double ratio_total = ratio + 1;
+
+       color->r = (color->r + other.r * ratio) / ratio_total;
+       color->g = (color->g + other.g * ratio) / ratio_total;
+       color->b = (color->b + other.b * ratio) / ratio_total;
+}
+
+void dir_to_xy(enum direction dir, int *x, int *y)
+{
+       switch (dir) {
+               case UP:
+                       (*y)--;
+                       break;
+               case LEFT:
+                       (*x)--;
+                       break;
+               case DOWN:
+                       (*y)++;
+                       break;
+               case RIGHT:
+                       (*x)++;
+                       break;
+       }
+}
+
+struct list *add_element(struct list *list, void *element)
+{
+       struct list **ptr;
+
+       for (ptr = &list; *ptr != NULL; ptr = &(*ptr)->next)
+               ;
+
+       *ptr = malloc(sizeof(struct list));
+       (*ptr)->element = element;
+       (*ptr)->next = NULL;
+
+       return list;
+}
+
+int clamp(int v, int min, int max)
+{
+       return v < min ? min : v > max ? max : v;
+}
+
+int max(int a, int b)
+{
+       return a > b ? a : b;
+}
+
+int min(int a, int b)
+{
+       return a < b ? a : b;
+}
+
+void *make_buffer(void *ptr, size_t size)
+{
+       void *buf = malloc(size);
+       memcpy(buf, ptr, size);
+
+       return buf;
+}
+
+/* Game-related utility functions */
+
+void quit()
+{
+       running = false;
+}
+
+bool player_dead()
+{
+       return player.health <= 0;
 }
 
+/* Map functions */
+
 struct node get_node(int x, int y)
 {
        return is_outside(x, y) ? (struct node) {&outside} : map[x][y];
 }
 
+bool is_outside(int x, int y)
+{
+       return x >= MAP_WIDTH || x < 0 || y >= MAP_HEIGHT || y < 0;
+}
+
 bool is_solid(int x, int y)
 {
        return get_node(x, y).material->solid;
 }
 
+/* Entity functions */
+
+bool spawn(struct entity def, int x, int y, void *data)
+{
+       if (is_solid(x, y))
+               return false;
+
+       if (def.collide_with_entities && entity_collision_map[x][y])
+               return false;
+
+       def.x = x;
+       def.y = y;
+
+       struct entity *entity = malloc(sizeof(struct entity));
+       *entity = def;
+
+       add_element(entities, entity);
+
+       if (entity->collide_with_entities)
+               entity_collision_map[x][y] = entity;
+
+       if (entity->on_spawn)
+               entity->on_spawn(entity, data);
+
+       return true;
+}
+
 bool move(struct entity *entity, int xoff, int yoff)
 {
        int x, y;
@@ -87,29 +204,6 @@ bool move(struct entity *entity, int xoff, int yoff)
        }
 }
 
-void spawn(struct entity def, int x, int y)
-{
-       if (is_outside(x, y))
-               return;
-
-       if (def.collide_with_entities && entity_collision_map[x][y])
-               return;
-
-       def.x = x;
-       def.y = y;
-
-       struct entity *entity = malloc(sizeof(struct entity));
-       *entity = def;
-
-       add_element(entities, entity);
-
-       if (entity->collide_with_entities)
-               entity_collision_map[x][y] = entity;
-
-       if (entity->on_spawn)
-               entity->on_spawn(entity);
-}
-
 void add_health(struct entity *entity, int health)
 {
        bool was_alive = entity->health > 0;
@@ -125,37 +219,25 @@ void add_health(struct entity *entity, int health)
                entity->on_death(entity);
 }
 
-void add_score(int s)
-{
-       score += s;
-}
+/* Register callback functions */
 
-bool player_dead()
+void register_air_function(struct generator_function func)
 {
-       return player.health <= 0;
+       air_functions = add_element(air_functions, make_buffer(&func, sizeof(struct generator_function)));
 }
 
-struct list *add_element(struct list *list, void *element)
+void register_input_handler(unsigned char c, struct input_handler handler)
 {
-       struct list **ptr;
-
-       for (ptr = &list; *ptr != NULL; ptr = &(*ptr)->next)
-               ;
-
-       *ptr = malloc(sizeof(struct list));
-       (*ptr)->element = element;
-       (*ptr)->next = NULL;
+       if (input_handlers[c])
+               return;
 
-       return list;
+       input_handlers[c] = make_buffer(&handler, sizeof(struct input_handler));
 }
 
-void register_air_function(struct generator_function func)
+void register_render_component(void (*callback)(struct winsize ws))
 {
-       struct generator_function *buf = malloc(sizeof(struct generator_function));
-       *buf = func;
-
-       air_functions = add_element(air_functions, buf);
-}
+       render_components = add_element(render_components, callback);
+};
 
 /* Player */
 
@@ -166,41 +248,98 @@ static void player_death(struct entity *self)
 
 static void player_damage(struct entity *self, int damage)
 {
-       damage_overlay = (double) damage * 0.5;
+       damage_overlay += (double) damage * 0.5;
 }
 
+struct entity player = {
+       .name = "player",
+       .x = MAP_WIDTH / 2,
+       .y = MAP_HEIGHT / 2,
+       .color = {0},
+       .use_color = false,
+       .texture = "🙂",
+       .remove = false,
+       .meta = NULL,
+       .health = 10,
+       .max_health = 10,
+       .collide_with_entities = true,
+
+       .on_step = NULL,
+       .on_collide = NULL,
+       .on_collide_with_entity = NULL,
+       .on_spawn = NULL,
+       .on_remove = NULL,
+       .on_death = &player_death,
+       .on_damage = &player_damage,
+};
+
 /* Mapgen */
 
-static bool check_direction(int x, int y, int dir)
+static void mapgen_set_air(int x, int y)
+{
+       if (is_outside(x, y))
+               return;
+
+       if (map[x][y].material == &air)
+               return;
+
+       map[x][y] = (struct node) {&air};
+
+       for (struct list *ptr = air_functions; ptr != NULL; ptr = ptr->next) {
+               struct generator_function *func = ptr->element;
+
+               if (rand() % func->chance == 0)
+                       func->callback(x, y);
+       }
+}
+
+static void generate_room(int origin_x, int origin_y)
+{
+       int left = 5 + rand() % 10;
+       int right = 5 + rand() % 10;
+
+       int up = 0;
+       int down = 0;
+
+       for (int x = -left; x <= right; x++) {
+               if (x < 0) {
+                       up += rand() % 2;
+                       down += rand() % 2;
+               } else {
+                       up -= rand() % 2;
+                       down -= rand() % 2;
+               }
+
+               for (int y = -up; y <= down; y++)
+                       mapgen_set_air(origin_x + x, origin_y + y);
+       }
+}
+
+static bool check_direction(int x, int y, enum direction dir)
 {
        if (dir % 2 == 0)
-               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);
-       else
                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);
+       else
+               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);
 }
 
-static void generate_corridor(int lx, int ly, int ldir, bool off)
+static void generate_corridor(int lx, int ly, enum direction ldir)
 {
        if (is_outside(lx, ly))
                return;
 
-       /*
-       if (off && rand() % 100 == 0)
+       if (rand() % 200 == 0) {
+               generate_room(lx, ly);
                return;
-       */
+       }
 
-       map[lx][ly] = (struct node) {&air};
+       mapgen_set_air(lx, ly);
 
-       for (struct list *ptr = air_functions; ptr != NULL; ptr = ptr->next) {
-               struct generator_function *func = ptr->element;
+       int x, y;
 
-               if (! func->chance || rand() % func->chance == 0) {
-                       func->callback(lx, ly);
-               }
-       }
+       enum direction dir;
+       enum direction ret = (ldir + 2) % 4;
 
-       int x, y, dir;
-       int ret = (ldir + 2) % 4;
        int limit = 50;
 
        do {
@@ -212,92 +351,52 @@ static void generate_corridor(int lx, int ly, int ldir, bool off)
                else
                        dir = rand() % 4;
 
-               switch (dir) {
-                       case 0:
-                               x++;
-                               break;
-                       case 1:
-                               y++;
-                               break;
-                       case 2:
-                               x--;
-                               break;
-                       case 3:
-                               y--;
-                               break;
-               }
-
+               dir_to_xy(dir, &x, &y);
        } while (dir == ret || (! check_direction(x, y, dir) && --limit));
 
        if (limit)
-               generate_corridor(x, y, dir, off);
+               generate_corridor(x, y, dir);
 
        if (rand() % 20 == 0)
-               generate_corridor(lx, ly, ldir, true);
+               generate_corridor(lx, ly, ldir);
 }
 
 static void generate_corridor_random(int x, int y)
 {
-       int dir = rand() % 4;
+       enum direction dir = rand() % 4;
 
-       generate_corridor(x, y, dir, false);
-       generate_corridor(x, y, (dir + 2) % 4, false);
+       generate_corridor(x, y, dir);
+       generate_corridor(x, y, (dir + 2) % 4);
 }
 
 /* Rendering */
 
-void set_color(struct color color, bool bg)
-{
-       printf("\e[%u;2;%u;%u;%um", bg ? 48 : 38, color.r, color.g, color.b);
-}
-
-void light_color(struct color *color, double light)
-{
-       color->r *= light;
-       color->g *= light;
-       color->b *= light;
-}
-
-void mix_color(struct color *color, struct color other, double ratio)
-{
-       double ratio_total = ratio + 1;
-
-       color->r = (color->r + other.r * ratio) / ratio_total;
-       color->g = (color->g + other.g * ratio) / ratio_total;
-       color->b = (color->b + other.b * ratio) / ratio_total;
-}
-
-static bool render_color(struct color color, double light, bool bg)
+static bool render_color(struct color color, double light, bool bg, bool use_color)
 {
        if (light <= 0.0) {
                set_color(black, bg);
                return false;
-       } else {
+       } else if (use_color) {
                if (damage_overlay > 0.0)
-                       mix_color(&color, get_color("#F20000"), damage_overlay * 2.0);
+                       mix_color(&color, damage_overlay_color, damage_overlay * 2.0);
 
                light_color(&color, light);
 
                set_color(color, bg);
                return true;
+       } else {
+               return true;
        }
 }
 
-static void render(render_entity_list entity_list)
+static void render_map(struct winsize ws)
 {
-       printf("\e[2J\e[0;0H");
-
-       struct winsize ws;
-       ioctl(STDIN_FILENO, TIOCGWINSZ, &ws);
-
        int cols = ws.ws_col / 2 - LIGHT * 2;
        int rows = ws.ws_row / 2 - LIGHT;
 
        int cols_left = ws.ws_col - cols - (LIGHT * 2 + 1) * 2;
        int rows_left = ws.ws_row - rows - (LIGHT * 2 + 1);
 
-       set_color(black, true);
-
        for (int i = 0; i < rows; i++)
                for (int i = 0; i < ws.ws_col; i++)
                        printf(" ");
@@ -317,11 +416,12 @@ static void render(render_entity_list entity_list)
                        double dist = sqrt(x * x + y * y);
                        double light = 1.0 - (double) dist / (double) LIGHT;
 
-                       render_color(node.material->color, light, true);
+                       render_color(node.material->color, light, true, true);
 
-                       struct entity *entity = entity_list[x + LIGHT][y + LIGHT];
+                       struct entity *entity = render_entities[x + LIGHT][y + LIGHT];
+                       render_entities[x + LIGHT][y + LIGHT] = NULL;
 
-                       if (entity && render_color(entity->color, light, false))
+                       if (entity && render_color(entity->color, light, false, entity->use_color))
                                printf("%s", entity->texture);
                        else
                                printf("  ");
@@ -333,75 +433,43 @@ static void render(render_entity_list entity_list)
                        printf(" ");
        }
 
-       for (int i = 0; i < rows_left + 1; i++)
+       for (int i = 0; i < rows_left; i++)
                for (int i = 0; i < ws.ws_col; i++)
                        printf(" ");
+}
 
-       printf("\e[0;0H\e[39m");
-
-       printf("\e[32m\e[3mScore:\e[23m %d\e[39m", score);
-
-       printf("\e[0;0");
-
-       for (int i = 0; i < rows; i++)
-               printf("\n");
-
-       printf("\t\e[1mInventory\e[22m\n\n");
-       printf("\t0x\t\e[3mNothing\e[23m\n");
-
-       printf("\e[0;0H");
-
-       for (int i = 0; i < ws.ws_row - 2; i++)
-               printf("\n");
-
-       int hearts_cols = ws.ws_col / 2 - player.max_health;
+static void render()
+{
+       printf("\e[2J");
 
-       for (int i = 0; i < hearts_cols; i++)
-               printf(" ");
+       struct winsize ws;
+       ioctl(STDIN_FILENO, TIOCGWINSZ, &ws);
 
-       set_color((struct color) {255, 0, 0}, false);
+       for (struct list *ptr = render_components; ptr != NULL; ptr = ptr->next) {
+               printf("\e[0m\e[0;0H");
+               set_color(black, true);
 
-       for (int i = 0; i < player.max_health; i++) {
-               if (i >= player.health)
-                       set_color(get_color("#5A5A5A"), false);
-               printf("\u2665 ");
+               ((void (*)(struct winsize ws)) ptr->element)(ws);
        }
 
-       printf("\e[39m\n");
+       fflush(stdout);
 }
 
 /* Input */
 
-static void handle_input(char c)
+static void handle_interrupt(int signal)
 {
-       bool dead = player_dead();
+       (void) signal;
 
-       switch (c) {
-               case 'q':
-                       quit();
-                       break;
-               case 'w':
-                       dead || move(&player, 0, -1);
-                       break;
-               case 'a':
-                       dead || move(&player, -1, 0);
-                       break;
-               case 's':
-                       dead || move(&player, 0, 1);
-                       break;
-               case 'd':
-                       dead || move(&player, 1, 0);
-                       break;
-       }
+       quit();
 }
 
-/* Multithreading */
-
-static void handle_interrupt(int signal)
+static void handle_input(unsigned char c)
 {
-       (void) signal;
+       struct input_handler *handler = input_handlers[c];
 
-       running = false;
+       if (handler && (handler->run_if_dead || ! player_dead()))
+               handler->callback();
 }
 
 static void *input_thread(void *unused)
@@ -416,55 +484,8 @@ static void *input_thread(void *unused)
 
 /* Main Game */
 
-__attribute__ ((constructor)) static void init()
-{
-       wall = (struct material) {
-               .solid = true,
-               .color = get_color("#5B2F00"),
-       };
-
-       air = (struct material) {
-               .solid = false,
-               .color = get_color("#FFE027"),
-       };
-
-       outside = (struct material) {
-               .solid = true,
-               .color = black,
-       };
-
-       player = (struct entity) {
-               .name = "player",
-               .x = MAP_WIDTH / 2,
-               .y = MAP_HEIGHT / 2,
-               .color = get_color("#00FFFF"),
-               .texture = "🙂",
-               .remove = false,
-               .meta = NULL,
-               .health = 10,
-               .max_health = 10,
-               .collide_with_entities = true,
-
-               .on_step = NULL,
-               .on_collide = NULL,
-               .on_collide_with_entity = NULL,
-               .on_spawn = NULL,
-               .on_remove = NULL,
-               .on_death = &player_death,
-               .on_damage = &player_damage,
-       };
-
-       entity_collision_map[player.x][player.y] = &player;
-
-       for (int x = 0; x < MAP_WIDTH; x++)
-               for (int y = 0; y < MAP_HEIGHT; y++)
-                       map[x][y] = (struct node) {&wall};
-}
-
 void game()
 {
-       srand(time(0));
-
        struct sigaction sa;
        sa.sa_handler = &handle_interrupt;
        sigaction(SIGINT, &sa, NULL);
@@ -495,10 +516,12 @@ void game()
 
                bool dead = player_dead();
 
-               if (! dead && damage_overlay > 0.0)
+               if (! dead && damage_overlay > 0.0) {
                        damage_overlay -= dtime;
 
-               render_entity_list render_list = {{NULL}};
+                       if (damage_overlay < 0.0)
+                               damage_overlay = 0.0;
+               }
 
                for (struct list **ptr = &entities; *ptr != NULL; ) {
                        struct entity *entity = (*ptr)->element;
@@ -513,6 +536,9 @@ void game()
                                if (entity->meta)
                                        free(entity->meta);
 
+                               if (entity->collide_with_entities)
+                                       entity_collision_map[entity->x][entity->y] = NULL;
+
                                free(entity);
                                free(*ptr);
 
@@ -528,7 +554,7 @@ void game()
                        bool visible = abs(dx) <= LIGHT && abs(dy) <= LIGHT;
 
                        if (visible)
-                               render_list[dx + LIGHT][dy + LIGHT] = entity;
+                               render_entities[dx + LIGHT][dy + LIGHT] = entity;
 
                        if (! dead && entity->on_step)
                                entity->on_step(entity, (struct entity_step_data) {
@@ -541,7 +567,7 @@ void game()
                        ptr = &(*ptr)->next;
                }
 
-               render(render_list);
+               render();
 
                // there is no such thing as glfwSwapBuffers, so we just wait 1 / 60 seconds to prevent artifacts
                usleep(1000000 / 60);
@@ -551,6 +577,43 @@ void game()
        tcsetattr(STDIN_FILENO, TCSANOW, &oldtio);
 }
 
+/* Initializer function */
+
+__attribute__ ((constructor)) static void init()
+{
+       srand(time(0));
+
+       wall = (struct material) {
+               .solid = true,
+               .color = get_color("#5B2F00"),
+       };
+
+       air = (struct material) {
+               .solid = false,
+               .color = get_color("#FFE027"),
+       };
+
+       outside = (struct material) {
+               .solid = true,
+               .color = black,
+       };
+
+       entity_collision_map[player.x][player.y] = &player;
+
+       for (int x = 0; x < MAP_WIDTH; x++)
+               for (int y = 0; y < MAP_HEIGHT; y++)
+                       map[x][y] = (struct node) {&wall};
+
+       register_input_handler('q', (struct input_handler) {
+               .run_if_dead = true,
+               .callback = &quit,
+       });
+
+       register_render_component(&render_map);
+
+       damage_overlay_color = get_color("#F20000");
+}
+
 /* Use later */
 
 /*