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