comparison libmlk-adventure/adventure/action/spawner.c @ 272:a49ae1b6ea4f

adventure: don't use plural in directories
author David Demelier <markand@malikania.fr>
date Sat, 12 Dec 2020 12:16:47 +0100
parents libmlk-adventure/adventure/actions/spawner.c@bfde372bf152
children e28429dbdaaf
comparison
equal deleted inserted replaced
271:eadd3dbfa0af 272:a49ae1b6ea4f
1 /*
2 * spawner.c -- spawn battle while moving
3 *
4 * Copyright (c) 2020 David Demelier <markand@malikania.fr>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18
19 #include <assert.h>
20 #include <math.h>
21 #include <stdlib.h>
22
23 #include <core/alloc.h>
24 #include <core/game.h>
25 #include <core/util.h>
26
27 #include <rpg/map.h>
28
29 #include "spawner.h"
30
31 struct self {
32 struct action action;
33 struct map *map;
34 int last_x;
35 int last_y;
36 unsigned int steps;
37 };
38
39 static inline unsigned int
40 distance(const struct self *self)
41 {
42 unsigned int gap_x = fmax(self->last_x, self->map->player_x) -
43 fmin(self->last_x, self->map->player_x);
44 unsigned int gap_y = fmax(self->last_y, self->map->player_y) -
45 fmin(self->last_y, self->map->player_y);
46
47 return fmin(self->steps, gap_x + gap_y);
48 }
49
50 static bool
51 update(struct action *act, unsigned int ticks)
52 {
53 (void)ticks;
54
55 struct self *self = act->data;
56
57 if (self->map->player_movement) {
58 self->steps -= distance(self);
59 self->last_x = self->map->player_x;
60 self->last_y = self->map->player_y;
61
62 if (self->steps == 0) {
63 /* TODO: start battle here. */
64 return false;
65 }
66 }
67
68 return false;
69 }
70
71 static void
72 finish(struct action *act)
73 {
74 free(act->data);
75 }
76
77 struct action *
78 spawner_new(struct map *map, unsigned int low, unsigned int high)
79 {
80 assert(map);
81
82 struct self *self;
83
84 self = alloc_new0(sizeof (*self));
85 self->map = map;
86 self->last_x = map->player_x;
87 self->last_y = map->player_y;
88 self->steps = util_nrand(low, high);
89
90 self->action.data = self;
91 self->action.update = update;
92 self->action.finish = finish;
93
94 return &self->action;
95 }