home · contact · privacy
Fix buggy healthy_addch().
[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             c_pointer_to_string
28     from server.config.world_data import symbols_passable
29     tt = world_db["ThingTypes"][t["T_TYPE"]]
30
31     def zero_score_map_where_char_on_memdepthmap(c):
32         # OUTSOURCED FOR PERFORMANCE REASONS TO libplomrogue.so:
33         # for i in [i for i in range(world_db["MAP_LENGTH"] ** 2)
34         #           if t["T_MEMDEPTHMAP"][i] == mem_depth_c[0]]:
35         #     set_map_score(i, 0)
36         map = c_pointer_to_bytearray(t["T_MEMDEPTHMAP"])
37         if libpr.zero_score_map_where_char_on_memdepthmap(c, map):
38             raise RuntimeError("No score map allocated for "
39                                "zero_score_map_where_char_on_memdepthmap().")
40
41     def set_map_score(pos, score):
42         test = libpr.set_map_score(pos, score)
43         if test:
44             raise RuntimeError("No score map allocated for set_map_score().")
45
46     def get_map_score(pos):
47         result = libpr.get_map_score(pos)
48         if result < 0:
49             raise RuntimeError("No score map allocated for get_map_score().")
50         return result
51
52     def animates_in_fov(maplength):
53         return [Thing for Thing in world_db["Things"].values()
54                 if Thing["T_LIFEPOINTS"] and not Thing["carried"]
55                 and 118 == t["fovmap"][Thing["pos"]] and not Thing == t]
56
57     def good_attack_target(v):
58         eat_cost = tt["eat_vs_hunger_threshold"]
59         ty = world_db["ThingTypes"][v["T_TYPE"]]
60         type_corpse = world_db["ThingTypes"][ty["TT_CORPSE_ID"]]
61         if t["T_LIFEPOINTS"] > ty["TT_LIFEPOINTS"] \
62         and type_corpse["TT_TOOL"] == "food" \
63         and type_corpse["TT_TOOLPOWER"] > eat_cost:
64             return True
65         return False
66
67     def good_flee_target(m):
68         corpse_type = world_db["ThingTypes"][tt["TT_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         scoremap = c_pointer_to_bytearray(t["T_MEMMAP"])
109         passable_string = c_pointer_to_string(symbols_passable)
110         if libpr.set_cells_passable_on_memmap_to_65534_on_scoremap(scoremap,
111                     passable_string):
112             raise RuntimeError("No score map allocated for set_cells_passable"
113                                "_on_memmap_to_65534_on_scoremap().")
114
115     def init_score_map():
116         test = libpr.init_score_map()
117         if test:
118             raise RuntimeError("Malloc error in init_score_map().")
119         ord_v = ord("v")
120         ord_blank = ord(" ")
121         set_cells_passable_on_memmap_to_65534_on_scoremap()
122         maplen = world_db["MAP_LENGTH"]
123         if "a" == filter:
124             [set_map_score(Thing["pos"], 0) for
125              Thing in animates_in_fov(maplen) if good_attack_target(Thing)]
126         elif "f" == filter:
127             [set_map_score(Thing["pos"], 0) for
128              Thing in animates_in_fov(maplen) if good_flee_target(Thing)]
129         elif "c" == filter:
130             eat_cost = tt["eat_vs_hunger_threshold"]
131             ord_blank = ord(" ")
132             [set_map_score(mt[1] * maplen + mt[2], 0)
133              for mt in t["T_MEMTHING"]
134              if ord_blank != t["T_MEMMAP"][mt[1] * maplen + mt[2]]
135              if world_db["ThingTypes"][mt[0]]["TT_TOOL"] == "food"
136              if world_db["ThingTypes"][mt[0]]["TT_TOOLPOWER"] > eat_cost]
137         elif "s" == filter:
138             zero_score_map_where_char_on_memdepthmap(mem_depth_c[0])
139         if "f" == filter:
140             [set_map_score(Thing["pos"], 65535)
141              for Thing in animates_in_fov(maplen)
142              if get_map_score(Thing["pos"])]
143         elif "a" != filter:
144             [set_map_score(Thing["pos"], 65535)
145              for Thing in animates_in_fov(maplen)]
146
147     def rand_target_dir(neighbors, cmp, dirs):
148         candidates = []
149         n_candidates = 0
150         for i in range(len(dirs)):
151             if cmp == neighbors[i]:
152                 candidates.append(dirs[i])
153                 n_candidates += 1
154         return candidates[rand.next() % n_candidates] if n_candidates else 0
155
156     def get_neighbor_scores(dirs, eye_pos):
157         scores = []
158         if libpr.ready_neighbor_scores(eye_pos):
159             raise RuntimeError("No score map allocated for " +
160                                "ready_neighbor_scores.()")
161         for i in range(len(dirs)):
162             scores.append(libpr.get_neighbor_score(i))
163         return scores
164
165     def get_dir_from_neighbors():
166         import math
167         dir_to_target = False
168         dirs = "edcxsw"
169         eye_pos = t["pos"]
170         neighbors = get_neighbor_scores(dirs, eye_pos)
171         minmax_start = 0 if "f" == filter else 65535 - 1
172         minmax_neighbor = minmax_start
173         for i in range(len(dirs)):
174             if ("f" == filter and get_map_score(eye_pos) < neighbors[i] and
175                 minmax_neighbor < neighbors[i] and 65535 != neighbors[i]) \
176                or ("f" != filter and minmax_neighbor > neighbors[i]):
177                 minmax_neighbor = neighbors[i]
178         if minmax_neighbor != minmax_start:
179             dir_to_target = rand_target_dir(neighbors, minmax_neighbor, dirs)
180         if "f" == filter:
181             distance = get_map_score(eye_pos)
182             fear_distance = world_db["MAP_LENGTH"]
183             if t["T_SATIATION"] < 0 and math.sqrt(-t["T_SATIATION"]) > 0:
184                 fear_distance = fear_distance / math.sqrt(-t["T_SATIATION"])
185             attack_distance = 1
186             if not dir_to_target:
187                 if attack_distance >= distance:
188                     dir_to_target = rand_target_dir(neighbors,
189                                                     distance - 1, dirs)
190                 elif fear_distance >= distance:
191                     t["T_COMMAND"] = [id for id in world_db["ThingActions"]
192                                       if
193                                       world_db["ThingActions"][id]["TA_NAME"]
194                                       == "wait"][0]
195                     return 1
196             elif dir_to_target and fear_distance < distance:
197                 dir_to_target = 0
198         return dir_to_target
199
200     dir_to_target = False
201     mem_depth_c = b' '
202     run_i = 9 + 1 if "s" == filter else 1
203     while run_i and not dir_to_target and ("s" == filter or seeing_thing()):
204         run_i -= 1
205         init_score_map()
206         mem_depth_c = b'9' if b' ' == mem_depth_c \
207             else bytes([mem_depth_c[0] - 1])
208         if libpr.dijkstra_map():
209             raise RuntimeError("No score map allocated for dijkstra_map().")
210         dir_to_target = get_dir_from_neighbors()
211         libpr.free_score_map()
212         if dir_to_target and str == type(dir_to_target):
213             t["T_COMMAND"] = [id for id in world_db["ThingActions"]
214                               if world_db["ThingActions"][id]["TA_NAME"]
215                               == "move"][0]
216             t["T_ARGUMENT"] = ord(dir_to_target)
217     return dir_to_target
218
219
220 def standing_on_food(t):
221     """Return True/False whether t is standing on healthy consumable."""
222     tt = world_db["ThingTypes"][t["T_TYPE"]]
223     eat_cost = tt["eat_vs_hunger_threshold"]
224     for id in [id for id in world_db["Things"] if world_db["Things"][id] != t
225                if not world_db["Things"][id]["carried"]
226                if world_db["Things"][id]["pos"] == t["pos"]
227                if world_db["ThingTypes"][world_db["Things"][id]["T_TYPE"]]
228                   ["TT_TOOL"] == "food"
229                if world_db["ThingTypes"][world_db["Things"][id]["T_TYPE"]]
230                   ["TT_TOOLPOWER"] > eat_cost]:
231         return True
232     return False
233
234
235 def get_inventory_slot_to_consume(t):
236     """Return invent. slot of healthiest consumable(if any healthy),else -1."""
237     cmp_food = -1
238     selection = -1
239     i = 0
240     tt = world_db["ThingTypes"][t["T_TYPE"]]
241     eat_cost = tt["eat_vs_hunger_threshold"]
242     for id in t["T_CARRIES"]:
243         type = world_db["Things"][id]["T_TYPE"]
244         if world_db["ThingTypes"][type]["TT_TOOL"] == "food" \
245            and world_db["ThingTypes"][type]["TT_TOOLPOWER"]:
246             nutvalue = world_db["ThingTypes"][type]["TT_TOOLPOWER"]
247             tmp_cmp = abs(t["T_SATIATION"] + nutvalue - eat_cost)
248             if (cmp_food < 0 and tmp_cmp < abs(t["T_SATIATION"])) \
249             or tmp_cmp < cmp_food:
250                 cmp_food = tmp_cmp
251                 selection = i
252         i += 1
253     return selection
254
255
256 def ai(t):
257     """Determine next command/argment for actor t via AI algorithms."""
258     t["T_COMMAND"] = [id for id in world_db["ThingActions"]
259                       if world_db["ThingActions"][id]["TA_NAME"] == "wait"][0]
260     eating = len([id for id in world_db["ThingActions"]
261                   if world_db["ThingActions"][id]["TA_NAME"] == "use"]) > 0
262     picking = len([id for id in world_db["ThingActions"]
263                    if world_db["ThingActions"][id]["TA_NAME"] == "pickup"]) > 0
264     if eating and picking:
265         if get_dir_to_target(t, "f"):
266             return
267         sel = get_inventory_slot_to_consume(t)
268         from server.config.ai import ai_hook_pickup_test
269         if -1 != sel:
270             t["T_COMMAND"] = [id for id in world_db["ThingActions"]
271                               if world_db["ThingActions"][id]["TA_NAME"]
272                                  == "use"][0]
273             t["T_ARGUMENT"] = sel
274         elif standing_on_food(t) and ai_hook_pickup_test(t):
275                 t["T_COMMAND"] = [id for id in world_db["ThingActions"]
276                                   if world_db["ThingActions"][id]["TA_NAME"]
277                                   == "pickup"][0]
278         else:
279             going_to_known_food_spot = get_dir_to_target(t, "c")
280             if not going_to_known_food_spot:
281                 aiming_for_walking_food = get_dir_to_target(t, "a")
282                 if not aiming_for_walking_food:
283                     get_dir_to_target(t, "s")