home · contact · privacy
Server/AI: From directions of equal attractiveness, choose randomly.
[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 animate, but of a type that is not "t_eye"'s, and
71  *      starts out weaker than it is; build path as avoiding things of "t_eye"'s
72  *      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 in neighbor cell, that cell
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 && 1 == score_map[pos_i])
339         {
340             dir_to_nearest_target = rand_target_dir(dirs, 0, neighbors);
341         }
342         else if (dir_to_nearest_target && minmax_neighbor > 3)
343         {
344             dir_to_nearest_target = 0;
345         }
346     }
347     return dir_to_nearest_target;
348 }
349
350
351
352 static uint8_t get_dir_to_nearest_target(struct Thing * t_eye, char filter)
353 {
354     char dir_to_nearest_target = 0;
355     uint8_t mem_depth_char = ' ';
356     uint8_t run_i = 's' == filter ? 9 /* max explored mem depth age */ + 1 : 1;
357     while (    run_i && !dir_to_nearest_target
358            && ('s' == filter || seeing_thing(t_eye, filter)))
359     {
360         run_i--;
361         uint32_t map_size = world.map.length * world.map.length;
362         uint16_t * score_map = try_malloc(map_size * sizeof(uint16_t),__func__);
363         init_score_map('s' == filter ? mem_depth_char : filter,
364                        score_map, map_size, t_eye);
365         mem_depth_char = ' ' == mem_depth_char ? '9' : mem_depth_char - 1;
366         dijkstra_map(score_map, UINT16_MAX-1);
367         dir_to_nearest_target = get_dir_from_neighbors(filter,t_eye,score_map);
368         free(score_map);
369         if (dir_to_nearest_target)
370         {
371             t_eye->command = get_thing_action_id_by_name(s[S_CMD_MOVE]);
372             t_eye->arg = dir_to_nearest_target;
373         }
374     }
375     return dir_to_nearest_target;
376 }
377
378
379
380 static uint8_t seeing_thing(struct Thing * t_eye, char filter)
381 {
382     if (t_eye->fov_map && ('a' == filter || 'f' == filter))
383     {
384         struct Thing * t = world.things;
385         for (; t; t = t->next)
386         {
387             if (   t != t_eye && t->lifepoints && t->type != t_eye->type
388                 && 'v' == t_eye->fov_map[t->pos.y*world.map.length + t->pos.x])
389             {
390                 struct ThingType * tt = get_thing_type(t->type);
391                 if (   ('f' == filter && tt->lifepoints >= t_eye->lifepoints)
392                     || ('a' == filter && tt->lifepoints <  t_eye->lifepoints))
393                 {
394                     return 1;
395                 }
396             }
397         }
398     }
399     else if (t_eye->mem_map && 'c' == filter)
400     {
401         struct ThingInMemory * tm = t_eye->t_mem;
402         for (; tm; tm = tm->next)
403         {
404             if (     ' ' != t_eye->mem_map[tm->pos.y*world.map.length+tm->pos.x]
405                 && get_thing_type(tm->type)->consumable)
406             {
407                 return 1;
408             }
409         }
410     }
411     return 0;
412 }
413
414
415
416 static int16_t get_inventory_slot_to_consume(struct Thing * t_owner)
417 {
418     uint8_t compare_consumability = 0;
419     int16_t selection = -1;
420     struct Thing * t = t_owner->owns;;
421     uint8_t i;
422     for (i = 0; t; t = t->next, i++)
423     {
424         struct ThingType * tt = get_thing_type(t->type);
425         if (tt->consumable > compare_consumability)
426         {
427             compare_consumability = tt->consumable;
428             selection = i;
429         }
430     }
431     return selection;
432 }
433
434
435
436 static uint8_t standing_on_consumable(struct Thing * t_standing)
437 {
438     struct Thing * t = world.things;
439     for (; t; t = t->next)
440     {
441         if (   t != t_standing
442             && t->pos.y == t_standing->pos.y && t->pos.x == t_standing->pos.x
443             && get_thing_type(t->type)->consumable)
444         {
445             return 1;
446         }
447     }
448     return 0;
449 }
450
451
452
453 extern void ai(struct Thing * t)
454 {
455     t->command = get_thing_action_id_by_name(s[S_CMD_WAIT]);
456     if (!get_dir_to_nearest_target(t, 'f'))
457     {
458         int16_t sel = get_inventory_slot_to_consume(t);
459         if (-1 != sel)
460         {
461             t->command = get_thing_action_id_by_name(s[S_CMD_USE]);
462             t->arg = (uint8_t) sel;
463         }
464         else if (standing_on_consumable(t))
465         {
466             t->command = get_thing_action_id_by_name(s[S_CMD_PICKUP]);
467         }
468         else if (   !get_dir_to_nearest_target(t, 'c')
469                  && !get_dir_to_nearest_target(t, 'a'))
470         {
471             get_dir_to_nearest_target(t, 's');
472         }
473     }
474 }