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