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