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