home · contact · privacy
Server: Fix bug in carry list of newly instantiated Things.
[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
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]):
247                     break
248                 i += 1
249                 if i == 65535:
250                     raise SystemExit(err)
251             # Replica of C code, wrongly ignores animatedness of new Thing.
252             pos_clear = (0 == len([id for id in world_db["Things"]
253                                    if world_db["Things"][id]["T_LIFEPOINTS"]
254                                    if world_db["Things"][id]["T_POSY"] == y
255                                    if world_db["Things"][id]["T_POSX"] == x]))
256             if pos_clear:
257                 break
258         return (y, x)
259
260     rand.seed = seed 
261     if world_db["MAP_LENGTH"] < 1:
262         print("Ignoring: No map length >= 1 defined.")
263         return
264     libpr.set_maplength(world_db["MAP_LENGTH"])
265     player_will_be_generated = False
266     playertype = world_db["PLAYER_TYPE"]
267     for ThingType in world_db["ThingTypes"]:
268         if playertype == ThingType:
269             if 0 < world_db["ThingTypes"][ThingType]["TT_START_NUMBER"]:
270                 player_will_be_generated = True
271             break
272     if not player_will_be_generated:
273         print("Ignoring: No player type with start number >0 defined.")
274         return
275     wait_action = False
276     for ThingAction in world_db["ThingActions"]:
277         if "wait" == world_db["ThingActions"][ThingAction]["TA_NAME"]:
278             wait_action = True
279     if not wait_action:
280         print("Ignoring beyond SEED_MAP: " +
281               "No thing action with name 'wait' defined.")
282         return
283     world_db["Things"] = {}
284     make_map()
285     world_db["WORLD_ACTIVE"] = 1
286     world_db["TURN"] = 1
287     for i in range(world_db["ThingTypes"][playertype]["TT_START_NUMBER"]):
288         id = id_setter(-1, "Things")
289         world_db["Things"][id] = new_Thing(playertype, free_pos())
290     if not world_db["Things"][0]["fovmap"]:
291         empty_fovmap = bytearray(b" " * world_db["MAP_LENGTH"] ** 2)
292         world_db["Things"][0]["fovmap"] = empty_fovmap
293     update_map_memory(world_db["Things"][0])
294     for type in world_db["ThingTypes"]:
295         for i in range(world_db["ThingTypes"][type]["TT_START_NUMBER"]):
296             if type != playertype:
297                 id = id_setter(-1, "Things")
298                 world_db["Things"][id] = new_Thing(type, free_pos())
299     from server.config.io import io_db
300     from server.io import strong_write
301     strong_write(io_db["file_out"], "NEW_WORLD\n")
302
303
304 def turn_over():
305     """Run game world and its inhabitants until new player input expected."""
306     from server.config.actions import action_db, ai_func
307     id = 0
308     whilebreaker = False
309     while world_db["Things"][0]["T_LIFEPOINTS"]:
310         proliferable_map = world_db["MAP"][:]
311         for id in [id for id in world_db["Things"]
312                    if not world_db["Things"][id]["carried"]]:
313             y = world_db["Things"][id]["T_POSY"]
314             x = world_db["Things"][id]["T_POSX"]
315             proliferable_map[y * world_db["MAP_LENGTH"] + x] = ord('X')
316         for id in [id for id in world_db["Things"]]:  # Only what's from start!
317             if not id in world_db["Things"] or \
318                world_db["Things"][id]["carried"]:   # May have been consumed or
319                 continue                            # picked up during turn …
320             Thing = world_db["Things"][id]
321             if Thing["T_LIFEPOINTS"]:
322                 if not Thing["T_COMMAND"]:
323                     update_map_memory(Thing)
324                     if 0 == id:
325                         whilebreaker = True
326                         break
327                     ai_func(Thing)
328                 try_healing(Thing)
329                 hunger(Thing)
330                 if Thing["T_LIFEPOINTS"]:
331                     Thing["T_PROGRESS"] += 1
332                     taid = [a for a in world_db["ThingActions"]
333                               if a == Thing["T_COMMAND"]][0]
334                     ThingAction = world_db["ThingActions"][taid]
335                     if Thing["T_PROGRESS"] == ThingAction["TA_EFFORT"]:
336                         action = action_db["actor_" + ThingAction["TA_NAME"]]
337                         action(Thing)
338                         Thing["T_COMMAND"] = 0
339                         Thing["T_PROGRESS"] = 0
340             thingproliferation(Thing, proliferable_map)
341         if whilebreaker:
342             break
343         world_db["TURN"] += 1