home · contact · privacy
TCE: Add fleeing AI.
[plomrogue] / plugins / server / TheCrawlingEater.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 play_drink():
10     if action_exists("drink") and world_db["WORLD_ACTIVE"]:
11         pos = world_db["Things"][0]["pos"]
12         if not (chr(world_db["MAP"][pos]) == "0"
13                 and world_db["wetmap"][pos] > ord("0")):
14             log("NOTHING to drink here.")
15             return
16         elif world_db["Things"][0]["T_KIDNEY"] >= 32:
17             log("You're too FULL to drink more.")
18             return
19         world_db["set_command"]("drink")
20
21
22 def actor_drink(t):
23     pos = t["pos"]
24     if chr(world_db["MAP"][pos]) == "0" and \
25                 world_db["wetmap"][pos] > ord("0") and t["T_KIDNEY"] < 32:
26         if world_db["Things"][0] == t:
27             log("You DRINK.")
28         t["T_KIDNEY"] += 1
29         world_db["wetmap"][pos] -= 1
30         if world_db["wetmap"][pos] == ord("0"):
31             world_db["MAP"][pos] = ord("0")
32     elif t == world_db["Things"][0]:
33         log("YOU FAIL TO DRINK " + str(world_db["MAP"][pos] - ord("0")))
34
35
36 def play_pee():
37     if action_exists("pee") and world_db["WORLD_ACTIVE"]:
38         if world_db["Things"][0]["T_BLADDER"] < 1:
39             log("Nothing to drop from empty bladder.")
40             return
41         world_db["set_command"]("pee")
42
43
44 def actor_pee(t):
45     if t["T_BLADDER"] < 1:
46         return
47     if t == world_db["Things"][0]:
48         log("You LOSE fluid.")
49     if not world_db["test_air"](t):
50         return
51     t["T_BLADDER"] -= 1
52     world_db["wetmap"][t["pos"]] += 1
53
54
55 def play_drop():
56     if action_exists("drop") and world_db["WORLD_ACTIVE"]:
57         if world_db["Things"][0]["T_BOWEL"] < 1:
58             log("Nothing to drop from empty bowel.")
59             return
60         world_db["set_command"]("drop")
61
62
63 def actor_drop(t):
64     if t["T_BOWEL"] < 1:
65         return
66     if t == world_db["Things"][0]:
67         log("You DROP waste.")
68     if not world_db["test_air"](t):
69         return
70     world_db["MAP"][t["pos"]] += 1
71     t["T_BOWEL"] -= 1
72
73
74 def play_move(str_arg):
75     """Try "move" as player's T_COMMAND, str_arg as T_ARGUMENT / direction."""
76     if action_exists("move") and world_db["WORLD_ACTIVE"]:
77         from server.config.world_data import directions_db, symbols_passable
78         t = world_db["Things"][0]
79         if not str_arg in directions_db:
80             print("Illegal move direction string.")
81             return
82         d = ord(directions_db[str_arg])
83         from server.utils import mv_yx_in_dir_legal
84         move_result = mv_yx_in_dir_legal(chr(d), t["T_POSY"], t["T_POSX"])
85         if 1 == move_result[0]:
86             pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
87             hitted = [tid for tid in world_db["Things"]
88                       if world_db["Things"][tid]["T_POSY"] == move_result[1]
89                       if world_db["Things"][tid]["T_POSX"] == move_result[2]]
90             if len(hitted) > 0:
91                 if t["T_STOMACH"] >= 32 and t["T_KIDNEY"] >= 32:
92                     if t == world_db["Things"][0]:
93                         log("You're too FULL to suck from another creature.")
94                     return
95                 world_db["Things"][0]["T_ARGUMENT"] = d
96                 world_db["set_command"]("eat")
97                 return
98             if chr(world_db["MAP"][pos]) in "34":
99                 if t["T_STOMACH"] >= 32:
100                     if t == world_db["Things"][0]:
101                         log("You're too FULL to eat.")
102                     return
103                 world_db["Things"][0]["T_ARGUMENT"] = d
104                 world_db["set_command"]("eat")
105                 return
106             if chr(world_db["MAP"][pos]) in symbols_passable:
107                 world_db["Things"][0]["T_ARGUMENT"] = d
108                 world_db["set_command"]("move")
109                 return
110         log("You CAN'T eat your way through there.")
111
112
113 def actor_eat(t):
114     from server.utils import mv_yx_in_dir_legal, rand
115     from server.config.world_data import symbols_passable
116     passable = False
117     move_result = mv_yx_in_dir_legal(chr(t["T_ARGUMENT"]),
118                                      t["T_POSY"], t["T_POSX"])
119     if 1 == move_result[0]:
120         pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
121         hitted = [tid for tid in world_db["Things"]
122                   if world_db["Things"][tid]["T_POSY"] == move_result[1]
123                   if world_db["Things"][tid]["T_POSX"] == move_result[2]]
124         if len(hitted):
125             hit_id = hitted[0]
126             hitted_tid = world_db["Things"][hit_id]["T_TYPE"]
127             if t == world_db["Things"][0]:
128                 hitted_name = world_db["ThingTypes"][hitted_tid]["TT_NAME"]
129                 log("You SUCK from " + hitted_name + ".")
130             elif 0 == hit_id:
131                 hitter_name = world_db["ThingTypes"][t["T_TYPE"]]["TT_NAME"]
132                 log(hitter_name +" SUCKS from you.")
133             hitted = world_db["Things"][hit_id]
134             if t["T_STOMACH"] < 32:
135                 t["T_STOMACH"] = t["T_STOMACH"] + 1
136                 hitted["T_STOMACH"] -= 1
137             if t["T_KIDNEY"] < 32:
138                 t["T_KIDNEY"] = t["T_KIDNEY"] + 1
139                 hitted["T_KIDNEY"] -= 1
140             return
141         passable = chr(world_db["MAP"][pos]) in symbols_passable
142     if passable and t == world_db["Things"][0]:
143         log("You try to EAT, but fail.")
144     else:
145         height = world_db["MAP"][pos] - ord("0")
146         if t["T_STOMACH"] >= 32 or height == 5:
147             return
148         t["T_STOMACH"] += 1
149         if t == world_db["Things"][0]:
150             log("You EAT.")
151         eaten = (height == 3 and 0 == int(rand.next() % 2)) or \
152                 (height == 4 and 0 == int(rand.next() % 5))
153         if eaten:
154             world_db["MAP"][pos] = ord("0")
155             if t["T_STOMACH"] > 32:
156                 t["T_STOMACH"] = 32
157
158
159 def actor_move(t):
160     from server.build_fov_map import build_fov_map
161     from server.utils import mv_yx_in_dir_legal, rand
162     from server.config.world_data import symbols_passable
163     passable = False
164     move_result = mv_yx_in_dir_legal(chr(t["T_ARGUMENT"]),
165                                      t["T_POSY"], t["T_POSX"])
166     if 1 == move_result[0]:
167         pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
168         hitted = [tid for tid in world_db["Things"]
169                   if world_db["Things"][tid]["T_POSY"] == move_result[1]
170                   if world_db["Things"][tid]["T_POSX"] == move_result[2]]
171         if len(hitted):
172             hit_id = hitted[0]
173             hitted_tid = world_db["Things"][hit_id]["T_TYPE"]
174             if t == world_db["Things"][0]:
175                 hitted_name = world_db["ThingTypes"][hitted_tid]["TT_NAME"]
176                 log("You BUMP into " + hitted_name + ".")
177             elif 0 == hit_id:
178                 hitter_name = world_db["ThingTypes"][t["T_TYPE"]]["TT_NAME"]
179                 log(hitter_name +" BUMPS into you.")
180             return
181         passable = chr(world_db["MAP"][pos]) in symbols_passable
182     if passable:
183         t["T_POSY"] = move_result[1]
184         t["T_POSX"] = move_result[2]
185         t["pos"] = move_result[1] * world_db["MAP_LENGTH"] + move_result[2]
186         build_fov_map(t)
187         #if t != world_db["Things"][0]:
188         #    world_db["Things"][0]["T_MEMMAP"][t["pos"]] = ord("?")
189     elif t == world_db["Things"][0]:
190         log("You try to MOVE there, but fail.")
191
192
193 def test_hole(t):
194     if world_db["MAP"][t["pos"]] == ord("-"):
195         world_db["die"](t, "You FALL in a hole, and die.")
196         return False
197     return True
198 world_db["test_hole"] = test_hole
199
200
201 def test_air(t):
202     if world_db["terrain_fullness"](t["pos"]) > 5:
203         world_db["die"](t, "You SUFFOCATE")
204         return False
205     return True
206 world_db["test_air"] = test_air
207
208
209 def die(t, message):
210     t["T_LIFEPOINTS"] = 0
211     if t == world_db["Things"][0]:
212         t["fovmap"] = bytearray(b' ' * (world_db["MAP_LENGTH"] ** 2))
213         t["T_MEMMAP"][t["pos"]] = ord("@")
214         log(message)
215     else:
216         world_db["MAP"][t["pos"]] = ord("5")
217         world_db["HUMILITY"] = t["T_KIDNEY"] + t["T_BLADDER"] + \
218             (world_db["wetmap"][t["pos"]] - ord("0"))
219         world_db["wetmap"][t["pos"]] = 0
220         tid = next(tid for tid in world_db["Things"]
221                    if world_db["Things"][tid] == t)
222         del world_db["Things"][tid]
223 world_db["die"] = die
224
225
226 def make_map():
227     from server.make_map import new_pos, is_neighbor
228     from server.utils import rand
229     world_db["MAP"] = bytearray(b'5' * (world_db["MAP_LENGTH"] ** 2))
230     length = world_db["MAP_LENGTH"]
231     add_half_width = (not (length % 2)) * int(length / 2)
232     world_db["MAP"][int((length ** 2) / 2) + add_half_width] = ord("4")
233     while (1):
234         y, x, pos = new_pos()
235         if "5" == chr(world_db["MAP"][pos]) and is_neighbor((y, x), "4"):
236             if y == 0 or y == (length - 1) or x == 0 or x == (length - 1):
237                 break
238             world_db["MAP"][pos] = ord("4")
239     n_ground = int((length ** 2) / 16)
240     i_ground = 0
241     while (i_ground <= n_ground):
242         single_allowed = rand.next() % 32
243         y, x, pos = new_pos()
244         if "4" == chr(world_db["MAP"][pos]) \
245                 and ((not single_allowed) or is_neighbor((y, x), "0")):
246             world_db["MAP"][pos] = ord("0")
247             i_ground += 1
248     n_water = int((length ** 2) / 32)
249     i_water = 0
250     while (i_water <= n_water):
251         y, x, pos = new_pos()
252         if ord("0") == world_db["MAP"][pos] and \
253                 ord("0") == world_db["wetmap"][pos]:
254             world_db["wetmap"][pos] = ord("3")
255             i_water += 1
256
257
258 def calc_effort(ta, t):
259     from server.utils import mv_yx_in_dir_legal
260     if ta["TA_NAME"] == "move":
261         move_result = mv_yx_in_dir_legal(chr(t["T_ARGUMENT"]),
262                                          t["T_POSY"], t["T_POSX"])
263         if 1 == move_result[0]:
264             pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
265             narrowness = world_db["MAP"][pos] - ord("0")
266             return 2 ** narrowness
267     return 1
268 world_db["calc_effort"] = calc_effort
269
270
271 def turn_over():
272     from server.ai import ai
273     from server.config.actions import action_db
274     from server.update_map_memory import update_map_memory
275     from server.io import try_worldstate_update
276     from server.config.io import io_db
277     from server.utils import rand
278     while world_db["Things"][0]["T_LIFEPOINTS"]:
279         for tid in [tid for tid in world_db["Things"]]:
280             if not tid in world_db["Things"]:
281                 continue
282             t = world_db["Things"][tid]
283             if t["T_LIFEPOINTS"]:
284                 if not (world_db["test_air"](t) and world_db["test_hole"](t)):
285                     continue
286                 if not t["T_COMMAND"]:
287                     update_map_memory(t)
288                     if 0 == tid:
289                         return
290                     world_db["ai"](t)
291                 if t["T_LIFEPOINTS"]:
292                     t["T_PROGRESS"] += 1
293                     taid = [a for a in world_db["ThingActions"]
294                               if a == t["T_COMMAND"]][0]
295                     ThingAction = world_db["ThingActions"][taid]
296                     effort = world_db["calc_effort"](ThingAction, t)
297                     if t["T_PROGRESS"] >= effort:
298                         action = action_db["actor_" + ThingAction["TA_NAME"]]
299                         action(t)
300                         t["T_COMMAND"] = 0
301                         t["T_PROGRESS"] = 0
302                     if t["T_BOWEL"] > 16:
303                         if 0 == (rand.next() % (33 - t["T_BOWEL"])):
304                             action_db["actor_drop"](t)
305                     if t["T_BLADDER"] > 16:
306                         if 0 == (rand.next() % (33 - t["T_BLADDER"])):
307                             action_db["actor_pee"](t)
308                     if 0 == world_db["TURN"] % 5:
309                         t["T_STOMACH"] -= 1
310                         t["T_BOWEL"] += 1
311                         t["T_KIDNEY"] -= 1
312                         t["T_BLADDER"] += 1
313                     if t["T_STOMACH"] <= 0:
314                         world_db["die"](t, "You DIE of hunger.")
315                     elif t["T_KIDNEY"] <= 0:
316                         world_db["die"](t, "You DIE of dehydration.")
317         for pos in range(world_db["MAP_LENGTH"] ** 2):
318             wetness = world_db["wetmap"][pos] - ord("0")
319             height = world_db["MAP"][pos] - ord("0")
320             if height == 0 and wetness > 0 \
321                     and 0 == rand.next() % ((2 ** 13) / (2 ** wetness)):
322                 world_db["MAP"][pos] = ord("-")
323             if ((wetness > 0 and height != 0) or wetness > 1) \
324                 and 0 == rand.next() % 5:
325                 world_db["wetmap"][pos] -= 1
326                 world_db["HUMIDITY"] += 1
327         if world_db["HUMIDITY"] > 0:
328             if world_db["HUMIDITY"] > 2 and 0 == rand.next() % 2:
329                 world_db["NEW_SPAWN"] += 1
330                 world_db["HUMIDITY"] -= 1
331             if world_db["NEW_SPAWN"] >= 16:
332                 world_db["NEW_SPAWN"] -= 16
333                 from server.new_thing import new_Thing
334                 while 1:
335                     y = rand.next() % world_db["MAP_LENGTH"]
336                     x = rand.next() % world_db["MAP_LENGTH"]
337                     if chr(world_db["MAP"][y * world_db["MAP_LENGTH"] + x]) !=\
338                         "5":
339                         from server.utils import id_setter
340                         tid = id_setter(-1, "Things")
341                         world_db["Things"][tid] = new_Thing(
342                             world_db["PLAYER_TYPE"], (y, x))
343                         pos = y * world_db["MAP_LENGTH"] + x
344                         break
345             positions_to_wet = []
346             for pos in range(world_db["MAP_LENGTH"] ** 2):
347                 if world_db["MAP"][pos] == ord("0") \
348                         and world_db["wetmap"][pos] < ord("5"):
349                     positions_to_wet += [pos]
350             while world_db["HUMIDITY"] > 0 and len(positions_to_wet) > 0:
351                 select = rand.next() % len(positions_to_wet)
352                 pos = positions_to_wet[select]
353                 world_db["wetmap"][pos] += 1
354                 positions_to_wet.remove(pos)
355                 world_db["HUMIDITY"] -= 1
356         world_db["TURN"] += 1
357         io_db["worldstate_updateable"] = True
358         try_worldstate_update()
359 world_db["turn_over"] = turn_over
360
361
362 def command_ai():
363     """Call ai() on player Thing, then turn_over()."""
364     from server.ai import ai
365     if world_db["WORLD_ACTIVE"]:
366         ai(world_db["Things"][0])
367         world_db["turn_over"]()
368
369
370 def set_command(action):
371     """Set player's T_COMMAND, then call turn_over()."""
372     tid = [x for x in world_db["ThingActions"]
373            if world_db["ThingActions"][x]["TA_NAME"] == action][0]
374     world_db["Things"][0]["T_COMMAND"] = tid
375     world_db["turn_over"]()
376 world_db["set_command"] = set_command
377
378
379 def play_wait():
380     """Try "wait" as player's T_COMMAND."""
381     if world_db["WORLD_ACTIVE"]:
382         world_db["set_command"]("wait")
383
384
385 def save_wetmap():
386     length = world_db["MAP_LENGTH"]
387     string = ""
388     for i in range(length):
389         line = world_db["wetmap"][i * length:(i * length) + length].decode()
390         string = string + "WETMAP" + " "  + str(i) + " " + line + "\n"
391     return string
392
393
394 def wetmapset(str_int, mapline):
395     def valid_map_line(str_int, mapline):
396         from server.utils import integer_test
397         val = integer_test(str_int, 0, 255)
398         if None != val:
399             if val >= world_db["MAP_LENGTH"]:
400                 print("Illegal value for map line number.")
401             elif len(mapline) != world_db["MAP_LENGTH"]:
402                 print("Map line length is unequal map width.")
403             else:
404                 return val
405         return None
406     val = valid_map_line(str_int, mapline)
407     if None != val:
408         length = world_db["MAP_LENGTH"]
409         if not world_db["wetmap"]:
410             m = bytearray(b' ' * (length ** 2))
411         else:
412             m = world_db["wetmap"]
413         m[val * length:(val * length) + length] = mapline.encode()
414         if not world_db["wetmap"]:
415             world_db["wetmap"] = m
416
417 def write_wetmap():
418     from server.worldstate_write_helpers import write_map
419     length = world_db["MAP_LENGTH"]
420     visible_wetmap = bytearray(b' ' * (length ** 2))
421     for i in range(length ** 2):
422         if world_db["Things"][0]["fovmap"][i] == ord('v'):
423             visible_wetmap[i] = world_db["wetmap"][i]
424     return write_map(visible_wetmap, world_db["MAP_LENGTH"])
425
426
427 def command_ai():
428     if world_db["WORLD_ACTIVE"]:
429         world_db["ai"](world_db["Things"][0])
430         world_db["turn_over"]()
431
432
433 def get_dir_to_target(t, target):
434
435     from server.utils import rand, libpr, c_pointer_to_bytearray
436     from server.config.world_data import symbols_passable
437
438     def get_map_score(pos):
439         result = libpr.get_map_score(pos)
440         if result < 0:
441             raise RuntimeError("No score map allocated for get_map_score().")
442         return result
443
444     def zero_score_map_where_char_on_memdepthmap(c):
445         map = c_pointer_to_bytearray(t["T_MEMDEPTHMAP"])
446         if libpr.zero_score_map_where_char_on_memdepthmap(c, map):
447             raise RuntimeError("No score map allocated for "
448                                "zero_score_map_where_char_on_memdepthmap().")
449
450     def set_map_score(pos, score):
451         test = libpr.set_map_score(pos, score)
452         if test:
453             raise RuntimeError("No score map allocated for set_map_score().")
454
455     def set_movement_cost_map():
456         memmap = c_pointer_to_bytearray(t["T_MEMMAP"])
457         if libpr.TCE_set_movement_cost_map(memmap):
458             raise RuntimeError("No movement cost map allocated for "
459                                "set_movement_cost_map().")
460
461     def animates_in_fov(maplength):
462         return [Thing for Thing in world_db["Things"].values()
463                 if Thing["T_LIFEPOINTS"] if 118 == t["fovmap"][Thing["pos"]]
464                 if not Thing == t]
465
466     def seeing_thing():
467         def exists(gen):
468             try:
469                 next(gen)
470             except StopIteration:
471                 return False
472             return True
473         mapsize = world_db["MAP_LENGTH"] ** 2
474         if target == "food" and t["T_MEMMAP"]:
475             return exists(pos for pos in range(mapsize)
476                            if ord("2") < t["T_MEMMAP"][pos] < ord("5"))
477         elif target == "fluid_certain" and t["fovmap"]:
478             return exists(pos for pos in range(mapsize)
479                            if t["fovmap"] == ord("v")
480                            if world_db["MAP"][pos] == ord("0")
481                            if world_db["wetmap"][pos] > ord("0"))
482         elif target == "fluid_potential" and t["T_MEMMAP"] and t["fovmap"]:
483             return exists(pos for pos in range(mapsize)
484                            if t["T_MEMMAP"][pos] == ord("0")
485                            if t["fovmap"] != ord("v"))
486         elif target == "space" and t["T_MEMMAP"] and t["fovmap"]:
487             return exists(pos for pos in range(mapsize)
488                           if ord("0") <= t["T_MEMMAP"][pos] <= ord("2")
489                           if (t["fovmap"] != ord("v")
490                               or world_db["terrain_fullness"](pos) < 5))
491         elif target == "flee" and t["fovmap"]:
492             return exists(Thing for
493                           Thing in animates_in_fov(world_db["MAP_LENGTH"]))
494         return False
495
496     def init_score_map():
497         test = libpr.init_score_map()
498         set_movement_cost_map()
499         mapsize = world_db["MAP_LENGTH"] ** 2
500         if test:
501             raise RuntimeError("Malloc error in init_score_map().")
502         if target == "food" and t["T_MEMMAP"]:
503             [set_map_score(pos, 0) for pos in range(mapsize)
504              if ord("2") < t["T_MEMMAP"][pos] < ord("5")]
505         elif target == "fluid_certain" and t["fovmap"]:
506             [set_map_score(pos, 0) for pos in range(mapsize)
507              if t["fovmap"] == ord("v")
508              if world_db["MAP"][pos] == ord("0")
509              if world_db["wetmap"][pos] > ord("0")]
510         elif target == "fluid_potential" and t["T_MEMMAP"] and t["fovmap"]:
511             [set_map_score(pos, 0) for pos in range(mapsize)
512              if t["T_MEMMAP"][pos] == ord("0")
513              if t["fovmap"] != ord("v")]
514         elif target == "space" and t["T_MEMMAP"] and t["fovmap"]:
515             [set_map_score(pos, 0) for pos in range(mapsize)
516              if ord("0") <= t["T_MEMMAP"][pos] <= ord("2")
517              if (t["fovmap"] != ord("v")
518                  or world_db["terrain_fullness"](pos) < 5)]
519         elif target == "search":
520             zero_score_map_where_char_on_memdepthmap(mem_depth_c[0])
521         elif target == "flee":
522             [set_map_score(Thing["pos"], 0) for
523              Thing in animates_in_fov(world_db["MAP_LENGTH"])]
524
525     def rand_target_dir(neighbors, cmp, dirs):
526         candidates = []
527         n_candidates = 0
528         for i in range(len(dirs)):
529             if cmp == neighbors[i]:
530                 candidates.append(dirs[i])
531                 n_candidates += 1
532         return candidates[rand.next() % n_candidates] if n_candidates else 0
533
534     def get_neighbor_scores(dirs, eye_pos):
535         scores = []
536         if libpr.ready_neighbor_scores(eye_pos):
537             raise RuntimeError("No score map allocated for " +
538                                "ready_neighbor_scores.()")
539         for i in range(len(dirs)):
540             scores.append(libpr.get_neighbor_score(i))
541         return scores
542
543     def get_dir_from_neighbors():
544         import math
545         dir_to_target = False
546         dirs = "edcxsw"
547         eye_pos = t["pos"]
548         neighbors = get_neighbor_scores(dirs, eye_pos)
549         minmax_start = 0 if "flee" == target else 65535 - 1
550         minmax_neighbor = minmax_start
551         for i in range(len(dirs)):
552             if ("flee" == target and get_map_score(t["pos"]) < neighbors[i] and
553                 minmax_neighbor < neighbors[i] and 65535 != neighbors[i]) \
554                or ("flee" != target and minmax_neighbor > neighbors[i]):
555                 minmax_neighbor = neighbors[i]
556         if minmax_neighbor != minmax_start:
557             dir_to_target = rand_target_dir(neighbors, minmax_neighbor, dirs)
558         if "flee" == target:
559             distance = get_map_score(t["pos"])
560             fear_distance = 5
561             attack_distance = 1
562             if not dir_to_target:
563                 if attack_distance >= distance:
564                     dir_to_target = rand_target_dir(neighbors,
565                                                     distance - 1, dirs)
566                 elif fear_distance >= distance:
567                     t["T_COMMAND"] = [taid for
568                                       taid in world_db["ThingActions"]
569                                       if
570                                       world_db["ThingActions"][taid]["TA_NAME"]
571                                       == "wait"][0]
572                     return 1, 0
573             elif dir_to_target and fear_distance < distance:
574                 dir_to_target = 0
575         return dir_to_target, minmax_neighbor
576
577     dir_to_target = False
578     mem_depth_c = b' '
579     run_i = 9 + 1 if "search" == target else 1
580     minmax_neighbor = 0
581     while run_i and not dir_to_target and \
582             ("search" == target or seeing_thing()):
583         run_i -= 1
584         init_score_map()
585         mem_depth_c = b'9' if b' ' == mem_depth_c \
586             else bytes([mem_depth_c[0] - 1])
587         if libpr.TCE_dijkstra_map_with_movement_cost():
588             raise RuntimeError("No score map allocated for dijkstra_map().")
589         dir_to_target, minmax_neighbor = get_dir_from_neighbors()
590         libpr.free_score_map()
591         if dir_to_target and str == type(dir_to_target):
592             action = "move"
593             from server.utils import mv_yx_in_dir_legal
594             move_result = mv_yx_in_dir_legal(dir_to_target, t["T_POSY"],
595                                                             t["T_POSX"])
596             if 1 != move_result[0]:
597                 return False, 0
598             pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
599             hitted = [tid for tid in world_db["Things"]
600                       if world_db["Things"][tid]["pos"] == pos]
601             if world_db["MAP"][pos] > ord("2") or len(hitted) > 0:
602                 action = "eat"
603             t["T_COMMAND"] = [taid for taid in world_db["ThingActions"]
604                               if world_db["ThingActions"][taid]["TA_NAME"]
605                               == action][0]
606             t["T_ARGUMENT"] = ord(dir_to_target)
607     return dir_to_target, minmax_neighbor
608 world_db["get_dir_to_target"] = get_dir_to_target
609
610
611 def terrain_fullness(pos):
612     return (world_db["MAP"][pos] - ord("0")) + \
613         (world_db["wetmap"][pos] - ord("0"))
614 world_db["terrain_fullness"] = terrain_fullness
615
616
617 def ai(t):
618
619     if t["T_LIFEPOINTS"] == 0:
620         return
621
622     def standing_on_fluid(t):
623         if world_db["MAP"][t["pos"]] == ord("0") and \
624             world_db["wetmap"][t["pos"]] > ord("0"):
625                 return True
626         else:
627             return False
628
629     def thing_action_id(name):
630         return [taid for taid in world_db["ThingActions"]
631                 if world_db["ThingActions"][taid]
632                 ["TA_NAME"] == name][0]
633
634     t["T_COMMAND"] = thing_action_id("wait")
635     needs = {
636         "flee": 24,
637         "safe_pee": (world_db["terrain_fullness"](t["pos"]) * t["T_BLADDER"]) / 4,
638         "safe_drop": (world_db["terrain_fullness"](t["pos"]) * t["T_BOWEL"]) / 4,
639         "food": 33 - t["T_STOMACH"],
640         "fluid_certain": 33 - t["T_KIDNEY"],
641         "fluid_potential": 32 - t["T_KIDNEY"],
642         "search": 1,
643     }
644     from operator import itemgetter
645     needs = sorted(needs.items(), key=itemgetter(1,0))
646     needs.reverse()
647     for need in needs:
648         if need[1] > 0:
649             if need[0] in {"fluid_certain", "fluid_potential"}:
650                 if standing_on_fluid(t):
651                     t["T_COMMAND"] = thing_action_id("drink")
652                     return
653                 elif t["T_BLADDER"] > 0 and \
654                          world_db["MAP"][t["pos"]] == ord("0"):
655                     t["T_COMMAND"] = thing_action_id("pee")
656                     return
657             elif need[0] in {"safe_pee", "safe_drop"}:
658                 action_name = need[0][len("safe_"):]
659                 if world_db["terrain_fullness"](t["pos"]) < 4:
660                     t["T_COMMAND"] = thing_action_id(action_name)
661                     return
662                 else:
663                     test = world_db["get_dir_to_target"](t, "space")
664                     if test[0]:
665                         if (not test[1] < 5) and \
666                                 world_db["terrain_fullness"](t["pos"]) < 5:
667                             t["T_COMMAND"] = thing_action_id(action_name)
668                         return
669                     if t["T_STOMACH"] < 32 and \
670                             world_db["get_dir_to_target"](t, "food")[0]:
671                         return
672                 continue
673             if world_db["get_dir_to_target"](t, need[0])[0]:
674                 return
675             elif t["T_STOMACH"] < 32 and \
676                     need[0] in {"fluid_certain", "fluid_potential"} and \
677                     world_db["get_dir_to_target"](t, "food")[0]:
678                 return
679 world_db["ai"] = ai
680
681
682 from server.config.io import io_db
683 io_db["worldstate_write_order"] += [["T_STOMACH", "player_int"]]
684 io_db["worldstate_write_order"] += [["T_KIDNEY", "player_int"]]
685 io_db["worldstate_write_order"] += [["T_BOWEL", "player_int"]]
686 io_db["worldstate_write_order"] += [["T_BLADDER", "player_int"]]
687 io_db["worldstate_write_order"] += [[write_wetmap, "func"]]
688 import server.config.world_data
689 server.config.world_data.symbols_hide = "345"
690 server.config.world_data.symbols_passable = "012-"
691 server.config.world_data.thing_defaults["T_STOMACH"] = 16
692 server.config.world_data.thing_defaults["T_BOWEL"] = 0
693 server.config.world_data.thing_defaults["T_KIDNEY"] = 16
694 server.config.world_data.thing_defaults["T_BLADDER"] = 0
695 world_db["wetmap"] = bytearray(b"0" * world_db["MAP_LENGTH"] ** 2)
696 if not "NEW_SPAWN" in world_db:
697     world_db["NEW_SPAWN"] = 0
698 if not "HUMIDITY" in world_db:
699     world_db["HUMIDITY"] = 0
700 io_db["hook_save"] = save_wetmap
701 import server.config.make_world_helpers
702 server.config.make_world_helpers.make_map = make_map
703 from server.config.commands import commands_db
704 commands_db["THINGS_HERE"] = (2, True, lambda x, y: None)
705 commands_db["ai"] = (0, False, command_ai)
706 commands_db["move"] = (1, False, play_move)
707 commands_db["eat"] = (1, False, play_move)
708 commands_db["wait"] = (0, False, play_wait)
709 commands_db["drop"] = (0, False, play_drop)
710 commands_db["drink"] = (0, False, play_drink)
711 commands_db["pee"] = (0, False, play_pee)
712 commands_db["use"] = (1, False, lambda x: None)
713 commands_db["pickup"] = (0, False, lambda: None)
714 commands_db["NEW_SPAWN"] = (1, False, setter(None, "NEW_SPAWN", 0, 255))
715 commands_db["HUMIDITY"] = (1, False, setter(None, "HUMIDITY", 0, 65535))
716 commands_db["T_STOMACH"] = (1, False, setter("Thing", "T_STOMACH", 0, 255))
717 commands_db["T_KIDNEY"] = (1, False, setter("Thing", "T_KIDNEY", 0, 255))
718 commands_db["T_BOWEL"] = (1, False, setter("Thing", "T_BOWEL", 0, 255))
719 commands_db["T_BLADDER"] = (1, False, setter("Thing", "T_BLADDER", 0, 255))
720 commands_db["WETMAP"] = (2, False, wetmapset)
721 from server.actions import actor_wait
722 import server.config.actions
723 server.config.actions.action_db = {
724     "actor_wait": actor_wait,
725     "actor_move": actor_move,
726     "actor_drop": actor_drop,
727     "actor_drink": actor_drink,
728     "actor_pee": actor_pee,
729     "actor_eat": actor_eat,
730 }
731
732 strong_write(io_db["file_out"], "PLUGIN TheCrawlingEater\n")