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