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
7 from server.config.io import io_db
8 from server.io import log, strong_write
9 from server.utils import integer_test, id_setter
10 from server.world import set_world_inactive, turn_over
11 from server.update_map_memory import update_map_memory
12 from server.build_fov_map import build_fov_map
15 def command_plugin(str_plugin):
16 """Run code in plugins/[str_plugin]."""
18 if (str_plugin.replace("_", "").isalnum()
19 and os.access("plugins/server/" + str_plugin + ".py", os.F_OK)):
20 exec(open("plugins/server/" + str_plugin + ".py").read())
21 world_db["PLUGIN"] += [str_plugin]
23 print("Bad plugin name:", str_plugin)
27 """Send PONG line to server output file."""
28 strong_write(io_db["file_out"], "PONG\n")
32 """Abort server process."""
33 from server.io import save_world, atomic_write
34 from server.utils import opts
35 if None == opts.replay:
36 if world_db["WORLD_ACTIVE"]:
38 atomic_write(io_db["path_record"], io_db["record_chunk"],
40 raise SystemExit("received QUIT command")
43 def command_thingshere(str_y, str_x):
44 """Write to out file list of Things known to player at coordinate y, x."""
45 if world_db["WORLD_ACTIVE"]:
46 y = integer_test(str_y, 0, 255)
47 x = integer_test(str_x, 0, 255)
48 length = world_db["MAP_LENGTH"]
49 if None != y and None != x and y < length and x < length:
50 pos = (y * world_db["MAP_LENGTH"]) + x
51 strong_write(io_db["file_out"], "THINGS_HERE START\n")
52 terrain = chr(world_db["Things"][0]["T_MEMMAP"][pos])
53 terrain_name = world_db["terrain_names"][terrain]
54 strong_write(io_db["file_out"], "terrain: " + terrain_name + "\n")
55 if "v" == chr(world_db["Things"][0]["fovmap"][pos]):
56 for id in [id for tid in sorted(list(world_db["ThingTypes"]))
57 for id in world_db["Things"]
58 if not world_db["Things"][id]["carried"]
59 if world_db["Things"][id]["T_TYPE"] == tid
60 if y == world_db["Things"][id]["T_POSY"]
61 if x == world_db["Things"][id]["T_POSX"]]:
62 type = world_db["Things"][id]["T_TYPE"]
63 name = world_db["ThingTypes"][type]["TT_NAME"]
64 strong_write(io_db["file_out"], name + "\n")
66 for mt in [mt for tid in sorted(list(world_db["ThingTypes"]))
67 for mt in world_db["Things"][0]["T_MEMTHING"]
68 if mt[0] == tid if y == mt[1] if x == mt[2]]:
69 name = world_db["ThingTypes"][mt[0]]["TT_NAME"]
70 strong_write(io_db["file_out"], name + "\n")
71 strong_write(io_db["file_out"], "THINGS_HERE END\n")
73 print("Ignoring: Invalid map coordinates.")
75 print("Ignoring: Command only works on existing worlds.")
78 def command_seedrandomness(seed_string):
79 """Set rand seed to int(seed_string)."""
80 from server.utils import rand
81 val = integer_test(seed_string, 0, 4294967295)
86 def command_makeworld(seed_string):
87 """Call make_world()."""
88 val = integer_test(seed_string, 0, 4294967295)
90 from server.make_world import make_world
94 def command_maplength(maplength_string):
95 """Redefine map length. Invalidate map, therefore lose all things on it."""
96 val = integer_test(maplength_string, 1, 256)
98 from server.utils import libpr
99 world_db["MAP_LENGTH"] = val
100 world_db["MAP"] = False
102 world_db["Things"] = {}
103 libpr.set_maplength(val)
106 def command_worldactive(worldactive_string):
107 """Toggle world_db["WORLD_ACTIVE"] if possible.
109 An active world can always be set inactive. An inactive world can only be
110 set active with a "wait" ThingAction, and a player Thing (of ID 0), and a
111 map. On activation, rebuild all Things' FOVs, and the player's map memory.
113 val = integer_test(worldactive_string, 0, 1)
115 if 0 != world_db["WORLD_ACTIVE"]:
119 print("World already active.")
120 elif 0 == world_db["WORLD_ACTIVE"]:
121 for ThingAction in world_db["ThingActions"]:
122 if "wait" == world_db["ThingActions"][ThingAction]["TA_NAME"]:
125 print("Ignored: No wait action defined for world to activate.")
127 for Thing in world_db["Things"]:
131 print("Ignored: No player defined for world to activate.")
134 for id in world_db["Things"]:
135 if world_db["Things"][id]["T_LIFEPOINTS"]:
136 build_fov_map(world_db["Things"][id])
138 update_map_memory(world_db["Things"][id], False)
139 if not world_db["Things"][0]["T_LIFEPOINTS"]:
140 empty_fovmap = bytearray(b" " * world_db["MAP_LENGTH"] ** 2)
141 world_db["Things"][0]["fovmap"] = empty_fovmap
142 world_db["WORLD_ACTIVE"] = 1
144 print("Ignoring: No map defined for world to activate.")
147 def command_tid(id_string):
148 """Set ID of Thing to manipulate. ID unused? Create new one.
150 Default new Thing's type to the first available ThingType, others: zero.
152 tid = id_setter(id_string, "Things", command_tid)
154 if world_db["ThingTypes"] == {}:
155 print("Ignoring: No ThingType to settle new Thing in.")
157 ty = list(world_db["ThingTypes"].keys())[0]
158 from server.new_thing import new_Thing
159 world_db["Things"][tid] = new_Thing(ty)
162 def command_ttid(id_string):
163 """Set ID of ThingType to manipulate. ID unused? Create new one.
165 Set new type's TT_CORPSE_ID to self, other fields to thingtype_defaults.
167 ttid = id_setter(id_string, "ThingTypes", command_ttid)
169 from server.config.world_data import thingtype_defaults
170 world_db["ThingTypes"][ttid] = {}
171 for key in thingtype_defaults:
172 world_db["ThingTypes"][ttid][key] = thingtype_defaults[key]
173 world_db["ThingTypes"][ttid]["TT_CORPSE_ID"] = ttid
176 def command_taid(id_string):
177 """Set ID of ThingAction to manipulate. ID unused? Create new one.
179 Default new ThingAction's TA_EFFORT to 1, its TA_NAME to "wait".
181 taid = id_setter(id_string, "ThingActions", command_taid, True)
183 world_db["ThingActions"][taid] = {
189 def test_for_id_maker(object, category):
190 """Return decorator testing for object having "id" attribute."""
193 if hasattr(object, "id"):
196 print("Ignoring: No " + category +
197 " defined to manipulate yet.")
202 test_Thing_id = test_for_id_maker(command_tid, "Thing")
203 test_ThingType_id = test_for_id_maker(command_ttid, "ThingType")
204 test_ThingAction_id = test_for_id_maker(command_taid, "ThingAction")
208 def command_tcommand(str_int):
209 """Set T_COMMAND of selected Thing."""
210 val = integer_test(str_int, 0)
212 if 0 == val or val in world_db["ThingActions"]:
213 world_db["Things"][command_tid.id]["T_COMMAND"] = val
215 print("Ignoring: ThingAction ID belongs to no known ThingAction.")
219 def command_ttype(str_int):
220 """Set T_TYPE of selected Thing."""
221 val = integer_test(str_int, 0)
223 if val in world_db["ThingTypes"]:
224 world_db["Things"][command_tid.id]["T_TYPE"] = val
226 print("Ignoring: ThingType ID belongs to no known ThingType.")
230 def command_tcarries(str_int):
231 """Append int(str_int) to T_CARRIES of selected Thing.
233 The ID int(str_int) must not be of the selected Thing, and must belong to a
234 Thing with unset "carried" flag. Its "carried" flag will be set on owning.
236 val = integer_test(str_int, 0)
238 if val == command_tid.id:
239 print("Ignoring: Thing cannot carry itself.")
240 elif val in world_db["Things"] \
241 and not world_db["Things"][val]["carried"]:
242 world_db["Things"][command_tid.id]["T_CARRIES"].append(val)
243 world_db["Things"][val]["carried"] = True
245 print("Ignoring: Thing not available for carrying.")
246 # Note that the whole carrying structure is different from the C version:
247 # Carried-ness is marked by a "carried" flag, not by Things containing
252 def command_tmemthing(str_t, str_y, str_x):
253 """Add (int(str_t), int(str_y), int(str_x)) to selected Thing's T_MEMTHING.
255 The type must fit to an existing ThingType, and the position into the map.
257 type = integer_test(str_t, 0)
258 posy = integer_test(str_y, 0, 255)
259 posx = integer_test(str_x, 0, 255)
260 if None != type and None != posy and None != posx:
261 if type not in world_db["ThingTypes"] \
262 or posy >= world_db["MAP_LENGTH"] or posx >= world_db["MAP_LENGTH"]:
263 print("Ignoring: Illegal value for thing type or position.")
265 memthing = (type, posy, posx)
266 world_db["Things"][command_tid.id]["T_MEMTHING"].append(memthing)
270 def command_ttname(name):
271 """Set TT_NAME of selected ThingType."""
272 world_db["ThingTypes"][command_ttid.id]["TT_NAME"] = name
276 def command_tttool(name):
277 """Set TT_TOOL of selected ThingType."""
278 world_db["ThingTypes"][command_ttid.id]["TT_TOOL"] = name
282 def command_ttsymbol(char):
283 """Set TT_SYMBOL of selected ThingType. """
285 world_db["ThingTypes"][command_ttid.id]["TT_SYMBOL"] = char
287 print("Ignoring: Argument must be single character.")
291 def command_ttcorpseid(str_int):
292 """Set TT_CORPSE_ID of selected ThingType."""
293 val = integer_test(str_int, 0)
295 if val in world_db["ThingTypes"]:
296 world_db["ThingTypes"][command_ttid.id]["TT_CORPSE_ID"] = val
298 print("Ignoring: Corpse ID belongs to no known ThignType.")
302 def command_taname(name):
303 """Set TA_NAME of selected ThingAction.
305 The name must match a valid thing action function. If after the name
306 setting no ThingAction with name "wait" remains, call set_world_inactive().
308 if name == "wait" or name == "move" or name == "use" or name == "drop" \
310 world_db["ThingActions"][command_taid.id]["TA_NAME"] = name
311 if 1 == world_db["WORLD_ACTIVE"]:
312 for id in world_db["ThingActions"]:
313 if "wait" == world_db["ThingActions"][id]["TA_NAME"]:
318 print("Ignoring: Invalid action name.")
321 def setter(category, key, min, max=None):
322 """Build setter for world_db([category + "s"][id])[key] to >=min/<=max."""
325 val = integer_test(val_string, min, max)
329 if category == "Thing":
330 id_store = command_tid
331 decorator = test_Thing_id
332 elif category == "ThingType":
333 id_store = command_ttid
334 decorator = test_ThingType_id
335 elif category == "ThingAction":
336 id_store = command_taid
337 decorator = test_ThingAction_id
341 val = integer_test(val_string, min, max)
343 world_db[category + "s"][id_store.id][key] = val
347 def setter_map(maptype):
348 """Set (world or Thing's) map of maptype's int(str_int)-th line to mapline.
350 If no map of maptype exists yet, initialize it with ' ' bytes first.
353 def valid_map_line(str_int, mapline):
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.")
364 def nonThingMap_helper(str_int, mapline):
365 val = valid_map_line(str_int, mapline)
367 length = world_db["MAP_LENGTH"]
368 if not world_db["MAP"]:
369 map = bytearray(b' ' * (length ** 2))
371 map = world_db["MAP"]
372 map[val * length:(val * length) + length] = mapline.encode()
373 if not world_db["MAP"]:
374 world_db["MAP"] = map
377 def ThingMap_helper(str_int, mapline):
378 val = valid_map_line(str_int, mapline)
380 length = world_db["MAP_LENGTH"]
381 if not world_db["Things"][command_tid.id][maptype]:
382 map = bytearray(b' ' * (length ** 2))
384 map = world_db["Things"][command_tid.id][maptype]
385 map[val * length:(val * length) + length] = mapline.encode()
386 if not world_db["Things"][command_tid.id][maptype]:
387 world_db["Things"][command_tid.id][maptype] = map
389 return nonThingMap_helper if maptype == "MAP" else ThingMap_helper
393 def setter_tpos(axis):
394 """Generate setter for T_POSX or T_POSY of selected Thing.
396 If world is active, rebuilds animate things' fovmap, player's memory map.
400 val = integer_test(str_int, 0, 255)
402 if val < world_db["MAP_LENGTH"]:
403 world_db["Things"][command_tid.id]["T_POS" + axis] = val
404 if world_db["WORLD_ACTIVE"] \
405 and world_db["Things"][command_tid.id]["T_LIFEPOINTS"]:
406 build_fov_map(world_db["Things"][command_tid.id])
407 if 0 == command_tid.id:
408 update_map_memory(world_db["Things"][command_tid.id])
410 print("Ignoring: Position is outside of map.")
414 def set_command(action):
415 """Set player's T_COMMAND, then call turn_over()."""
416 id = [x for x in world_db["ThingActions"]
417 if world_db["ThingActions"][x]["TA_NAME"] == action][0]
418 world_db["Things"][0]["T_COMMAND"] = id
423 """Try "wait" as player's T_COMMAND."""
427 def action_exists(action):
428 matching_actions = [x for x in world_db["ThingActions"]
429 if world_db["ThingActions"][x]["TA_NAME"] == action]
430 if len(matching_actions) >= 1:
432 print("No appropriate ThingAction defined.")
437 """Try "pickup" as player's T_COMMAND"."""
438 if action_exists("pickup"):
439 t = world_db["Things"][0]
440 ids = [id for id in world_db["Things"] if id
441 if not world_db["Things"][id]["carried"]
442 if world_db["Things"][id]["T_POSY"] == t["T_POSY"]
443 if world_db["Things"][id]["T_POSX"] == t["T_POSX"]]
445 log("NOTHING to pick up.")
447 set_command("pickup")
450 def play_drop(str_arg):
451 """Try "drop" as player's T_COMMAND, int(str_arg) as T_ARGUMENT / slot."""
452 if action_exists("drop"):
453 t = world_db["Things"][0]
454 if 0 == len(t["T_CARRIES"]):
455 log("You have NOTHING to drop in your inventory.")
457 val = integer_test(str_arg, 0, 255)
458 if None != val and val < len(t["T_CARRIES"]):
459 world_db["Things"][0]["T_ARGUMENT"] = val
462 print("Illegal inventory index.")
465 def play_use(str_arg):
466 """Try "use" as player's T_COMMAND, int(str_arg) as T_ARGUMENT / slot."""
467 if action_exists("use"):
468 t = world_db["Things"][0]
469 if 0 == len(t["T_CARRIES"]):
470 log("You have NOTHING to use in your inventory.")
472 val = integer_test(str_arg, 0, 255)
473 if None != val and val < len(t["T_CARRIES"]):
474 id = t["T_CARRIES"][val]
475 type = world_db["Things"][id]["T_TYPE"]
476 if not world_db["ThingTypes"][type]["TT_TOOL"] == "food":
477 log("You CAN'T consume this thing.")
479 world_db["Things"][0]["T_ARGUMENT"] = val
482 print("Illegal inventory index.")
485 def play_move(str_arg):
486 """Try "move" as player's T_COMMAND, str_arg as T_ARGUMENT / direction."""
487 if action_exists("move"):
488 from server.config.world_data import directions_db, symbols_passable
489 t = world_db["Things"][0]
490 if not str_arg in directions_db:
491 print("Illegal move direction string.")
493 dir = ord(directions_db[str_arg])
494 from server.utils import mv_yx_in_dir_legal
495 move_result = mv_yx_in_dir_legal(chr(dir), t["T_POSY"], t["T_POSX"])
496 if 1 == move_result[0]:
497 pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
498 if ord("~") == world_db["MAP"][pos]:
499 log("You can't SWIM.")
501 if chr(world_db["MAP"][pos]) in symbols_passable:
502 world_db["Things"][0]["T_ARGUMENT"] = dir
505 log("You CAN'T move there.")
509 """Call ai() on player Thing, then turn_over()."""
510 from server.ai import ai
511 ai(world_db["Things"][0])