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