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