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