home · contact · privacy
1a296ce18ffc7038bed075d77da719be39d817ef
[plomrogue] / src / server / ai.c
1 /* src/server/ai.c
2  *
3  * This file is part of PlomRogue. PlomRogue is licensed under the GPL version 3
4  * or any later version. For details on its copyright, license, and warranties,
5  * see the file NOTICE in the root directory of the PlomRogue source package.
6  */
7
8 #include "ai.h"
9 #include <stdint.h> /* uint8_t, uint16_t, uint32_t, int16_t, UINT16_MAX */
10 #include <stdlib.h> /* free() */
11 #include "../common/try_malloc.h" /* try_malloc() */
12 #include "hardcoded_strings.h" /* s */
13 #include "rrand.h" /* rrand() */
14 #include "thing_actions.h" /* get_thing_action_id_by_name() */
15 #include "things.h" /* Thing, ThingType, ThingInMemory, get_thing_type() */
16 #include "world.h" /* world */
17
18 #define N_DIRS 6
19
20
21
22 /* Return "score_map"["pos"] unless "check_inhabitant" and cell is inhabited. */
23 static uint16_t set_neighbor_val(uint16_t * score_map, uint8_t check_inhabitant,
24                                  uint16_t kill_score, uint16_t pos);
25
26 /* Write into "neighbors" scores of the N_DIRS immediate neighbors of the
27  * "score_map" cell at "pos_i" (array index), as found in the directions
28  * north-east, east, south-east etc. (clockwise order). Use "kill_score" for
29  * illegal neighborhoods (i.e. if direction would lead beyond the map's border,
30  * or, if "check_inhabitants" is non-zero, into animate-inhabited cell).
31  */
32 static void get_neighbor_scores(uint16_t * score_map, uint16_t pos_i,
33                                 uint16_t kill_score, uint16_t * neighbors,
34                                 uint8_t check_inhabitants);
35
36 /* Iterate over scored cells in "score_map" of world.map's geometry. Compare
37  * each cell's score against the score of its immediate neighbors in N_DIRS
38  * directions. If any neighbor's score is at least two points lower than the
39  * current cell's score, re-set it to 1 point higher than its lowest-scored
40  * neighbor. Repeat this whole process until all cells have settled on their
41  * final score. Ignore cells whose score is greater than "max_score". Expect
42  * "max_score" to be the maximum score for cells, marking them as unreachable.
43  */
44 static void dijkstra_map(uint16_t * score_map, uint16_t max_score);
45
46 /* Helpers to init_score_map(), realizing individual filters. */
47 static uint8_t score_map_filter_attack(uint8_t filter, uint16_t * score_map,
48                                        struct Thing * t_eye);
49 static uint8_t score_map_filter_flee(uint8_t filter, uint16_t * score_map,
50                                      struct Thing * t_eye);
51 static uint8_t score_map_filter_consume(uint8_t filter, uint16_t * score_map,
52                                         struct Thing * t_eye);
53 static uint8_t score_map_filter_search(uint8_t filter, uint16_t * score_map,
54                                        struct Thing * t_eye);
55
56 /* get_dir_to_nearest_target() helper: Prepare "score_map" for dijkstra_map(). */
57 static void init_score_map(char filter, uint16_t * score_map, uint32_t map_size,
58                            struct Thing * t_eye);
59
60 /* From "targets" select random "cmp" match as directory by order in "dirs". */
61 static char rand_target_dir(char * dirs, uint16_t cmp, uint16_t * targets);
62
63 /* Helper to get_dir_to_nearest_target(). */
64 static char get_dir_from_neighbors(char filter, struct Thing * t_eye,
65                                    uint16_t * score_map);
66
67 /* Set (if possible) as "t_eye"'s command a move to the path to the path-wise
68  * nearest target that is not "t_eye" and fits criteria set by "filter". On
69  * success, return !0, else 0. Values for "filter":
70  * "a": thing in FOV is below a certain distance, animate, but of a type that is
71  *      not "t_eye"'s, and starts out weaker than it is; build path as avoiding
72  *      things of "t_eye"'s type
73  * "f": neighbor cell (not inhabited by any animate thing) further away from
74  *      animate thing not further than x steps away and in FOV and of a type
75  *      that is not "t_eye"'s, and starts out stronger or as strong as "t_eye"
76  *      is currently; or (cornered), if no such flight cell, but thing of above
77  *      criteria is too near, a cell closer to it, or, if less near, just wait
78  * "c": thing in memorized map is consumable
79  * "s": memory map cell with greatest-reachable degree of unexploredness
80  */
81 static uint8_t get_dir_to_nearest_target(struct Thing * t_eye, char filter);
82
83 /* Return 1 if any thing not "t_eye" is known and fulfills some criteria defined
84  * by "filter", else 0. Values for "filter":
85  * "a" or "f": thing in FOV is animate, but of type that not that of "t_eye",
86  *             and starts out weaker ("a") / stronger ("f") than "t_eye" is
87  * "c"       : thing in memorized map is consumable
88  */
89 static uint8_t seeing_thing(struct Thing * t_eye, char filter);
90
91 /* Return slot ID of strongest consumable in "t_owner"'s inventory, else -1. */
92 static int16_t get_inventory_slot_to_consume(struct Thing * t_owner);
93
94 /* Return 1 if "t_standing" is standing on a consumable, else 0. */
95 static uint8_t standing_on_consumable(struct Thing * t_standing);
96
97
98
99 static uint16_t set_neighbor_val(uint16_t * score_map, uint8_t check_inhabitant,
100                                  uint16_t kill_score, uint16_t pos)
101 {
102     if (check_inhabitant)
103     {
104         struct Thing * t = world.things;
105         for (; t; t = t->next)
106         {
107             if (t->lifepoints && pos == t->pos.y * world.map.length + t->pos.x)
108             {
109                 return kill_score;
110             }
111         }
112     }
113     return score_map[pos];
114 }
115
116
117
118 static void get_neighbor_scores(uint16_t * score_map, uint16_t pos_i,
119                                 uint16_t kill_score, uint16_t * neighbors,
120                                 uint8_t check_inhabitants)
121 {
122     uint32_t map_size = world.map.length * world.map.length;
123     uint8_t open_north     = pos_i >= world.map.length;
124     uint8_t open_east      = pos_i + 1 % world.map.length;
125     uint8_t open_south     = pos_i + world.map.length < map_size;
126     uint8_t open_west      = pos_i % world.map.length;
127     uint8_t is_indented    = (pos_i / world.map.length) % 2;
128     uint8_t open_diag_west = is_indented || open_west;
129     uint8_t open_diag_east = !is_indented || open_east;
130     neighbors[0] = !(open_north && open_diag_east) ? kill_score :
131                    set_neighbor_val(score_map, check_inhabitants, kill_score,
132                                     pos_i - world.map.length + is_indented);
133     neighbors[1] = !(open_east) ? kill_score :
134                    set_neighbor_val(score_map, check_inhabitants, kill_score,
135                                     pos_i + 1);
136     neighbors[2] = !(open_south && open_diag_east) ? kill_score :
137                    set_neighbor_val(score_map, check_inhabitants, kill_score,
138                                     pos_i + world.map.length + is_indented);
139     neighbors[3] = !(open_south && open_diag_west) ? kill_score :
140                    set_neighbor_val(score_map, check_inhabitants, kill_score,
141                                     pos_i + world.map.length - !is_indented);
142     neighbors[4] = !(open_west) ? kill_score :
143                    set_neighbor_val(score_map, check_inhabitants, kill_score,
144                                     pos_i - 1);
145     neighbors[5] = !(open_north && open_diag_west) ? kill_score :
146                    set_neighbor_val(score_map, check_inhabitants, kill_score,
147                                     pos_i - world.map.length - !is_indented);
148 }
149
150
151
152 static void dijkstra_map(uint16_t * score_map, uint16_t max_score)
153 {
154     uint32_t map_size = world.map.length * world.map.length;
155     uint32_t pos;
156     uint16_t i_scans, neighbors[N_DIRS], min_neighbor;
157     uint8_t scores_still_changing = 1;
158     uint8_t i_dirs;
159     for (i_scans = 0; scores_still_changing; i_scans++)
160     {
161         scores_still_changing = 0;
162         for (pos = 0; pos < map_size; pos++)
163         {
164             if (score_map[pos] <= max_score)
165             {
166                 get_neighbor_scores(score_map, pos, max_score, neighbors, 0);
167                 min_neighbor = max_score;
168                 for (i_dirs = 0; i_dirs < N_DIRS; i_dirs++)
169                 {
170                     if (min_neighbor > neighbors[i_dirs])
171                     {
172                         min_neighbor = neighbors[i_dirs];
173                     }
174                 }
175                 if (score_map[pos] > min_neighbor + 1)
176                 {
177                     score_map[pos] = min_neighbor + 1;
178                     scores_still_changing = 1;
179                 }
180             }
181         }
182     }
183 }
184
185
186
187 static uint8_t score_map_filter_attack(uint8_t filter, uint16_t * score_map,
188                                        struct Thing * t_eye)
189 {
190     if ('a' != filter)
191     {
192         return 0;
193     }
194     struct Thing * t = world.things;
195     for (; t; t = t->next)
196     {
197         if (   t != t_eye && t->lifepoints && t->type != t_eye->type
198             && 'v' == t_eye->fov_map[t->pos.y*world.map.length + t->pos.x]
199             && get_thing_type(t->type)->lifepoints < t_eye->lifepoints)
200         {
201             score_map[t->pos.y * world.map.length + t->pos.x] = 0;
202         }
203         else if (t->type == t_eye->type)
204         {
205             score_map[t->pos.y * world.map.length + t->pos.x] = UINT16_MAX;
206         }
207     }
208     return 1;
209 }
210
211
212
213 static uint8_t score_map_filter_flee(uint8_t filter, uint16_t * score_map,
214                                      struct Thing * t_eye)
215 {
216     if ('f' != filter)
217     {
218         return 0;
219     }
220     struct Thing * t = world.things;
221     for (; t; t = t->next)
222     {
223         if (   t->lifepoints && t->type != t_eye->type
224             && 'v' == t_eye->fov_map[t->pos.y*world.map.length + t->pos.x]
225             && get_thing_type(t->type)->lifepoints >= t_eye->lifepoints)
226         {
227             score_map[t->pos.y * world.map.length + t->pos.x] = 0;
228         }
229     }
230     return 1;
231 }
232
233
234
235 static uint8_t score_map_filter_consume(uint8_t filter, uint16_t * score_map,
236                                         struct Thing * t_eye)
237 {
238     if ('c' != filter)
239     {
240         return 0;
241     }
242     struct ThingInMemory * tm = t_eye->t_mem;
243     for (; tm; tm = tm->next)
244     {
245         if (   ' ' != t_eye->mem_map[tm->pos.y * world.map.length + tm->pos.x]
246             && get_thing_type(tm->type)->consumable)
247         {
248             score_map[tm->pos.y * world.map.length + tm->pos.x] = 0;
249         }
250     }
251     return 1;
252 }
253
254
255
256 static uint8_t score_map_filter_search(uint8_t filter, uint16_t * score_map,
257                                        struct Thing * t_eye)
258 {
259     if (!(('0' < filter && '9' >= filter) || ' ' == filter))
260     {
261         return 0;
262     }
263     uint32_t i;
264     for (i = 0; i < (uint32_t) (world.map.length * world.map.length); i++)
265     {
266         score_map[i] = filter == t_eye->mem_depth_map[i] ? 0 : score_map[i];
267     }
268     return 1;
269 }
270
271
272
273 static void init_score_map(char filter, uint16_t * score_map, uint32_t map_size,
274                            struct Thing * t_eye)
275 {
276     uint32_t i;
277     for (i = 0; i < map_size; i++)
278     {
279         score_map[i] = UINT16_MAX;
280         if ('.' == t_eye->mem_map[i])
281         {
282             score_map[i] = UINT16_MAX-1;
283         }
284     }
285     if (   score_map_filter_attack(filter, score_map, t_eye)
286         || score_map_filter_flee(filter, score_map, t_eye)
287         || score_map_filter_consume(filter, score_map, t_eye)
288         || score_map_filter_search(filter, score_map, t_eye))
289     {
290     }
291 }
292
293
294 static char rand_target_dir(char * dirs, uint16_t cmp, uint16_t * targets)
295 {
296     char candidates[N_DIRS];
297     uint8_t n_candidates = 0;
298     uint8_t i;
299     for (i = 0; i < N_DIRS; i++)
300     {
301         if (cmp == targets[i])
302         {
303             candidates[n_candidates] = dirs[i];
304             n_candidates++;
305         }
306     }
307     return n_candidates ? candidates[rrand() % n_candidates] : 0;
308 }
309
310
311
312 static char get_dir_from_neighbors(char filter, struct Thing * t_eye,
313                                    uint16_t * score_map)
314 {
315     char dir_to_nearest_target = 0;
316     uint16_t pos_i = (t_eye->pos.y * world.map.length) + t_eye->pos.x;
317     char * dirs = "edcxsw";   /* get_neighbor_scores()'s clockwise dir order. */
318     uint16_t neighbors[N_DIRS];
319     get_neighbor_scores(score_map, pos_i, UINT16_MAX, neighbors, 'f'==filter);
320     uint16_t minmax_start = 'f' == filter ? 0 : UINT16_MAX-1;
321     uint16_t minmax_neighbor = minmax_start;
322     uint8_t i;
323     for (i = 0; i < N_DIRS; i++)
324     {
325         if (   (   'f' == filter && score_map[pos_i] < neighbors[i]
326                 && minmax_neighbor < neighbors[i] && UINT16_MAX != neighbors[i])
327             || ('f' != filter && minmax_neighbor > neighbors[i]))
328         {
329             minmax_neighbor = neighbors[i];
330         }
331     }
332     if (minmax_neighbor != minmax_start)
333     {
334         dir_to_nearest_target = rand_target_dir(dirs,minmax_neighbor,neighbors);
335     }
336     if ('f' == filter)
337     {
338         if (!dir_to_nearest_target)
339         {
340             if (1 == score_map[pos_i])     /* Attack if cornered too closely. */
341             {
342                 dir_to_nearest_target = rand_target_dir(dirs, 0, neighbors);
343             }
344             else if (3 >= score_map[pos_i])    /* If less closely, just wait. */
345             {
346                 t_eye->command = get_thing_action_id_by_name(s[S_CMD_WAIT]);
347                 return 1;
348             }
349         }
350         else if (dir_to_nearest_target && 3 < score_map[pos_i]) /* Don't flee */
351         {                                                       /* enemy of   */
352             dir_to_nearest_target = 0;                          /* a certain  */
353         }                                                       /* distance.  */
354     }
355     else if ('a' == filter && 10 <= score_map[pos_i])
356     {
357         dir_to_nearest_target = 0;
358     }
359     return dir_to_nearest_target;
360 }
361
362
363
364 static uint8_t get_dir_to_nearest_target(struct Thing * t_eye, char filter)
365 {
366     char dir_to_nearest_target = 0;
367     uint8_t mem_depth_char = ' ';
368     uint8_t run_i = 's' == filter ? 9 /* max explored mem depth age */ + 1 : 1;
369     while (    run_i && !dir_to_nearest_target
370            && ('s' == filter || seeing_thing(t_eye, filter)))
371     {
372         run_i--;
373         uint32_t map_size = world.map.length * world.map.length;
374         uint16_t * score_map = try_malloc(map_size * sizeof(uint16_t),__func__);
375         init_score_map('s' == filter ? mem_depth_char : filter,
376                        score_map, map_size, t_eye);
377         mem_depth_char = ' ' == mem_depth_char ? '9' : mem_depth_char - 1;
378         dijkstra_map(score_map, UINT16_MAX-1);
379         dir_to_nearest_target = get_dir_from_neighbors(filter,t_eye,score_map);
380         free(score_map);
381         if (dir_to_nearest_target)
382         {
383             t_eye->command = get_thing_action_id_by_name(s[S_CMD_MOVE]);
384             t_eye->arg = dir_to_nearest_target;
385         }
386     }
387     return dir_to_nearest_target;
388 }
389
390
391
392 static uint8_t seeing_thing(struct Thing * t_eye, char filter)
393 {
394     if (t_eye->fov_map && ('a' == filter || 'f' == filter))
395     {
396         struct Thing * t = world.things;
397         for (; t; t = t->next)
398         {
399             if (   t != t_eye && t->lifepoints && t->type != t_eye->type
400                 && 'v' == t_eye->fov_map[t->pos.y*world.map.length + t->pos.x])
401             {
402                 struct ThingType * tt = get_thing_type(t->type);
403                 if (   ('f' == filter && tt->lifepoints >= t_eye->lifepoints)
404                     || ('a' == filter && tt->lifepoints <  t_eye->lifepoints))
405                 {
406                     return 1;
407                 }
408             }
409         }
410     }
411     else if (t_eye->mem_map && 'c' == filter)
412     {
413         struct ThingInMemory * tm = t_eye->t_mem;
414         for (; tm; tm = tm->next)
415         {
416             if (     ' ' != t_eye->mem_map[tm->pos.y*world.map.length+tm->pos.x]
417                 && get_thing_type(tm->type)->consumable)
418             {
419                 return 1;
420             }
421         }
422     }
423     return 0;
424 }
425
426
427
428 static int16_t get_inventory_slot_to_consume(struct Thing * t_owner)
429 {
430     uint8_t compare_consumability = 0;
431     int16_t selection = -1;
432     struct Thing * t = t_owner->owns;;
433     uint8_t i;
434     for (i = 0; t; t = t->next, i++)
435     {
436         struct ThingType * tt = get_thing_type(t->type);
437         if (tt->consumable > compare_consumability)
438         {
439             compare_consumability = tt->consumable;
440             selection = i;
441         }
442     }
443     return selection;
444 }
445
446
447
448 static uint8_t standing_on_consumable(struct Thing * t_standing)
449 {
450     struct Thing * t = world.things;
451     for (; t; t = t->next)
452     {
453         if (   t != t_standing
454             && t->pos.y == t_standing->pos.y && t->pos.x == t_standing->pos.x
455             && get_thing_type(t->type)->consumable)
456         {
457             return 1;
458         }
459     }
460     return 0;
461 }
462
463
464
465 extern void ai(struct Thing * t)
466 {
467     t->command = get_thing_action_id_by_name(s[S_CMD_WAIT]);
468     if (!get_dir_to_nearest_target(t, 'f'))
469     {
470         int16_t sel = get_inventory_slot_to_consume(t);
471         if (-1 != sel)
472         {
473             t->command = get_thing_action_id_by_name(s[S_CMD_USE]);
474             t->arg = (uint8_t) sel;
475         }
476         else if (standing_on_consumable(t))
477         {
478             t->command = get_thing_action_id_by_name(s[S_CMD_PICKUP]);
479         }
480         else if (   !get_dir_to_nearest_target(t, 'c')
481                  && !get_dir_to_nearest_target(t, 'a'))
482         {
483             get_dir_to_nearest_target(t, 's');
484         }
485     }
486 }