home · contact · privacy
42f9d11956e696def0bc58ef76df19c1483d399b
[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         #if t != world_db["Things"][0]:
187         #    world_db["Things"][0]["T_MEMMAP"][t["pos"]] = ord("?")
188     elif t == world_db["Things"][0]:
189         log("You try to MOVE there, but fail.")
190
191
192 def test_hole(t):
193     if world_db["MAP"][t["pos"]] == ord("-"):
194         world_db["die"](t, "You FALL in a hole, and die.")
195         return False
196     return True
197 world_db["test_hole"] = test_hole
198
199
200 def test_air(t):
201     if world_db["terrain_fullness"](t["pos"]) > 5:
202         world_db["die"](t, "You SUFFOCATE")
203         return False
204     return True
205 world_db["test_air"] = test_air
206
207
208 def die(t, message):
209     t["T_LIFEPOINTS"] = 0
210     if t == world_db["Things"][0]:
211         t["fovmap"] = bytearray(b' ' * (world_db["MAP_LENGTH"] ** 2))
212         t["T_MEMMAP"][t["pos"]] = ord("@")
213         log(message)
214     else:
215         world_db["MAP"][t["pos"]] = ord("5")
216         world_db["HUMILITY"] = t["T_KIDNEY"] + t["T_BLADDER"] + \
217             (world_db["wetmap"][t["pos"]] - ord("0"))
218         world_db["wetmap"][t["pos"]] = 0
219         tid = next(tid for tid in world_db["Things"]
220                    if world_db["Things"][tid] == t)
221         del world_db["Things"][tid]
222 world_db["die"] = die
223
224
225 def make_map():
226     from server.make_map import new_pos, is_neighbor
227     from server.utils import rand
228     world_db["MAP"] = bytearray(b'5' * (world_db["MAP_LENGTH"] ** 2))
229     length = world_db["MAP_LENGTH"]
230     add_half_width = (not (length % 2)) * int(length / 2)
231     world_db["MAP"][int((length ** 2) / 2) + add_half_width] = ord("4")
232     while (1):
233         y, x, pos = new_pos()
234         if "5" == chr(world_db["MAP"][pos]) and is_neighbor((y, x), "4"):
235             if y == 0 or y == (length - 1) or x == 0 or x == (length - 1):
236                 break
237             world_db["MAP"][pos] = ord("4")
238     n_ground = int((length ** 2) / 16)
239     i_ground = 0
240     while (i_ground <= n_ground):
241         single_allowed = rand.next() % 32
242         y, x, pos = new_pos()
243         if "4" == chr(world_db["MAP"][pos]) \
244                 and ((not single_allowed) or is_neighbor((y, x), "0")):
245             world_db["MAP"][pos] = ord("0")
246             i_ground += 1
247     n_water = int((length ** 2) / 32)
248     i_water = 0
249     while (i_water <= n_water):
250         y, x, pos = new_pos()
251         if ord("0") == world_db["MAP"][pos] and \
252                 ord("0") == world_db["wetmap"][pos]:
253             world_db["wetmap"][pos] = ord("3")
254             i_water += 1
255
256
257 def calc_effort(ta, t):
258     from server.utils import mv_yx_in_dir_legal
259     if ta["TA_NAME"] == "move":
260         move_result = mv_yx_in_dir_legal(chr(t["T_ARGUMENT"]),
261                                          t["T_POSY"], t["T_POSX"])
262         if 1 == move_result[0]:
263             pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
264             narrowness = world_db["MAP"][pos] - ord("0")
265             return 2 ** narrowness
266     return 1
267 world_db["calc_effort"] = calc_effort
268
269
270 def turn_over():
271     from server.ai import ai
272     from server.config.actions import action_db
273     from server.update_map_memory import update_map_memory
274     from server.io import try_worldstate_update
275     from server.config.io import io_db
276     from server.utils import rand
277     from server.build_fov_map import build_fov_map
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                     build_fov_map(t)
289                     if 0 == tid:
290                         return
291                     world_db["ai"](t)
292                 if t["T_LIFEPOINTS"]:
293                     t["T_PROGRESS"] += 1
294                     taid = [a for a in world_db["ThingActions"]
295                               if a == t["T_COMMAND"]][0]
296                     ThingAction = world_db["ThingActions"][taid]
297                     effort = world_db["calc_effort"](ThingAction, t)
298                     if t["T_PROGRESS"] >= effort:
299                         action = action_db["actor_" + ThingAction["TA_NAME"]]
300                         action(t)
301                         t["T_COMMAND"] = 0
302                         t["T_PROGRESS"] = 0
303                     if t["T_BOWEL"] > 16:
304                         if 0 == (rand.next() % (33 - t["T_BOWEL"])):
305                             action_db["actor_drop"](t)
306                     if t["T_BLADDER"] > 16:
307                         if 0 == (rand.next() % (33 - t["T_BLADDER"])):
308                             action_db["actor_pee"](t)
309                     if 0 == world_db["TURN"] % 5:
310                         t["T_STOMACH"] -= 1
311                         t["T_BOWEL"] += 1
312                         t["T_KIDNEY"] -= 1
313                         t["T_BLADDER"] += 1
314                     if t["T_STOMACH"] <= 0:
315                         world_db["die"](t, "You DIE of hunger.")
316                     elif t["T_KIDNEY"] <= 0:
317                         world_db["die"](t, "You DIE of dehydration.")
318         for pos in range(world_db["MAP_LENGTH"] ** 2):
319             wetness = world_db["wetmap"][pos] - ord("0")
320             height = world_db["MAP"][pos] - ord("0")
321             if height == 0 and wetness > 0 \
322                     and 0 == rand.next() % ((2 ** 13) / (2 ** wetness)):
323                 world_db["MAP"][pos] = ord("-")
324             if ((wetness > 0 and height != 0) or wetness > 1) \
325                 and 0 == rand.next() % 5:
326                 world_db["wetmap"][pos] -= 1
327                 world_db["HUMIDITY"] += 1
328         if world_db["HUMIDITY"] > 0:
329             if world_db["HUMIDITY"] > 2 and 0 == rand.next() % 2:
330                 world_db["NEW_SPAWN"] += 1
331                 world_db["HUMIDITY"] -= 1
332             if world_db["NEW_SPAWN"] >= 16:
333                 world_db["NEW_SPAWN"] -= 16
334                 from server.new_thing import new_Thing
335                 while 1:
336                     y = rand.next() % world_db["MAP_LENGTH"]
337                     x = rand.next() % world_db["MAP_LENGTH"]
338                     if chr(world_db["MAP"][y * world_db["MAP_LENGTH"] + x]) !=\
339                         "5":
340                         from server.utils import id_setter
341                         tid = id_setter(-1, "Things")
342                         world_db["Things"][tid] = new_Thing(
343                             world_db["PLAYER_TYPE"], (y, x))
344                         pos = y * world_db["MAP_LENGTH"] + x
345                         break
346             positions_to_wet = []
347             for pos in range(world_db["MAP_LENGTH"] ** 2):
348                 if world_db["MAP"][pos] == ord("0") \
349                         and world_db["wetmap"][pos] < ord("5"):
350                     positions_to_wet += [pos]
351             while world_db["HUMIDITY"] > 0 and len(positions_to_wet) > 0:
352                 select = rand.next() % len(positions_to_wet)
353                 pos = positions_to_wet[select]
354                 world_db["wetmap"][pos] += 1
355                 positions_to_wet.remove(pos)
356                 world_db["HUMIDITY"] -= 1
357         world_db["TURN"] += 1
358         io_db["worldstate_updateable"] = True
359         try_worldstate_update()
360 world_db["turn_over"] = turn_over
361
362
363 def command_ai():
364     """Call ai() on player Thing, then turn_over()."""
365     from server.ai import ai
366     if world_db["WORLD_ACTIVE"]:
367         ai(world_db["Things"][0])
368         world_db["turn_over"]()
369
370
371 def set_command(action):
372     """Set player's T_COMMAND, then call turn_over()."""
373     tid = [x for x in world_db["ThingActions"]
374            if world_db["ThingActions"][x]["TA_NAME"] == action][0]
375     world_db["Things"][0]["T_COMMAND"] = tid
376     world_db["turn_over"]()
377 world_db["set_command"] = set_command
378
379
380 def play_wait():
381     """Try "wait" as player's T_COMMAND."""
382     if world_db["WORLD_ACTIVE"]:
383         world_db["set_command"]("wait")
384
385
386 def save_wetmap():
387     length = world_db["MAP_LENGTH"]
388     string = ""
389     for i in range(length):
390         line = world_db["wetmap"][i * length:(i * length) + length].decode()
391         string = string + "WETMAP" + " "  + str(i) + " " + line + "\n"
392     return string
393
394
395 def wetmapset(str_int, mapline):
396     def valid_map_line(str_int, mapline):
397         from server.utils import integer_test
398         val = integer_test(str_int, 0, 255)
399         if None != val:
400             if val >= world_db["MAP_LENGTH"]:
401                 print("Illegal value for map line number.")
402             elif len(mapline) != world_db["MAP_LENGTH"]:
403                 print("Map line length is unequal map width.")
404             else:
405                 return val
406         return None
407     val = valid_map_line(str_int, mapline)
408     if None != val:
409         length = world_db["MAP_LENGTH"]
410         if not world_db["wetmap"]:
411             m = bytearray(b' ' * (length ** 2))
412         else:
413             m = world_db["wetmap"]
414         m[val * length:(val * length) + length] = mapline.encode()
415         if not world_db["wetmap"]:
416             world_db["wetmap"] = m
417
418 def write_wetmap():
419     from server.worldstate_write_helpers import write_map
420     length = world_db["MAP_LENGTH"]
421     visible_wetmap = bytearray(b' ' * (length ** 2))
422     for i in range(length ** 2):
423         if world_db["Things"][0]["fovmap"][i] == ord('v'):
424             visible_wetmap[i] = world_db["wetmap"][i]
425     return write_map(visible_wetmap, world_db["MAP_LENGTH"])
426
427
428 def command_ai():
429     if world_db["WORLD_ACTIVE"]:
430         world_db["ai"](world_db["Things"][0])
431         world_db["turn_over"]()
432
433
434 def get_dir_to_target(t, target):
435
436     from server.utils import rand, libpr, c_pointer_to_bytearray
437     from server.config.world_data import symbols_passable
438
439     def get_map_score(pos):
440         result = libpr.get_map_score(pos)
441         if result < 0:
442             raise RuntimeError("No score map allocated for get_map_score().")
443         return result
444
445     def zero_score_map_where_char_on_memdepthmap(c):
446         map = c_pointer_to_bytearray(t["T_MEMDEPTHMAP"])
447         if libpr.zero_score_map_where_char_on_memdepthmap(c, map):
448             raise RuntimeError("No score map allocated for "
449                                "zero_score_map_where_char_on_memdepthmap().")
450
451     def set_map_score(pos, score):
452         test = libpr.set_map_score(pos, score)
453         if test:
454             raise RuntimeError("No score map allocated for set_map_score().")
455
456     def set_movement_cost_map():
457         memmap = c_pointer_to_bytearray(t["T_MEMMAP"])
458         if libpr.TCE_set_movement_cost_map(memmap):
459             raise RuntimeError("No movement cost map allocated for "
460                                "set_movement_cost_map().")
461
462     def animates_in_fov(maplength):
463         return [Thing for Thing in world_db["Things"].values()
464                 if Thing["T_LIFEPOINTS"] and 118 == t["fovmap"][Thing["pos"]]
465                 and (not Thing == t)]
466
467     def seeing_thing():
468         def exists(gen):
469             try:
470                 next(gen)
471             except StopIteration:
472                 return False
473             return True
474         mapsize = world_db["MAP_LENGTH"] ** 2
475         if target == "food" and t["T_MEMMAP"]:
476             return exists(pos for pos in range(mapsize)
477                            if ord("2") < t["T_MEMMAP"][pos] < ord("5"))
478         elif target == "fluid_certain" and t["fovmap"]:
479             return exists(pos for pos in range(mapsize)
480                            if t["fovmap"] == ord("v")
481                            if world_db["MAP"][pos] == ord("0")
482                            if world_db["wetmap"][pos] > ord("0"))
483         elif target == "fluid_potential" and t["T_MEMMAP"] and t["fovmap"]:
484             return exists(pos for pos in range(mapsize)
485                            if t["T_MEMMAP"][pos] == ord("0")
486                            if t["fovmap"] != ord("v"))
487         elif target == "space" and t["T_MEMMAP"] and t["fovmap"]:
488             return exists(pos for pos in range(mapsize)
489                           if ord("0") <= t["T_MEMMAP"][pos] <= ord("2")
490                           if (t["fovmap"] != ord("v")
491                               or world_db["terrain_fullness"](pos) < 5))
492         elif target in {"hunt", "flee"} and t["fovmap"]:
493             return exists(Thing for
494                           Thing in animates_in_fov(world_db["MAP_LENGTH"]))
495         return False
496
497     def init_score_map():
498         test = libpr.init_score_map()
499         set_movement_cost_map()
500         mapsize = world_db["MAP_LENGTH"] ** 2
501         if test:
502             raise RuntimeError("Malloc error in init_score_map().")
503         if target == "food" and t["T_MEMMAP"]:
504             [set_map_score(pos, 0) for pos in range(mapsize)
505              if ord("2") < t["T_MEMMAP"][pos] < ord("5")]
506         elif target == "fluid_certain" and t["fovmap"]:
507             [set_map_score(pos, 0) for pos in range(mapsize)
508              if t["fovmap"] == ord("v")
509              if world_db["MAP"][pos] == ord("0")
510              if world_db["wetmap"][pos] > ord("0")]
511         elif target == "fluid_potential" and t["T_MEMMAP"] and t["fovmap"]:
512             [set_map_score(pos, 0) for pos in range(mapsize)
513              if t["T_MEMMAP"][pos] == ord("0")
514              if t["fovmap"] != ord("v")]
515         elif target == "space" and t["T_MEMMAP"] and t["fovmap"]:
516             [set_map_score(pos, 0) for pos in range(mapsize)
517              if ord("0") <= t["T_MEMMAP"][pos] <= ord("2")
518              if (t["fovmap"] != ord("v")
519                  or world_db["terrain_fullness"](pos) < 5)]
520         elif target == "search":
521             zero_score_map_where_char_on_memdepthmap(mem_depth_c[0])
522         elif target in {"hunt", "flee"}:
523             [set_map_score(Thing["pos"], 0) for
524              Thing in animates_in_fov(world_db["MAP_LENGTH"])]
525
526     def rand_target_dir(neighbors, cmp, dirs):
527         candidates = []
528         n_candidates = 0
529         for i in range(len(dirs)):
530             if cmp == neighbors[i]:
531                 candidates.append(dirs[i])
532                 n_candidates += 1
533         return candidates[rand.next() % n_candidates] if n_candidates else 0
534
535     def get_neighbor_scores(dirs, eye_pos):
536         scores = []
537         if libpr.ready_neighbor_scores(eye_pos):
538             raise RuntimeError("No score map allocated for " +
539                                "ready_neighbor_scores.()")
540         for i in range(len(dirs)):
541             scores.append(libpr.get_neighbor_score(i))
542         return scores
543
544     def get_dir_from_neighbors():
545         import math
546         dir_to_target = False
547         dirs = "edcxsw"
548         eye_pos = t["pos"]
549         neighbors = get_neighbor_scores(dirs, eye_pos)
550         minmax_start = 0 if "flee" == target else 65535 - 1
551         minmax_neighbor = minmax_start
552         for i in range(len(dirs)):
553             if ("flee" == target and get_map_score(t["pos"]) < neighbors[i] and
554                 minmax_neighbor < neighbors[i] and 65535 != neighbors[i]) \
555                or ("flee" != target and minmax_neighbor > neighbors[i]):
556                 minmax_neighbor = neighbors[i]
557         if minmax_neighbor != minmax_start:
558             dir_to_target = rand_target_dir(neighbors, minmax_neighbor, dirs)
559         if "flee" == target:
560             distance = get_map_score(t["pos"])
561             fear_distance = 5
562             attack_distance = 1
563             if not dir_to_target:
564                 if attack_distance >= distance:
565                     dir_to_target = rand_target_dir(neighbors,
566                                                     distance - 1, dirs)
567             elif dir_to_target and fear_distance < distance:
568                 dir_to_target = 0
569         return dir_to_target, minmax_neighbor
570
571     dir_to_target = False
572     mem_depth_c = b' '
573     run_i = 9 + 1 if "search" == target else 1
574     minmax_neighbor = 0
575     while run_i and not dir_to_target and \
576             ("search" == target or seeing_thing()):
577         run_i -= 1
578         init_score_map()
579         mem_depth_c = b'9' if b' ' == mem_depth_c \
580             else bytes([mem_depth_c[0] - 1])
581         if libpr.TCE_dijkstra_map_with_movement_cost():
582             raise RuntimeError("No score map allocated for dijkstra_map().")
583         dir_to_target, minmax_neighbor = get_dir_from_neighbors()
584         libpr.free_score_map()
585         if dir_to_target and str == type(dir_to_target):
586             action = "move"
587             from server.utils import mv_yx_in_dir_legal
588             move_result = mv_yx_in_dir_legal(dir_to_target, t["T_POSY"],
589                                                             t["T_POSX"])
590             if 1 != move_result[0]:
591                 return False, 0
592             pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
593             hitted = [tid for tid in world_db["Things"]
594                       if world_db["Things"][tid]["pos"] == pos]
595             if world_db["MAP"][pos] > ord("2") or len(hitted) > 0:
596                 action = "eat"
597             t["T_COMMAND"] = [taid for taid in world_db["ThingActions"]
598                               if world_db["ThingActions"][taid]["TA_NAME"]
599                               == action][0]
600             t["T_ARGUMENT"] = ord(dir_to_target)
601     return dir_to_target, minmax_neighbor
602 world_db["get_dir_to_target"] = get_dir_to_target
603
604
605 def terrain_fullness(pos):
606     return (world_db["MAP"][pos] - ord("0")) + \
607         (world_db["wetmap"][pos] - ord("0"))
608 world_db["terrain_fullness"] = terrain_fullness
609
610
611 def ai(t):
612
613     if t["T_LIFEPOINTS"] == 0:
614         return
615
616     def standing_on_fluid(t):
617         if world_db["MAP"][t["pos"]] == ord("0") and \
618             world_db["wetmap"][t["pos"]] > ord("0"):
619                 return True
620         else:
621             return False
622
623     def thing_action_id(name):
624         return [taid for taid in world_db["ThingActions"]
625                 if world_db["ThingActions"][taid]
626                 ["TA_NAME"] == name][0]
627
628     t["T_COMMAND"] = thing_action_id("wait")
629     needs = {
630         "flee": 24,
631         "safe_pee": (world_db["terrain_fullness"](t["pos"]) * t["T_BLADDER"]) / 4,
632         "safe_drop": (world_db["terrain_fullness"](t["pos"]) * t["T_BOWEL"]) / 4,
633         "food": 33 - t["T_STOMACH"],
634         "fluid_certain": 33 - t["T_KIDNEY"],
635         "fluid_potential": 32 - t["T_KIDNEY"],
636         "search": 1,
637     }
638     from operator import itemgetter
639     needs = sorted(needs.items(), key=itemgetter(1,0))
640     needs.reverse()
641     for need in needs:
642         if need[1] > 0:
643             if need[0] in {"fluid_certain", "fluid_potential"}:
644                 if standing_on_fluid(t):
645                     t["T_COMMAND"] = thing_action_id("drink")
646                     return
647                 elif t["T_BLADDER"] > 0 and \
648                          world_db["MAP"][t["pos"]] == ord("0"):
649                     t["T_COMMAND"] = thing_action_id("pee")
650                     return
651             elif need[0] in {"safe_pee", "safe_drop"}:
652                 action_name = need[0][len("safe_"):]
653                 if world_db["terrain_fullness"](t["pos"]) < 4:
654                     t["T_COMMAND"] = thing_action_id(action_name)
655                     return
656                 else:
657                     test = world_db["get_dir_to_target"](t, "space")
658                     if test[0]:
659                         if (not test[1] < 5) and \
660                                 world_db["terrain_fullness"](t["pos"]) < 5:
661                             t["T_COMMAND"] = thing_action_id(action_name)
662                         return
663                     if t["T_STOMACH"] < 32 and \
664                             world_db["get_dir_to_target"](t, "food")[0]:
665                         return
666                 continue
667             if need[0] in {"fluid_certain", "fluid_potential", "food"}:
668                 if world_db["get_dir_to_target"](t, need[0])[0]:
669                     return
670                 elif world_db["get_dir_to_target"](t, "hunt")[0]:
671                     return
672                 elif need[0] != "food" and t["T_STOMACH"] < 32 and \
673                         world_db["get_dir_to_target"](t, "food")[0]:
674                     return
675             elif world_db["get_dir_to_target"](t, need[0])[0]:
676                 return
677 world_db["ai"] = ai
678
679
680 from server.config.io import io_db
681 io_db["worldstate_write_order"] += [["T_STOMACH", "player_int"]]
682 io_db["worldstate_write_order"] += [["T_KIDNEY", "player_int"]]
683 io_db["worldstate_write_order"] += [["T_BOWEL", "player_int"]]
684 io_db["worldstate_write_order"] += [["T_BLADDER", "player_int"]]
685 io_db["worldstate_write_order"] += [[write_wetmap, "func"]]
686 import server.config.world_data
687 server.config.world_data.symbols_hide = "345"
688 server.config.world_data.symbols_passable = "012-"
689 server.config.world_data.thing_defaults["T_STOMACH"] = 16
690 server.config.world_data.thing_defaults["T_BOWEL"] = 0
691 server.config.world_data.thing_defaults["T_KIDNEY"] = 16
692 server.config.world_data.thing_defaults["T_BLADDER"] = 0
693 world_db["wetmap"] = bytearray(b"0" * world_db["MAP_LENGTH"] ** 2)
694 if not "NEW_SPAWN" in world_db:
695     world_db["NEW_SPAWN"] = 0
696 if not "HUMIDITY" in world_db:
697     world_db["HUMIDITY"] = 0
698 io_db["hook_save"] = save_wetmap
699 import server.config.make_world_helpers
700 server.config.make_world_helpers.make_map = make_map
701 from server.config.commands import commands_db
702 commands_db["THINGS_HERE"] = (2, True, lambda x, y: None)
703 commands_db["ai"] = (0, False, command_ai)
704 commands_db["move"] = (1, False, play_move)
705 commands_db["eat"] = (1, False, play_move)
706 commands_db["wait"] = (0, False, play_wait)
707 commands_db["drop"] = (0, False, play_drop)
708 commands_db["drink"] = (0, False, play_drink)
709 commands_db["pee"] = (0, False, play_pee)
710 commands_db["use"] = (1, False, lambda x: None)
711 commands_db["pickup"] = (0, False, lambda: None)
712 commands_db["NEW_SPAWN"] = (1, False, setter(None, "NEW_SPAWN", 0, 255))
713 commands_db["HUMIDITY"] = (1, False, setter(None, "HUMIDITY", 0, 65535))
714 commands_db["T_STOMACH"] = (1, False, setter("Thing", "T_STOMACH", 0, 255))
715 commands_db["T_KIDNEY"] = (1, False, setter("Thing", "T_KIDNEY", 0, 255))
716 commands_db["T_BOWEL"] = (1, False, setter("Thing", "T_BOWEL", 0, 255))
717 commands_db["T_BLADDER"] = (1, False, setter("Thing", "T_BLADDER", 0, 255))
718 commands_db["WETMAP"] = (2, False, wetmapset)
719 from server.actions import actor_wait
720 import server.config.actions
721 server.config.actions.action_db = {
722     "actor_wait": actor_wait,
723     "actor_move": actor_move,
724     "actor_drop": actor_drop,
725     "actor_drink": actor_drink,
726     "actor_pee": actor_pee,
727     "actor_eat": actor_eat,
728 }
729
730 strong_write(io_db["file_out"], "PLUGIN TheCrawlingEater\n")