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