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.
6 from server.config.world_data import world_db
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
18 def get_dir_to_target(t, filter):
19 """Try to set T_COMMAND/T_ARGUMENT for move to "filter"-determined target.
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.
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
35 from server.utils import rand, libpr, c_pointer_to_bytearray
36 from server.config.world_data import symbols_passable
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]]:
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().")
48 def set_map_score(pos, score):
49 test = libpr.set_map_score(pos, score)
51 raise RuntimeError("No score map allocated for set_map_score().")
53 def get_map_score(pos):
54 result = libpr.get_map_score(pos)
56 raise RuntimeError("No score map allocated for get_map_score().")
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 118 == t["fovmap"][Thing["pos"]] and not Thing == t]
64 def good_attack_target(v):
65 eat_cost = eat_vs_hunger_threshold(t["T_TYPE"])
66 ty = world_db["ThingTypes"][v["T_TYPE"]]
67 type_corpse = world_db["ThingTypes"][ty["TT_CORPSE_ID"]]
68 if t["T_LIFEPOINTS"] > ty["TT_LIFEPOINTS"] \
69 and type_corpse["TT_TOOL"] == "food" \
70 and type_corpse["TT_TOOLPOWER"] > eat_cost:
74 def good_flee_target(m):
75 own_corpse_id = world_db["ThingTypes"][t["T_TYPE"]]["TT_CORPSE_ID"]
76 corpse_type = world_db["ThingTypes"][own_corpse_id]
77 targetness = 0 if corpse_type["TT_TOOL"] != "food" \
78 else corpse_type["TT_TOOLPOWER"]
79 type = world_db["ThingTypes"][m["T_TYPE"]]
80 if t["T_LIFEPOINTS"] < type["TT_LIFEPOINTS"] \
81 and targetness > eat_vs_hunger_threshold(m["T_TYPE"]):
92 maplength = world_db["MAP_LENGTH"]
93 if t["fovmap"] and "a" == filter:
94 return exists(Thing for Thing in animates_in_fov(maplength)
95 if good_attack_target(Thing))
96 elif t["fovmap"] and "f" == filter:
97 return exists(Thing for Thing in animates_in_fov(maplength)
98 if good_flee_target(Thing))
99 elif t["T_MEMMAP"] and "c" == filter:
100 eat_cost = eat_vs_hunger_threshold(t["T_TYPE"])
102 map_len = world_db["MAP_LENGTH"]
103 return exists(mt for mt in t["T_MEMTHING"]
104 if ord_blank != t["T_MEMMAP"][mt[1] * map_len + mt[2]]
105 and world_db["ThingTypes"][mt[0]]["TT_TOOL"] == "food"
106 and world_db["ThingTypes"][mt[0]]["TT_TOOLPOWER"]
110 def set_cells_passable_on_memmap_to_65534_on_scoremap():
111 # OUTSOURCED FOR PERFORMANCE REASONS TO libplomrogue.so:
112 # memmap = t["T_MEMMAP"]
113 # for i in [i for i in range(world_db["MAP_LENGTH"] ** 2)
114 # if memmap[i] in symbols_passable]:
115 # set_map_score(i, 65534) # i.e. 65535-1
116 map = c_pointer_to_bytearray(t["T_MEMMAP"])
117 if libpr.set_cells_passable_on_memmap_to_65534_on_scoremap(map,
119 raise RuntimeError("No score map allocated for set_cells_passable"
120 "_on_memmap_to_65534_on_scoremap().")
122 def init_score_map():
123 test = libpr.init_score_map()
125 raise RuntimeError("Malloc error in init_score_map().")
128 set_cells_passable_on_memmap_to_65534_on_scoremap()
129 maplen = world_db["MAP_LENGTH"]
131 [set_map_score(Thing["pos"], 0) for
132 Thing in animates_in_fov(maplen) if good_attack_target(Thing)]
134 [set_map_score(Thing["pos"], 0) for
135 Thing in animates_in_fov(maplen) if good_flee_target(Thing)]
137 eat_cost = eat_vs_hunger_threshold(t["T_TYPE"])
139 [set_map_score(mt[1] * maplen + mt[2], 0)
140 for mt in t["T_MEMTHING"]
141 if ord_blank != t["T_MEMMAP"][mt[1] * maplen + mt[2]]
142 if world_db["ThingTypes"][mt[0]]["TT_TOOL"] == "food"
143 if world_db["ThingTypes"][mt[0]]["TT_TOOLPOWER"] > eat_cost]
145 zero_score_map_where_char_on_memdepthmap(mem_depth_c[0])
147 [set_map_score(Thing["pos"], 65535)
148 for Thing in animates_in_fov(maplen)
149 if get_map_score(Thing["pos"])]
151 [set_map_score(Thing["pos"], 65535)
152 for Thing in animates_in_fov(maplen)]
154 def rand_target_dir(neighbors, cmp, dirs):
157 for i in range(len(dirs)):
158 if cmp == neighbors[i]:
159 candidates.append(dirs[i])
161 return candidates[rand.next() % n_candidates] if n_candidates else 0
163 def get_neighbor_scores(dirs, eye_pos):
165 if libpr.ready_neighbor_scores(eye_pos):
166 raise RuntimeError("No score map allocated for " +
167 "ready_neighbor_scores.()")
168 for i in range(len(dirs)):
169 scores.append(libpr.get_neighbor_score(i))
172 def get_dir_from_neighbors():
174 dir_to_target = False
177 neighbors = get_neighbor_scores(dirs, eye_pos)
178 minmax_start = 0 if "f" == filter else 65535 - 1
179 minmax_neighbor = minmax_start
180 for i in range(len(dirs)):
181 if ("f" == filter and get_map_score(eye_pos) < neighbors[i] and
182 minmax_neighbor < neighbors[i] and 65535 != neighbors[i]) \
183 or ("f" != filter and minmax_neighbor > neighbors[i]):
184 minmax_neighbor = neighbors[i]
185 if minmax_neighbor != minmax_start:
186 dir_to_target = rand_target_dir(neighbors, minmax_neighbor, dirs)
188 distance = get_map_score(eye_pos)
189 fear_distance = world_db["MAP_LENGTH"]
190 if t["T_SATIATION"] < 0 and math.sqrt(-t["T_SATIATION"]) > 0:
191 fear_distance = fear_distance / math.sqrt(-t["T_SATIATION"])
193 if not dir_to_target:
194 if attack_distance >= distance:
195 dir_to_target = rand_target_dir(neighbors,
197 elif fear_distance >= distance:
198 t["T_COMMAND"] = [id for id in world_db["ThingActions"]
200 world_db["ThingActions"][id]["TA_NAME"]
203 elif dir_to_target and fear_distance < distance:
207 dir_to_target = False
209 run_i = 9 + 1 if "s" == filter else 1
210 while run_i and not dir_to_target and ("s" == filter or seeing_thing()):
213 mem_depth_c = b'9' if b' ' == mem_depth_c \
214 else bytes([mem_depth_c[0] - 1])
215 if libpr.dijkstra_map():
216 raise RuntimeError("No score map allocated for dijkstra_map().")
217 dir_to_target = get_dir_from_neighbors()
218 libpr.free_score_map()
219 if dir_to_target and str == type(dir_to_target):
220 t["T_COMMAND"] = [id for id in world_db["ThingActions"]
221 if world_db["ThingActions"][id]["TA_NAME"]
223 t["T_ARGUMENT"] = ord(dir_to_target)
227 def standing_on_food(t):
228 """Return True/False whether t is standing on healthy consumable."""
229 eat_cost = eat_vs_hunger_threshold(t["T_TYPE"])
230 for id in [id for id in world_db["Things"] if world_db["Things"][id] != t
231 if not world_db["Things"][id]["carried"]
232 if world_db["Things"][id]["pos"] == t["pos"]
233 if world_db["ThingTypes"][world_db["Things"][id]["T_TYPE"]]
234 ["TT_TOOL"] == "food"
235 if world_db["ThingTypes"][world_db["Things"][id]["T_TYPE"]]
236 ["TT_TOOLPOWER"] > eat_cost]:
241 def get_inventory_slot_to_consume(t):
242 """Return invent. slot of healthiest consumable(if any healthy),else -1."""
246 eat_cost = eat_vs_hunger_threshold(t["T_TYPE"])
247 for id in t["T_CARRIES"]:
248 type = world_db["Things"][id]["T_TYPE"]
249 if world_db["ThingTypes"][type]["TT_TOOL"] == "food" \
250 and world_db["ThingTypes"][type]["TT_TOOLPOWER"]:
251 nutvalue = world_db["ThingTypes"][type]["TT_TOOLPOWER"]
252 tmp_cmp = abs(t["T_SATIATION"] + nutvalue - eat_cost)
253 if (cmp_food < 0 and tmp_cmp < abs(t["T_SATIATION"])) \
254 or tmp_cmp < cmp_food:
262 """Determine next command/argment for actor t via AI algorithms."""
263 t["T_COMMAND"] = [id for id in world_db["ThingActions"]
264 if world_db["ThingActions"][id]["TA_NAME"] == "wait"][0]
265 eating = len([id for id in world_db["ThingActions"]
266 if world_db["ThingActions"][id]["TA_NAME"] == "use"]) > 0
267 picking = len([id for id in world_db["ThingActions"]
268 if world_db["ThingActions"][id]["TA_NAME"] == "pickup"]) > 0
269 if eating and picking:
270 if get_dir_to_target(t, "f"):
272 sel = get_inventory_slot_to_consume(t)
273 from server.config.ai import ai_hook_pickup_test
275 t["T_COMMAND"] = [id for id in world_db["ThingActions"]
276 if world_db["ThingActions"][id]["TA_NAME"]
278 t["T_ARGUMENT"] = sel
279 elif standing_on_food(t) and ai_hook_pickup_test(t):
280 t["T_COMMAND"] = [id for id in world_db["ThingActions"]
281 if world_db["ThingActions"][id]["TA_NAME"]
284 going_to_known_food_spot = get_dir_to_target(t, "c")
285 if not going_to_known_food_spot:
286 aiming_for_walking_food = get_dir_to_target(t, "a")
287 if not aiming_for_walking_food:
288 get_dir_to_target(t, "s")