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.
6 from server.config.world_data import world_db
10 if action_exists("drink") and world_db["WORLD_ACTIVE"]:
11 pos = world_db["Things"][0]["pos"]
12 if not (chr(world_db["MAP"][pos]) == "0"
13 and world_db["wetmap"][pos] > ord("0")):
14 log("NOTHING to drink here.")
16 elif world_db["Things"][0]["T_KIDNEY"] >= 32:
17 log("You're too FULL to drink more.")
19 world_db["set_command"]("drink")
23 pos = world_db["Things"][0]["pos"]
24 if chr(world_db["MAP"][pos]) == "0" and \
25 world_db["wetmap"][pos] > ord("0") and t["T_KIDNEY"] < 32:
28 world_db["wetmap"][pos] -= 1
29 if world_db["wetmap"][pos] == ord("0"):
30 world_db["MAP"][pos] = ord("0")
34 if action_exists("pee") and world_db["WORLD_ACTIVE"]:
35 if world_db["Things"][0]["T_BLADDER"] < 1:
36 log("Nothing to drop from empty bladder.")
38 world_db["set_command"]("pee")
42 if t["T_BLADDER"] < 1:
44 if t == world_db["Things"][0]:
45 log("You LOSE fluid.")
46 if not world_db["test_air"](t):
49 world_db["wetmap"][t["pos"]] += 1
53 if action_exists("drop") and world_db["WORLD_ACTIVE"]:
54 if world_db["Things"][0]["T_BOWEL"] < 1:
55 log("Nothing to drop from empty bowel.")
57 world_db["set_command"]("drop")
63 if t == world_db["Things"][0]:
64 log("You DROP waste.")
65 if not world_db["test_air"](t):
67 world_db["MAP"][t["pos"]] += 1
71 def play_move(str_arg):
72 """Try "move" as player's T_COMMAND, str_arg as T_ARGUMENT / direction."""
73 if action_exists("move") and world_db["WORLD_ACTIVE"]:
74 from server.config.world_data import directions_db, symbols_passable
75 t = world_db["Things"][0]
76 if not str_arg in directions_db:
77 print("Illegal move direction string.")
79 d = ord(directions_db[str_arg])
80 from server.utils import mv_yx_in_dir_legal
81 move_result = mv_yx_in_dir_legal(chr(d), t["T_POSY"], t["T_POSX"])
82 if 1 == move_result[0]:
83 pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
84 if chr(world_db["MAP"][pos]) in "34":
85 if t["T_STOMACH"] >= 32:
86 if t == world_db["Things"][0]:
87 log("You're too FULL to eat.")
89 world_db["Things"][0]["T_ARGUMENT"] = d
90 world_db["set_command"]("eat")
92 if chr(world_db["MAP"][pos]) in symbols_passable:
93 world_db["Things"][0]["T_ARGUMENT"] = d
94 world_db["set_command"]("move")
96 log("You CAN'T eat your way through there.")
100 from server.utils import mv_yx_in_dir_legal, rand
101 from server.config.world_data import symbols_passable
103 move_result = mv_yx_in_dir_legal(chr(t["T_ARGUMENT"]),
104 t["T_POSY"], t["T_POSX"])
105 if 1 == move_result[0]:
106 pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
107 #hitted = [tid for tid in world_db["Things"]
108 # if world_db["Things"][tid] != t
109 # if world_db["Things"][tid]["T_LIFEPOINTS"]
110 # if world_db["Things"][tid]["T_POSY"] == move_result[1]
111 # if world_db["Things"][tid]["T_POSX"] == move_result[2]]
114 # hitted_tid = world_db["Things"][hit_id]["T_TYPE"]
115 # if t == world_db["Things"][0]:
116 # hitted_name = world_db["ThingTypes"][hitted_tid]["TT_NAME"]
117 # log("You BUMP into " + hitted_name + ".")
119 # hitter_name = world_db["ThingTypes"][t["T_TYPE"]]["TT_NAME"]
120 # log(hitter_name +" BUMPS into you.")
122 passable = chr(world_db["MAP"][pos]) in symbols_passable
124 log("You try to EAT, but fail.")
126 height = world_db["MAP"][pos] - ord("0")
127 if t["T_STOMACH"] >= 32 or height == 5:
131 eaten = (height == 3 and 0 == int(rand.next() % 2)) or \
132 (height == 4 and 0 == int(rand.next() % 5))
134 world_db["MAP"][pos] = ord("0")
135 if t["T_STOMACH"] > 32:
140 from server.build_fov_map import build_fov_map
141 from server.utils import mv_yx_in_dir_legal, rand
142 from server.config.world_data import symbols_passable
144 move_result = mv_yx_in_dir_legal(chr(t["T_ARGUMENT"]),
145 t["T_POSY"], t["T_POSX"])
146 if 1 == move_result[0]:
147 pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
148 #hitted = [tid for tid in world_db["Things"]
149 # if world_db["Things"][tid] != t
150 # if world_db["Things"][tid]["T_LIFEPOINTS"]
151 # if world_db["Things"][tid]["T_POSY"] == move_result[1]
152 # if world_db["Things"][tid]["T_POSX"] == move_result[2]]
155 # hitted_tid = world_db["Things"][hit_id]["T_TYPE"]
156 # if t == world_db["Things"][0]:
157 # hitted_name = world_db["ThingTypes"][hitted_tid]["TT_NAME"]
158 # log("You BUMP into " + hitted_name + ".")
160 # hitter_name = world_db["ThingTypes"][t["T_TYPE"]]["TT_NAME"]
161 # log(hitter_name +" BUMPS into you.")
163 passable = chr(world_db["MAP"][pos]) in symbols_passable
165 t["T_POSY"] = move_result[1]
166 t["T_POSX"] = move_result[2]
167 t["pos"] = move_result[1] * world_db["MAP_LENGTH"] + move_result[2]
170 log("You try to MOVE there, but fail.")
174 if world_db["MAP"][t["pos"]] == ord("-"):
175 world_db["die"](t, "You FALL in a hole, and die.")
178 world_db["test_hole"] = test_hole
182 if world_db["terrain_fullness"](t["pos"]) > 5:
183 world_db["die"](t, "You SUFFOCATE")
186 world_db["test_air"] = test_air
190 t["T_LIFEPOINTS"] = 0
191 if t == world_db["Things"][0]:
192 t["fovmap"] = bytearray(b' ' * (world_db["MAP_LENGTH"] ** 2))
193 t["T_MEMMAP"][t["pos"]] = ord("@")
195 world_db["die"] = die
199 from server.make_map import new_pos, is_neighbor
200 from server.utils import rand
201 world_db["MAP"] = bytearray(b'5' * (world_db["MAP_LENGTH"] ** 2))
202 length = world_db["MAP_LENGTH"]
203 add_half_width = (not (length % 2)) * int(length / 2)
204 world_db["MAP"][int((length ** 2) / 2) + add_half_width] = ord("4")
206 y, x, pos = new_pos()
207 if "5" == chr(world_db["MAP"][pos]) and is_neighbor((y, x), "4"):
208 if y == 0 or y == (length - 1) or x == 0 or x == (length - 1):
210 world_db["MAP"][pos] = ord("4")
211 n_ground = int((length ** 2) / 16)
213 while (i_ground <= n_ground):
214 single_allowed = rand.next() % 32
215 y, x, pos = new_pos()
216 if "4" == chr(world_db["MAP"][pos]) \
217 and ((not single_allowed) or is_neighbor((y, x), "0")):
218 world_db["MAP"][pos] = ord("0")
220 n_water = int((length ** 2) / 64)
222 while (i_water <= n_water):
223 y, x, pos = new_pos()
224 if ord("0") == world_db["MAP"][pos] and \
225 ord("0") == world_db["wetmap"][pos]:
226 world_db["wetmap"][pos] = ord("3")
230 def calc_effort(ta, t):
231 from server.utils import mv_yx_in_dir_legal
232 if ta["TA_NAME"] == "move":
233 move_result = mv_yx_in_dir_legal(chr(t["T_ARGUMENT"]),
234 t["T_POSY"], t["T_POSX"])
235 if 1 == move_result[0]:
236 pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
237 narrowness = world_db["MAP"][pos] - ord("0")
238 return 2 ** narrowness
240 world_db["calc_effort"] = calc_effort
244 from server.ai import ai
245 from server.config.actions import action_db
246 from server.update_map_memory import update_map_memory
247 from server.io import try_worldstate_update
248 from server.config.io import io_db
249 from server.utils import rand
250 while world_db["Things"][0]["T_LIFEPOINTS"]:
251 for tid in [tid for tid in world_db["Things"]]:
252 if not tid in world_db["Things"]:
254 t = world_db["Things"][tid]
255 if t["T_LIFEPOINTS"]:
256 if not (world_db["test_air"](t) and world_db["test_hole"](t)):
258 if not t["T_COMMAND"]:
263 if t["T_LIFEPOINTS"]:
265 taid = [a for a in world_db["ThingActions"]
266 if a == t["T_COMMAND"]][0]
267 ThingAction = world_db["ThingActions"][taid]
268 effort = world_db["calc_effort"](ThingAction, t)
269 if t["T_PROGRESS"] >= effort:
270 action = action_db["actor_" + ThingAction["TA_NAME"]]
274 if t["T_BOWEL"] > 16:
275 if 0 == (rand.next() % (33 - t["T_BOWEL"])):
276 action_db["actor_drop"](t)
277 if t["T_BLADDER"] > 16:
278 if 0 == (rand.next() % (33 - t["T_BLADDER"])):
279 action_db["actor_pee"](t)
280 if 0 == world_db["TURN"] % 5:
285 if t["T_STOMACH"] <= 0:
286 world_db["die"](t, "You DIE of hunger.")
287 elif t["T_KIDNEY"] <= 0:
288 world_db["die"](t, "You DIE of dehydration.")
289 positions_to_wet = []
290 i_positions_to_wet = len(positions_to_wet)
291 for pos in range(world_db["MAP_LENGTH"] ** 2):
292 wetness = world_db["wetmap"][pos] - ord("0")
293 height = world_db["MAP"][pos] - ord("0")
294 if height == 0 and wetness > 0 \
295 and 0 == rand.next() % ((2 ** 13) / (2 ** wetness)):
296 world_db["MAP"][pos] = ord("-")
297 if ((wetness > 0 and height != 0) or wetness > 1) \
298 and 0 == rand.next() % 5:
299 world_db["wetmap"][pos] -= 1
300 world_db["HUMIDITY"] += 1
301 i_positions_to_wet -= 1
302 if world_db["HUMIDITY"] > 0:
303 for pos in range(world_db["MAP_LENGTH"] ** 2):
304 if world_db["MAP"][pos] == ord("0") \
305 and world_db["wetmap"][pos] < ord("5"):
306 positions_to_wet += [pos]
307 while world_db["HUMIDITY"] > 0 and len(positions_to_wet) > 0:
308 select = rand.next() % len(positions_to_wet)
309 pos = positions_to_wet[select]
310 world_db["wetmap"][pos] += 1
311 positions_to_wet.remove(pos)
312 world_db["HUMIDITY"] -= 1
313 world_db["TURN"] += 1
314 io_db["worldstate_updateable"] = True
315 try_worldstate_update()
316 world_db["turn_over"] = turn_over
320 """Call ai() on player Thing, then turn_over()."""
321 from server.ai import ai
322 if world_db["WORLD_ACTIVE"]:
323 ai(world_db["Things"][0])
324 world_db["turn_over"]()
327 def set_command(action):
328 """Set player's T_COMMAND, then call turn_over()."""
329 tid = [x for x in world_db["ThingActions"]
330 if world_db["ThingActions"][x]["TA_NAME"] == action][0]
331 world_db["Things"][0]["T_COMMAND"] = tid
332 world_db["turn_over"]()
333 world_db["set_command"] = set_command
337 """Try "wait" as player's T_COMMAND."""
338 if world_db["WORLD_ACTIVE"]:
339 world_db["set_command"]("wait")
343 length = world_db["MAP_LENGTH"]
345 for i in range(length):
346 line = world_db["wetmap"][i * length:(i * length) + length].decode()
347 string = string + "WETMAP" + " " + str(i) + " " + line + "\n"
351 def wetmapset(str_int, mapline):
352 def valid_map_line(str_int, mapline):
353 from server.utils import integer_test
354 val = integer_test(str_int, 0, 255)
356 if val >= world_db["MAP_LENGTH"]:
357 print("Illegal value for map line number.")
358 elif len(mapline) != world_db["MAP_LENGTH"]:
359 print("Map line length is unequal map width.")
363 val = valid_map_line(str_int, mapline)
365 length = world_db["MAP_LENGTH"]
366 if not world_db["wetmap"]:
367 m = bytearray(b' ' * (length ** 2))
369 m = world_db["wetmap"]
370 m[val * length:(val * length) + length] = mapline.encode()
371 if not world_db["wetmap"]:
372 world_db["wetmap"] = m
375 from server.worldstate_write_helpers import write_map
376 length = world_db["MAP_LENGTH"]
377 visible_wetmap = bytearray(b' ' * (length ** 2))
378 for i in range(length ** 2):
379 if world_db["Things"][0]["fovmap"][i] == ord('v'):
380 visible_wetmap[i] = world_db["wetmap"][i]
381 return write_map(visible_wetmap, world_db["MAP_LENGTH"])
385 if world_db["WORLD_ACTIVE"]:
386 world_db["ai"](world_db["Things"][0])
387 world_db["turn_over"]()
390 def get_dir_to_target(t, target):
392 from server.utils import rand, libpr, c_pointer_to_bytearray
393 from server.config.world_data import symbols_passable
395 def zero_score_map_where_char_on_memdepthmap(c):
396 map = c_pointer_to_bytearray(t["T_MEMDEPTHMAP"])
397 if libpr.zero_score_map_where_char_on_memdepthmap(c, map):
398 raise RuntimeError("No score map allocated for "
399 "zero_score_map_where_char_on_memdepthmap().")
401 def set_map_score(pos, score):
402 test = libpr.set_map_score(pos, score)
404 raise RuntimeError("No score map allocated for set_map_score().")
406 def set_movement_cost_map():
407 memmap = c_pointer_to_bytearray(t["T_MEMMAP"])
408 if libpr.TCE_set_movement_cost_map(memmap):
409 raise RuntimeError("No movement cost map allocated for "
410 "set_movement_cost_map().")
416 except StopIteration:
419 mapsize = world_db["MAP_LENGTH"] ** 2
420 if target == "food" and t["T_MEMMAP"]:
421 return exists(pos for pos in range(mapsize)
422 if ord("2") < t["T_MEMMAP"][pos] < ord("5"))
423 elif target == "fluid_certain" and t["fovmap"]:
424 return exists(pos for pos in range(mapsize)
425 if t["fovmap"] == ord("v")
426 if world_db["MAP"][pos] == ord("0")
427 if world_db["wetmap"][pos] > ord("0"))
428 elif target == "fluid_potential" and t["T_MEMMAP"] and t["fovmap"]:
429 return exists(pos for pos in range(mapsize)
430 if t["T_MEMMAP"][pos] == ord("0")
431 if t["fovmap"] != ord("v"))
432 elif target == "space" and t["T_MEMMAP"] and t["fovmap"]:
433 return exists(pos for pos in range(mapsize)
434 if ord("0") <= t["T_MEMMAP"][pos] <= ord("2")
435 if (t["fovmap"] != ord("v")
436 or world_db["terrain_fullness"](pos) < 5))
439 def init_score_map():
440 test = libpr.init_score_map()
441 set_movement_cost_map()
442 mapsize = world_db["MAP_LENGTH"] ** 2
444 raise RuntimeError("Malloc error in init_score_map().")
445 if target == "food" and t["T_MEMMAP"]:
446 [set_map_score(pos, 0) for pos in range(mapsize)
447 if ord("2") < t["T_MEMMAP"][pos] < ord("5")]
448 elif target == "fluid_certain" and t["fovmap"]:
449 [set_map_score(pos, 0) for pos in range(mapsize)
450 if t["fovmap"] == ord("v")
451 if world_db["MAP"][pos] == ord("0")
452 if world_db["wetmap"][pos] > ord("0")]
453 elif target == "fluid_potential" and t["T_MEMMAP"] and t["fovmap"]:
454 [set_map_score(pos, 0) for pos in range(mapsize)
455 if t["T_MEMMAP"][pos] == ord("0")
456 if t["fovmap"] != ord("v")]
457 elif target == "space" and t["T_MEMMAP"] and t["fovmap"]:
458 [set_map_score(pos, 0) for pos in range(mapsize)
459 if ord("0") <= t["T_MEMMAP"][pos] <= ord("2")
460 if (t["fovmap"] != ord("v")
461 or world_db["terrain_fullness"](pos) < 5)]
462 elif target == "search":
463 zero_score_map_where_char_on_memdepthmap(mem_depth_c[0])
465 def rand_target_dir(neighbors, cmp, dirs):
468 for i in range(len(dirs)):
469 if cmp == neighbors[i]:
470 candidates.append(dirs[i])
472 return candidates[rand.next() % n_candidates] if n_candidates else 0
474 def get_neighbor_scores(dirs, eye_pos):
476 if libpr.ready_neighbor_scores(eye_pos):
477 raise RuntimeError("No score map allocated for " +
478 "ready_neighbor_scores.()")
479 for i in range(len(dirs)):
480 scores.append(libpr.get_neighbor_score(i))
483 def get_dir_from_neighbors():
485 dir_to_target = False
488 neighbors = get_neighbor_scores(dirs, eye_pos)
489 minmax_start = 65535 - 1
490 minmax_neighbor = minmax_start
491 for i in range(len(dirs)):
492 if minmax_neighbor > neighbors[i]:
493 minmax_neighbor = neighbors[i]
494 if minmax_neighbor != minmax_start:
495 dir_to_target = rand_target_dir(neighbors, minmax_neighbor, dirs)
496 return dir_to_target, minmax_neighbor
498 dir_to_target = False
500 run_i = 9 + 1 if "search" == target else 1
502 while run_i and not dir_to_target and \
503 ("search" == target or seeing_thing()):
506 mem_depth_c = b'9' if b' ' == mem_depth_c \
507 else bytes([mem_depth_c[0] - 1])
508 if libpr.TCE_dijkstra_map_with_movement_cost():
509 raise RuntimeError("No score map allocated for dijkstra_map().")
510 dir_to_target, minmax_neighbor = get_dir_from_neighbors()
511 libpr.free_score_map()
512 if dir_to_target and str == type(dir_to_target):
514 from server.utils import mv_yx_in_dir_legal
515 move_result = mv_yx_in_dir_legal(dir_to_target, t["T_POSY"],
517 if 1 != move_result[0]:
519 pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
520 if world_db["MAP"][pos] > ord("2"):
522 t["T_COMMAND"] = [taid for taid in world_db["ThingActions"]
523 if world_db["ThingActions"][taid]["TA_NAME"]
525 t["T_ARGUMENT"] = ord(dir_to_target)
526 return dir_to_target, minmax_neighbor
527 world_db["get_dir_to_target"] = get_dir_to_target
530 def terrain_fullness(pos):
531 return (world_db["MAP"][pos] - ord("0")) + \
532 (world_db["wetmap"][pos] - ord("0"))
533 world_db["terrain_fullness"] = terrain_fullness
538 if t["T_LIFEPOINTS"] == 0:
541 def standing_on_fluid(t):
542 if world_db["MAP"][t["pos"]] == ord("0") and \
543 world_db["wetmap"][t["pos"]] > ord("0"):
548 def thing_action_id(name):
549 return [taid for taid in world_db["ThingActions"]
550 if world_db["ThingActions"][taid]
551 ["TA_NAME"] == name][0]
553 t["T_COMMAND"] = thing_action_id("wait")
555 "safe_pee": (world_db["terrain_fullness"](t["pos"]) * t["T_BLADDER"]) / 4,
556 "safe_drop": (world_db["terrain_fullness"](t["pos"]) * t["T_BOWEL"]) / 4,
557 "food": 33 - t["T_STOMACH"],
558 "fluid_certain": 33 - t["T_KIDNEY"],
559 "fluid_potential": 32 - t["T_KIDNEY"],
562 from operator import itemgetter
563 needs = sorted(needs.items(), key=itemgetter(1,0))
567 if need[0] in {"fluid_certain", "fluid_potential"}:
568 if standing_on_fluid(t):
569 t["T_COMMAND"] = thing_action_id("drink")
571 elif t["T_BLADDER"] > 0 and \
572 world_db["MAP"][t["pos"]] == ord("0"):
573 t["T_COMMAND"] = thing_action_id("pee")
575 elif need[0] in {"safe_pee", "safe_drop"}:
576 action_name = need[0][len("safe_"):]
577 if world_db["terrain_fullness"](t["pos"]) < 4:
578 t["T_COMMAND"] = thing_action_id(action_name)
581 test = world_db["get_dir_to_target"](t, "space")
583 if (not test[1] < 5) and \
584 world_db["terrain_fullness"](t["pos"]) < 5:
585 t["T_COMMAND"] = thing_action_id(action_name)
587 if t["T_STOMACH"] < 32 and \
588 world_db["get_dir_to_target"](t, "food")[0]:
591 if world_db["get_dir_to_target"](t, need[0])[0]:
593 elif t["T_STOMACH"] < 32 and \
594 need[0] in {"fluid_certain", "fluid_potential"} and \
595 world_db["get_dir_to_target"](t, "food")[0]:
600 from server.config.io import io_db
601 io_db["worldstate_write_order"] += [["T_STOMACH", "player_int"]]
602 io_db["worldstate_write_order"] += [["T_KIDNEY", "player_int"]]
603 io_db["worldstate_write_order"] += [["T_BOWEL", "player_int"]]
604 io_db["worldstate_write_order"] += [["T_BLADDER", "player_int"]]
605 io_db["worldstate_write_order"] += [[write_wetmap, "func"]]
606 import server.config.world_data
607 server.config.world_data.symbols_hide = "345"
608 server.config.world_data.symbols_passable = "012-"
609 server.config.world_data.thing_defaults["T_STOMACH"] = 16
610 server.config.world_data.thing_defaults["T_BOWEL"] = 0
611 server.config.world_data.thing_defaults["T_KIDNEY"] = 16
612 server.config.world_data.thing_defaults["T_BLADDER"] = 0
613 world_db["wetmap"] = bytearray(b"0" * world_db["MAP_LENGTH"] ** 2)
614 if not "HUMIDITY" in world_db:
615 world_db["HUMIDITY"] = 0
616 io_db["hook_save"] = save_wetmap
617 import server.config.make_world_helpers
618 server.config.make_world_helpers.make_map = make_map
619 from server.config.commands import commands_db
620 commands_db["THINGS_HERE"] = (2, True, lambda x, y: None)
621 commands_db["ai"] = (0, False, command_ai)
622 commands_db["move"] = (1, False, play_move)
623 commands_db["eat"] = (1, False, play_move)
624 commands_db["wait"] = (0, False, play_wait)
625 commands_db["drop"] = (0, False, play_drop)
626 commands_db["drink"] = (0, False, play_drink)
627 commands_db["pee"] = (0, False, play_pee)
628 commands_db["use"] = (1, False, lambda x: None)
629 commands_db["pickup"] = (0, False, lambda: None)
630 commands_db["HUMIDITY"] = (1, False, setter(None, "HUMIDITY", 0, 65535))
631 commands_db["T_STOMACH"] = (1, False, setter("Thing", "T_STOMACH", 0, 255))
632 commands_db["T_KIDNEY"] = (1, False, setter("Thing", "T_KIDNEY", 0, 255))
633 commands_db["T_BOWEL"] = (1, False, setter("Thing", "T_BOWEL", 0, 255))
634 commands_db["T_BLADDER"] = (1, False, setter("Thing", "T_BLADDER", 0, 255))
635 commands_db["WETMAP"] = (2, False, wetmapset)
636 from server.actions import actor_wait
637 import server.config.actions
638 server.config.actions.action_db = {
639 "actor_wait": actor_wait,
640 "actor_move": actor_move,
641 "actor_drop": actor_drop,
642 "actor_drink": actor_drink,
643 "actor_pee": actor_pee,
644 "actor_eat": actor_eat,
647 strong_write(io_db["file_out"], "PLUGIN TheCrawlingEater\n")