home · contact · privacy
Server: Make list of symbols of passable fields configurable.
[plomrogue] / server / world.py
1 from server.config.world_data import world_db
2 from server.io import log
3 from server.utils import rand, libpr, c_pointer_to_bytearray
4 from server.utils import id_setter
5
6
7 def thingproliferation(t, prol_map):
8     """To chance of 1/TT_PROLIFERATE, create t offspring in open neighbor cell.
9
10     Naturally only works with TT_PROLIFERATE > 0. The neighbor cell must be be
11     marked "." in prol_map. If there are several map cell candidates, one is
12     selected randomly.
13     """
14     from server.config.world_data import directions_db
15     from server.utils import mv_yx_in_dir_legal
16     prolscore = world_db["ThingTypes"][t["T_TYPE"]]["TT_PROLIFERATE"]
17     if prolscore and (1 == prolscore or 1 == (rand.next() % prolscore)):
18         candidates = []
19         for dir in [directions_db[key] for key in sorted(directions_db.keys())]:
20             mv_result = mv_yx_in_dir_legal(dir, t["T_POSY"], t["T_POSX"])
21             if mv_result[0] and  ord(".") == prol_map[mv_result[1]
22                                                       * world_db["MAP_LENGTH"]
23                                                       + mv_result[2]]:
24                 candidates.append((mv_result[1], mv_result[2]))
25         if len(candidates):
26             i = rand.next() % len(candidates)
27             id = id_setter(-1, "Things")
28             newT = new_Thing(t["T_TYPE"], (candidates[i][0], candidates[i][1]))
29             world_db["Things"][id] = newT
30
31
32 def update_map_memory(t, age_map=True):
33     """Update t's T_MEMMAP with what's in its FOV now,age its T_MEMMEPTHMAP."""
34
35     def age_some_memdepthmap_on_nonfov_cells():
36         # OUTSOURCED FOR PERFORMANCE REASONS TO libplomrogue.so:
37         # ord_v = ord("v")
38         # ord_0 = ord("0")
39         # ord_9 = ord("9")
40         # for pos in [pos for pos in range(world_db["MAP_LENGTH"] ** 2)
41         #             if not ord_v == t["fovmap"][pos]
42         #             if ord_0 <= t["T_MEMDEPTHMAP"][pos]
43         #             if ord_9 > t["T_MEMDEPTHMAP"][pos]
44         #             if not rand.next() % (2 **
45         #                                   (t["T_MEMDEPTHMAP"][pos] - 48))]:
46         #     t["T_MEMDEPTHMAP"][pos] += 1
47         memdepthmap = c_pointer_to_bytearray(t["T_MEMDEPTHMAP"])
48         fovmap = c_pointer_to_bytearray(t["fovmap"])
49         libpr.age_some_memdepthmap_on_nonfov_cells(memdepthmap, fovmap)
50
51     if not t["T_MEMMAP"]:
52         t["T_MEMMAP"] = bytearray(b' ' * (world_db["MAP_LENGTH"] ** 2))
53     if not t["T_MEMDEPTHMAP"]:
54         t["T_MEMDEPTHMAP"] = bytearray(b' ' * (world_db["MAP_LENGTH"] ** 2))
55     ord_v = ord("v")
56     ord_0 = ord("0")
57     for pos in [pos for pos in range(world_db["MAP_LENGTH"] ** 2)
58                 if ord_v == t["fovmap"][pos]]:
59         t["T_MEMDEPTHMAP"][pos] = ord_0
60         t["T_MEMMAP"][pos] = world_db["MAP"][pos]
61     if age_map:
62         age_some_memdepthmap_on_nonfov_cells()
63     t["T_MEMTHING"] = [mt for mt in t["T_MEMTHING"]
64                        if ord_v != t["fovmap"][(mt[1] * world_db["MAP_LENGTH"])
65                                                + mt[2]]]
66     for id in [id for id in world_db["Things"]
67                if not world_db["Things"][id]["carried"]]:
68         type = world_db["Things"][id]["T_TYPE"]
69         if not world_db["ThingTypes"][type]["TT_LIFEPOINTS"]:
70             y = world_db["Things"][id]["T_POSY"]
71             x = world_db["Things"][id]["T_POSX"]
72             if ord_v == t["fovmap"][(y * world_db["MAP_LENGTH"]) + x]:
73                 t["T_MEMTHING"].append((type, y, x))
74
75
76 def build_fov_map(t):
77     """Build Thing's FOV map."""
78     t["fovmap"] = bytearray(b'v' * (world_db["MAP_LENGTH"] ** 2))
79     fovmap = c_pointer_to_bytearray(t["fovmap"])
80     map = c_pointer_to_bytearray(world_db["MAP"])
81     if libpr.build_fov_map(t["T_POSY"], t["T_POSX"], fovmap, map):
82         raise RuntimeError("Malloc error in build_fov_Map().")
83
84
85 def new_Thing(_type, pos=(0, 0)):
86     """Return Thing of type T_TYPE, with fovmap if alive and world active."""
87     from server.config.world_data import thing_defaults
88     thing = {}
89     for key in thing_defaults:
90         thing[key] = thing_defaults[key]
91         if type(thing[key]) == list:
92             thing[key] = thing[key][:]
93     thing["T_LIFEPOINTS"] = world_db["ThingTypes"][_type]["TT_LIFEPOINTS"]
94     thing["T_TYPE"] = _type
95     thing["T_POSY"] = pos[0]
96     thing["T_POSX"] = pos[1]
97     if world_db["WORLD_ACTIVE"] and thing["T_LIFEPOINTS"]:
98         build_fov_map(thing)
99     return thing
100
101
102 def decrement_lifepoints(t):
103     """Decrement t's lifepoints by 1, and if to zero, corpse it.
104
105     If t is the player avatar, only blank its fovmap, so that the client may
106     still display memory data. On non-player things, erase fovmap and memory.
107     Dying actors drop all their things.
108     """
109     t["T_LIFEPOINTS"] -= 1
110     if 0 == t["T_LIFEPOINTS"]:
111         for id in t["T_CARRIES"]:
112             t["T_CARRIES"].remove(id)
113             world_db["Things"][id]["T_POSY"] = t["T_POSY"]
114             world_db["Things"][id]["T_POSX"] = t["T_POSX"]
115             world_db["Things"][id]["carried"] = False
116         t["T_TYPE"] = world_db["ThingTypes"][t["T_TYPE"]]["TT_CORPSE_ID"]
117         if world_db["Things"][0] == t:
118             t["fovmap"] = bytearray(b' ' * (world_db["MAP_LENGTH"] ** 2))
119             log("You die.")
120             log("See README on how to start over.")
121         else:
122             t["fovmap"] = False
123             t["T_MEMMAP"] = False
124             t["T_MEMDEPTHMAP"] = False
125             t["T_MEMTHING"] = []
126
127
128 def try_healing(t):
129     """If t's HP < max, increment them if well-nourished, maybe waiting."""
130     if t["T_LIFEPOINTS"] < \
131        world_db["ThingTypes"][t["T_TYPE"]]["TT_LIFEPOINTS"]:
132         wait_id = [id for id in world_db["ThingActions"]
133                       if world_db["ThingActions"][id]["TA_NAME"] == "wait"][0]
134         wait_divider = 8 if t["T_COMMAND"] == wait_id else 1
135         testval = int(abs(t["T_SATIATION"]) / wait_divider)
136         if (testval <= 1 or 1 == (rand.next() % testval)):
137             t["T_LIFEPOINTS"] += 1
138             if t == world_db["Things"][0]:
139                 log("You HEAL.")
140
141
142 def hunger_per_turn(type_id):
143     """The amount of satiation score lost per turn for things of given type."""
144     import math
145     return int(math.sqrt(world_db["ThingTypes"][type_id]["TT_LIFEPOINTS"]))
146
147
148 def hunger(t):
149     """Decrement t's satiation,dependent on it trigger lifepoint dec chance."""
150     if t["T_SATIATION"] > -32768:
151         t["T_SATIATION"] -= hunger_per_turn(t["T_TYPE"])
152     if 0 != t["T_SATIATION"] and 0 == int(rand.next() / abs(t["T_SATIATION"])):
153         if t == world_db["Things"][0]:
154             if t["T_SATIATION"] < 0:
155                 log("You SUFFER from hunger.")
156             else:
157                 log("You SUFFER from over-eating.")
158         decrement_lifepoints(t)
159
160
161 def set_world_inactive():
162     """Set world_db["WORLD_ACTIVE"] to 0 and remove worldstate file."""
163     from server.io import safely_remove_worldstate_file
164     safely_remove_worldstate_file()
165     world_db["WORLD_ACTIVE"] = 0
166
167
168 def make_map():
169     """(Re-)make island map.
170
171     Let "~" represent water, "." land, "X" trees: Build island shape randomly,
172     start with one land cell in the middle, then go into cycle of repeatedly
173     selecting a random sea cell and transforming it into land if it is neighbor
174     to land. The cycle ends when a land cell is due to be created at the map's
175     border. Then put some trees on the map (TODO: more precise algorithm desc).
176     """
177
178     def is_neighbor(coordinates, type):
179         y = coordinates[0]
180         x = coordinates[1]
181         length = world_db["MAP_LENGTH"]
182         ind = y % 2
183         diag_west = x + (ind > 0)
184         diag_east = x + (ind < (length - 1))
185         pos = (y * length) + x
186         if (y > 0 and diag_east
187             and type == chr(world_db["MAP"][pos - length + ind])) \
188            or (x < (length - 1)
189                and type == chr(world_db["MAP"][pos + 1])) \
190            or (y < (length - 1) and diag_east
191                and type == chr(world_db["MAP"][pos + length + ind])) \
192            or (y > 0 and diag_west
193                and type == chr(world_db["MAP"][pos - length - (not ind)])) \
194            or (x > 0
195                and type == chr(world_db["MAP"][pos - 1])) \
196            or (y < (length - 1) and diag_west
197                and type == chr(world_db["MAP"][pos + length - (not ind)])):
198             return True
199         return False
200
201     world_db["MAP"] = bytearray(b'~' * (world_db["MAP_LENGTH"] ** 2))
202     length = world_db["MAP_LENGTH"]
203     add_half_width = (not (length % 2)) * int(length / 2)
204     world_db["MAP"][int((length ** 2) / 2) + add_half_width] = ord(".")
205     while (1):
206         y = rand.next() % length
207         x = rand.next() % length
208         pos = (y * length) + x
209         if "~" == chr(world_db["MAP"][pos]) and is_neighbor((y, x), "."):
210             if y == 0 or y == (length - 1) or x == 0 or x == (length - 1):
211                 break
212             world_db["MAP"][pos] = ord(".")
213     n_trees = int((length ** 2) / 16)
214     i_trees = 0
215     while (i_trees <= n_trees):
216         single_allowed = rand.next() % 32
217         y = rand.next() % length
218         x = rand.next() % length
219         pos = (y * length) + x
220         if "." == chr(world_db["MAP"][pos]) \
221                 and ((not single_allowed) or is_neighbor((y, x), "X")):
222             world_db["MAP"][pos] = ord("X")
223             i_trees += 1
224     # This all-too-precise replica of the original C code misses iter_limit().
225
226
227 def make_world(seed):
228     """(Re-)build game world, i.e. map, things, to a new turn 1 from seed.
229
230     Seed rand with seed. Do more only with a "wait" ThingAction and
231     world["PLAYER_TYPE"] matching ThingType of TT_START_NUMBER > 0. Then,
232     world_db["Things"] emptied, call make_map() and set
233     world_db["WORLD_ACTIVE"], world_db["TURN"] to 1. Build new Things
234     according to ThingTypes' TT_START_NUMBERS, with Thing of ID 0 to ThingType
235     of ID = world["PLAYER_TYPE"]. Place Things randomly, and actors not on each
236     other. Init player's memory map. Write "NEW_WORLD" line to out file.
237     """
238     from server.config.world_data import symbols_passable
239
240     def free_pos():
241         i = 0
242         while 1:
243             err = "Space to put thing on too hard to find. Map too small?"
244             while 1:
245                 y = rand.next() % world_db["MAP_LENGTH"]
246                 x = rand.next() % world_db["MAP_LENGTH"]
247                 if chr(world_db["MAP"][y * world_db["MAP_LENGTH"] + x]) in \
248                     symbols_passable:
249                     break
250                 i += 1
251                 if i == 65535:
252                     raise SystemExit(err)
253             # Replica of C code, wrongly ignores animatedness of new Thing.
254             pos_clear = (0 == len([id for id in world_db["Things"]
255                                    if world_db["Things"][id]["T_LIFEPOINTS"]
256                                    if world_db["Things"][id]["T_POSY"] == y
257                                    if world_db["Things"][id]["T_POSX"] == x]))
258             if pos_clear:
259                 break
260         return (y, x)
261
262     rand.seed = seed 
263     if world_db["MAP_LENGTH"] < 1:
264         print("Ignoring: No map length >= 1 defined.")
265         return
266     libpr.set_maplength(world_db["MAP_LENGTH"])
267     player_will_be_generated = False
268     playertype = world_db["PLAYER_TYPE"]
269     for ThingType in world_db["ThingTypes"]:
270         if playertype == ThingType:
271             if 0 < world_db["ThingTypes"][ThingType]["TT_START_NUMBER"]:
272                 player_will_be_generated = True
273             break
274     if not player_will_be_generated:
275         print("Ignoring: No player type with start number >0 defined.")
276         return
277     wait_action = False
278     for ThingAction in world_db["ThingActions"]:
279         if "wait" == world_db["ThingActions"][ThingAction]["TA_NAME"]:
280             wait_action = True
281     if not wait_action:
282         print("Ignoring beyond SEED_MAP: " +
283               "No thing action with name 'wait' defined.")
284         return
285     world_db["Things"] = {}
286     make_map()
287     world_db["WORLD_ACTIVE"] = 1
288     world_db["TURN"] = 1
289     for i in range(world_db["ThingTypes"][playertype]["TT_START_NUMBER"]):
290         id = id_setter(-1, "Things")
291         world_db["Things"][id] = new_Thing(playertype, free_pos())
292     if not world_db["Things"][0]["fovmap"]:
293         empty_fovmap = bytearray(b" " * world_db["MAP_LENGTH"] ** 2)
294         world_db["Things"][0]["fovmap"] = empty_fovmap
295     update_map_memory(world_db["Things"][0])
296     for type in world_db["ThingTypes"]:
297         for i in range(world_db["ThingTypes"][type]["TT_START_NUMBER"]):
298             if type != playertype:
299                 id = id_setter(-1, "Things")
300                 world_db["Things"][id] = new_Thing(type, free_pos())
301     from server.config.io import io_db
302     from server.io import strong_write
303     strong_write(io_db["file_out"], "NEW_WORLD\n")
304
305
306 def turn_over():
307     """Run game world and its inhabitants until new player input expected."""
308     from server.config.actions import action_db, ai_func
309     id = 0
310     whilebreaker = False
311     while world_db["Things"][0]["T_LIFEPOINTS"]:
312         proliferable_map = world_db["MAP"][:]
313         for id in [id for id in world_db["Things"]
314                    if not world_db["Things"][id]["carried"]]:
315             y = world_db["Things"][id]["T_POSY"]
316             x = world_db["Things"][id]["T_POSX"]
317             proliferable_map[y * world_db["MAP_LENGTH"] + x] = ord('X')
318         for id in [id for id in world_db["Things"]]:  # Only what's from start!
319             if not id in world_db["Things"] or \
320                world_db["Things"][id]["carried"]:   # May have been consumed or
321                 continue                            # picked up during turn …
322             Thing = world_db["Things"][id]
323             if Thing["T_LIFEPOINTS"]:
324                 if not Thing["T_COMMAND"]:
325                     update_map_memory(Thing)
326                     if 0 == id:
327                         whilebreaker = True
328                         break
329                     ai_func(Thing)
330                 try_healing(Thing)
331                 hunger(Thing)
332                 if Thing["T_LIFEPOINTS"]:
333                     Thing["T_PROGRESS"] += 1
334                     taid = [a for a in world_db["ThingActions"]
335                               if a == Thing["T_COMMAND"]][0]
336                     ThingAction = world_db["ThingActions"][taid]
337                     if Thing["T_PROGRESS"] == ThingAction["TA_EFFORT"]:
338                         action = action_db["actor_" + ThingAction["TA_NAME"]]
339                         action(Thing)
340                         Thing["T_COMMAND"] = 0
341                         Thing["T_PROGRESS"] = 0
342             thingproliferation(Thing, proliferable_map)
343         if whilebreaker:
344             break
345         world_db["TURN"] += 1