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