home · contact · privacy
TCE: Only give GRACE capabilities to player.
[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 t == world_db["Things"][0]:
230         if world_db["GRACE"] >= 32 and world_db["MAP"][t["pos"]] == ord("&"):
231             world_db["die"](t, "YOU WIN, CONGRATULATIONS.")
232             return False
233         if world_db["GRACE"] >= 24:
234             return True
235     if chr(world_db["MAP"][t["pos"]]) in "*&":
236         world_db["die"](t, "You FALL in a hole, and die.")
237         return False
238     return True
239 world_db["test_hole"] = test_hole
240
241
242 def test_air(t):
243     if world_db["terrain_fullness"](t["pos"]) > 5:
244         world_db["die"](t, "You SUFFOCATE")
245         return False
246     return True
247 world_db["test_air"] = test_air
248
249
250 def die(t, message):
251     t["T_LIFEPOINTS"] = 0
252     if t == world_db["Things"][0]:
253         t["fovmap"] = bytearray(b' ' * (world_db["MAP_LENGTH"] ** 2))
254         t["T_MEMMAP"][t["pos"]] = ord("@")
255         log(message)
256     else:
257         if world_db["MAP"][t["pos"]] != ord("$"):
258             world_db["MAP"][t["pos"]] = ord("5")
259         world_db["HUMILITY"] = t["T_KIDNEY"] + t["T_BLADDER"] + \
260             (world_db["wetmap"][t["pos"]] - ord("0"))
261         world_db["wetmap"][t["pos"]] = 0
262         tid = next(tid for tid in world_db["Things"]
263                    if world_db["Things"][tid] == t)
264         del world_db["Things"][tid]
265 world_db["die"] = die
266
267
268 def make_map():
269     from server.make_map import new_pos, is_neighbor
270     from server.utils import rand
271     world_db["MAP"] = bytearray(b'5' * (world_db["MAP_LENGTH"] ** 2))
272     length = world_db["MAP_LENGTH"]
273     add_half_width = (not (length % 2)) * int(length / 2)
274     world_db["MAP"][int((length ** 2) / 2) + add_half_width] = ord("4")
275     while (1):
276         y, x, pos = new_pos()
277         if "5" == chr(world_db["MAP"][pos]) and is_neighbor((y, x), "4"):
278             if y == 0 or y == (length - 1) or x == 0 or x == (length - 1):
279                 break
280             world_db["MAP"][pos] = ord("4")
281     n_ground = int((length ** 2) / 16)
282     i_ground = 0
283     while (i_ground <= n_ground):
284         single_allowed = rand.next() % 32
285         y, x, pos = new_pos()
286         if "4" == chr(world_db["MAP"][pos]) \
287                 and ((not single_allowed) or is_neighbor((y, x), "0")):
288             world_db["MAP"][pos] = ord("0")
289             i_ground += 1
290     n_water = int((length ** 2) / 32)
291     i_water = 0
292     while (i_water <= n_water):
293         y, x, pos = new_pos()
294         if ord("0") == world_db["MAP"][pos] and \
295                 ord("0") == world_db["wetmap"][pos]:
296             world_db["wetmap"][pos] = ord("3")
297             i_water += 1
298     n_altars = 4
299     i_altars = 0
300     while (i_altars < n_altars):
301         y, x, pos = new_pos()
302         if ord("0") == world_db["MAP"][pos]:
303             world_db["MAP"][pos] = ord("$")
304             i_altars += 1
305
306
307 def calc_effort(ta, t):
308     from server.utils import mv_yx_in_dir_legal
309     if ta["TA_NAME"] == "move":
310         move_result = mv_yx_in_dir_legal(chr(t["T_ARGUMENT"]),
311                                          t["T_POSY"], t["T_POSX"])
312         if 1 == move_result[0]:
313             pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
314             if chr(world_db["MAP"][pos]) in "012":
315                 narrowness = world_db["MAP"][pos] - ord("0")
316                 return 2 ** narrowness
317     return 1
318 world_db["calc_effort"] = calc_effort
319
320
321 def turn_over():
322     from server.ai import ai
323     from server.config.actions import action_db
324     from server.update_map_memory import update_map_memory
325     from server.io import try_worldstate_update
326     from server.config.io import io_db
327     from server.utils import rand
328     from server.build_fov_map import build_fov_map
329     while world_db["Things"][0]["T_LIFEPOINTS"]:
330         for tid in [tid for tid in world_db["Things"]]:
331             if not tid in world_db["Things"]:
332                 continue
333             t = world_db["Things"][tid]
334             if t["T_LIFEPOINTS"]:
335                 if not (world_db["test_air"](t) and world_db["test_hole"](t)):
336                     continue
337                 if not t["T_COMMAND"]:
338                     update_map_memory(t)
339                     build_fov_map(t)
340                     if 0 == tid:
341                         return
342                     world_db["ai"](t)
343                 if t["T_LIFEPOINTS"]:
344                     t["T_PROGRESS"] += 1
345                     taid = [a for a in world_db["ThingActions"]
346                               if a == t["T_COMMAND"]][0]
347                     ThingAction = world_db["ThingActions"][taid]
348                     effort = world_db["calc_effort"](ThingAction, t)
349                     if t["T_PROGRESS"] >= effort:
350                         action = action_db["actor_" + ThingAction["TA_NAME"]]
351                         action(t)
352                         t["T_COMMAND"] = 0
353                         t["T_PROGRESS"] = 0
354                     if t["T_BOWEL"] > 16:
355                         if 0 == (rand.next() % (33 - t["T_BOWEL"])):
356                             action_db["actor_drop"](t)
357                     if t["T_BLADDER"] > 16:
358                         if 0 == (rand.next() % (33 - t["T_BLADDER"])):
359                             action_db["actor_pee"](t)
360                     if 0 == world_db["TURN"] % 5:
361                         t["T_STOMACH"] -= 1
362                         t["T_BOWEL"] += 1
363                         t["T_KIDNEY"] -= 1
364                         t["T_BLADDER"] += 1
365                     if t["T_STOMACH"] <= 0:
366                         world_db["die"](t, "You DIE of hunger.")
367                     elif t["T_KIDNEY"] <= 0:
368                         world_db["die"](t, "You DIE of dehydration.")
369         mapsize = world_db["MAP_LENGTH"] ** 2
370         for pos in range(mapsize):
371             wetness = world_db["wetmap"][pos] - ord("0")
372             height = world_db["MAP"][pos] - ord("0")
373             if world_db["MAP"][pos] == ord("-"):
374                 height = -1
375             elif world_db["MAP"][pos] == ord("+"):
376                 height = -2
377             elif world_db["MAP"][pos] == ord("$"):
378                 height = -3
379             if height == -2 and wetness > 1 \
380                     and 0 == rand.next() % ((2 ** 11) / (2 ** wetness)):
381                 world_db["MAP"][pos] = ord("*")
382                 world_db["HUMIDITY"] += wetness
383             if height == -1 and wetness > 1 \
384                     and 0 == rand.next() % ((2 ** 10) / (2 ** wetness)):
385                 world_db["MAP"][pos] = ord("+")
386             if height == 0 and wetness > 1 \
387                     and 0 == rand.next() % ((2 ** 9) / (2 ** wetness)):
388                 world_db["MAP"][pos] = ord("-")
389             if ((wetness > 0 and height > 0) or wetness > 1) \
390                 and 0 == rand.next() % 5:
391                 world_db["wetmap"][pos] -= 1
392                 world_db["HUMIDITY"] += 1
393         if world_db["HUMIDITY"] > 0:
394             if world_db["HUMIDITY"] > 2 and 0 == rand.next() % 2:
395                 world_db["NEW_SPAWN"] += 1
396                 world_db["HUMIDITY"] -= 1
397             if world_db["NEW_SPAWN"] >= 16:
398                 world_db["NEW_SPAWN"] -= 16
399                 from server.new_thing import new_Thing
400                 while 1:
401                     y = rand.next() % world_db["MAP_LENGTH"]
402                     x = rand.next() % world_db["MAP_LENGTH"]
403                     if chr(world_db["MAP"][y * world_db["MAP_LENGTH"] + x]) !=\
404                         "5":
405                         from server.utils import id_setter
406                         tid = id_setter(-1, "Things")
407                         world_db["Things"][tid] = new_Thing(
408                             world_db["PLAYER_TYPE"], (y, x))
409                         pos = y * world_db["MAP_LENGTH"] + x
410                         break
411             positions_to_wet = []
412             for pos in range(mapsize):
413                 if chr(world_db["MAP"][pos]) in "0-+" \
414                         and world_db["wetmap"][pos] < ord("5"):
415                     positions_to_wet += [pos]
416             while world_db["HUMIDITY"] > 0 and len(positions_to_wet) > 0:
417                 select = rand.next() % len(positions_to_wet)
418                 pos = positions_to_wet[select]
419                 world_db["wetmap"][pos] += 1
420                 positions_to_wet.remove(pos)
421                 world_db["HUMIDITY"] -= 1
422         for pos in range(mapsize):
423             if world_db["soundmap"][pos] > ord("0"):
424                 world_db["soundmap"][pos] -= 1
425         from server.utils import libpr
426         libpr.init_score_map()
427         def set_map_score(pos, score):
428             test = libpr.set_map_score(pos, score)
429             if test:
430                 raise RuntimeError("No score map allocated for set_map_score().")
431         [set_map_score(pos, 1) for pos in range(mapsize)
432          if world_db["MAP"][pos] == ord("*")]
433         for pos in range(mapsize):
434             if world_db["MAP"][pos] == ord("*"):
435                 if libpr.ready_neighbor_scores(pos):
436                     raise RuntimeError("No score map allocated for " +
437                                        "ready_neighbor_scores.()")
438                 score = 0
439                 dirs = "edcxsw"
440                 for i in range(len(dirs)):
441                     score += libpr.get_neighbor_score(i)
442                 if score == 5 or score == 6:
443                     world_db["MAP"][pos] = ord("&")
444         libpr.free_score_map()
445         world_db["TURN"] += 1
446         io_db["worldstate_updateable"] = True
447         try_worldstate_update()
448 world_db["turn_over"] = turn_over
449
450
451 def set_command(action):
452     """Set player's T_COMMAND, then call turn_over()."""
453     tid = [x for x in world_db["ThingActions"]
454            if world_db["ThingActions"][x]["TA_NAME"] == action][0]
455     world_db["Things"][0]["T_COMMAND"] = tid
456     world_db["turn_over"]()
457 world_db["set_command"] = set_command
458
459
460 def play_wait():
461     """Try "wait" as player's T_COMMAND."""
462     if world_db["WORLD_ACTIVE"]:
463         world_db["set_command"]("wait")
464
465
466 def save_maps():
467     length = world_db["MAP_LENGTH"]
468     string = ""
469     for i in range(length):
470         line = world_db["wetmap"][i * length:(i * length) + length].decode()
471         string = string + "WETMAP" + " "  + str(i) + " " + line + "\n"
472     for i in range(length):
473         line = world_db["soundmap"][i * length:(i * length) + length].decode()
474         string = string + "SOUNDMAP" + " "  + str(i) + " " + line + "\n"
475     return string
476
477
478 def soundmapset(str_int, mapline):
479     def valid_map_line(str_int, mapline):
480         from server.utils import integer_test
481         val = integer_test(str_int, 0, 255)
482         if None != val:
483             if val >= world_db["MAP_LENGTH"]:
484                 print("Illegal value for map line number.")
485             elif len(mapline) != world_db["MAP_LENGTH"]:
486                 print("Map line length is unequal map width.")
487             else:
488                 return val
489         return None
490     val = valid_map_line(str_int, mapline)
491     if None != val:
492         length = world_db["MAP_LENGTH"]
493         if not world_db["soundmap"]:
494             m = bytearray(b' ' * (length ** 2))
495         else:
496             m = world_db["soundmap"]
497         m[val * length:(val * length) + length] = mapline.encode()
498         if not world_db["soundmap"]:
499             world_db["soundmap"] = m
500
501
502 def wetmapset(str_int, mapline):
503     def valid_map_line(str_int, mapline):
504         from server.utils import integer_test
505         val = integer_test(str_int, 0, 255)
506         if None != val:
507             if val >= world_db["MAP_LENGTH"]:
508                 print("Illegal value for map line number.")
509             elif len(mapline) != world_db["MAP_LENGTH"]:
510                 print("Map line length is unequal map width.")
511             else:
512                 return val
513         return None
514     val = valid_map_line(str_int, mapline)
515     if None != val:
516         length = world_db["MAP_LENGTH"]
517         if not world_db["wetmap"]:
518             m = bytearray(b' ' * (length ** 2))
519         else:
520             m = world_db["wetmap"]
521         m[val * length:(val * length) + length] = mapline.encode()
522         if not world_db["wetmap"]:
523             world_db["wetmap"] = m
524
525
526 def write_soundmap():
527     from server.worldstate_write_helpers import write_map
528     length = world_db["MAP_LENGTH"]
529     return write_map(world_db["soundmap"], world_db["MAP_LENGTH"])
530
531
532 def write_wetmap():
533     from server.worldstate_write_helpers import write_map
534     length = world_db["MAP_LENGTH"]
535     visible_wetmap = bytearray(b' ' * (length ** 2))
536     for i in range(length ** 2):
537         if world_db["Things"][0]["fovmap"][i] == ord('v'):
538             visible_wetmap[i] = world_db["wetmap"][i]
539     return write_map(visible_wetmap, world_db["MAP_LENGTH"])
540
541
542 def get_dir_to_target(t, target):
543
544     from server.utils import rand, libpr, c_pointer_to_bytearray
545     from server.config.world_data import symbols_passable
546
547     def get_map_score(pos):
548         result = libpr.get_map_score(pos)
549         if result < 0:
550             raise RuntimeError("No score map allocated for get_map_score().")
551         return result
552
553     def zero_score_map_where_char_on_memdepthmap(c):
554         map = c_pointer_to_bytearray(t["T_MEMDEPTHMAP"])
555         if libpr.zero_score_map_where_char_on_memdepthmap(c, map):
556             raise RuntimeError("No score map allocated for "
557                                "zero_score_map_where_char_on_memdepthmap().")
558
559     def set_map_score(pos, score):
560         test = libpr.set_map_score(pos, score)
561         if test:
562             raise RuntimeError("No score map allocated for set_map_score().")
563
564     def set_movement_cost_map():
565         copy_memmap = t["T_MEMMAP"][:]
566         copy_memmap.replace(b' ', b'4')
567         memmap = c_pointer_to_bytearray(copy_memmap)
568         if libpr.TCE_set_movement_cost_map(memmap):
569             raise RuntimeError("No movement cost map allocated for "
570                                "set_movement_cost_map().")
571
572     def animates_in_fov(maplength):
573         return [Thing for Thing in world_db["Things"].values()
574                 if Thing["T_LIFEPOINTS"] and 118 == t["fovmap"][Thing["pos"]]
575                 and (not Thing == t)]
576
577     def seeing_thing():
578         def exists(gen):
579             try:
580                 next(gen)
581             except StopIteration:
582                 return False
583             return True
584         mapsize = world_db["MAP_LENGTH"] ** 2
585         if target == "food" and t["T_MEMMAP"]:
586             return exists(pos for pos in range(mapsize)
587                            if ord("2") < t["T_MEMMAP"][pos] < ord("5"))
588         elif target == "fluid_certain" and t["fovmap"]:
589             return exists(pos for pos in range(mapsize)
590                            if t["fovmap"] == ord("v")
591                            if world_db["MAP"][pos] == ord("0")
592                            if world_db["wetmap"][pos] > ord("0"))
593         elif target == "crack" and t["T_MEMMAP"]:
594             return exists(pos for pos in range(mapsize)
595                            if t["T_MEMMAP"][pos] == ord("-"))
596         elif target == "fluid_potential" and t["T_MEMMAP"] and t["fovmap"]:
597             return exists(pos for pos in range(mapsize)
598                            if t["T_MEMMAP"][pos] == ord("0")
599                            if t["fovmap"] != ord("v"))
600         elif target == "space" and t["T_MEMMAP"] and t["fovmap"]:
601             return exists(pos for pos in range(mapsize)
602                           if ord("-") <= t["T_MEMMAP"][pos] <= ord("2")
603                           if (t["fovmap"] != ord("v")
604                               or world_db["terrain_fullness"](pos) < 5))
605         elif target in {"hunt", "flee"} and t["fovmap"]:
606             return exists(Thing for
607                           Thing in animates_in_fov(world_db["MAP_LENGTH"])) \
608                 or exists(pos for pos in range(mapsize)
609                           if world_db["soundmap"][pos] > ord("0")
610                           if t["fovmap"][pos] != ord("v"))
611         return False
612
613     def init_score_map():
614         mapsize = world_db["MAP_LENGTH"] ** 2
615         test = libpr.TCE_init_score_map()
616         [set_map_score(pos, 65535) for pos in range(mapsize)
617          if chr(t["T_MEMMAP"][pos]) in "5*&"]
618         set_movement_cost_map()
619         if test:
620             raise RuntimeError("Malloc error in init_score_map().")
621         if target == "food" and t["T_MEMMAP"]:
622             [set_map_score(pos, 0) for pos in range(mapsize)
623              if ord("2") < t["T_MEMMAP"][pos] < ord("5")]
624         elif target == "fluid_certain" and t["fovmap"]:
625             [set_map_score(pos, 0) for pos in range(mapsize)
626              if t["fovmap"] == ord("v")
627              if world_db["MAP"][pos] == ord("0")
628              if world_db["wetmap"][pos] > ord("0")]
629         elif target == "crack" and t["T_MEMMAP"]:
630             [set_map_score(pos, 0) for pos in range(mapsize)
631              if t["T_MEMMAP"][pos] == ord("-")]
632         elif target == "fluid_potential" and t["T_MEMMAP"] and t["fovmap"]:
633             [set_map_score(pos, 0) for pos in range(mapsize)
634              if t["T_MEMMAP"][pos] == ord("0")
635              if t["fovmap"] != ord("v")]
636         elif target == "space" and t["T_MEMMAP"] and t["fovmap"]:
637             [set_map_score(pos, 0) for pos in range(mapsize)
638              if ord("-") <= t["T_MEMMAP"][pos] <= ord("2")
639              if (t["fovmap"] != ord("v")
640                  or world_db["terrain_fullness"](pos) < 5)]
641         elif target == "search":
642             zero_score_map_where_char_on_memdepthmap(mem_depth_c[0])
643         elif target in {"hunt", "flee"}:
644             [set_map_score(Thing["pos"], 0) for
645              Thing in animates_in_fov(world_db["MAP_LENGTH"])]
646             [set_map_score(pos, 0) for pos in range(mapsize)
647              if world_db["soundmap"][pos] > ord("0")
648              if t["fovmap"][pos] != ord("v")]
649
650     def rand_target_dir(neighbors, cmp, dirs):
651         candidates = []
652         n_candidates = 0
653         for i in range(len(dirs)):
654             if cmp == neighbors[i]:
655                 candidates.append(dirs[i])
656                 n_candidates += 1
657         return candidates[rand.next() % n_candidates] if n_candidates else 0
658
659     def get_neighbor_scores(dirs, eye_pos):
660         scores = []
661         if libpr.ready_neighbor_scores(eye_pos):
662             raise RuntimeError("No score map allocated for " +
663                                "ready_neighbor_scores.()")
664         for i in range(len(dirs)):
665             scores.append(libpr.get_neighbor_score(i))
666         return scores
667
668     def get_dir_from_neighbors():
669         import math
670         dir_to_target = False
671         dirs = "edcxsw"
672         eye_pos = t["pos"]
673         neighbors = get_neighbor_scores(dirs, eye_pos)
674         minmax_start = 0 if "flee" == target else 65535 - 1
675         minmax_neighbor = minmax_start
676         for i in range(len(dirs)):
677             if ("flee" == target and get_map_score(t["pos"]) < neighbors[i] and
678                 minmax_neighbor < neighbors[i] and 65535 != neighbors[i]) \
679                or ("flee" != target and minmax_neighbor > neighbors[i]):
680                 minmax_neighbor = neighbors[i]
681         if minmax_neighbor != minmax_start:
682             dir_to_target = rand_target_dir(neighbors, minmax_neighbor, dirs)
683         if "flee" == target:
684             distance = get_map_score(t["pos"])
685             fear_distance = 5
686             attack_distance = 1
687             if not dir_to_target:
688                 if attack_distance >= distance:
689                     dir_to_target = rand_target_dir(neighbors,
690                                                     distance - 1, dirs)
691             elif dir_to_target and fear_distance < distance:
692                 dir_to_target = 0
693         return dir_to_target, minmax_neighbor
694
695     dir_to_target = False
696     mem_depth_c = b' '
697     run_i = 9 + 1 if "search" == target else 1
698     minmax_neighbor = 0
699     while run_i and not dir_to_target and \
700             ("search" == target or seeing_thing()):
701         run_i -= 1
702         init_score_map()
703         mem_depth_c = b'9' if b' ' == mem_depth_c \
704             else bytes([mem_depth_c[0] - 1])
705         if libpr.TCE_dijkstra_map_with_movement_cost():
706             raise RuntimeError("No score map allocated for dijkstra_map().")
707         dir_to_target, minmax_neighbor = get_dir_from_neighbors()
708         libpr.free_score_map()
709         if dir_to_target and str == type(dir_to_target):
710             action = "move"
711             from server.utils import mv_yx_in_dir_legal
712             move_result = mv_yx_in_dir_legal(dir_to_target, t["T_POSY"],
713                                                             t["T_POSX"])
714             if 1 != move_result[0]:
715                 return False, 0
716             pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
717             hitted = [tid for tid in world_db["Things"]
718                       if world_db["Things"][tid]["pos"] == pos]
719             if world_db["MAP"][pos] > ord("2") or len(hitted) > 0:
720                 action = "eat"
721             t["T_COMMAND"] = [taid for taid in world_db["ThingActions"]
722                               if world_db["ThingActions"][taid]["TA_NAME"]
723                               == action][0]
724             t["T_ARGUMENT"] = ord(dir_to_target)
725     return dir_to_target, minmax_neighbor
726 world_db["get_dir_to_target"] = get_dir_to_target
727
728
729 def terrain_fullness(pos):
730     wetness = world_db["wetmap"][pos] - ord("0")
731     if chr(world_db["MAP"][pos]) in "-+":
732         height = 0
733     else:
734         height = world_db["MAP"][pos] - ord("0")
735     return wetness + height
736 world_db["terrain_fullness"] = terrain_fullness
737
738
739 def ai(t):
740
741     if t["T_LIFEPOINTS"] == 0:
742         return
743
744     def standing_on_fluid(t):
745         if world_db["MAP"][t["pos"]] == ord("0") and \
746             world_db["wetmap"][t["pos"]] > ord("0"):
747                 return True
748         else:
749             return False
750
751     def thing_action_id(name):
752         return [taid for taid in world_db["ThingActions"]
753                 if world_db["ThingActions"][taid]
754                 ["TA_NAME"] == name][0]
755
756     t["T_COMMAND"] = thing_action_id("wait")
757     needs = {
758         "fix_cracks": 24,
759         "flee": 24,
760         "safe_pee": (world_db["terrain_fullness"](t["pos"]) * t["T_BLADDER"]) / 4,
761         "safe_drop": (world_db["terrain_fullness"](t["pos"]) * t["T_BOWEL"]) / 4,
762         "food": 33 - t["T_STOMACH"],
763         "fluid_certain": 33 - t["T_KIDNEY"],
764         "fluid_potential": 32 - t["T_KIDNEY"],
765         "search": 1,
766     }
767     from operator import itemgetter
768     needs = sorted(needs.items(), key=itemgetter(1,0))
769     needs.reverse()
770     for need in needs:
771         if need[1] > 0:
772             if need[0] == "fix_cracks":
773                 if world_db["MAP"][t["pos"]] == ord("-") and \
774                         t["T_BOWEL"] > 0 and \
775                         world_db["terrain_fullness"](t["pos"]) <= 3:
776                     t["T_COMMAND"] = thing_action_id("drop")
777                     return
778                 elif world_db["get_dir_to_target"](t, "crack"):
779                     return
780             if need[0] in {"fluid_certain", "fluid_potential"}:
781                 if standing_on_fluid(t):
782                     t["T_COMMAND"] = thing_action_id("drink")
783                     return
784                 elif t["T_BLADDER"] > 0 and \
785                          world_db["MAP"][t["pos"]] == ord("0"):
786                     t["T_COMMAND"] = thing_action_id("pee")
787                     return
788             elif need[0] in {"safe_pee", "safe_drop"}:
789                 action_name = need[0][len("safe_"):]
790                 if world_db["terrain_fullness"](t["pos"]) <= 3:
791                     t["T_COMMAND"] = thing_action_id(action_name)
792                     return
793                 test = world_db["get_dir_to_target"](t, "space")
794                 if test[0]:
795                     if test[1] < 5:
796                         return
797                     elif world_db["terrain_fullness"](t["pos"]) < 5:
798                         t["T_COMMAND"] = thing_action_id(action_name)
799                     return
800                 if t["T_STOMACH"] < 32 and \
801                         world_db["get_dir_to_target"](t, "food")[0]:
802                     return
803                 continue
804             if need[0] in {"fluid_certain", "fluid_potential", "food"}:
805                 if world_db["get_dir_to_target"](t, need[0])[0]:
806                     return
807                 elif world_db["get_dir_to_target"](t, "hunt")[0]:
808                     return
809                 elif need[0] != "food" and t["T_STOMACH"] < 32 and \
810                         world_db["get_dir_to_target"](t, "food")[0]:
811                     return
812             elif world_db["get_dir_to_target"](t, need[0])[0]:
813                 return
814 world_db["ai"] = ai
815
816
817 from server.config.io import io_db
818 io_db["worldstate_write_order"] += [["T_STOMACH", "player_int"]]
819 io_db["worldstate_write_order"] += [["T_KIDNEY", "player_int"]]
820 io_db["worldstate_write_order"] += [["T_BOWEL", "player_int"]]
821 io_db["worldstate_write_order"] += [["T_BLADDER", "player_int"]]
822 io_db["worldstate_write_order"] += [[write_wetmap, "func"]]
823 io_db["worldstate_write_order"] += [[write_soundmap, "func"]]
824 io_db["worldstate_write_order"] += [["GRACE", "world_int"]]
825 import server.config.world_data
826 server.config.world_data.symbols_hide = "345"
827 server.config.world_data.symbols_passable = "012-+*&$"
828 server.config.world_data.thing_defaults["T_STOMACH"] = 16
829 server.config.world_data.thing_defaults["T_BOWEL"] = 0
830 server.config.world_data.thing_defaults["T_KIDNEY"] = 16
831 server.config.world_data.thing_defaults["T_BLADDER"] = 0
832 world_db["soundmap"] = bytearray(b"0" * world_db["MAP_LENGTH"] ** 2)
833 world_db["wetmap"] = bytearray(b"0" * world_db["MAP_LENGTH"] ** 2)
834 if not "NEW_SPAWN" in world_db:
835     world_db["NEW_SPAWN"] = 0
836 if not "HUMIDITY" in world_db:
837     world_db["HUMIDITY"] = 0
838 if not "GRACE" in world_db:
839     world_db["GRACE"] = 0
840 io_db["hook_save"] = save_maps
841 import server.config.make_world_helpers
842 server.config.make_world_helpers.make_map = make_map
843 from server.config.commands import commands_db
844 commands_db["THINGS_HERE"] = (2, True, lambda x, y: None)
845 commands_db["HELP"] = (1, False, command_help)
846 commands_db["ai"] = (0, False, command_ai)
847 commands_db["move"] = (1, False, play_move)
848 commands_db["eat"] = (1, False, play_move)
849 commands_db["wait"] = (0, False, play_wait)
850 commands_db["drop"] = (0, False, play_drop)
851 commands_db["drink"] = (0, False, play_drink)
852 commands_db["pee"] = (0, False, play_pee)
853 commands_db["use"] = (1, False, lambda x: None)
854 commands_db["pickup"] = (0, False, lambda: None)
855 commands_db["GRACE"] = (1, False, setter(None, "GRACE", 0, 255))
856 commands_db["NEW_SPAWN"] = (1, False, setter(None, "NEW_SPAWN", 0, 255))
857 commands_db["HUMIDITY"] = (1, False, setter(None, "HUMIDITY", 0, 65535))
858 commands_db["T_STOMACH"] = (1, False, setter("Thing", "T_STOMACH", 0, 255))
859 commands_db["T_KIDNEY"] = (1, False, setter("Thing", "T_KIDNEY", 0, 255))
860 commands_db["T_BOWEL"] = (1, False, setter("Thing", "T_BOWEL", 0, 255))
861 commands_db["T_BLADDER"] = (1, False, setter("Thing", "T_BLADDER", 0, 255))
862 commands_db["WETMAP"] = (2, False, wetmapset)
863 commands_db["SOUNDMAP"] = (2, False, soundmapset)
864 from server.actions import actor_wait
865 import server.config.actions
866 server.config.actions.action_db = {
867     "actor_wait": actor_wait,
868     "actor_move": actor_move,
869     "actor_drop": actor_drop,
870     "actor_drink": actor_drink,
871     "actor_pee": actor_pee,
872     "actor_eat": actor_eat,
873 }
874
875 strong_write(io_db["file_out"], "PLUGIN TheCrawlingEater\n")