9 def strong_write(file, string):
10 """Apply write(string), flush(), and os.fsync() to file."""
16 def setup_server_io():
17 """Fill IO files DB with proper file( path)s. Write process IO test string.
19 Ensure IO files directory at server/. Remove any old input file if found.
20 Set up new input file for reading, and new output file for writing. Start
21 output file with process hash line of format PID + " " + floated UNIX time
22 (io_db["teststring"]). Raise SystemExit if file is found at path of either
23 record or save file plus io_db["tmp_suffix"].
25 def detect_atomic_leftover(path, tmp_suffix):
26 path_tmp = path + tmp_suffix
27 msg = "Found file '" + path_tmp + "' that may be a leftover from an " \
28 "aborted previous attempt to write '" + path + "'. Aborting " \
29 "until matter is resolved by removing it from its current path."
30 if os.access(path_tmp, os.F_OK):
32 io_db["teststring"] = str(os.getpid()) + " " + str(time.time())
33 os.makedirs(io_db["path_server"], exist_ok=True)
34 io_db["file_out"] = open(io_db["path_out"], "w")
35 strong_write(io_db["file_out"], io_db["teststring"] + "\n")
36 if os.access(io_db["path_in"], os.F_OK):
37 os.remove(io_db["path_in"])
38 io_db["file_in"] = open(io_db["path_in"], "w")
39 io_db["file_in"].close()
40 io_db["file_in"] = open(io_db["path_in"], "r")
41 detect_atomic_leftover(io_db["path_save"], io_db["tmp_suffix"])
42 detect_atomic_leftover(io_db["path_record"], io_db["tmp_suffix"])
45 def cleanup_server_io():
46 """Close and (if io_db["kicked_by_rival"] false) remove files in io_db."""
47 def helper(file_key, path_key):
49 io_db[file_key].close()
50 if not io_db["kicked_by_rival"] \
51 and os.access(io_db[path_key], os.F_OK):
52 os.remove(io_db[path_key])
53 helper("file_out", "path_out")
54 helper("file_in", "path_in")
55 helper("file_worldstate", "path_worldstate")
56 if "file_record" in io_db:
57 io_db["file_record"].close()
60 def obey(command, prefix, replay=False, do_record=False):
61 """Call function from commands_db mapped to command's first token.
63 Tokenize command string with shlex.split(comments=True). If replay is set,
64 a non-meta command from the commands_db merely triggers obey() on the next
65 command from the records file. If not, non-meta commands set
66 io_db["worldstate_updateable"] to world_db["WORLD_EXISTS"], and, if
67 do_record is set, are recorded via record(), and save_world() is called.
68 The prefix string is inserted into the server's input message between its
69 beginning 'input ' & ':'. All activity is preceded by a server_test() call.
72 print("input " + prefix + ": " + command)
74 tokens = shlex.split(command, comments=True)
75 except ValueError as err:
76 print("Can't tokenize command string: " + str(err) + ".")
78 if len(tokens) > 0 and tokens[0] in commands_db \
79 and len(tokens) == commands_db[tokens[0]][0] + 1:
80 if commands_db[tokens[0]][1]:
81 commands_db[tokens[0]][2](*tokens[1:])
83 print("Due to replay mode, reading command as 'go on in record'.")
84 line = io_db["file_record"].readline()
86 obey(line.rstrip(), io_db["file_record"].prefix
87 + str(io_db["file_record"].line_n))
88 io_db["file_record"].line_n = io_db["file_record"].line_n + 1
90 print("Reached end of record file.")
92 commands_db[tokens[0]][2](*tokens[1:])
96 io_db["worldstate_updateable"] = world_db["WORLD_ACTIVE"]
97 elif 0 != len(tokens):
98 print("Invalid command/argument, or bad number of tokens.")
101 def atomic_write(path, text, do_append=False):
102 """Atomic write of text to file at path, appended if do_append is set."""
103 path_tmp = path + io_db["tmp_suffix"]
107 if os.access(path, os.F_OK):
108 shutil.copyfile(path, path_tmp)
109 file = open(path_tmp, mode)
110 strong_write(file, text)
112 if os.access(path, os.F_OK):
114 os.rename(path_tmp, path)
118 """Append command string plus newline to record file. (Atomic.)"""
119 # This misses some optimizations from the original record(), namely only
120 # finishing the atomic write with expensive flush() and fsync() every 15
121 # seconds unless explicitely forced. Implement as needed.
122 atomic_write(io_db["path_record"], command + "\n", do_append=True)
126 """Save all commands needed to reconstruct current world state."""
127 # TODO: Misses same optimizations as record() from the original record().
130 string = string.replace("\u005C", '\u005C\u005C')
131 return '"' + string.replace('"', '\u005C"') + '"'
136 if world_db["Things"][id][key]:
137 map = world_db["Things"][id][key]
138 length = world_db["MAP_LENGTH"]
139 for i in range(length):
140 line = map[i * length:(i * length) + length].decode()
141 string = string + key + " " + str(i) + " " + quote(line) \
148 for memthing in world_db["Things"][id]["T_MEMTHING"]:
149 string = string + "T_MEMTHING " + str(memthing[0]) + " " + \
150 str(memthing[1]) + " " + str(memthing[2]) + "\n"
153 def helper(category, id_string, special_keys={}):
155 for id in world_db[category]:
156 string = string + id_string + " " + str(id) + "\n"
157 for key in world_db[category][id]:
158 if not key in special_keys:
159 x = world_db[category][id][key]
160 argument = quote(x) if str == type(x) else str(x)
161 string = string + key + " " + argument + "\n"
162 elif special_keys[key]:
163 string = string + special_keys[key](id)
168 if dict != type(world_db[key]) and key != "MAP":
169 string = string + key + " " + str(world_db[key]) + "\n"
170 string = string + helper("ThingActions", "TA_ID")
171 string = string + helper("ThingTypes", "TT_ID", {"TT_CORPSE_ID": False})
172 for id in world_db["ThingTypes"]:
173 string = string + "TT_ID " + str(id) + "\n" + "TT_CORPSE_ID " + \
174 str(world_db["ThingTypes"][id]["TT_CORPSE_ID"]) + "\n"
175 string = string + helper("Things", "T_ID",
176 {"T_CARRIES": False, "carried": False,
177 "T_MEMMAP": mapsetter("T_MEMMAP"),
178 "T_MEMTHING": memthing, "fovmap": False,
179 "T_MEMDEPTHMAP": mapsetter("T_MEMDEPTHMAP")})
180 for id in world_db["Things"]:
181 if [] != world_db["Things"][id]["T_CARRIES"]:
182 string = string + "T_ID " + str(id) + "\n"
183 for carried_id in world_db["Things"][id]["T_CARRIES"]:
184 string = string + "T_CARRIES " + str(carried_id) + "\n"
185 string = string + "WORLD_ACTIVE " + str(world_db["WORLD_ACTIVE"])
186 atomic_write(io_db["path_save"], string)
189 def obey_lines_in_file(path, name, do_record=False):
190 """Call obey() on each line of path's file, use name in input prefix."""
191 file = open(path, "r")
193 for line in file.readlines():
194 obey(line.rstrip(), name + "file line " + str(line_n),
200 def parse_command_line_arguments():
201 """Return settings values read from command line arguments."""
202 parser = argparse.ArgumentParser()
203 parser.add_argument('-s', nargs='?', type=int, dest='replay', const=1,
205 opts, unknown = parser.parse_known_args()
210 """Ensure valid server out file belonging to current process.
212 This is done by comparing io_db["teststring"] to what's found at the start
213 of the current file at io_db["path_out"]. On failure, set
214 io_db["kicked_by_rival"] and raise SystemExit.
216 if not os.access(io_db["path_out"], os.F_OK):
217 raise SystemExit("Server output file has disappeared.")
218 file = open(io_db["path_out"], "r")
219 test = file.readline().rstrip("\n")
221 if test != io_db["teststring"]:
222 io_db["kicked_by_rival"] = True
223 msg = "Server test string in server output file does not match. This" \
224 " indicates that the current server process has been " \
225 "superseded by another one."
226 raise SystemExit(msg)
230 """Return next newline-delimited command from server in file.
232 Keep building return string until a newline is encountered. Pause between
233 unsuccessful reads, and after too much waiting, run server_test().
240 add = io_db["file_in"].readline()
242 command = command + add
243 if len(command) > 0 and "\n" == command[-1]:
244 command = command[:-1]
247 time.sleep(wait_on_fail)
248 if now + max_wait < time.time():
254 def try_worldstate_update():
255 """Write worldstate file if io_db["worldstate_updateable"] is set."""
256 if io_db["worldstate_updateable"]:
258 def draw_visible_Things(map, run):
259 for id in world_db["Things"]:
260 type = world_db["Things"][id]["T_TYPE"]
261 consumable = world_db["ThingTypes"][type]["TT_CONSUMABLE"]
262 alive = world_db["ThingTypes"][type]["TT_LIFEPOINTS"]
263 if (0 == run and not consumable and not alive) \
264 or (1 == run and consumable and not alive) \
265 or (2 == run and alive):
266 y = world_db["Things"][id]["T_POSY"]
267 x = world_db["Things"][id]["T_POSX"]
268 fovflag = world_db["Things"][0]["fovmap"][(y * length) + x]
269 if 'v' == chr(fovflag):
270 c = world_db["ThingTypes"][type]["TT_SYMBOL"]
271 map[(y * length) + x] = ord(c)
273 def write_map(string, map):
274 for i in range(length):
275 line = map[i * length:(i * length) + length].decode()
276 string = string + line + "\n"
280 if [] == world_db["Things"][0]["T_CARRIES"]:
281 inventory = "(none)\n"
283 for id in world_db["Things"][0]["T_CARRIES"]:
284 type_id = world_db["Things"][id]["T_TYPE"]
285 name = world_db["ThingTypes"][type_id]["TT_NAME"]
286 inventory = inventory + name + "\n"
287 string = str(world_db["TURN"]) + "\n" + \
288 str(world_db["Things"][0]["T_LIFEPOINTS"]) + "\n" + \
289 str(world_db["Things"][0]["T_SATIATION"]) + "\n" + \
290 inventory + "%\n" + \
291 str(world_db["Things"][0]["T_POSY"]) + "\n" + \
292 str(world_db["Things"][0]["T_POSX"]) + "\n" + \
293 str(world_db["MAP_LENGTH"]) + "\n"
294 length = world_db["MAP_LENGTH"]
295 fov = bytearray(b' ' * (length ** 2))
296 for pos in range(length ** 2):
297 if 'v' == chr(world_db["Things"][0]["fovmap"][pos]):
298 fov[pos] = world_db["MAP"][pos]
300 draw_visible_Things(fov, i)
301 string = write_map(string, fov)
302 mem = world_db["Things"][0]["T_MEMMAP"][:]
304 for memthing in world_db["Things"][0]["T_MEMTHING"]:
305 type = world_db["Things"][memthing[0]]["T_TYPE"]
306 consumable = world_db["ThingTypes"][type]["TT_CONSUMABLE"]
307 if (i == 0 and not consumable) or (i == 1 and consumable):
308 c = world_db["ThingTypes"][type]["TT_SYMBOL"]
309 mem[(memthing[1] * length) + memthing[2]] = ord(c)
310 string = write_map(string, mem)
311 atomic_write(io_db["path_worldstate"], string)
312 strong_write(io_db["file_out"], "WORLD_UPDATED\n")
313 io_db["worldstate_updateable"] = False
317 """Replay game from record file.
319 Use opts.replay as breakpoint turn to which to replay automatically before
320 switching to manual input by non-meta commands in server input file
321 triggering further reads of record file. Ensure opts.replay is at least 1.
322 Run try_worldstate_update() before each interactive obey()/read_command().
326 print("Replay mode. Auto-replaying up to turn " + str(opts.replay) +
327 " (if so late a turn is to be found).")
328 if not os.access(io_db["path_record"], os.F_OK):
329 raise SystemExit("No record file found to replay.")
330 io_db["file_record"] = open(io_db["path_record"], "r")
331 io_db["file_record"].prefix = "record file line "
332 io_db["file_record"].line_n = 1
333 while world_db["TURN"] < opts.replay:
334 line = io_db["file_record"].readline()
337 obey(line.rstrip(), io_db["file_record"].prefix
338 + str(io_db["file_record"].line_n))
339 io_db["file_record"].line_n = io_db["file_record"].line_n + 1
341 try_worldstate_update()
342 obey(read_command(), "in file", replay=True)
346 """Play game by server input file commands. Before, load save file found.
348 If no save file is found, a new world is generated from the commands in the
349 world config plus a 'MAKE WORLD [current Unix timestamp]'. Record this
350 command and all that follow via the server input file. Run
351 try_worldstate_update() before each interactive obey()/read_command().
353 if os.access(io_db["path_save"], os.F_OK):
354 obey_lines_in_file(io_db["path_save"], "save")
356 if not os.access(io_db["path_worldconf"], os.F_OK):
357 msg = "No world config file from which to start a new world."
358 raise SystemExit(msg)
359 obey_lines_in_file(io_db["path_worldconf"], "world config ",
361 obey("MAKE_WORLD " + str(int(time.time())), "in file", do_record=True)
363 try_worldstate_update()
364 obey(read_command(), "in file", do_record=True)
369 world_db["MAP"] = bytearray(b'.' * (world_db["MAP_LENGTH"] ** 2))
372 def update_map_memory(t):
373 """Update t's T_MEMMAP with what's in its FOV now,age its T_MEMMEPTHMAP."""
374 if not t["T_MEMMAP"]:
375 t["T_MEMMAP"] = bytearray(b' ' * (world_db["MAP_LENGTH"] ** 2))
376 if not t["T_MEMDEPTHMAP"]:
377 t["T_MEMDEPTHMAP"] = bytearray(b' ' * (world_db["MAP_LENGTH"] ** 2))
378 for pos in range(world_db["MAP_LENGTH"] ** 2):
379 if "v" == chr(t["fovmap"][pos]):
380 t["T_MEMDEPTHMAP"][pos] = ord("0")
381 if " " == chr(t["T_MEMMAP"][pos]):
382 t["T_MEMMAP"][pos] = world_db["MAP"][pos]
384 # TODO: Aging of MEMDEPTHMAP.
385 for memthing in t["T_MEMTHING"]:
386 y = world_db["Things"][memthing[0]]["T_POSY"]
387 x = world_db["Things"][memthing[1]]["T_POSY"]
388 if "v" == chr(t["fovmap"][(y * world_db["MAP_LENGTH"]) + x]):
389 t["T_MEMTHING"].remove(memthing)
390 for id in world_db["Things"]:
391 type = world_db["Things"][id]["T_TYPE"]
392 if not world_db["ThingTypes"][type]["TT_LIFEPOINTS"]:
393 y = world_db["Things"][id]["T_POSY"]
394 x = world_db["Things"][id]["T_POSY"]
395 if "v" == chr(t["fovmap"][(y * world_db["MAP_LENGTH"]) + x]):
396 t["T_MEMTHING"].append((type, y, x))
399 def set_world_inactive():
400 """Set world_db["WORLD_ACTIVE"] to 0 and remove worldstate file."""
402 if os.access(io_db["path_worldstate"], os.F_OK):
403 os.remove(io_db["path_worldstate"])
404 world_db["WORLD_ACTIVE"] = 0
407 def integer_test(val_string, min, max):
408 """Return val_string if possible integer >= min and <= max, else None."""
410 val = int(val_string)
411 if val < min or val > max:
415 print("Ignoring: Please use integer >= " + str(min) + " and <= " +
420 def setter(category, key, min, max):
421 """Build setter for world_db([category + "s"][id])[key] to >=min/<=max."""
424 val = integer_test(val_string, min, max)
428 if category == "Thing":
429 id_store = command_tid
430 decorator = test_Thing_id
431 elif category == "ThingType":
432 id_store = command_ttid
433 decorator = test_ThingType_id
434 elif category == "ThingAction":
435 id_store = command_taid
436 decorator = test_ThingAction_id
440 val = integer_test(val_string, min, max)
442 world_db[category + "s"][id_store.id][key] = val
446 def build_fov_map(t):
447 """Build Thing's FOV map."""
448 t["fovmap"] = bytearray(b'v' * (world_db["MAP_LENGTH"] ** 2))
449 # DUMMY so far. Just builds an all-visible map.
453 """Return Thing of type T_TYPE, with fovmap if alive and world active."""
455 "T_LIFEPOINTS": world_db["ThingTypes"][type]["TT_LIFEPOINTS"],
467 "T_MEMDEPTHMAP": False,
470 if world_db["WORLD_ACTIVE"] and thing["T_LIFEPOINTS"]:
475 def id_setter(id, category, id_store=False, start_at_1=False):
476 """Set ID of object of category to manipulate ID unused? Create new one.
478 The ID is stored as id_store.id (if id_store is set). If the integer of the
479 input is valid (if start_at_1, >= 0 and <= 255, else >= -32768 and <=
480 32767), but <0 or (if start_at_1) <1, calculate new ID: lowest unused ID
481 >=0 or (if start_at_1) >= 1, and <= 255. None is always returned when no
482 new object is created, otherwise the new object's ID.
484 min = 0 if start_at_1 else -32768
485 max = 255 if start_at_1 else 32767
487 id = integer_test(id, min, max)
489 if id in world_db[category]:
494 if (start_at_1 and 0 == id) \
495 or ((not start_at_1) and (id < 0 or id > 255)):
499 if id not in world_db[category]:
503 "No unused ID available to add to ID list.")
511 """Send PONG line to server output file."""
512 strong_write(io_db["file_out"], "PONG\n")
516 """Abort server process."""
517 raise SystemExit("received QUIT command")
520 def command_thingshere(str_y, str_x):
521 """Write to out file list of Things known to player at coordinate y, x."""
522 def write_thing_if_here():
523 if y == world_db["Things"][id]["T_POSY"] \
524 and x == world_db["Things"][id]["T_POSX"]:
525 type = world_db["Things"][id]["T_TYPE"]
526 name = world_db["ThingTypes"][type]["TT_NAME"]
527 strong_write(io_db["file_out"], name + "\n")
528 if world_db["WORLD_ACTIVE"]:
529 y = integer_test(str_y, 0, 255)
530 x = integer_test(str_x, 0, 255)
531 length = world_db["MAP_LENGTH"]
532 if None != y and None != x and y < length and x < length:
533 pos = (y * world_db["MAP_LENGTH"]) + x
534 strong_write(io_db["file_out"], "THINGS_HERE START\n")
535 if "v" == chr(world_db["Things"][0]["fovmap"][pos]):
536 for id in world_db["Things"]:
537 write_thing_if_here()
539 for id in world_db["Things"]["T_MEMTHING"]:
540 write_thing_if_here()
541 strong_write(io_db["file_out"], "THINGS_HERE END\n")
543 print("Ignoring: Invalid map coordinates.")
545 print("Ignoring: Command only works on existing worlds.")
548 def play_commander(action, args=False):
549 """Setter for player's T_COMMAND (to "action") and T_ARGUMENT.
551 T_ARGUMENT is set to direction char if action=="wait",or 8-bit int if args.
555 id = [x for x in world_db["ThingActions"]
556 if world_db["ThingActions"][x]["TA_NAME"] == action][0]
557 world_db["Things"][0]["T_COMMAND"] = id
558 # TODO: call turn_over()
560 def set_command_and_argument_int(str_arg):
561 val = integer_test(str_arg, 0, 255)
563 world_db["Things"][0]["T_ARGUMENT"] = val
566 print("Ignoring: Argument must be integer >= 0 <=255.")
568 def set_command_and_argument_movestring(str_arg):
569 dirs = {"east": "d", "south-east": "c", "south-west": "x",
570 "west": "s", "north-west": "w", "north-east": "e"}
572 world_db["Things"][0]["T_ARGUMENT"] = dirs[str_arg]
575 print("Ignoring: Argument must be valid direction string.")
578 return set_command_and_argument_movestring
580 return set_command_and_argument_int
585 def command_seedmap(seed_string):
586 """Set world_db["SEED_MAP"] to int(seed_string), then (re-)make map."""
587 setter(None, "SEED_MAP", 0, 4294967295)(seed_string)
591 def command_makeworld(seed_string):
592 """(Re-)build game world, i.e. map, things, to a new turn 1 from seed.
594 Make seed world_db["SEED_RANDOMNESS"] and world_db["SEED_MAP"]. Do more
595 only with a "wait" ThingAction and world["PLAYER_TYPE"] matching ThingType
596 of TT_START_NUMBER > 0. Then, world_db["Things"] emptied, call remake_map()
597 and set world_db["WORLD_ACTIVE"], world_db["TURN"] to 1. Build new Things
598 according to ThingTypes' TT_START_NUMBERS, with Thing of ID 0 to ThingType
599 of ID = world["PLAYER_TYPE"]. Place Things randomly, and actors not on each
600 other. Init player's memory map. Write "NEW_WORLD" line to out file.
602 setter(None, "SEED_RANDOMNESS", 0, 4294967295)(seed_string)
603 setter(None, "SEED_MAP", 0, 4294967295)(seed_string)
604 player_will_be_generated = False
605 playertype = world_db["PLAYER_TYPE"]
606 for ThingType in world_db["ThingTypes"]:
607 if playertype == ThingType:
608 if 0 < world_db["ThingTypes"][ThingType]["TT_START_NUMBER"]:
609 player_will_be_generated = True
611 if not player_will_be_generated:
612 print("Ignoring beyond SEED_MAP: " +
613 "No player type with start number >0 defined.")
616 for ThingAction in world_db["ThingActions"]:
617 if "wait" == world_db["ThingActions"][ThingAction]["TA_NAME"]:
620 print("Ignoring beyond SEED_MAP: " +
621 "No thing action with name 'wait' defined.")
623 world_db["Things"] = {}
625 world_db["WORLD_ACTIVE"] = 1
627 for i in range(world_db["ThingTypes"][playertype]["TT_START_NUMBER"]):
628 id = id_setter(-1, "Things")
629 world_db["Things"][id] = new_Thing(playertype)
631 update_map_memory(world_db["Things"][0])
632 for type in world_db["ThingTypes"]:
633 for i in range(world_db["ThingTypes"][type]["TT_START_NUMBER"]):
634 if type != playertype:
635 id = id_setter(-1, "Things")
636 world_db["Things"][id] = new_Thing(type)
638 strong_write(io_db["file_out"], "NEW_WORLD\n")
641 def command_maplength(maplength_string):
642 """Redefine map length. Invalidate map, therefore lose all things on it."""
644 world_db["Things"] = {}
645 setter(None, "MAP_LENGTH", 1, 256)(maplength_string)
648 def command_worldactive(worldactive_string):
649 """Toggle world_db["WORLD_ACTIVE"] if possible.
651 An active world can always be set inactive. An inactive world can only be
652 set active with a "wait" ThingAction, and a player Thing (of ID 0). On
653 activation, rebuild all Things' FOVs, and the player's map memory.
655 # In original version, map existence was also tested (unnecessarily?).
656 val = integer_test(worldactive_string, 0, 1)
658 if 0 != world_db["WORLD_ACTIVE"]:
662 print("World already active.")
663 elif 0 == world_db["WORLD_ACTIVE"]:
665 for ThingAction in world_db["ThingActions"]:
666 if "wait" == world_db["ThingActions"][ThingAction]["TA_NAME"]:
669 player_exists = False
670 for Thing in world_db["Things"]:
674 if wait_exists and player_exists:
675 for id in world_db["Things"]:
676 if world_db["Things"][id]["T_LIFEPOINTS"]:
677 build_fov_map(world_db["Things"][id])
679 update_map_memory(world_db["Things"][id])
680 world_db["WORLD_ACTIVE"] = 1
683 def test_for_id_maker(object, category):
684 """Return decorator testing for object having "id" attribute."""
687 if hasattr(object, "id"):
690 print("Ignoring: No " + category +
691 " defined to manipulate yet.")
696 def command_tid(id_string):
697 """Set ID of Thing to manipulate. ID unused? Create new one.
699 Default new Thing's type to the first available ThingType, others: zero.
701 id = id_setter(id_string, "Things", command_tid)
703 if world_db["ThingTypes"] == {}:
704 print("Ignoring: No ThingType to settle new Thing in.")
706 type = list(world_db["ThingTypes"].keys())[0]
707 world_db["Things"][id] = new_Thing(type)
710 test_Thing_id = test_for_id_maker(command_tid, "Thing")
714 def command_tcommand(str_int):
715 """Set T_COMMAND of selected Thing."""
716 val = integer_test(str_int, 0, 255)
718 if 0 == val or val in world_db["ThingActions"]:
719 world_db["Things"][command_tid.id]["T_COMMAND"] = val
721 print("Ignoring: ThingAction ID belongs to no known ThingAction.")
725 def command_ttype(str_int):
726 """Set T_TYPE of selected Thing."""
727 val = integer_test(str_int, 0, 255)
729 if val in world_db["ThingTypes"]:
730 world_db["Things"][command_tid.id]["T_TYPE"] = val
732 print("Ignoring: ThingType ID belongs to no known ThingType.")
736 def command_tcarries(str_int):
737 """Append int(str_int) to T_CARRIES of selected Thing.
739 The ID int(str_int) must not be of the selected Thing, and must belong to a
740 Thing with unset "carried" flag. Its "carried" flag will be set on owning.
742 val = integer_test(str_int, 0, 255)
744 if val == command_tid.id:
745 print("Ignoring: Thing cannot carry itself.")
746 elif val in world_db["Things"] \
747 and not world_db["Things"][val]["carried"]:
748 world_db["Things"][command_tid.id]["T_CARRIES"].append(val)
749 world_db["Things"][val]["carried"] = True
751 print("Ignoring: Thing not available for carrying.")
752 # Note that the whole carrying structure is different from the C version:
753 # Carried-ness is marked by a "carried" flag, not by Things containing
758 def command_tmemthing(str_t, str_y, str_x):
759 """Add (int(str_t), int(str_y), int(str_x)) to selected Thing's T_MEMTHING.
761 The type must fit to an existing ThingType, and the position into the map.
763 type = integer_test(str_t, 0, 255)
764 posy = integer_test(str_y, 0, 255)
765 posx = integer_test(str_x, 0, 255)
766 if None != type and None != posy and None != posx:
767 if type not in world_db["ThingTypes"] \
768 or posy >= world_db["MAP_LENGTH"] or posx >= world_db["MAP_LENGTH"]:
769 print("Ignoring: Illegal value for thing type or position.")
771 memthing = (type, posy, posx)
772 world_db["Things"][command_tid.id]["T_MEMTHING"].append(memthing)
775 def setter_map(maptype):
776 """Set selected Thing's map of maptype's int(str_int)-th line to mapline.
778 If Thing has no map of maptype yet, initialize it with ' ' bytes first.
781 def helper(str_int, mapline):
782 val = integer_test(str_int, 0, 255)
784 if val >= world_db["MAP_LENGTH"]:
785 print("Illegal value for map line number.")
786 elif len(mapline) != world_db["MAP_LENGTH"]:
787 print("Map line length is unequal map width.")
789 length = world_db["MAP_LENGTH"]
791 if not world_db["Things"][command_tid.id][maptype]:
792 map = bytearray(b' ' * (length ** 2))
794 map = world_db["Things"][command_tid.id][maptype]
795 map[val * length:(val * length) + length] = mapline.encode()
796 world_db["Things"][command_tid.id][maptype] = map
800 def setter_tpos(axis):
801 """Generate setter for T_POSX or T_POSY of selected Thing.
803 If world is active, rebuilds animate things' fovmap, player's memory map.
807 val = integer_test(str_int, 0, 255)
809 if val < world_db["MAP_LENGTH"]:
810 world_db["Things"][command_tid.id]["T_POS" + axis] = val
811 if world_db["WORLD_ACTIVE"] \
812 and world_db["Things"][command_tid.id]["T_LIFEPOINTS"]:
813 build_fov_map(world_db["Things"][command_tid.id])
814 if 0 == command_tid.id:
815 update_map_memory(world_db["Things"][command_tid.id])
817 print("Ignoring: Position is outside of map.")
821 def command_ttid(id_string):
822 """Set ID of ThingType to manipulate. ID unused? Create new one.
824 Default new ThingType's TT_SYMBOL to "?", TT_CORPSE_ID to self, others: 0.
826 id = id_setter(id_string, "ThingTypes", command_ttid)
828 world_db["ThingTypes"][id] = {
833 "TT_START_NUMBER": 0,
839 test_ThingType_id = test_for_id_maker(command_ttid, "ThingType")
843 def command_ttname(name):
844 """Set TT_NAME of selected ThingType."""
845 world_db["ThingTypes"][command_ttid.id]["TT_NAME"] = name
849 def command_ttsymbol(char):
850 """Set TT_SYMBOL of selected ThingType. """
852 world_db["ThingTypes"][command_ttid.id]["TT_SYMBOL"] = char
854 print("Ignoring: Argument must be single character.")
858 def command_ttcorpseid(str_int):
859 """Set TT_CORPSE_ID of selected ThingType."""
860 val = integer_test(str_int, 0, 255)
862 if val in world_db["ThingTypes"]:
863 world_db["ThingTypes"][command_ttid.id]["TT_CORPSE_ID"] = val
865 print("Ignoring: Corpse ID belongs to no known ThignType.")
868 def command_taid(id_string):
869 """Set ID of ThingAction to manipulate. ID unused? Create new one.
871 Default new ThingAction's TA_EFFORT to 1, its TA_NAME to "wait".
873 id = id_setter(id_string, "ThingActions", command_taid, True)
875 world_db["ThingActions"][id] = {
881 test_ThingAction_id = test_for_id_maker(command_taid, "ThingAction")
885 def command_taname(name):
886 """Set TA_NAME of selected ThingAction.
888 The name must match a valid thing action function. If after the name
889 setting no ThingAction with name "wait" remains, call set_world_inactive().
891 if name == "wait" or name == "move" or name == "use" or name == "drop" \
892 or name == "pick_up":
893 world_db["ThingActions"][command_taid.id]["TA_NAME"] = name
894 if 1 == world_db["WORLD_ACTIVE"]:
896 for id in world_db["ThingActions"]:
897 if "wait" == world_db["ThingActions"][id]["TA_NAME"]:
903 print("Ignoring: Invalid action name.")
904 # In contrast to the original,naming won't map a function to a ThingAction.
907 """Commands database.
909 Map command start tokens to ([0]) number of expected command arguments, ([1])
910 the command's meta-ness (i.e. is it to be written to the record file, is it to
911 be ignored in replay mode if read from server input file), and ([2]) a function
915 "QUIT": (0, True, command_quit),
916 "PING": (0, True, command_ping),
917 "THINGS_HERE": (2, True, command_thingshere),
918 "MAKE_WORLD": (1, False, command_makeworld),
919 "SEED_MAP": (1, False, command_seedmap),
920 "SEED_RANDOMNESS": (1, False, setter(None, "SEED_RANDOMNESS",
922 "TURN": (1, False, setter(None, "TURN", 0, 65535)),
923 "PLAYER_TYPE": (1, False, setter(None, "PLAYER_TYPE", 0, 255)),
924 "MAP_LENGTH": (1, False, command_maplength),
925 "WORLD_ACTIVE": (1, False, command_worldactive),
926 "TA_ID": (1, False, command_taid),
927 "TA_EFFORT": (1, False, setter("ThingAction", "TA_EFFORT", 0, 255)),
928 "TA_NAME": (1, False, command_taname),
929 "TT_ID": (1, False, command_ttid),
930 "TT_NAME": (1, False, command_ttname),
931 "TT_SYMBOL": (1, False, command_ttsymbol),
932 "TT_CORPSE_ID": (1, False, command_ttcorpseid),
933 "TT_CONSUMABLE": (1, False, setter("ThingType", "TT_CONSUMABLE",
935 "TT_START_NUMBER": (1, False, setter("ThingType", "TT_START_NUMBER",
937 "TT_PROLIFERATE": (1, False, setter("ThingType", "TT_PROLIFERATE",
939 "TT_LIFEPOINTS": (1, False, setter("ThingType", "TT_LIFEPOINTS", 0, 255)),
940 "T_ID": (1, False, command_tid),
941 "T_ARGUMENT": (1, False, setter("Thing", "T_ARGUMENT", 0, 255)),
942 "T_PROGRESS": (1, False, setter("Thing", "T_PROGRESS", 0, 255)),
943 "T_LIFEPOINTS": (1, False, setter("Thing", "T_LIFEPOINTS", 0, 255)),
944 "T_SATIATION": (1, False, setter("Thing", "T_SATIATION", -32768, 32767)),
945 "T_COMMAND": (1, False, command_tcommand),
946 "T_TYPE": (1, False, command_ttype),
947 "T_CARRIES": (1, False, command_tcarries),
948 "T_MEMMAP": (2, False, setter_map("T_MEMMAP")),
949 "T_MEMDEPTHMAP": (2, False, setter_map("T_MEMDEPTHMAP")),
950 "T_MEMTHING": (3, False, command_tmemthing),
951 "T_POSY": (1, False, setter_tpos("Y")),
952 "T_POSX": (1, False, setter_tpos("X")),
953 "wait": (0, False, play_commander("wait")),
954 "move": (1, False, play_commander("move")),
955 "pick_up": (0, False, play_commander("pick_up")),
956 "drop": (1, False, play_commander("drop", True)),
957 "use": (1, False, play_commander("use", True)),
961 """World state database. With sane default values."""
965 "SEED_RANDOMNESS": 0,
975 """File IO database."""
978 "path_record": "record",
979 "path_worldconf": "confserver/world",
980 "path_server": "server/",
981 "path_in": "server/in",
982 "path_out": "server/out",
983 "path_worldstate": "server/worldstate",
984 "tmp_suffix": "_tmp",
985 "kicked_by_rival": False,
986 "worldstate_updateable": False
991 opts = parse_command_line_arguments()
993 if None != opts.replay:
997 except SystemExit as exit:
998 print("ABORTING: " + exit.args[0])
1000 print("SOMETHING WENT WRONG IN UNEXPECTED WAYS")