home · contact · privacy
Server: Minor code simplification.
[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         corpse_type = world_db["ThingTypes"][tt["TT_CORPSE_ID"]]
68         targetness = 0 if corpse_type["TT_TOOL"] != "food" \
69                        else corpse_type["TT_TOOLPOWER"]
70         type = world_db["ThingTypes"][m["T_TYPE"]]
71         if t["T_LIFEPOINTS"] < type["TT_LIFEPOINTS"] \
72             and targetness > type["eat_vs_hunger_threshold"]:
73             return True
74         return False
75
76     def seeing_thing():
77         def exists(gen):
78             try:
79                 next(gen)
80             except StopIteration:
81                 return False
82             return True
83         maplength = world_db["MAP_LENGTH"]
84         if t["fovmap"] and "a" == filter:
85             return exists(Thing for Thing in animates_in_fov(maplength)
86                                 if good_attack_target(Thing))
87         elif t["fovmap"] and "f" == filter:
88             return exists(Thing for Thing in animates_in_fov(maplength)
89                                 if good_flee_target(Thing))
90         elif t["T_MEMMAP"] and "c" == filter:
91             eat_cost = tt["eat_vs_hunger_threshold"]
92             ord_blank = ord(" ")
93             map_len = world_db["MAP_LENGTH"]
94             return exists(mt for mt in t["T_MEMTHING"]
95                           if ord_blank != t["T_MEMMAP"][mt[1] * map_len + mt[2]]
96                           and world_db["ThingTypes"][mt[0]]["TT_TOOL"] == "food"
97                           and world_db["ThingTypes"][mt[0]]["TT_TOOLPOWER"]
98                              > eat_cost)
99         return False
100
101     def set_cells_passable_on_memmap_to_65534_on_scoremap():
102         # OUTSOURCED FOR PERFORMANCE REASONS TO libplomrogue.so:
103         # memmap = t["T_MEMMAP"]
104         # for i in [i for i in range(world_db["MAP_LENGTH"] ** 2)
105         #            if memmap[i] in symbols_passable]:
106         #     set_map_score(i, 65534) # i.e. 65535-1
107         map = c_pointer_to_bytearray(t["T_MEMMAP"])
108         if libpr.set_cells_passable_on_memmap_to_65534_on_scoremap(map,
109                     symbols_passable):
110             raise RuntimeError("No score map allocated for set_cells_passable"
111                                "_on_memmap_to_65534_on_scoremap().")
112
113     def init_score_map():
114         test = libpr.init_score_map()
115         if test:
116             raise RuntimeError("Malloc error in init_score_map().")
117         ord_v = ord("v")
118         ord_blank = ord(" ")
119         set_cells_passable_on_memmap_to_65534_on_scoremap()
120         maplen = world_db["MAP_LENGTH"]
121         if "a" == filter:
122             [set_map_score(Thing["pos"], 0) for
123              Thing in animates_in_fov(maplen) if good_attack_target(Thing)]
124         elif "f" == filter:
125             [set_map_score(Thing["pos"], 0) for
126              Thing in animates_in_fov(maplen) if good_flee_target(Thing)]
127         elif "c" == filter:
128             eat_cost = tt["eat_vs_hunger_threshold"]
129             ord_blank = ord(" ")
130             [set_map_score(mt[1] * maplen + mt[2], 0)
131              for mt in t["T_MEMTHING"]
132              if ord_blank != t["T_MEMMAP"][mt[1] * maplen + mt[2]]
133              if world_db["ThingTypes"][mt[0]]["TT_TOOL"] == "food"
134              if world_db["ThingTypes"][mt[0]]["TT_TOOLPOWER"] > eat_cost]
135         elif "s" == filter:
136             zero_score_map_where_char_on_memdepthmap(mem_depth_c[0])
137         if "f" == filter:
138             [set_map_score(Thing["pos"], 65535)
139              for Thing in animates_in_fov(maplen)
140              if get_map_score(Thing["pos"])]
141         elif "a" != filter:
142             [set_map_score(Thing["pos"], 65535)
143              for Thing in animates_in_fov(maplen)]
144
145     def rand_target_dir(neighbors, cmp, dirs):
146         candidates = []
147         n_candidates = 0
148         for i in range(len(dirs)):
149             if cmp == neighbors[i]:
150                 candidates.append(dirs[i])
151                 n_candidates += 1
152         return candidates[rand.next() % n_candidates] if n_candidates else 0
153
154     def get_neighbor_scores(dirs, eye_pos):
155         scores = []
156         if libpr.ready_neighbor_scores(eye_pos):
157             raise RuntimeError("No score map allocated for " +
158                                "ready_neighbor_scores.()")
159         for i in range(len(dirs)):
160             scores.append(libpr.get_neighbor_score(i))
161         return scores
162
163     def get_dir_from_neighbors():
164         import math
165         dir_to_target = False
166         dirs = "edcxsw"
167         eye_pos = t["pos"]
168         neighbors = get_neighbor_scores(dirs, eye_pos)
169         minmax_start = 0 if "f" == filter else 65535 - 1
170         minmax_neighbor = minmax_start
171         for i in range(len(dirs)):
172             if ("f" == filter and get_map_score(eye_pos) < neighbors[i] and
173                 minmax_neighbor < neighbors[i] and 65535 != neighbors[i]) \
174                or ("f" != filter and minmax_neighbor > neighbors[i]):
175                 minmax_neighbor = neighbors[i]
176         if minmax_neighbor != minmax_start:
177             dir_to_target = rand_target_dir(neighbors, minmax_neighbor, dirs)
178         if "f" == filter:
179             distance = get_map_score(eye_pos)
180             fear_distance = world_db["MAP_LENGTH"]
181             if t["T_SATIATION"] < 0 and math.sqrt(-t["T_SATIATION"]) > 0:
182                 fear_distance = fear_distance / math.sqrt(-t["T_SATIATION"])
183             attack_distance = 1
184             if not dir_to_target:
185                 if attack_distance >= distance:
186                     dir_to_target = rand_target_dir(neighbors,
187                                                     distance - 1, dirs)
188                 elif fear_distance >= distance:
189                     t["T_COMMAND"] = [id for id in world_db["ThingActions"]
190                                       if
191                                       world_db["ThingActions"][id]["TA_NAME"]
192                                       == "wait"][0]
193                     return 1
194             elif dir_to_target and fear_distance < distance:
195                 dir_to_target = 0
196         return dir_to_target
197
198     dir_to_target = False
199     mem_depth_c = b' '
200     run_i = 9 + 1 if "s" == filter else 1
201     while run_i and not dir_to_target and ("s" == filter or seeing_thing()):
202         run_i -= 1
203         init_score_map()
204         mem_depth_c = b'9' if b' ' == mem_depth_c \
205             else bytes([mem_depth_c[0] - 1])
206         if libpr.dijkstra_map():
207             raise RuntimeError("No score map allocated for dijkstra_map().")
208         dir_to_target = get_dir_from_neighbors()
209         libpr.free_score_map()
210         if dir_to_target and str == type(dir_to_target):
211             t["T_COMMAND"] = [id for id in world_db["ThingActions"]
212                               if world_db["ThingActions"][id]["TA_NAME"]
213                               == "move"][0]
214             t["T_ARGUMENT"] = ord(dir_to_target)
215     return dir_to_target
216
217
218 def standing_on_food(t):
219     """Return True/False whether t is standing on healthy consumable."""
220     tt = world_db["ThingTypes"][t["T_TYPE"]]
221     eat_cost = tt["eat_vs_hunger_threshold"]
222     for id in [id for id in world_db["Things"] if world_db["Things"][id] != t
223                if not world_db["Things"][id]["carried"]
224                if world_db["Things"][id]["pos"] == t["pos"]
225                if world_db["ThingTypes"][world_db["Things"][id]["T_TYPE"]]
226                   ["TT_TOOL"] == "food"
227                if world_db["ThingTypes"][world_db["Things"][id]["T_TYPE"]]
228                   ["TT_TOOLPOWER"] > eat_cost]:
229         return True
230     return False
231
232
233 def get_inventory_slot_to_consume(t):
234     """Return invent. slot of healthiest consumable(if any healthy),else -1."""
235     cmp_food = -1
236     selection = -1
237     i = 0
238     tt = world_db["ThingTypes"][t["T_TYPE"]]
239     eat_cost = tt["eat_vs_hunger_threshold"]
240     for id in t["T_CARRIES"]:
241         type = world_db["Things"][id]["T_TYPE"]
242         if world_db["ThingTypes"][type]["TT_TOOL"] == "food" \
243            and world_db["ThingTypes"][type]["TT_TOOLPOWER"]:
244             nutvalue = world_db["ThingTypes"][type]["TT_TOOLPOWER"]
245             tmp_cmp = abs(t["T_SATIATION"] + nutvalue - eat_cost)
246             if (cmp_food < 0 and tmp_cmp < abs(t["T_SATIATION"])) \
247             or tmp_cmp < cmp_food:
248                 cmp_food = tmp_cmp
249                 selection = i
250         i += 1
251     return selection
252
253
254 def ai(t):
255     """Determine next command/argment for actor t via AI algorithms."""
256     t["T_COMMAND"] = [id for id in world_db["ThingActions"]
257                       if world_db["ThingActions"][id]["TA_NAME"] == "wait"][0]
258     eating = len([id for id in world_db["ThingActions"]
259                   if world_db["ThingActions"][id]["TA_NAME"] == "use"]) > 0
260     picking = len([id for id in world_db["ThingActions"]
261                    if world_db["ThingActions"][id]["TA_NAME"] == "pickup"]) > 0
262     if eating and picking:
263         if get_dir_to_target(t, "f"):
264             return
265         sel = get_inventory_slot_to_consume(t)
266         from server.config.ai import ai_hook_pickup_test
267         if -1 != sel:
268             t["T_COMMAND"] = [id for id in world_db["ThingActions"]
269                               if world_db["ThingActions"][id]["TA_NAME"]
270                                  == "use"][0]
271             t["T_ARGUMENT"] = sel
272         elif standing_on_food(t) and ai_hook_pickup_test(t):
273                 t["T_COMMAND"] = [id for id in world_db["ThingActions"]
274                                   if world_db["ThingActions"][id]["TA_NAME"]
275                                   == "pickup"][0]
276         else:
277             going_to_known_food_spot = get_dir_to_target(t, "c")
278             if not going_to_known_food_spot:
279                 aiming_for_walking_food = get_dir_to_target(t, "a")
280                 if not aiming_for_walking_food:
281                     get_dir_to_target(t, "s")