home · contact · privacy
db33eba88ebe79c368f72baf6a38e32c00c63c2f
[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     The ID is stored as id_store.id (if id_store is set). If the integer of the
47     input is valid (if start_at_1, >= 0, else >= -1), but <0 or (if start_at_1)
48     <1, calculate new ID: lowest unused ID >=0 or (if start_at_1) >= 1. None is
49     always returned when no new object is created, else the new object's ID.
50     """
51     from server.config.world_data import world_db
52     min = 0 if start_at_1 else -1
53     if str == type(id):
54         id = integer_test(id, min)
55     if None != id:
56         if id in world_db[category]:
57             if id_store:
58                 id_store.id = id
59             return None
60         else:
61             if (start_at_1 and 0 == id) \
62                or ((not start_at_1) and (id < 0)):
63                 id = 0 if start_at_1 else -1
64                 while 1:
65                     id = id + 1
66                     if id not in world_db[category]:
67                         break
68             if id_store:
69                 id_store.id = id
70     return id
71
72
73 def prep_library():
74     """Prepare ctypes library at ./libplomrogue.so"""
75     import os
76     libpath = ("./libplomrogue.so")
77     if not os.access(libpath, os.F_OK):
78         raise SystemExit("No library " + libpath + ", run ./build.sh first?")
79     libpr = ctypes.cdll.LoadLibrary(libpath)
80     libpr.seed_rrand.restype = ctypes.c_uint32
81     return libpr
82
83
84 def c_pointer_to_bytearray(ba):
85     """Return C char * pointer to ba."""
86     type = ctypes.c_char * len(ba)
87     return type.from_buffer(ba)
88
89
90 def parse_command_line_arguments():
91     """Return settings values read from command line arguments."""
92     import argparse
93     parser = argparse.ArgumentParser()
94     parser.add_argument('-s', nargs='?', type=int, dest='replay', const=1,
95                         action='store')
96     parser.add_argument('-l', nargs="?", const="save", dest='savefile',
97                         action="store")
98     parser.add_argument('-w', type=str, default="confserver/world",
99                         dest='worldconf', action='store')
100     parser.add_argument('-v', dest='verbose', action='store_true')
101     opts, unknown = parser.parse_known_args()
102     return opts
103
104
105 libpr = prep_library()
106 rand = RandomnessIO()
107 opts = parse_command_line_arguments()