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