home · contact · privacy
Make PtIG default game, add documentation.
[plomrogue] / server / utils.py
1 import ctypes
2
3
4 def mv_yx_in_dir_legal(dir, y, x):
5     """Wrapper around libpr.mv_yx_in_dir_legal to simplify its use."""
6     dir_c = dir.encode("ascii")[0]
7     test = libpr.mv_yx_in_dir_legal_wrap(dir_c, y, x)
8     if -1 == test:
9         raise RuntimeError("Too much wrapping in mv_yx_in_dir_legal_wrap()!")
10     return (test, libpr.result_y(), libpr.result_x())
11
12
13 class RandomnessIO:
14     """"Interface to libplomrogue's pseudo-randomness generator."""
15
16     def set_seed(self, seed):
17         libpr.seed_rrand(1, seed)
18
19     def get_seed(self):
20         return libpr.seed_rrand(0, 0)
21
22     def next(self):
23         return libpr.rrand()
24
25     seed = property(get_seed, set_seed)
26
27
28 def integer_test(val_string, min, max=None):
29     """Return val_string if integer >= min & (if max set) <= max, else None."""
30     try:
31         val = int(val_string)
32         if val < min or (max is not None and val > max):
33             raise ValueError
34         return val
35     except ValueError:
36         msg = "Ignoring: Please use integer >= " + str(min)
37         if max is not None:
38             msg += " and <= " + str(max)
39         msg += "."
40         print(msg)
41         return None
42
43
44 def id_setter(id, category, id_store=False, start_at_1=False):
45     """Set ID of object of category to manipulate. ID unused? Create new one.
46
47     The ID is stored as id_store.id (if id_store is set). If the integer of the
48     input is valid (if start_at_1, >= 0, else >= -1), but <0 or (if start_at_1)
49     <1, calculate new ID: lowest unused ID >=0 or (if start_at_1) >= 1. None is
50     always returned when no new object is created, else the new object's ID.
51     """
52     from server.config.world_data import world_db
53     min = 0 if start_at_1 else -1
54     if str == type(id):
55         id = integer_test(id, min)
56     if None != id:
57         if id in world_db[category]:
58             if id_store:
59                 id_store.id = id
60             return None
61         else:
62             if (start_at_1 and 0 == id) \
63                or ((not start_at_1) and (id < 0)):
64                 id = 0 if start_at_1 else -1
65                 while 1:
66                     id = id + 1
67                     if id not in world_db[category]:
68                         break
69             if id_store:
70                 id_store.id = id
71     return id
72
73
74 def prep_library():
75     """Prepare ctypes library at ./libplomrogue.so"""
76     import os
77     libpath = ("./libplomrogue.so")
78     if not os.access(libpath, os.F_OK):
79         raise SystemExit("No library " + libpath + ", run ./build.sh first?")
80     libpr = ctypes.cdll.LoadLibrary(libpath)
81     libpr.seed_rrand.restype = ctypes.c_uint32
82     return libpr
83
84
85 def c_pointer_to_bytearray(ba):
86     """Return C char * pointer to ba."""
87     ty = ctypes.c_char * len(ba)
88     return ty.from_buffer(ba)
89
90
91 def c_pointer_to_string(string):
92     """Return C char * pointer to string."""
93     p = ctypes.c_char_p(string.encode("ascii"))
94     return p
95
96
97 def parse_command_line_arguments():
98     """Return settings values read from command line arguments."""
99     import argparse
100     parser = argparse.ArgumentParser()
101     parser.add_argument('-s', nargs='?', type=int, dest='replay', const=1,
102                         action='store')
103     parser.add_argument('-l', nargs="?", const="save", dest='savefile',
104                         action="store")
105     parser.add_argument('-w', type=str,
106                         default="confserver/PleaseTheIslandGod",
107                         dest='worldconf', action='store')
108     parser.add_argument('-v', dest='verbose', action='store_true')
109     opts, unknown = parser.parse_known_args()
110     return opts
111
112
113 libpr = prep_library()
114 rand = RandomnessIO()
115 opts = parse_command_line_arguments()