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