]> git.lizzy.rs Git - dungeon_game.git/blob - plugins/fireball/fireball.c
1c3eeb6e31d6ab4a0b239de61b4d6ee883a02fe9
[dungeon_game.git] / plugins / fireball / fireball.c
1 #include <stdlib.h>
2 #include <stddef.h>
3 #include "../game/game.h"
4
5 static struct entity fireball;
6
7 struct fireball_data
8 {
9         double timer;
10         int vx;
11         int vy;
12 };
13
14 static void fireball_spawn(struct entity *self, void *data)
15 {
16         self->meta = malloc(sizeof(struct fireball_data));
17         *((struct fireball_data *) self->meta) = *((struct fireball_data *) data);
18 }
19
20 static void fireball_step(struct entity *self, struct entity_step_data stepdata)
21 {
22         struct fireball_data *data = self->meta;
23
24         if (stepdata.visible && (data->timer -= stepdata.dtime) <= 0.0) {
25                 data->timer = 0.1;
26                 move(self, data->vx, data->vy);
27         }
28 }
29
30 static void fireball_collide(struct entity *self, int x, int y)
31 {
32         (void) x, y;
33
34         self->remove = true;
35 }
36
37 static void fireball_collide_with_entity(struct entity *self, struct entity *other)
38 {
39         add_health(other, -(1 + rand() % 3));
40         self->remove = true;
41 }
42
43 static bool try_shoot(int x, int y, int vx, int vy)
44 {
45         x += vx;
46         y += vy;
47
48         return spawn(fireball, x, y, & (struct fireball_data) {
49                 .timer = 0.1,
50                 .vx = vx,
51                 .vy = vy,
52         });
53 }
54
55 static void shoot_fireball()
56 {
57         int x, y;
58
59         x = player.x;
60         y = player.y;
61
62         for (int tries = 10; tries > 0; tries--) {
63                 int vx, vy;
64
65                 vx = vy = 0;
66
67                 dir_to_xy(rand() % 4, &vx, &vy);
68
69                 if (try_shoot(x, y, vx, vy))
70                         return;
71         }
72 }
73
74 __attribute__((constructor)) static void init()
75 {
76         fireball = (struct entity) {
77                 .name = "fireball",
78                 .x = 0,
79                 .y = 0,
80                 .color = get_color("#FF6611"),
81                 .texture = "⬤ ",
82                 .remove = false,
83                 .meta = NULL,
84                 .health = 1,
85                 .max_health = 1,
86                 .collide_with_entities = true,
87
88                 .on_step = &fireball_step,
89                 .on_collide = &fireball_collide,
90                 .on_collide_with_entity = &fireball_collide_with_entity,
91                 .on_spawn = &fireball_spawn,
92                 .on_remove = NULL,
93                 .on_death = NULL,
94                 .on_damage = NULL,
95         };
96
97         register_input_handler(' ', (struct input_handler) {
98                 .run_if_dead = false,
99                 .callback = &shoot_fireball,
100         });
101 }