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