home · contact · privacy
turn_over(): hunger() before Thing action, so no suicide corpses hunger.
[plomrogue] / roguelike-server
1 #!/usr/bin/python3
2
3 # This file is part of PlomRogue. PlomRogue is licensed under the GPL version 3
4 # or any later version. For details on its copyright, license, and warranties,
5 # see the file NOTICE in the root directory of the PlomRogue source package.
6
7
8 import argparse
9 import errno
10 import os
11 import shlex
12 import shutil
13 import time
14 import ctypes
15
16
17 class RandomnessIO:
18     """"Interface to libplomrogue's pseudo-randomness generator."""
19
20     def set_seed(self, seed):
21         libpr.seed_rrand(1, seed)
22
23     def get_seed(self):
24         return libpr.seed_rrand(0, 0)
25
26     def next(self):
27         return libpr.rrand()
28
29     seed = property(get_seed, set_seed)
30
31
32 def prep_library():
33     """Prepare ctypes library at ./libplomrogue.so"""
34     libpath = ("./libplomrogue.so")
35     if not os.access(libpath, os.F_OK):
36         raise SystemExit("No library " + libpath + ", run ./redo first?")
37     libpr = ctypes.cdll.LoadLibrary(libpath)
38     libpr.seed_rrand.restype = ctypes.c_uint32
39     return libpr
40
41
42 def c_pointer_to_bytearray(ba):
43     """Return C char * pointer to ba."""
44     type = ctypes.c_char * len(ba)
45     return type.from_buffer(ba)
46
47
48 def strong_write(file, string):
49     """Apply write(string), then flush()."""
50     file.write(string)
51     file.flush()
52
53
54 def setup_server_io():
55     """Fill IO files DB with proper file( path)s. Write process IO test string.
56
57     Ensure IO files directory at server/. Remove any old input file if found.
58     Set up new input file for reading, and new output file for writing. Start
59     output file with process hash line of format PID + " " + floated UNIX time
60     (io_db["teststring"]). Raise SystemExit if file is found at path of either
61     record or save file plus io_db["tmp_suffix"].
62     """
63     def detect_atomic_leftover(path, tmp_suffix):
64         path_tmp = path + tmp_suffix
65         msg = "Found file '" + path_tmp + "' that may be a leftover from an " \
66               "aborted previous attempt to write '" + path + "'. Aborting " \
67               "until matter is resolved by removing it from its current path."
68         if os.access(path_tmp, os.F_OK):
69             raise SystemExit(msg)
70     io_db["teststring"] = str(os.getpid()) + " " + str(time.time())
71     io_db["save_wait"] = 0
72     io_db["verbose"] = False
73     io_db["record_chunk"] = ""
74     os.makedirs(io_db["path_server"], exist_ok=True)
75     io_db["file_out"] = open(io_db["path_out"], "w")
76     strong_write(io_db["file_out"], io_db["teststring"] + "\n")
77     if os.access(io_db["path_in"], os.F_OK):
78         os.remove(io_db["path_in"])
79     io_db["file_in"] = open(io_db["path_in"], "w")
80     io_db["file_in"].close()
81     io_db["file_in"] = open(io_db["path_in"], "r")
82     detect_atomic_leftover(io_db["path_save"], io_db["tmp_suffix"])
83     detect_atomic_leftover(io_db["path_record"], io_db["tmp_suffix"])
84
85
86 def cleanup_server_io():
87     """Close and (if io_db["kicked_by_rival"] false) remove files in io_db."""
88     def helper(file_key, path_key):
89         if file_key in io_db:
90             io_db[file_key].close()
91         if not io_db["kicked_by_rival"] \
92            and os.access(io_db[path_key], os.F_OK):
93             os.remove(io_db[path_key])
94     helper("file_in", "path_in")
95     helper("file_out", "path_out")
96     helper("file_worldstate", "path_worldstate")
97     if "file_record" in io_db:
98         io_db["file_record"].close()
99
100
101 def obey(command, prefix, replay=False, do_record=False):
102     """Call function from commands_db mapped to command's first token.
103
104     Tokenize command string with shlex.split(comments=True). If replay is set,
105     a non-meta command from the commands_db merely triggers obey() on the next
106     command from the records file. If not, non-meta commands set
107     io_db["worldstate_updateable"] to world_db["WORLD_ACTIVE"], and, if
108     do_record is set, are recorded to io_db["record_chunk"], and save_world()
109     is called (and io_db["record_chunk"] written) if 15 seconds have passed
110     since the last time it was called. The prefix string is inserted into the
111     server's input message between its beginning 'input ' and ':'. All activity
112     is preceded by a server_test() call. Commands that start with a lowercase
113     letter are ignored when world_db["WORLD_ACTIVE"] is False/0.
114     """
115     server_test()
116     if io_db["verbose"]:
117         print("input " + prefix + ": " + command)
118     try:
119         tokens = shlex.split(command, comments=True)
120     except ValueError as err:
121         print("Can't tokenize command string: " + str(err) + ".")
122         return
123     if len(tokens) > 0 and tokens[0] in commands_db \
124        and len(tokens) == commands_db[tokens[0]][0] + 1:
125         if commands_db[tokens[0]][1]:
126             commands_db[tokens[0]][2](*tokens[1:])
127         elif tokens[0][0].islower() and not world_db["WORLD_ACTIVE"]:
128             print("Ignoring lowercase-starting commands when world inactive.")
129         elif replay:
130             print("Due to replay mode, reading command as 'go on in record'.")
131             line = io_db["file_record"].readline()
132             if len(line) > 0:
133                 obey(line.rstrip(), io_db["file_record"].prefix
134                      + str(io_db["file_record"].line_n))
135                 io_db["file_record"].line_n = io_db["file_record"].line_n + 1
136             else:
137                 print("Reached end of record file.")
138         else:
139             commands_db[tokens[0]][2](*tokens[1:])
140             if do_record:
141                 io_db["record_chunk"] += command + "\n"
142                 if time.time() > io_db["save_wait"] + 15:
143                     atomic_write(io_db["path_record"], io_db["record_chunk"],
144                                  do_append=True)
145                     if world_db["WORLD_ACTIVE"]:
146                         save_world()
147                     io_db["record_chunk"] = ""
148                     io_db["save_wait"] = time.time()
149             io_db["worldstate_updateable"] = world_db["WORLD_ACTIVE"]
150     elif 0 != len(tokens):
151         print("Invalid command/argument, or bad number of tokens.")
152
153
154 def atomic_write(path, text, do_append=False, delete=True):
155     """Atomic write of text to file at path, appended if do_append is set."""
156     path_tmp = path + io_db["tmp_suffix"]
157     mode = "w"
158     if do_append:
159         mode = "a"
160         if os.access(path, os.F_OK):
161             shutil.copyfile(path, path_tmp)
162     file = open(path_tmp, mode)
163     strong_write(file, text)
164     file.close()
165     if delete and os.access(path, os.F_OK):
166         os.remove(path)
167     os.rename(path_tmp, path)
168
169
170 def save_world():
171     """Save all commands needed to reconstruct current world state."""
172
173     def quote(string):
174         string = string.replace("\u005C", '\u005C\u005C')
175         return '"' + string.replace('"', '\u005C"') + '"'
176
177     def mapsetter(key):
178         def helper(id=None):
179             string = ""
180             if key == "MAP" or world_db["Things"][id][key]:
181                 map = world_db["MAP"] if key == "MAP" \
182                                       else world_db["Things"][id][key]
183                 length = world_db["MAP_LENGTH"]
184                 for i in range(length):
185                     line = map[i * length:(i * length) + length].decode()
186                     string = string + key + " " + str(i) + " " + quote(line) \
187                         + "\n"
188             return string
189         return helper
190
191     def memthing(id):
192         string = ""
193         for memthing in world_db["Things"][id]["T_MEMTHING"]:
194             string = string + "T_MEMTHING " + str(memthing[0]) + " " + \
195                 str(memthing[1]) + " " + str(memthing[2]) + "\n"
196         return string
197
198     def helper(category, id_string, special_keys={}):
199         string = ""
200         for id in sorted(world_db[category].keys()):
201             string = string + id_string + " " + str(id) + "\n"
202             for key in sorted(world_db[category][id].keys()):
203                 if not key in special_keys:
204                     x = world_db[category][id][key]
205                     argument = quote(x) if str == type(x) else str(x)
206                     string = string + key + " " + argument + "\n"
207                 elif special_keys[key]:
208                     string = string + special_keys[key](id)
209         return string
210
211     string = ""
212     for key in sorted(world_db.keys()):
213         if (not isinstance(world_db[key], dict)) and key != "MAP" and \
214            key != "WORLD_ACTIVE":
215             string = string + key + " " + str(world_db[key]) + "\n"
216     string = string + mapsetter("MAP")()
217     string = string + helper("ThingActions", "TA_ID")
218     string = string + helper("ThingTypes", "TT_ID", {"TT_CORPSE_ID": False})
219     for id in sorted(world_db["ThingTypes"].keys()):
220         string = string + "TT_ID " + str(id) + "\n" + "TT_CORPSE_ID " + \
221             str(world_db["ThingTypes"][id]["TT_CORPSE_ID"]) + "\n"
222     string = string + helper("Things", "T_ID",
223                              {"T_CARRIES": False, "carried": False,
224                               "T_MEMMAP": mapsetter("T_MEMMAP"),
225                               "T_MEMTHING": memthing, "fovmap": False,
226                               "T_MEMDEPTHMAP": mapsetter("T_MEMDEPTHMAP")})
227     for id in sorted(world_db["Things"].keys()):
228         if [] != world_db["Things"][id]["T_CARRIES"]:
229             string = string + "T_ID " + str(id) + "\n"
230             for carried in sorted(world_db["Things"][id]["T_CARRIES"]):
231                 string = string + "T_CARRIES " + str(carried) + "\n"
232     string = string + "SEED_RANDOMNESS " + str(rand.seed) + "\n" + \
233         "WORLD_ACTIVE " + str(world_db["WORLD_ACTIVE"])
234     atomic_write(io_db["path_save"], string)
235
236
237 def obey_lines_in_file(path, name, do_record=False):
238     """Call obey() on each line of path's file, use name in input prefix."""
239     file = open(path, "r")
240     line_n = 1
241     for line in file.readlines():
242         obey(line.rstrip(), name + "file line " + str(line_n),
243              do_record=do_record)
244         line_n = line_n + 1
245     file.close()
246
247
248 def parse_command_line_arguments():
249     """Return settings values read from command line arguments."""
250     parser = argparse.ArgumentParser()
251     parser.add_argument('-s', nargs='?', type=int, dest='replay', const=1,
252                         action='store')
253     parser.add_argument('-l', nargs="?", const="save", dest='savefile',
254                         action="store")
255     parser.add_argument('-v', dest='verbose', action='store_true')
256     opts, unknown = parser.parse_known_args()
257     return opts
258
259
260 def server_test():
261     """Ensure valid server out file belonging to current process.
262
263     This is done by comparing io_db["teststring"] to what's found at the start
264     of the current file at io_db["path_out"]. On failure, set
265     io_db["kicked_by_rival"] and raise SystemExit.
266     """
267     if not os.access(io_db["path_out"], os.F_OK):
268         raise SystemExit("Server output file has disappeared.")
269     file = open(io_db["path_out"], "r")
270     test = file.readline().rstrip("\n")
271     file.close()
272     if test != io_db["teststring"]:
273         io_db["kicked_by_rival"] = True
274         msg = "Server test string in server output file does not match. This" \
275               " indicates that the current server process has been " \
276               "superseded by another one."
277         raise SystemExit(msg)
278
279
280 def read_command():
281     """Return next newline-delimited command from server in file.
282
283     Keep building return string until a newline is encountered. Pause between
284     unsuccessful reads, and after too much waiting, run server_test().
285     """
286     wait_on_fail = 0.03333
287     max_wait = 5
288     now = time.time()
289     command = ""
290     while True:
291         add = io_db["file_in"].readline()
292         if len(add) > 0:
293             command = command + add
294             if len(command) > 0 and "\n" == command[-1]:
295                 command = command[:-1]
296                 break
297         else:
298             time.sleep(wait_on_fail)
299             if now + max_wait < time.time():
300                 server_test()
301                 now = time.time()
302     return command
303
304
305 def try_worldstate_update():
306     """Write worldstate file if io_db["worldstate_updateable"] is set."""
307     if io_db["worldstate_updateable"]:
308
309         def draw_visible_Things(map, run):
310             for id in world_db["Things"]:
311                 type = world_db["Things"][id]["T_TYPE"]
312                 consumable = world_db["ThingTypes"][type]["TT_CONSUMABLE"]
313                 alive = world_db["ThingTypes"][type]["TT_LIFEPOINTS"]
314                 if (0 == run and not consumable and not alive) \
315                    or (1 == run and consumable and not alive) \
316                    or (2 == run and alive):
317                     y = world_db["Things"][id]["T_POSY"]
318                     x = world_db["Things"][id]["T_POSX"]
319                     fovflag = world_db["Things"][0]["fovmap"][(y * length) + x]
320                     if 'v' == chr(fovflag):
321                         c = world_db["ThingTypes"][type]["TT_SYMBOL"]
322                         map[(y * length) + x] = ord(c)
323
324         def write_map(string, map):
325             for i in range(length):
326                 line = map[i * length:(i * length) + length].decode()
327                 string = string + line + "\n"
328             return string
329
330         inventory = ""
331         if [] == world_db["Things"][0]["T_CARRIES"]:
332             inventory = "(none)\n"
333         else:
334             for id in world_db["Things"][0]["T_CARRIES"]:
335                 type_id = world_db["Things"][id]["T_TYPE"]
336                 name = world_db["ThingTypes"][type_id]["TT_NAME"]
337                 inventory = inventory + name + "\n"
338         string = str(world_db["TURN"]) + "\n" + \
339             str(world_db["Things"][0]["T_LIFEPOINTS"]) + "\n" + \
340             str(world_db["Things"][0]["T_SATIATION"]) + "\n" + \
341             inventory + "%\n" + \
342             str(world_db["Things"][0]["T_POSY"]) + "\n" + \
343             str(world_db["Things"][0]["T_POSX"]) + "\n" + \
344             str(world_db["MAP_LENGTH"]) + "\n"
345         length = world_db["MAP_LENGTH"]
346         fov = bytearray(b' ' * (length ** 2))
347         for pos in range(length ** 2):
348             if 'v' == chr(world_db["Things"][0]["fovmap"][pos]):
349                 fov[pos] = world_db["MAP"][pos]
350         for i in range(3):
351             draw_visible_Things(fov, i)
352         string = write_map(string, fov)
353         mem = world_db["Things"][0]["T_MEMMAP"][:]
354         for i in range(2):
355             for mt in world_db["Things"][0]["T_MEMTHING"]:
356                 consumable = world_db["ThingTypes"][mt[0]]["TT_CONSUMABLE"]
357                 if (i == 0 and not consumable) or (i == 1 and consumable):
358                     c = world_db["ThingTypes"][mt[0]]["TT_SYMBOL"]
359                     mem[(mt[1] * length) + mt[2]] = ord(c)
360         string = write_map(string, mem)
361         atomic_write(io_db["path_worldstate"], string, delete=False)
362         strong_write(io_db["file_out"], "WORLD_UPDATED\n")
363         io_db["worldstate_updateable"] = False
364
365
366 def replay_game():
367     """Replay game from record file.
368
369     Use opts.replay as breakpoint turn to which to replay automatically before
370     switching to manual input by non-meta commands in server input file
371     triggering further reads of record file. Ensure opts.replay is at least 1.
372     Run try_worldstate_update() before each interactive obey()/read_command().
373     """
374     if opts.replay < 1:
375         opts.replay = 1
376     print("Replay mode. Auto-replaying up to turn " + str(opts.replay) +
377           " (if so late a turn is to be found).")
378     if not os.access(io_db["path_record"], os.F_OK):
379         raise SystemExit("No record file found to replay.")
380     io_db["file_record"] = open(io_db["path_record"], "r")
381     io_db["file_record"].prefix = "record file line "
382     io_db["file_record"].line_n = 1
383     while world_db["TURN"] < opts.replay:
384         line = io_db["file_record"].readline()
385         if "" == line:
386             break
387         obey(line.rstrip(), io_db["file_record"].prefix
388              + str(io_db["file_record"].line_n))
389         io_db["file_record"].line_n = io_db["file_record"].line_n + 1
390     while True:
391         try_worldstate_update()
392         obey(read_command(), "in file", replay=True)
393
394
395 def play_game():
396     """Play game by server input file commands. Before, load save file found.
397
398     If no save file is found, a new world is generated from the commands in the
399     world config plus a 'MAKE WORLD [current Unix timestamp]'. Record this
400     command and all that follow via the server input file. Run
401     try_worldstate_update() before each interactive obey()/read_command().
402     """
403     if os.access(io_db["path_save"], os.F_OK):
404         obey_lines_in_file(io_db["path_save"], "save")
405     else:
406         if not os.access(io_db["path_worldconf"], os.F_OK):
407             msg = "No world config file from which to start a new world."
408             raise SystemExit(msg)
409         obey_lines_in_file(io_db["path_worldconf"], "world config ",
410                            do_record=True)
411         obey("MAKE_WORLD " + str(int(time.time())), "in file", do_record=True)
412     while True:
413         try_worldstate_update()
414         obey(read_command(), "in file", do_record=True)
415
416
417 def make_map():
418     """(Re-)make island map.
419
420     Let "~" represent water, "." land, "X" trees: Build island shape randomly,
421     start with one land cell in the middle, then go into cycle of repeatedly
422     selecting a random sea cell and transforming it into land if it is neighbor
423     to land. The cycle ends when a land cell is due to be created at the map's
424     border. Then put some trees on the map (TODO: more precise algorithm desc).
425     """
426
427     def is_neighbor(coordinates, type):
428         y = coordinates[0]
429         x = coordinates[1]
430         length = world_db["MAP_LENGTH"]
431         ind = y % 2
432         diag_west = x + (ind > 0)
433         diag_east = x + (ind < (length - 1))
434         pos = (y * length) + x
435         if (y > 0 and diag_east
436             and type == chr(world_db["MAP"][pos - length + ind])) \
437            or (x < (length - 1)
438                and type == chr(world_db["MAP"][pos + 1])) \
439            or (y < (length - 1) and diag_east
440                and type == chr(world_db["MAP"][pos + length + ind])) \
441            or (y > 0 and diag_west
442                and type == chr(world_db["MAP"][pos - length - (not ind)])) \
443            or (x > 0
444                and type == chr(world_db["MAP"][pos - 1])) \
445            or (y < (length - 1) and diag_west
446                and type == chr(world_db["MAP"][pos + length - (not ind)])):
447             return True
448         return False
449
450     world_db["MAP"] = bytearray(b'~' * (world_db["MAP_LENGTH"] ** 2))
451     length = world_db["MAP_LENGTH"]
452     add_half_width = (not (length % 2)) * int(length / 2)
453     world_db["MAP"][int((length ** 2) / 2) + add_half_width] = ord(".")
454     while (1):
455         y = rand.next() % length
456         x = rand.next() % length
457         pos = (y * length) + x
458         if "~" == chr(world_db["MAP"][pos]) and is_neighbor((y, x), "."):
459             if y == 0 or y == (length - 1) or x == 0 or x == (length - 1):
460                 break
461             world_db["MAP"][pos] = ord(".")
462     n_trees = int((length ** 2) / 16)
463     i_trees = 0
464     while (i_trees <= n_trees):
465         single_allowed = rand.next() % 32
466         y = rand.next() % length
467         x = rand.next() % length
468         pos = (y * length) + x
469         if "." == chr(world_db["MAP"][pos]) \
470                 and ((not single_allowed) or is_neighbor((y, x), "X")):
471             world_db["MAP"][pos] = ord("X")
472             i_trees += 1
473     # This all-too-precise replica of the original C code misses iter_limit().
474
475
476 def update_map_memory(t, age_map=True):
477     """Update t's T_MEMMAP with what's in its FOV now,age its T_MEMMEPTHMAP."""
478
479     def age_some_memdepthmap_on_nonfov_cells():
480         # OUTSOURCED FOR PERFORMANCE REASONS TO libplomrogue.so:
481         # ord_v = ord("v")
482         # ord_0 = ord("0")
483         # ord_9 = ord("9")
484         # for pos in [pos for pos in range(world_db["MAP_LENGTH"] ** 2)
485         #             if not ord_v == t["fovmap"][pos]
486         #             if ord_0 <= t["T_MEMDEPTHMAP"][pos]
487         #             if ord_9 > t["T_MEMDEPTHMAP"][pos]
488         #             if not rand.next() % (2 **
489         #                                   (t["T_MEMDEPTHMAP"][pos] - 48))]:
490         #     t["T_MEMDEPTHMAP"][pos] += 1
491         memdepthmap = c_pointer_to_bytearray(t["T_MEMDEPTHMAP"])
492         fovmap = c_pointer_to_bytearray(t["fovmap"])
493         libpr.age_some_memdepthmap_on_nonfov_cells(memdepthmap, fovmap)
494
495     if not t["T_MEMMAP"]:
496         t["T_MEMMAP"] = bytearray(b' ' * (world_db["MAP_LENGTH"] ** 2))
497     if not t["T_MEMDEPTHMAP"]:
498         t["T_MEMDEPTHMAP"] = bytearray(b' ' * (world_db["MAP_LENGTH"] ** 2))
499     ord_v = ord("v")
500     ord_0 = ord("0")
501     ord_space = ord(" ")
502     for pos in [pos for pos in range(world_db["MAP_LENGTH"] ** 2)
503                 if ord_v == t["fovmap"][pos]]:
504         t["T_MEMDEPTHMAP"][pos] = ord_0
505         if ord_space == t["T_MEMMAP"][pos]:
506             t["T_MEMMAP"][pos] = world_db["MAP"][pos]
507     if age_map:
508         age_some_memdepthmap_on_nonfov_cells()
509     t["T_MEMTHING"] = [mt for mt in t["T_MEMTHING"]
510                        if ord_v != t["fovmap"][(mt[1] * world_db["MAP_LENGTH"])
511                                                + mt[2]]]
512     for id in [id for id in world_db["Things"]
513                if not world_db["Things"][id]["carried"]]:
514         type = world_db["Things"][id]["T_TYPE"]
515         if not world_db["ThingTypes"][type]["TT_LIFEPOINTS"]:
516             y = world_db["Things"][id]["T_POSY"]
517             x = world_db["Things"][id]["T_POSX"]
518             if ord_v == t["fovmap"][(y * world_db["MAP_LENGTH"]) + x]:
519                 t["T_MEMTHING"].append((type, y, x))
520
521
522 def set_world_inactive():
523     """Set world_db["WORLD_ACTIVE"] to 0 and remove worldstate file."""
524     server_test()
525     if os.access(io_db["path_worldstate"], os.F_OK):
526         os.remove(io_db["path_worldstate"])
527     world_db["WORLD_ACTIVE"] = 0
528
529
530 def integer_test(val_string, min, max=None):
531     """Return val_string if integer >= min & (if max set) <= max, else None."""
532     try:
533         val = int(val_string)
534         if val < min or (max is not None and val > max):
535             raise ValueError
536         return val
537     except ValueError:
538         msg = "Ignoring: Please use integer >= " + str(min)
539         if max is not None:
540             msg += " and <= " + str(max)
541         msg += "."
542         print(msg)
543         return None
544
545
546 def setter(category, key, min, max=None):
547     """Build setter for world_db([category + "s"][id])[key] to >=min/<=max."""
548     if category is None:
549         def f(val_string):
550             val = integer_test(val_string, min, max)
551             if None != val:
552                 world_db[key] = val
553     else:
554         if category == "Thing":
555             id_store = command_tid
556             decorator = test_Thing_id
557         elif category == "ThingType":
558             id_store = command_ttid
559             decorator = test_ThingType_id
560         elif category == "ThingAction":
561             id_store = command_taid
562             decorator = test_ThingAction_id
563
564         @decorator
565         def f(val_string):
566             val = integer_test(val_string, min, max)
567             if None != val:
568                 world_db[category + "s"][id_store.id][key] = val
569     return f
570
571
572 def build_fov_map(t):
573     """Build Thing's FOV map."""
574     t["fovmap"] = bytearray(b'v' * (world_db["MAP_LENGTH"] ** 2))
575     fovmap = c_pointer_to_bytearray(t["fovmap"])
576     map = c_pointer_to_bytearray(world_db["MAP"])
577     if libpr.build_fov_map(t["T_POSY"], t["T_POSX"], fovmap, map):
578         raise RuntimeError("Malloc error in build_fov_Map().")
579
580
581 def decrement_lifepoints(t):
582     """Decrement t's lifepoints by 1, and if to zero, corpse it.
583
584     If t is the player avatar, only blank its fovmap, so that the client may
585     still display memory data. On non-player things, erase fovmap and memory.
586     Dying actors drop all their things.
587     """
588     t["T_LIFEPOINTS"] -= 1
589     if 0 == t["T_LIFEPOINTS"]:
590         for id in t["T_CARRIES"]:
591             t["T_CARRIES"].remove(id)
592             world_db["Things"][id]["T_POSY"] = t["T_POSY"]
593             world_db["Things"][id]["T_POSX"] = t["T_POSX"]
594             world_db["Things"][id]["carried"] = False
595         t["T_TYPE"] = world_db["ThingTypes"][t["T_TYPE"]]["TT_CORPSE_ID"]
596         if world_db["Things"][0] == t:
597             t["fovmap"] = bytearray(b' ' * (world_db["MAP_LENGTH"] ** 2))
598             strong_write(io_db["file_out"], "LOG You die.\n")
599         else:
600             t["fovmap"] = False
601             t["T_MEMMAP"] = False
602             t["T_MEMDEPTHMAP"] = False
603             t["T_MEMTHING"] = []
604
605
606 def mv_yx_in_dir_legal(dir, y, x):
607     """Wrapper around libpr.mv_yx_in_dir_legal to simplify its use."""
608     dir_c = dir.encode("ascii")[0]
609     test = libpr.mv_yx_in_dir_legal_wrap(dir_c, y, x)
610     if -1 == test:
611         raise RuntimeError("Too much wrapping in mv_yx_in_dir_legal_wrap()!")
612     return (test, libpr.result_y(), libpr.result_x())
613
614
615 def actor_wait(t):
616     """Make t do nothing (but loudly, if player avatar)."""
617     if t == world_db["Things"][0]:
618         strong_write(io_db["file_out"], "LOG You wait.\n")
619
620
621 def actor_move(t):
622     """If passable, move/collide(=attack) thing into T_ARGUMENT's direction."""
623     passable = False
624     move_result = mv_yx_in_dir_legal(chr(t["T_ARGUMENT"]),
625                                      t["T_POSY"], t["T_POSX"])
626     if 1 == move_result[0]:
627         pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
628         passable = "." == chr(world_db["MAP"][pos])
629         hitted = [id for id in world_db["Things"]
630                   if world_db["Things"][id] != t
631                   if world_db["Things"][id]["T_LIFEPOINTS"]
632                   if world_db["Things"][id]["T_POSY"] == move_result[1]
633                   if world_db["Things"][id]["T_POSX"] == move_result[2]]
634         if len(hitted):
635             hit_id = hitted[0]
636             if t == world_db["Things"][0]:
637                 hitted_type = world_db["Things"][hit_id]["T_TYPE"]
638                 hitted_name = world_db["ThingTypes"][hitted_type]["TT_NAME"]
639                 strong_write(io_db["file_out"], "LOG You wound "
640                                                 + hitted_name + ".\n")
641             elif 0 == hit_id:
642                 hitter_name = world_db["ThingTypes"][t["T_TYPE"]]["TT_NAME"]
643                 strong_write(io_db["file_out"], "LOG " + hitter_name +
644                                                 " wounds you.\n")
645             decrement_lifepoints(world_db["Things"][hit_id])
646             return
647     dir = [dir for dir in directions_db
648            if directions_db[dir] == chr(t["T_ARGUMENT"])][0]
649     if passable:
650         t["T_POSY"] = move_result[1]
651         t["T_POSX"] = move_result[2]
652         for id in t["T_CARRIES"]:
653             world_db["Things"][id]["T_POSY"] = move_result[1]
654             world_db["Things"][id]["T_POSX"] = move_result[2]
655         build_fov_map(t)
656         if t == world_db["Things"][0]:
657             strong_write(io_db["file_out"], "LOG You move " + dir + ".\n")
658     elif t == world_db["Things"][0]:
659         strong_write(io_db["file_out"], "LOG You fail to move " + dir + ".\n")
660
661
662 def actor_pick_up(t):
663     """Make t pick up (topmost?) Thing from ground into inventory."""
664     # Topmostness is actually not defined so far. Picks most nutritious Thing.
665     ids = [id for id in world_db["Things"] if world_db["Things"][id] != t
666            if not world_db["Things"][id]["carried"]
667            if world_db["Things"][id]["T_POSY"] == t["T_POSY"]
668            if world_db["Things"][id]["T_POSX"] == t["T_POSX"]]
669     if len(ids):
670         highest_id = ids[0]
671         nutritious = 0
672         for id in ids:
673             type = world_db["Things"][id]["T_TYPE"]
674             if world_db["ThingTypes"][type]["TT_CONSUMABLE"] > nutritious:
675                 nutritious = world_db["ThingTypes"][type]["TT_CONSUMABLE"]
676                 highest_id = id
677         world_db["Things"][highest_id]["carried"] = True
678         t["T_CARRIES"].append(highest_id)
679         if t == world_db["Things"][0]:
680             strong_write(io_db["file_out"], "LOG You pick up an object.\n")
681     elif t == world_db["Things"][0]:
682         err = "You try to pick up an object, but there is none."
683         strong_write(io_db["file_out"], "LOG " + err + "\n")
684
685
686 def actor_drop(t):
687     """Make t rop Thing from inventory to ground indexed by T_ARGUMENT."""
688     # TODO: Handle case where T_ARGUMENT matches nothing.
689     if len(t["T_CARRIES"]):
690         id = t["T_CARRIES"][t["T_ARGUMENT"]]
691         t["T_CARRIES"].remove(id)
692         world_db["Things"][id]["carried"] = False
693         if t == world_db["Things"][0]:
694             strong_write(io_db["file_out"], "LOG You drop an object.\n")
695     elif t == world_db["Things"][0]:
696         err = "You try to drop an object, but you own none."
697         strong_write(io_db["file_out"], "LOG " + err + "\n")
698
699
700 def actor_use(t):
701     """Make t use (for now: consume) T_ARGUMENT-indexed Thing in inventory."""
702     # TODO: Handle case where T_ARGUMENT matches nothing.
703     if len(t["T_CARRIES"]):
704         id = t["T_CARRIES"][t["T_ARGUMENT"]]
705         type = world_db["Things"][id]["T_TYPE"]
706         if world_db["ThingTypes"][type]["TT_CONSUMABLE"]:
707             t["T_CARRIES"].remove(id)
708             del world_db["Things"][id]
709             t["T_SATIATION"] += world_db["ThingTypes"][type]["TT_CONSUMABLE"]
710             if t == world_db["Things"][0]:
711                 strong_write(io_db["file_out"],
712                              "LOG You consume this object.\n")
713         elif t == world_db["Things"][0]:
714             strong_write(io_db["file_out"],
715                          "LOG You try to use this object, but fail.\n")
716     elif t == world_db["Things"][0]:
717         strong_write(io_db["file_out"],
718                      "LOG You try to use an object, but you own none.\n")
719
720
721 def thingproliferation(t, prol_map):
722     """To chance of 1/TT_PROLIFERATE, create t offspring in open neighbor cell.
723
724     Naturally only works with TT_PROLIFERATE > 0. The neighbor cell must be be
725     marked '.' in prol_map. If there are several map cell candidates, one is
726     selected randomly.
727     """
728     prolscore = world_db["ThingTypes"][t["T_TYPE"]]["TT_PROLIFERATE"]
729     if prolscore and (1 == prolscore or 1 == (rand.next() % prolscore)):
730         candidates = []
731         for dir in [directions_db[key] for key in directions_db]:
732             mv_result = mv_yx_in_dir_legal(dir, t["T_POSY"], t["T_POSX"])
733             if mv_result[0] and  ord('.') == prol_map[mv_result[1]
734                                                       * world_db["MAP_LENGTH"]
735                                                       + mv_result[2]]:
736                 candidates.append((mv_result[1], mv_result[2]))
737         if len(candidates):
738             i = rand.next() % len(candidates)
739             id = id_setter(-1, "Things")
740             newT = new_Thing(t["T_TYPE"], (candidates[i][0], candidates[i][1]))
741             world_db["Things"][id] = newT
742
743
744 def try_healing(t):
745     """Grow t's HP to a 1/32 chance if < HP max, satiation > 0, and waiting.
746
747     On success, decrease satiation score by 32.
748     """
749     if t["T_SATIATION"] > 0 \
750        and t["T_LIFEPOINTS"] < \
751         world_db["ThingTypes"][t["T_TYPE"]]["TT_LIFEPOINTS"] \
752        and 0 == (rand.next() % 31) \
753        and t["T_COMMAND"] == [id for id in world_db["ThingActions"]
754                               if world_db["ThingActions"][id]["TA_NAME"] ==
755                               "wait"][0]:
756         t["T_LIFEPOINTS"] += 1
757         t["T_SATIATION"] -= 32
758         if t == world_db["Things"][0]:
759             strong_write(io_db["file_out"], "LOG You heal.\n")
760
761
762 def hunger(t):
763     """Decrement t's satiation,dependent on it trigger lifepoint dec chance."""
764     if t["T_SATIATION"] > -32768:
765         t["T_SATIATION"] -= 1
766     testbase = t["T_SATIATION"] if t["T_SATIATION"] >= 0 else -t["T_SATIATION"]
767     if not world_db["ThingTypes"][t["T_TYPE"]]["TT_LIFEPOINTS"]:
768         raise RuntimeError("A thing that should not hunger is hungering.")
769     stomach = int(32767 / world_db["ThingTypes"][t["T_TYPE"]]["TT_LIFEPOINTS"])
770     if int(int(testbase / stomach) / ((rand.next() % stomach) + 1)):
771         if t == world_db["Things"][0]:
772             strong_write(io_db["file_out"], "LOG You suffer from hunger.\n")
773         decrement_lifepoints(t)
774
775
776 def get_dir_to_target(t, filter):
777     """Try to set T_COMMAND/T_ARGUMENT for move to "filter"-determined target.
778
779     The path-wise nearest target is chosen, via the shortest available path.
780     Target must not be t. On succcess, return positive value, else False.
781     Filters:
782     "a": Thing in FOV is below a certain distance, animate, but of ThingType
783          that is not t's, and starts out weaker than t is; build path as
784          avoiding things of t's ThingType
785     "f": neighbor cell (not inhabited by any animate Thing) further away from
786          animate Thing not further than x steps away and in FOV and of a
787          ThingType that is not t's, and starts out stronger or as strong as t
788          is currently; or (cornered), if no such flight cell, but Thing of
789          above criteria is too near,1 a cell closer to it, or, if less near,
790          just wait
791     "c": Thing in memorized map is consumable
792     "s": memory map cell with greatest-reachable degree of unexploredness
793     """
794
795     def zero_score_map_where_char_on_memdepthmap(c):
796         # OUTSOURCED FOR PERFORMANCE REASONS TO libplomrogue.so:
797         # for i in [i for i in range(world_db["MAP_LENGTH"] ** 2)
798         #           if t["T_MEMDEPTHMAP"][i] == mem_depth_c[0]]:
799         #     set_map_score(i, 0)
800         map = c_pointer_to_bytearray(t["T_MEMDEPTHMAP"])
801         if libpr.zero_score_map_where_char_on_memdepthmap(c, map):
802             raise RuntimeError("No score map allocated for "
803                                "zero_score_map_where_char_on_memdepthmap().")
804
805     def set_map_score(pos, score):
806         test = libpr.set_map_score(pos, score)
807         if test:
808             raise RuntimeError("No score map allocated for set_map_score().")
809
810     def get_map_score(pos):
811         result = libpr.get_map_score(pos)
812         if result < 0:
813             raise RuntimeError("No score map allocated for get_map_score().")
814         return result
815
816     def seeing_thing():
817         if t["fovmap"] and ("a" == filter or "f" == filter):
818             for id in world_db["Things"]:
819                 Thing = world_db["Things"][id]
820                 if Thing != t and Thing["T_LIFEPOINTS"] and \
821                    t["T_TYPE"] != Thing["T_TYPE"] and \
822                    'v' == chr(t["fovmap"][(Thing["T_POSY"]
823                                           * world_db["MAP_LENGTH"])
824                                           + Thing["T_POSX"]]):
825                     ThingType = world_db["ThingTypes"][Thing["T_TYPE"]]
826                     if ("f" == filter and ThingType["TT_LIFEPOINTS"] >=
827                         t["T_LIFEPOINTS"]) \
828                        or ("a" == filter and ThingType["TT_LIFEPOINTS"] <
829                             t["T_LIFEPOINTS"]):
830                         return True
831         elif t["T_MEMMAP"] and "c" == filter:
832             for mt in t["T_MEMTHING"]:
833                 if ' ' != chr(t["T_MEMMAP"][(mt[1] * world_db["MAP_LENGTH"])
834                                             + mt[2]]) \
835                    and world_db["ThingTypes"][mt[0]]["TT_CONSUMABLE"]:
836                     return True
837         return False
838
839     def set_cells_passable_on_memmap_to_65534_on_scoremap():
840         # OUTSOURCED FOR PERFORMANCE REASONS TO libplomrogue.so:
841         # ord_dot = ord(".")
842         # memmap = t["T_MEMMAP"]
843         # for i in [i for i in range(world_db["MAP_LENGTH"] ** 2)
844         #            if ord_dot == memmap[i]]:
845         #     set_map_score(i, 65534) # i.e. 65535-1
846         map = c_pointer_to_bytearray(t["T_MEMMAP"])
847         if libpr.set_cells_passable_on_memmap_to_65534_on_scoremap(map):
848             raise RuntimeError("No score map allocated for set_cells_passable"
849                                "_on_memmap_to_65534_on_scoremap().")
850
851     def init_score_map():
852         test = libpr.init_score_map()
853         if test:
854             raise RuntimeError("Malloc error in init_score_map().")
855         ord_v = ord("v")
856         ord_blank = ord(" ")
857         set_cells_passable_on_memmap_to_65534_on_scoremap()
858         if "a" == filter:
859             for id in world_db["Things"]:
860                 Thing = world_db["Things"][id]
861                 pos = Thing["T_POSY"] * world_db["MAP_LENGTH"] \
862                     + Thing["T_POSX"]
863                 if t != Thing and Thing["T_LIFEPOINTS"] and \
864                    t["T_TYPE"] != Thing["T_TYPE"] and \
865                    ord_v == t["fovmap"][pos] and \
866                    t["T_LIFEPOINTS"] > \
867                    world_db["ThingTypes"][Thing["T_TYPE"]]["TT_LIFEPOINTS"]:
868                     set_map_score(pos, 0)
869                 elif t["T_TYPE"] == Thing["T_TYPE"]:
870                     set_map_score(pos, 65535)
871         elif "f" == filter:
872             for id in [id for id in world_db["Things"]
873                        if world_db["Things"][id]["T_LIFEPOINTS"]]:
874                 Thing = world_db["Things"][id]
875                 pos = Thing["T_POSY"] * world_db["MAP_LENGTH"] \
876                     + Thing["T_POSX"]
877                 if t["T_TYPE"] != Thing["T_TYPE"] and \
878                    ord_v == t["fovmap"][pos] and \
879                    t["T_LIFEPOINTS"] <= \
880                    world_db["ThingTypes"][Thing["T_TYPE"]]["TT_LIFEPOINTS"]:
881                     set_map_score(pos, 0)
882         elif "c" == filter:
883             for mt in [mt for mt in t["T_MEMTHING"]
884                        if ord_blank != t["T_MEMMAP"][mt[1]
885                                                      * world_db["MAP_LENGTH"]
886                                                      + mt[2]]
887                        if world_db["ThingTypes"][mt[0]]["TT_CONSUMABLE"]]:
888                 set_map_score(mt[1] * world_db["MAP_LENGTH"] + mt[2], 0)
889         elif "s" == filter:
890             zero_score_map_where_char_on_memdepthmap(mem_depth_c[0])
891
892     def rand_target_dir(neighbors, cmp, dirs):
893         candidates = []
894         n_candidates = 0
895         for i in range(len(dirs)):
896             if cmp == neighbors[i]:
897                 candidates.append(dirs[i])
898                 n_candidates += 1
899         return candidates[rand.next() % n_candidates] if n_candidates else 0
900
901     def get_neighbor_scores(dirs, eye_pos):
902         scores = []
903         if libpr.ready_neighbor_scores(eye_pos):
904             raise RuntimeError("No score map allocated for " +
905                                "ready_neighbor_scores.()")
906         for i in range(len(dirs)):
907             scores.append(libpr.get_neighbor_score(i))
908         return scores
909
910     def get_dir_from_neighbors():
911         dir_to_target = False
912         dirs = "edcxsw"
913         eye_pos = t["T_POSY"] * world_db["MAP_LENGTH"] + t["T_POSX"]
914         neighbors = get_neighbor_scores(dirs, eye_pos)
915         if "f" == filter:
916             inhabited = [world_db["Things"][id]["T_POSY"]
917                          * world_db["MAP_LENGTH"]
918                          + world_db["Things"][id]["T_POSX"]
919                          for id in world_db["Things"]
920                          if world_db["Things"][id]["T_LIFEPOINTS"]]
921             for i in range(len(dirs)):
922                 mv_yx_in_dir_legal(dirs[i], t["T_POSY"], t["T_POSX"])
923                 pos_cmp = libpr.result_y() * world_db["MAP_LENGTH"] \
924                     + libpr.result_x()
925                 for pos in [pos for pos in inhabited if pos == pos_cmp]:
926                     neighbors[i] = 65535
927                     break
928         minmax_start = 0 if "f" == filter else 65535 - 1
929         minmax_neighbor = minmax_start
930         for i in range(len(dirs)):
931             if ("f" == filter and get_map_score(eye_pos) < neighbors[i] and
932                 minmax_neighbor < neighbors[i] and 65535 != neighbors[i]) \
933                or ("f" != filter and minmax_neighbor > neighbors[i]):
934                 minmax_neighbor = neighbors[i]
935         if minmax_neighbor != minmax_start:
936             dir_to_target = rand_target_dir(neighbors, minmax_neighbor, dirs)
937         if "f" == filter:
938             if not dir_to_target:
939                 if 1 == get_map_score(eye_pos):
940                     dir_to_target = rand_target_dir(neighbors, 0, dirs)
941                 elif 3 >= get_map_score(eye_pos):
942                     t["T_COMMAND"] = [id for id in world_db["ThingActions"]
943                                       if
944                                       world_db["ThingActions"][id]["TA_NAME"]
945                                       == "wait"][0]
946                     return 1
947             elif dir_to_target and 3 < get_map_score(eye_pos):
948                 dir_to_target = 0
949         elif "a" == filter and 10 <= get_map_score(eye_pos):
950             dir_to_target = 0
951         return dir_to_target
952
953     dir_to_target = False
954     mem_depth_c = b' '
955     run_i = 9 + 1 if "s" == filter else 1
956     while run_i and not dir_to_target and ("s" == filter or seeing_thing()):
957         run_i -= 1
958         init_score_map()
959         mem_depth_c = b'9' if b' ' == mem_depth_c \
960             else bytes([mem_depth_c[0] - 1])
961         if libpr.dijkstra_map():
962             raise RuntimeError("No score map allocated for dijkstra_map().")
963         dir_to_target = get_dir_from_neighbors()
964         libpr.free_score_map()
965         if dir_to_target and str == type(dir_to_target):
966             t["T_COMMAND"] = [id for id in world_db["ThingActions"]
967                               if world_db["ThingActions"][id]["TA_NAME"]
968                               == "move"][0]
969             t["T_ARGUMENT"] = ord(dir_to_target)
970     return dir_to_target
971
972
973 def standing_on_consumable(t):
974     """Return True/False whether t is standing on a consumable."""
975     for id in [id for id in world_db["Things"] if world_db["Things"][id] != t
976                if world_db["Things"][id]["T_POSY"] == t["T_POSY"]
977                if world_db["Things"][id]["T_POSX"] == t["T_POSX"]
978                if world_db["ThingTypes"][world_db["Things"][id]["T_TYPE"]]
979                           ["TT_CONSUMABLE"]]:
980         return True
981     return False
982
983
984 def get_inventory_slot_to_consume(t):
985     """Return slot Id of strongest consumable in t's inventory, else -1."""
986     cmp_consumability = 0
987     selection = -1
988     i = 0
989     for id in t["T_CARRIES"]:
990         type = world_db["Things"][id]["T_TYPE"]
991         if world_db["ThingTypes"][type]["TT_CONSUMABLE"] > cmp_consumability:
992             cmp_consumability = world_db["ThingTypes"][type]["TT_CONSUMABLE"]
993             selection = i
994         i += 1
995     return selection
996
997
998 def ai(t):
999     """Determine next command/argment for actor t via AI algorithms.
1000
1001     AI will look for, and move towards, enemies (animate Things not of their
1002     own ThingType); if they see none, they will consume consumables in their
1003     inventory; if there are none, they will pick up what they stand on if they
1004     stand on consumables; if they stand on none, they will move towards the
1005     next consumable they see or remember on the map; if they see or remember
1006     none, they will explore parts of the map unseen since ever or for at least
1007     one turn; if there is nothing to explore, they will simply wait.
1008     """
1009     t["T_COMMAND"] = [id for id in world_db["ThingActions"]
1010                       if world_db["ThingActions"][id]["TA_NAME"] == "wait"][0]
1011     if not get_dir_to_target(t, "f"):
1012         sel = get_inventory_slot_to_consume(t)
1013         if -1 != sel:
1014             t["T_COMMAND"] = [id for id in world_db["ThingActions"]
1015                               if world_db["ThingActions"][id]["TA_NAME"]
1016                               == "use"][0]
1017             t["T_ARGUMENT"] = sel
1018         elif standing_on_consumable(t):
1019             t["T_COMMAND"] = [id for id in world_db["ThingActions"]
1020                               if world_db["ThingActions"][id]["TA_NAME"]
1021                               == "pick_up"][0]
1022         elif (not get_dir_to_target(t, "c")) and \
1023              (not get_dir_to_target(t, "a")):
1024             get_dir_to_target(t, "s")
1025
1026
1027 def turn_over():
1028     """Run game world and its inhabitants until new player input expected."""
1029     id = 0
1030     whilebreaker = False
1031     while world_db["Things"][0]["T_LIFEPOINTS"]:
1032         proliferable_map = world_db["MAP"][:]
1033         for id in [id for id in world_db["Things"]
1034                    if not world_db["Things"][id]["carried"]]:
1035             y = world_db["Things"][id]["T_POSY"]
1036             x = world_db["Things"][id]["T_POSX"]
1037             proliferable_map[y * world_db["MAP_LENGTH"] + x] = ord('X')
1038         for id in [id for id in world_db["Things"]]:  # Only what's from start!
1039             if not id in world_db["Things"] or \
1040                world_db["Things"][id]["carried"]:   # May have been consumed or
1041                 continue                            # picked up during turn …
1042             Thing = world_db["Things"][id]
1043             if Thing["T_LIFEPOINTS"]:
1044                 if not Thing["T_COMMAND"]:
1045                     update_map_memory(Thing)
1046                     if 0 == id:
1047                         whilebreaker = True
1048                         break
1049                     ai(Thing)
1050                 try_healing(Thing)
1051                 hunger(Thing)
1052                 if Thing["T_LIFEPOINTS"]:
1053                     Thing["T_PROGRESS"] += 1
1054                     taid = [a for a in world_db["ThingActions"]
1055                               if a == Thing["T_COMMAND"]][0]
1056                     ThingAction = world_db["ThingActions"][taid]
1057                     if Thing["T_PROGRESS"] == ThingAction["TA_EFFORT"]:
1058                         eval("actor_" + ThingAction["TA_NAME"])(Thing)
1059                         Thing["T_COMMAND"] = 0
1060                         Thing["T_PROGRESS"] = 0
1061             thingproliferation(Thing, proliferable_map)
1062         if whilebreaker:
1063             break
1064         world_db["TURN"] += 1
1065
1066
1067 def new_Thing(type, pos=(0, 0)):
1068     """Return Thing of type T_TYPE, with fovmap if alive and world active."""
1069     thing = {
1070         "T_LIFEPOINTS": world_db["ThingTypes"][type]["TT_LIFEPOINTS"],
1071         "T_ARGUMENT": 0,
1072         "T_PROGRESS": 0,
1073         "T_SATIATION": 0,
1074         "T_COMMAND": 0,
1075         "T_TYPE": type,
1076         "T_POSY": pos[0],
1077         "T_POSX": pos[1],
1078         "T_CARRIES": [],
1079         "carried": False,
1080         "T_MEMTHING": [],
1081         "T_MEMMAP": False,
1082         "T_MEMDEPTHMAP": False,
1083         "fovmap": False
1084     }
1085     if world_db["WORLD_ACTIVE"] and thing["T_LIFEPOINTS"]:
1086         build_fov_map(thing)
1087     return thing
1088
1089
1090 def id_setter(id, category, id_store=False, start_at_1=False):
1091     """Set ID of object of category to manipulate ID unused? Create new one.
1092     The ID is stored as id_store.id (if id_store is set). If the integer of the
1093     input is valid (if start_at_1, >= 0, else >= -1), but <0 or (if start_at_1)
1094     <1, calculate new ID: lowest unused ID >=0 or (if start_at_1) >= 1. None is
1095     always returned when no new object is created, else the new object's ID.
1096     """
1097     min = 0 if start_at_1 else -1
1098     if str == type(id):
1099         id = integer_test(id, min)
1100     if None != id:
1101         if id in world_db[category]:
1102             if id_store:
1103                 id_store.id = id
1104             return None
1105         else:
1106             if (start_at_1 and 0 == id) \
1107                or ((not start_at_1) and (id < 0)):
1108                 id = 0 if start_at_1 else -1
1109                 while 1:
1110                     id = id + 1
1111                     if id not in world_db[category]:
1112                         break
1113             if id_store:
1114                 id_store.id = id
1115     return id
1116
1117
1118 def command_ping():
1119     """Send PONG line to server output file."""
1120     strong_write(io_db["file_out"], "PONG\n")
1121
1122
1123 def command_quit():
1124     """Abort server process."""
1125     if None == opts.replay:
1126         if world_db["WORLD_ACTIVE"]:
1127             save_world()
1128         atomic_write(io_db["path_record"], io_db["record_chunk"], do_append=True)
1129     raise SystemExit("received QUIT command")
1130
1131
1132 def command_thingshere(str_y, str_x):
1133     """Write to out file list of Things known to player at coordinate y, x."""
1134     if world_db["WORLD_ACTIVE"]:
1135         y = integer_test(str_y, 0, 255)
1136         x = integer_test(str_x, 0, 255)
1137         length = world_db["MAP_LENGTH"]
1138         if None != y and None != x and y < length and x < length:
1139             pos = (y * world_db["MAP_LENGTH"]) + x
1140             strong_write(io_db["file_out"], "THINGS_HERE START\n")
1141             if "v" == chr(world_db["Things"][0]["fovmap"][pos]):
1142                 for id in world_db["Things"]:
1143                     if y == world_db["Things"][id]["T_POSY"] \
1144                        and x == world_db["Things"][id]["T_POSX"] \
1145                        and not world_db["Things"][id]["carried"]:
1146                         type = world_db["Things"][id]["T_TYPE"]
1147                         name = world_db["ThingTypes"][type]["TT_NAME"]
1148                         strong_write(io_db["file_out"], name + "\n")
1149             else:
1150                 for mt in world_db["Things"][0]["T_MEMTHING"]:
1151                     if y == mt[1] and x == mt[2]:
1152                         name = world_db["ThingTypes"][mt[0]]["TT_NAME"]
1153                         strong_write(io_db["file_out"], name + "\n")
1154             strong_write(io_db["file_out"], "THINGS_HERE END\n")
1155         else:
1156             print("Ignoring: Invalid map coordinates.")
1157     else:
1158         print("Ignoring: Command only works on existing worlds.")
1159
1160
1161 def play_commander(action, args=False):
1162     """Setter for player's T_COMMAND and T_ARGUMENT, then calling turn_over().
1163
1164     T_ARGUMENT is set to direction char if action=="wait",or 8-bit int if args.
1165     """
1166
1167     def set_command():
1168         id = [x for x in world_db["ThingActions"]
1169               if world_db["ThingActions"][x]["TA_NAME"] == action][0]
1170         world_db["Things"][0]["T_COMMAND"] = id
1171         turn_over()
1172
1173     def set_command_and_argument_int(str_arg):
1174         val = integer_test(str_arg, 0, 255)
1175         if None != val:
1176             world_db["Things"][0]["T_ARGUMENT"] = val
1177             set_command()
1178
1179     def set_command_and_argument_movestring(str_arg):
1180         if str_arg in directions_db:
1181             world_db["Things"][0]["T_ARGUMENT"] = ord(directions_db[str_arg])
1182             set_command()
1183         else:
1184             print("Ignoring: Argument must be valid direction string.")
1185
1186     if action == "move":
1187         return set_command_and_argument_movestring
1188     elif args:
1189         return set_command_and_argument_int
1190     else:
1191         return set_command
1192
1193
1194 def command_seedrandomness(seed_string):
1195     """Set rand seed to int(seed_string)."""
1196     val = integer_test(seed_string, 0, 4294967295)
1197     if None != val:
1198         rand.seed = val
1199
1200
1201 def command_makeworld(seed_string):
1202     """(Re-)build game world, i.e. map, things, to a new turn 1 from seed.
1203
1204     Seed rand with seed. Do more only with a "wait" ThingAction and
1205     world["PLAYER_TYPE"] matching ThingType of TT_START_NUMBER > 0. Then,
1206     world_db["Things"] emptied, call make_map() and set
1207     world_db["WORLD_ACTIVE"], world_db["TURN"] to 1. Build new Things
1208     according to ThingTypes' TT_START_NUMBERS, with Thing of ID 0 to ThingType
1209     of ID = world["PLAYER_TYPE"]. Place Things randomly, and actors not on each
1210     other. Init player's memory map. Write "NEW_WORLD" line to out file.
1211     """
1212
1213     def free_pos():
1214         i = 0
1215         while 1:
1216             err = "Space to put thing on too hard to find. Map too small?"
1217             while 1:
1218                 y = rand.next() % world_db["MAP_LENGTH"]
1219                 x = rand.next() % world_db["MAP_LENGTH"]
1220                 if "." == chr(world_db["MAP"][y * world_db["MAP_LENGTH"] + x]):
1221                     break
1222                 i += 1
1223                 if i == 65535:
1224                     raise SystemExit(err)
1225             # Replica of C code, wrongly ignores animatedness of new Thing.
1226             pos_clear = (0 == len([id for id in world_db["Things"]
1227                                    if world_db["Things"][id]["T_LIFEPOINTS"]
1228                                    if world_db["Things"][id]["T_POSY"] == y
1229                                    if world_db["Things"][id]["T_POSX"] == x]))
1230             if pos_clear:
1231                 break
1232         return (y, x)
1233
1234     val = integer_test(seed_string, 0, 4294967295)
1235     if None == val:
1236         return
1237     rand.seed = val
1238     player_will_be_generated = False
1239     playertype = world_db["PLAYER_TYPE"]
1240     for ThingType in world_db["ThingTypes"]:
1241         if playertype == ThingType:
1242             if 0 < world_db["ThingTypes"][ThingType]["TT_START_NUMBER"]:
1243                 player_will_be_generated = True
1244             break
1245     if not player_will_be_generated:
1246         print("Ignoring: No player type with start number >0 defined.")
1247         return
1248     wait_action = False
1249     for ThingAction in world_db["ThingActions"]:
1250         if "wait" == world_db["ThingActions"][ThingAction]["TA_NAME"]:
1251             wait_action = True
1252     if not wait_action:
1253         print("Ignoring beyond SEED_MAP: " +
1254               "No thing action with name 'wait' defined.")
1255         return
1256     world_db["Things"] = {}
1257     make_map()
1258     world_db["WORLD_ACTIVE"] = 1
1259     world_db["TURN"] = 1
1260     for i in range(world_db["ThingTypes"][playertype]["TT_START_NUMBER"]):
1261         id = id_setter(-1, "Things")
1262         world_db["Things"][id] = new_Thing(playertype, free_pos())
1263     if not world_db["Things"][0]["fovmap"]:
1264         empty_fovmap = bytearray(b" " * world_db["MAP_LENGTH"] ** 2)
1265         world_db["Things"][0]["fovmap"] = empty_fovmap
1266     update_map_memory(world_db["Things"][0])
1267     for type in world_db["ThingTypes"]:
1268         for i in range(world_db["ThingTypes"][type]["TT_START_NUMBER"]):
1269             if type != playertype:
1270                 id = id_setter(-1, "Things")
1271                 world_db["Things"][id] = new_Thing(type, free_pos())
1272     strong_write(io_db["file_out"], "NEW_WORLD\n")
1273
1274
1275 def command_maplength(maplength_string):
1276     """Redefine map length. Invalidate map, therefore lose all things on it."""
1277     val = integer_test(maplength_string, 1, 256)
1278     if None != val:
1279         world_db["MAP_LENGTH"] = val
1280         world_db["MAP"] = False
1281         set_world_inactive()
1282         world_db["Things"] = {}
1283         libpr.set_maplength(val)
1284
1285
1286 def command_worldactive(worldactive_string):
1287     """Toggle world_db["WORLD_ACTIVE"] if possible.
1288
1289     An active world can always be set inactive. An inactive world can only be
1290     set active with a "wait" ThingAction, and a player Thing (of ID 0), and a
1291     map. On activation, rebuild all Things' FOVs, and the player's map memory.
1292     """
1293     val = integer_test(worldactive_string, 0, 1)
1294     if None != val:
1295         if 0 != world_db["WORLD_ACTIVE"]:
1296             if 0 == val:
1297                 set_world_inactive()
1298             else:
1299                 print("World already active.")
1300         elif 0 == world_db["WORLD_ACTIVE"]:
1301             wait_exists = False
1302             for ThingAction in world_db["ThingActions"]:
1303                 if "wait" == world_db["ThingActions"][ThingAction]["TA_NAME"]:
1304                     wait_exists = True
1305                     break
1306             player_exists = False
1307             for Thing in world_db["Things"]:
1308                 if 0 == Thing:
1309                     player_exists = True
1310                     break
1311             if wait_exists and player_exists and world_db["MAP"]:
1312                 for id in world_db["Things"]:
1313                     if world_db["Things"][id]["T_LIFEPOINTS"]:
1314                         build_fov_map(world_db["Things"][id])
1315                         if 0 == id:
1316                             update_map_memory(world_db["Things"][id], False)
1317                 if not world_db["Things"][0]["T_LIFEPOINTS"]:
1318                     empty_fovmap = bytearray(b" " * world_db["MAP_LENGTH"] ** 2)
1319                     world_db["Things"][0]["fovmap"] = empty_fovmap
1320                 world_db["WORLD_ACTIVE"] = 1
1321             else:
1322                 print("Ignoring: Not all conditions for world activation met.")
1323
1324
1325 def test_for_id_maker(object, category):
1326     """Return decorator testing for object having "id" attribute."""
1327     def decorator(f):
1328         def helper(*args):
1329             if hasattr(object, "id"):
1330                 f(*args)
1331             else:
1332                 print("Ignoring: No " + category +
1333                       " defined to manipulate yet.")
1334         return helper
1335     return decorator
1336
1337
1338 def command_tid(id_string):
1339     """Set ID of Thing to manipulate. ID unused? Create new one.
1340
1341     Default new Thing's type to the first available ThingType, others: zero.
1342     """
1343     id = id_setter(id_string, "Things", command_tid)
1344     if None != id:
1345         if world_db["ThingTypes"] == {}:
1346             print("Ignoring: No ThingType to settle new Thing in.")
1347             return
1348         type = list(world_db["ThingTypes"].keys())[0]
1349         world_db["Things"][id] = new_Thing(type)
1350
1351
1352 test_Thing_id = test_for_id_maker(command_tid, "Thing")
1353
1354
1355 @test_Thing_id
1356 def command_tcommand(str_int):
1357     """Set T_COMMAND of selected Thing."""
1358     val = integer_test(str_int, 0)
1359     if None != val:
1360         if 0 == val or val in world_db["ThingActions"]:
1361             world_db["Things"][command_tid.id]["T_COMMAND"] = val
1362         else:
1363             print("Ignoring: ThingAction ID belongs to no known ThingAction.")
1364
1365
1366 @test_Thing_id
1367 def command_ttype(str_int):
1368     """Set T_TYPE of selected Thing."""
1369     val = integer_test(str_int, 0)
1370     if None != val:
1371         if val in world_db["ThingTypes"]:
1372             world_db["Things"][command_tid.id]["T_TYPE"] = val
1373         else:
1374             print("Ignoring: ThingType ID belongs to no known ThingType.")
1375
1376
1377 @test_Thing_id
1378 def command_tcarries(str_int):
1379     """Append int(str_int) to T_CARRIES of selected Thing.
1380
1381     The ID int(str_int) must not be of the selected Thing, and must belong to a
1382     Thing with unset "carried" flag. Its "carried" flag will be set on owning.
1383     """
1384     val = integer_test(str_int, 0)
1385     if None != val:
1386         if val == command_tid.id:
1387             print("Ignoring: Thing cannot carry itself.")
1388         elif val in world_db["Things"] \
1389                 and not world_db["Things"][val]["carried"]:
1390             world_db["Things"][command_tid.id]["T_CARRIES"].append(val)
1391             world_db["Things"][val]["carried"] = True
1392         else:
1393             print("Ignoring: Thing not available for carrying.")
1394     # Note that the whole carrying structure is different from the C version:
1395     # Carried-ness is marked by a "carried" flag, not by Things containing
1396     # Things internally.
1397
1398
1399 @test_Thing_id
1400 def command_tmemthing(str_t, str_y, str_x):
1401     """Add (int(str_t), int(str_y), int(str_x)) to selected Thing's T_MEMTHING.
1402
1403     The type must fit to an existing ThingType, and the position into the map.
1404     """
1405     type = integer_test(str_t, 0)
1406     posy = integer_test(str_y, 0, 255)
1407     posx = integer_test(str_x, 0, 255)
1408     if None != type and None != posy and None != posx:
1409         if type not in world_db["ThingTypes"] \
1410            or posy >= world_db["MAP_LENGTH"] or posx >= world_db["MAP_LENGTH"]:
1411             print("Ignoring: Illegal value for thing type or position.")
1412         else:
1413             memthing = (type, posy, posx)
1414             world_db["Things"][command_tid.id]["T_MEMTHING"].append(memthing)
1415
1416
1417 def setter_map(maptype):
1418     """Set (world or Thing's) map of maptype's int(str_int)-th line to mapline.
1419
1420     If no map of maptype exists yet, initialize it with ' ' bytes first.
1421     """
1422
1423     def valid_map_line(str_int, mapline):
1424         val = integer_test(str_int, 0, 255)
1425         if None != val:
1426             if val >= world_db["MAP_LENGTH"]:
1427                 print("Illegal value for map line number.")
1428             elif len(mapline) != world_db["MAP_LENGTH"]:
1429                 print("Map line length is unequal map width.")
1430             else:
1431                 return val
1432         return None
1433
1434     def nonThingMap_helper(str_int, mapline):
1435         val = valid_map_line(str_int, mapline)
1436         if None != val:
1437             length = world_db["MAP_LENGTH"]
1438             if not world_db["MAP"]:
1439                 map = bytearray(b' ' * (length ** 2))
1440             else:
1441                 map = world_db["MAP"]
1442             map[val * length:(val * length) + length] = mapline.encode()
1443             if not world_db["MAP"]:
1444                 world_db["MAP"] = map
1445
1446     @test_Thing_id
1447     def ThingMap_helper(str_int, mapline):
1448         val = valid_map_line(str_int, mapline)
1449         if None != val:
1450             length = world_db["MAP_LENGTH"]
1451             if not world_db["Things"][command_tid.id][maptype]:
1452                 map = bytearray(b' ' * (length ** 2))
1453             else:
1454                 map = world_db["Things"][command_tid.id][maptype]
1455             map[val * length:(val * length) + length] = mapline.encode()
1456             if not world_db["Things"][command_tid.id][maptype]:
1457                 world_db["Things"][command_tid.id][maptype] = map
1458
1459     return nonThingMap_helper if maptype == "MAP" else ThingMap_helper
1460
1461
1462
1463 def setter_tpos(axis):
1464     """Generate setter for T_POSX or  T_POSY of selected Thing.
1465
1466     If world is active, rebuilds animate things' fovmap, player's memory map.
1467     """
1468     @test_Thing_id
1469     def helper(str_int):
1470         val = integer_test(str_int, 0, 255)
1471         if None != val:
1472             if val < world_db["MAP_LENGTH"]:
1473                 world_db["Things"][command_tid.id]["T_POS" + axis] = val
1474                 if world_db["WORLD_ACTIVE"] \
1475                    and world_db["Things"][command_tid.id]["T_LIFEPOINTS"]:
1476                     build_fov_map(world_db["Things"][command_tid.id])
1477                     if 0 == command_tid.id:
1478                         update_map_memory(world_db["Things"][command_tid.id])
1479             else:
1480                 print("Ignoring: Position is outside of map.")
1481     return helper
1482
1483
1484 def command_ttid(id_string):
1485     """Set ID of ThingType to manipulate. ID unused? Create new one.
1486
1487     Default new ThingType's TT_SYMBOL to "?", TT_CORPSE_ID to self, others: 0.
1488     """
1489     id = id_setter(id_string, "ThingTypes", command_ttid)
1490     if None != id:
1491         world_db["ThingTypes"][id] = {
1492             "TT_NAME": "(none)",
1493             "TT_CONSUMABLE": 0,
1494             "TT_LIFEPOINTS": 0,
1495             "TT_PROLIFERATE": 0,
1496             "TT_START_NUMBER": 0,
1497             "TT_SYMBOL": "?",
1498             "TT_CORPSE_ID": id
1499         }
1500
1501
1502 test_ThingType_id = test_for_id_maker(command_ttid, "ThingType")
1503
1504
1505 @test_ThingType_id
1506 def command_ttname(name):
1507     """Set TT_NAME of selected ThingType."""
1508     world_db["ThingTypes"][command_ttid.id]["TT_NAME"] = name
1509
1510
1511 @test_ThingType_id
1512 def command_ttsymbol(char):
1513     """Set TT_SYMBOL of selected ThingType. """
1514     if 1 == len(char):
1515         world_db["ThingTypes"][command_ttid.id]["TT_SYMBOL"] = char
1516     else:
1517         print("Ignoring: Argument must be single character.")
1518
1519
1520 @test_ThingType_id
1521 def command_ttcorpseid(str_int):
1522     """Set TT_CORPSE_ID of selected ThingType."""
1523     val = integer_test(str_int, 0)
1524     if None != val:
1525         if val in world_db["ThingTypes"]:
1526             world_db["ThingTypes"][command_ttid.id]["TT_CORPSE_ID"] = val
1527         else:
1528             print("Ignoring: Corpse ID belongs to no known ThignType.")
1529
1530
1531 def command_taid(id_string):
1532     """Set ID of ThingAction to manipulate. ID unused? Create new one.
1533
1534     Default new ThingAction's TA_EFFORT to 1, its TA_NAME to "wait".
1535     """
1536     id = id_setter(id_string, "ThingActions", command_taid, True)
1537     if None != id:
1538         world_db["ThingActions"][id] = {
1539             "TA_EFFORT": 1,
1540             "TA_NAME": "wait"
1541         }
1542
1543
1544 test_ThingAction_id = test_for_id_maker(command_taid, "ThingAction")
1545
1546
1547 @test_ThingAction_id
1548 def command_taname(name):
1549     """Set TA_NAME of selected ThingAction.
1550
1551     The name must match a valid thing action function. If after the name
1552     setting no ThingAction with name "wait" remains, call set_world_inactive().
1553     """
1554     if name == "wait" or name == "move" or name == "use" or name == "drop" \
1555        or name == "pick_up":
1556         world_db["ThingActions"][command_taid.id]["TA_NAME"] = name
1557         if 1 == world_db["WORLD_ACTIVE"]:
1558             wait_defined = False
1559             for id in world_db["ThingActions"]:
1560                 if "wait" == world_db["ThingActions"][id]["TA_NAME"]:
1561                     wait_defined = True
1562                     break
1563             if not wait_defined:
1564                 set_world_inactive()
1565     else:
1566         print("Ignoring: Invalid action name.")
1567     # In contrast to the original,naming won't map a function to a ThingAction.
1568
1569
1570 def command_ai():
1571     """Call ai() on player Thing, then turn_over()."""
1572     ai(world_db["Things"][0])
1573     turn_over()
1574
1575
1576 """Commands database.
1577
1578 Map command start tokens to ([0]) number of expected command arguments, ([1])
1579 the command's meta-ness (i.e. is it to be written to the record file, is it to
1580 be ignored in replay mode if read from server input file), and ([2]) a function
1581 to be called on it.
1582 """
1583 commands_db = {
1584     "QUIT": (0, True, command_quit),
1585     "PING": (0, True, command_ping),
1586     "THINGS_HERE": (2, True, command_thingshere),
1587     "MAKE_WORLD": (1, False, command_makeworld),
1588     "SEED_RANDOMNESS": (1, False, command_seedrandomness),
1589     "TURN": (1, False, setter(None, "TURN", 0, 65535)),
1590     "PLAYER_TYPE": (1, False, setter(None, "PLAYER_TYPE", 0)),
1591     "MAP_LENGTH": (1, False, command_maplength),
1592     "WORLD_ACTIVE": (1, False, command_worldactive),
1593     "MAP": (2, False, setter_map("MAP")),
1594     "TA_ID": (1, False, command_taid),
1595     "TA_EFFORT": (1, False, setter("ThingAction", "TA_EFFORT", 0, 255)),
1596     "TA_NAME": (1, False, command_taname),
1597     "TT_ID": (1, False, command_ttid),
1598     "TT_NAME": (1, False, command_ttname),
1599     "TT_SYMBOL": (1, False, command_ttsymbol),
1600     "TT_CORPSE_ID": (1, False, command_ttcorpseid),
1601     "TT_CONSUMABLE": (1, False, setter("ThingType", "TT_CONSUMABLE",
1602                                        0, 65535)),
1603     "TT_START_NUMBER": (1, False, setter("ThingType", "TT_START_NUMBER",
1604                                          0, 255)),
1605     "TT_PROLIFERATE": (1, False, setter("ThingType", "TT_PROLIFERATE",
1606                                         0, 255)),
1607     "TT_LIFEPOINTS": (1, False, setter("ThingType", "TT_LIFEPOINTS", 0, 255)),
1608     "T_ID": (1, False, command_tid),
1609     "T_ARGUMENT": (1, False, setter("Thing", "T_ARGUMENT", 0, 255)),
1610     "T_PROGRESS": (1, False, setter("Thing", "T_PROGRESS", 0, 255)),
1611     "T_LIFEPOINTS": (1, False, setter("Thing", "T_LIFEPOINTS", 0, 255)),
1612     "T_SATIATION": (1, False, setter("Thing", "T_SATIATION", -32768, 32767)),
1613     "T_COMMAND": (1, False, command_tcommand),
1614     "T_TYPE": (1, False, command_ttype),
1615     "T_CARRIES": (1, False, command_tcarries),
1616     "T_MEMMAP": (2, False, setter_map("T_MEMMAP")),
1617     "T_MEMDEPTHMAP": (2, False, setter_map("T_MEMDEPTHMAP")),
1618     "T_MEMTHING": (3, False, command_tmemthing),
1619     "T_POSY": (1, False, setter_tpos("Y")),
1620     "T_POSX": (1, False, setter_tpos("X")),
1621     "wait": (0, False, play_commander("wait")),
1622     "move": (1, False, play_commander("move")),
1623     "pick_up": (0, False, play_commander("pick_up")),
1624     "drop": (1, False, play_commander("drop", True)),
1625     "use": (1, False, play_commander("use", True)),
1626     "ai": (0, False, command_ai)
1627 }
1628 # TODO: Unhandled cases: (Un-)killing animates (esp. player!) with T_LIFEPOINTS.
1629
1630
1631 """World state database. With sane default values. (Randomness is in rand.)"""
1632 world_db = {
1633     "TURN": 0,
1634     "MAP_LENGTH": 64,
1635     "PLAYER_TYPE": 0,
1636     "WORLD_ACTIVE": 0,
1637     "MAP": False,
1638     "ThingActions": {},
1639     "ThingTypes": {},
1640     "Things": {}
1641 }
1642
1643 """Mapping of direction names to internal direction chars."""
1644 directions_db = {"east": "d", "south-east": "c", "south-west": "x",
1645                  "west": "s", "north-west": "w", "north-east": "e"}
1646
1647 """File IO database."""
1648 io_db = {
1649     "path_save": "save",
1650     "path_record": "record_save",
1651     "path_worldconf": "confserver/world",
1652     "path_server": "server/",
1653     "path_in": "server/in",
1654     "path_out": "server/out",
1655     "path_worldstate": "server/worldstate",
1656     "tmp_suffix": "_tmp",
1657     "kicked_by_rival": False,
1658     "worldstate_updateable": False
1659 }
1660
1661
1662 try:
1663     libpr = prep_library()
1664     rand = RandomnessIO()
1665     opts = parse_command_line_arguments()
1666     if opts.savefile:
1667         io_db["path_save"] = opts.savefile
1668         io_db["path_record"] = "record_" + opts.savefile
1669     setup_server_io()
1670     if opts.verbose:
1671         io_db["verbose"] = True
1672     if None != opts.replay:
1673         replay_game()
1674     else:
1675         play_game()
1676 except SystemExit as exit:
1677     print("ABORTING: " + exit.args[0])
1678 except:
1679     print("SOMETHING WENT WRONG IN UNEXPECTED WAYS")
1680     raise
1681 finally:
1682     cleanup_server_io()