home · contact · privacy
db40625659d00878ef866e467d6973c09ee563e7
[plomrogue] / server / ai.py
1 # This file is part of PlomRogue. PlomRogue is licensed under the GPL version 3
2 # or any later version. For details on its copyright, license, and warranties,
3 # see the file NOTICE in the root directory of the PlomRogue source package.
4
5
6 from server.config.world_data import world_db
7
8
9 def get_dir_to_target(t, filter):
10     """Try to set T_COMMAND/T_ARGUMENT for move to "filter"-determined target.
11
12     The path-wise nearest target is chosen, via the shortest available path.
13     Target must not be t. On succcess, return positive value, else False.
14     Filters:
15     "a": Thing in FOV is animate, but of ThingType, starts out weaker than t
16          is, and its corpse would be healthy food for t
17     "f": move away from an enemy – any visible actor whose thing type has more
18          TT_LIFEPOINTS than t LIFEPOINTS, and might find t's corpse healthy
19          food – if it is closer than n steps, where n will shrink as t's hunger
20          grows; if enemy is too close, move towards (attack) the enemy instead;
21          if no fleeing is possible, nor attacking useful, wait; don't tread on
22          non-enemies for fleeing
23     "c": Thing in memorized map is consumable of sufficient nutrition for t
24     "s": memory map cell with greatest-reachable degree of unexploredness
25     """
26     from server.utils import rand, libpr, c_pointer_to_bytearray
27     from server.config.world_data import symbols_passable
28     tt = world_db["ThingTypes"][t["T_TYPE"]]
29
30     def zero_score_map_where_char_on_memdepthmap(c):
31         # OUTSOURCED FOR PERFORMANCE REASONS TO libplomrogue.so:
32         # for i in [i for i in range(world_db["MAP_LENGTH"] ** 2)
33         #           if t["T_MEMDEPTHMAP"][i] == mem_depth_c[0]]:
34         #     set_map_score(i, 0)
35         map = c_pointer_to_bytearray(t["T_MEMDEPTHMAP"])
36         if libpr.zero_score_map_where_char_on_memdepthmap(c, map):
37             raise RuntimeError("No score map allocated for "
38                                "zero_score_map_where_char_on_memdepthmap().")
39
40     def set_map_score(pos, score):
41         test = libpr.set_map_score(pos, score)
42         if test:
43             raise RuntimeError("No score map allocated for set_map_score().")
44
45     def get_map_score(pos):
46         result = libpr.get_map_score(pos)
47         if result < 0:
48             raise RuntimeError("No score map allocated for get_map_score().")
49         return result
50
51     def animates_in_fov(maplength):
52         return [Thing for Thing in world_db["Things"].values()
53                 if Thing["T_LIFEPOINTS"] and not Thing["carried"]
54                 and 118 == t["fovmap"][Thing["pos"]] and not Thing == t]
55
56     def good_attack_target(v):
57         eat_cost = tt["eat_vs_hunger_threshold"]
58         ty = world_db["ThingTypes"][v["T_TYPE"]]
59         type_corpse = world_db["ThingTypes"][ty["TT_CORPSE_ID"]]
60         if t["T_LIFEPOINTS"] > ty["TT_LIFEPOINTS"] \
61         and type_corpse["TT_TOOL"] == "food" \
62         and type_corpse["TT_TOOLPOWER"] > eat_cost:
63             return True
64         return False
65
66     def good_flee_target(m):
67         own_corpse_id = world_db["ThingTypes"][t["T_TYPE"]]["TT_CORPSE_ID"]
68         corpse_type = world_db["ThingTypes"][own_corpse_id]
69         targetness = 0 if corpse_type["TT_TOOL"] != "food" \
70                        else corpse_type["TT_TOOLPOWER"]
71         type = world_db["ThingTypes"][m["T_TYPE"]]
72         if t["T_LIFEPOINTS"] < type["TT_LIFEPOINTS"] \
73             and targetness > type["eat_vs_hunger_threshold"]:
74             return True
75         return False
76
77     def seeing_thing():
78         def exists(gen):
79             try:
80                 next(gen)
81             except StopIteration:
82                 return False
83             return True
84         maplength = world_db["MAP_LENGTH"]
85         if t["fovmap"] and "a" == filter:
86             return exists(Thing for Thing in animates_in_fov(maplength)
87                                 if good_attack_target(Thing))
88         elif t["fovmap"] and "f" == filter:
89             return exists(Thing for Thing in animates_in_fov(maplength)
90                                 if good_flee_target(Thing))
91         elif t["T_MEMMAP"] and "c" == filter:
92             eat_cost = tt["eat_vs_hunger_threshold"]
93             ord_blank = ord(" ")
94             map_len = world_db["MAP_LENGTH"]
95             return exists(mt for mt in t["T_MEMTHING"]
96                           if ord_blank != t["T_MEMMAP"][mt[1] * map_len + mt[2]]
97                           and world_db["ThingTypes"][mt[0]]["TT_TOOL"] == "food"
98                           and world_db["ThingTypes"][mt[0]]["TT_TOOLPOWER"]
99                              > eat_cost)
100         return False
101
102     def set_cells_passable_on_memmap_to_65534_on_scoremap():
103         # OUTSOURCED FOR PERFORMANCE REASONS TO libplomrogue.so:
104         # memmap = t["T_MEMMAP"]
105         # for i in [i for i in range(world_db["MAP_LENGTH"] ** 2)
106         #            if memmap[i] in symbols_passable]:
107         #     set_map_score(i, 65534) # i.e. 65535-1
108         map = c_pointer_to_bytearray(t["T_MEMMAP"])
109         if libpr.set_cells_passable_on_memmap_to_65534_on_scoremap(map,
110                     symbols_passable):
111             raise RuntimeError("No score map allocated for set_cells_passable"
112                                "_on_memmap_to_65534_on_scoremap().")
113
114     def init_score_map():
115         test = libpr.init_score_map()
116         if test:
117             raise RuntimeError("Malloc error in init_score_map().")
118         ord_v = ord("v")
119         ord_blank = ord(" ")
120         set_cells_passable_on_memmap_to_65534_on_scoremap()
121         maplen = world_db["MAP_LENGTH"]
122         if "a" == filter:
123             [set_map_score(Thing["pos"], 0) for
124              Thing in animates_in_fov(maplen) if good_attack_target(Thing)]
125         elif "f" == filter:
126             [set_map_score(Thing["pos"], 0) for
127              Thing in animates_in_fov(maplen) if good_flee_target(Thing)]
128         elif "c" == filter:
129             eat_cost = tt["eat_vs_hunger_threshold"]
130             ord_blank = ord(" ")
131             [set_map_score(mt[1] * maplen + mt[2], 0)
132              for mt in t["T_MEMTHING"]
133              if ord_blank != t["T_MEMMAP"][mt[1] * maplen + mt[2]]
134              if world_db["ThingTypes"][mt[0]]["TT_TOOL"] == "food"
135              if world_db["ThingTypes"][mt[0]]["TT_TOOLPOWER"] > eat_cost]
136         elif "s" == filter:
137             zero_score_map_where_char_on_memdepthmap(mem_depth_c[0])
138         if "f" == filter:
139             [set_map_score(Thing["pos"], 65535)
140              for Thing in animates_in_fov(maplen)
141              if get_map_score(Thing["pos"])]
142         elif "a" != filter:
143             [set_map_score(Thing["pos"], 65535)
144              for Thing in animates_in_fov(maplen)]
145
146     def rand_target_dir(neighbors, cmp, dirs):
147         candidates = []
148         n_candidates = 0
149         for i in range(len(dirs)):
150             if cmp == neighbors[i]:
151                 candidates.append(dirs[i])
152                 n_candidates += 1
153         return candidates[rand.next() % n_candidates] if n_candidates else 0
154
155     def get_neighbor_scores(dirs, eye_pos):
156         scores = []
157         if libpr.ready_neighbor_scores(eye_pos):
158             raise RuntimeError("No score map allocated for " +
159                                "ready_neighbor_scores.()")
160         for i in range(len(dirs)):
161             scores.append(libpr.get_neighbor_score(i))
162         return scores
163
164     def get_dir_from_neighbors():
165         import math
166         dir_to_target = False
167         dirs = "edcxsw"
168         eye_pos = t["pos"]
169         neighbors = get_neighbor_scores(dirs, eye_pos)
170         minmax_start = 0 if "f" == filter else 65535 - 1
171         minmax_neighbor = minmax_start
172         for i in range(len(dirs)):
173             if ("f" == filter and get_map_score(eye_pos) < neighbors[i] and
174                 minmax_neighbor < neighbors[i] and 65535 != neighbors[i]) \
175                or ("f" != filter and minmax_neighbor > neighbors[i]):
176                 minmax_neighbor = neighbors[i]
177         if minmax_neighbor != minmax_start:
178             dir_to_target = rand_target_dir(neighbors, minmax_neighbor, dirs)
179         if "f" == filter:
180             distance = get_map_score(eye_pos)
181             fear_distance = world_db["MAP_LENGTH"]
182             if t["T_SATIATION"] < 0 and math.sqrt(-t["T_SATIATION"]) > 0:
183                 fear_distance = fear_distance / math.sqrt(-t["T_SATIATION"])
184             attack_distance = 1
185             if not dir_to_target:
186                 if attack_distance >= distance:
187                     dir_to_target = rand_target_dir(neighbors,
188                                                     distance - 1, dirs)
189                 elif fear_distance >= distance:
190                     t["T_COMMAND"] = [id for id in world_db["ThingActions"]
191                                       if
192                                       world_db["ThingActions"][id]["TA_NAME"]
193                                       == "wait"][0]
194                     return 1
195             elif dir_to_target and fear_distance < distance:
196                 dir_to_target = 0
197         return dir_to_target
198
199     dir_to_target = False
200     mem_depth_c = b' '
201     run_i = 9 + 1 if "s" == filter else 1
202     while run_i and not dir_to_target and ("s" == filter or seeing_thing()):
203         run_i -= 1
204         init_score_map()
205         mem_depth_c = b'9' if b' ' == mem_depth_c \
206             else bytes([mem_depth_c[0] - 1])
207         if libpr.dijkstra_map():
208             raise RuntimeError("No score map allocated for dijkstra_map().")
209         dir_to_target = get_dir_from_neighbors()
210         libpr.free_score_map()
211         if dir_to_target and str == type(dir_to_target):
212             t["T_COMMAND"] = [id for id in world_db["ThingActions"]
213                               if world_db["ThingActions"][id]["TA_NAME"]
214                               == "move"][0]
215             t["T_ARGUMENT"] = ord(dir_to_target)
216     return dir_to_target
217
218
219 def standing_on_food(t):
220     """Return True/False whether t is standing on healthy consumable."""
221     tt = world_db["ThingTypes"][t["T_TYPE"]]
222     eat_cost = tt["eat_vs_hunger_threshold"]
223     for id in [id for id in world_db["Things"] if world_db["Things"][id] != t
224                if not world_db["Things"][id]["carried"]
225                if world_db["Things"][id]["pos"] == t["pos"]
226                if world_db["ThingTypes"][world_db["Things"][id]["T_TYPE"]]
227                   ["TT_TOOL"] == "food"
228                if world_db["ThingTypes"][world_db["Things"][id]["T_TYPE"]]
229                   ["TT_TOOLPOWER"] > eat_cost]:
230         return True
231     return False
232
233
234 def get_inventory_slot_to_consume(t):
235     """Return invent. slot of healthiest consumable(if any healthy),else -1."""
236     cmp_food = -1
237     selection = -1
238     i = 0
239     tt = world_db["ThingTypes"][t["T_TYPE"]]
240     eat_cost = tt["eat_vs_hunger_threshold"]
241     for id in t["T_CARRIES"]:
242         type = world_db["Things"][id]["T_TYPE"]
243         if world_db["ThingTypes"][type]["TT_TOOL"] == "food" \
244            and world_db["ThingTypes"][type]["TT_TOOLPOWER"]:
245             nutvalue = world_db["ThingTypes"][type]["TT_TOOLPOWER"]
246             tmp_cmp = abs(t["T_SATIATION"] + nutvalue - eat_cost)
247             if (cmp_food < 0 and tmp_cmp < abs(t["T_SATIATION"])) \
248             or tmp_cmp < cmp_food:
249                 cmp_food = tmp_cmp
250                 selection = i
251         i += 1
252     return selection
253
254
255 def ai(t):
256     """Determine next command/argment for actor t via AI algorithms."""
257     t["T_COMMAND"] = [id for id in world_db["ThingActions"]
258                       if world_db["ThingActions"][id]["TA_NAME"] == "wait"][0]
259     eating = len([id for id in world_db["ThingActions"]
260                   if world_db["ThingActions"][id]["TA_NAME"] == "use"]) > 0
261     picking = len([id for id in world_db["ThingActions"]
262                    if world_db["ThingActions"][id]["TA_NAME"] == "pickup"]) > 0
263     if eating and picking:
264         if get_dir_to_target(t, "f"):
265             return
266         sel = get_inventory_slot_to_consume(t)
267         from server.config.ai import ai_hook_pickup_test
268         if -1 != sel:
269             t["T_COMMAND"] = [id for id in world_db["ThingActions"]
270                               if world_db["ThingActions"][id]["TA_NAME"]
271                                  == "use"][0]
272             t["T_ARGUMENT"] = sel
273         elif standing_on_food(t) and ai_hook_pickup_test(t):
274                 t["T_COMMAND"] = [id for id in world_db["ThingActions"]
275                                   if world_db["ThingActions"][id]["TA_NAME"]
276                                   == "pickup"][0]
277         else:
278             going_to_known_food_spot = get_dir_to_target(t, "c")
279             if not going_to_known_food_spot:
280                 aiming_for_walking_food = get_dir_to_target(t, "a")
281                 if not aiming_for_walking_food:
282                     get_dir_to_target(t, "s")