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