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
7 def thingproliferation(t, prol_map):
8 """To chance of 1/TT_PROLIFERATE, create t offspring in open neighbor cell.
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
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)):
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"]
24 candidates.append((mv_result[1], mv_result[2]))
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
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."""
35 def age_some_memdepthmap_on_nonfov_cells():
36 # OUTSOURCED FOR PERFORMANCE REASONS TO libplomrogue.so:
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)
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))
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]
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"])
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))
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().")
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
89 for key in thing_defaults:
90 thing[key] = thing_defaults[key]
91 thing["T_LIFEPOINTS"] = world_db["ThingTypes"][type]["TT_LIFEPOINTS"]
92 thing["T_TYPE"] = type
93 thing["T_POSY"] = pos[0]
94 thing["T_POSX"] = pos[1]
95 if world_db["WORLD_ACTIVE"] and thing["T_LIFEPOINTS"]:
100 def decrement_lifepoints(t):
101 """Decrement t's lifepoints by 1, and if to zero, corpse it.
103 If t is the player avatar, only blank its fovmap, so that the client may
104 still display memory data. On non-player things, erase fovmap and memory.
105 Dying actors drop all their things.
107 t["T_LIFEPOINTS"] -= 1
108 if 0 == t["T_LIFEPOINTS"]:
109 for id in t["T_CARRIES"]:
110 t["T_CARRIES"].remove(id)
111 world_db["Things"][id]["T_POSY"] = t["T_POSY"]
112 world_db["Things"][id]["T_POSX"] = t["T_POSX"]
113 world_db["Things"][id]["carried"] = False
114 t["T_TYPE"] = world_db["ThingTypes"][t["T_TYPE"]]["TT_CORPSE_ID"]
115 if world_db["Things"][0] == t:
116 t["fovmap"] = bytearray(b' ' * (world_db["MAP_LENGTH"] ** 2))
118 log("See README on how to start over.")
121 t["T_MEMMAP"] = False
122 t["T_MEMDEPTHMAP"] = False
127 """If t's HP < max, increment them if well-nourished, maybe waiting."""
128 if t["T_LIFEPOINTS"] < \
129 world_db["ThingTypes"][t["T_TYPE"]]["TT_LIFEPOINTS"]:
130 wait_id = [id for id in world_db["ThingActions"]
131 if world_db["ThingActions"][id]["TA_NAME"] == "wait"][0]
132 wait_divider = 8 if t["T_COMMAND"] == wait_id else 1
133 testval = int(abs(t["T_SATIATION"]) / wait_divider)
134 if (testval <= 1 or 1 == (rand.next() % testval)):
135 t["T_LIFEPOINTS"] += 1
136 if t == world_db["Things"][0]:
140 def hunger_per_turn(type_id):
141 """The amount of satiation score lost per turn for things of given type."""
143 return int(math.sqrt(world_db["ThingTypes"][type_id]["TT_LIFEPOINTS"]))
147 """Decrement t's satiation,dependent on it trigger lifepoint dec chance."""
148 if t["T_SATIATION"] > -32768:
149 t["T_SATIATION"] -= hunger_per_turn(t["T_TYPE"])
150 if 0 != t["T_SATIATION"] and 0 == int(rand.next() / abs(t["T_SATIATION"])):
151 if t == world_db["Things"][0]:
152 if t["T_SATIATION"] < 0:
153 log("You SUFFER from hunger.")
155 log("You SUFFER from over-eating.")
156 decrement_lifepoints(t)
159 def set_world_inactive():
160 """Set world_db["WORLD_ACTIVE"] to 0 and remove worldstate file."""
161 from server.io import safely_remove_worldstate_file
162 safely_remove_worldstate_file()
163 world_db["WORLD_ACTIVE"] = 0
167 """(Re-)make island map.
169 Let "~" represent water, "." land, "X" trees: Build island shape randomly,
170 start with one land cell in the middle, then go into cycle of repeatedly
171 selecting a random sea cell and transforming it into land if it is neighbor
172 to land. The cycle ends when a land cell is due to be created at the map's
173 border. Then put some trees on the map (TODO: more precise algorithm desc).
176 def is_neighbor(coordinates, type):
179 length = world_db["MAP_LENGTH"]
181 diag_west = x + (ind > 0)
182 diag_east = x + (ind < (length - 1))
183 pos = (y * length) + x
184 if (y > 0 and diag_east
185 and type == chr(world_db["MAP"][pos - length + ind])) \
187 and type == chr(world_db["MAP"][pos + 1])) \
188 or (y < (length - 1) and diag_east
189 and type == chr(world_db["MAP"][pos + length + ind])) \
190 or (y > 0 and diag_west
191 and type == chr(world_db["MAP"][pos - length - (not ind)])) \
193 and type == chr(world_db["MAP"][pos - 1])) \
194 or (y < (length - 1) and diag_west
195 and type == chr(world_db["MAP"][pos + length - (not ind)])):
199 world_db["MAP"] = bytearray(b'~' * (world_db["MAP_LENGTH"] ** 2))
200 length = world_db["MAP_LENGTH"]
201 add_half_width = (not (length % 2)) * int(length / 2)
202 world_db["MAP"][int((length ** 2) / 2) + add_half_width] = ord(".")
204 y = rand.next() % length
205 x = rand.next() % length
206 pos = (y * length) + x
207 if "~" == chr(world_db["MAP"][pos]) and is_neighbor((y, x), "."):
208 if y == 0 or y == (length - 1) or x == 0 or x == (length - 1):
210 world_db["MAP"][pos] = ord(".")
211 n_trees = int((length ** 2) / 16)
213 while (i_trees <= n_trees):
214 single_allowed = rand.next() % 32
215 y = rand.next() % length
216 x = rand.next() % length
217 pos = (y * length) + x
218 if "." == chr(world_db["MAP"][pos]) \
219 and ((not single_allowed) or is_neighbor((y, x), "X")):
220 world_db["MAP"][pos] = ord("X")
222 # This all-too-precise replica of the original C code misses iter_limit().
225 def make_world(seed):
226 """(Re-)build game world, i.e. map, things, to a new turn 1 from seed.
228 Seed rand with seed. Do more only with a "wait" ThingAction and
229 world["PLAYER_TYPE"] matching ThingType of TT_START_NUMBER > 0. Then,
230 world_db["Things"] emptied, call make_map() and set
231 world_db["WORLD_ACTIVE"], world_db["TURN"] to 1. Build new Things
232 according to ThingTypes' TT_START_NUMBERS, with Thing of ID 0 to ThingType
233 of ID = world["PLAYER_TYPE"]. Place Things randomly, and actors not on each
234 other. Init player's memory map. Write "NEW_WORLD" line to out file.
240 err = "Space to put thing on too hard to find. Map too small?"
242 y = rand.next() % world_db["MAP_LENGTH"]
243 x = rand.next() % world_db["MAP_LENGTH"]
244 if "." == chr(world_db["MAP"][y * world_db["MAP_LENGTH"] + x]):
248 raise SystemExit(err)
249 # Replica of C code, wrongly ignores animatedness of new Thing.
250 pos_clear = (0 == len([id for id in world_db["Things"]
251 if world_db["Things"][id]["T_LIFEPOINTS"]
252 if world_db["Things"][id]["T_POSY"] == y
253 if world_db["Things"][id]["T_POSX"] == x]))
259 if world_db["MAP_LENGTH"] < 1:
260 print("Ignoring: No map length >= 1 defined.")
262 libpr.set_maplength(world_db["MAP_LENGTH"])
263 player_will_be_generated = False
264 playertype = world_db["PLAYER_TYPE"]
265 for ThingType in world_db["ThingTypes"]:
266 if playertype == ThingType:
267 if 0 < world_db["ThingTypes"][ThingType]["TT_START_NUMBER"]:
268 player_will_be_generated = True
270 if not player_will_be_generated:
271 print("Ignoring: No player type with start number >0 defined.")
274 for ThingAction in world_db["ThingActions"]:
275 if "wait" == world_db["ThingActions"][ThingAction]["TA_NAME"]:
278 print("Ignoring beyond SEED_MAP: " +
279 "No thing action with name 'wait' defined.")
281 world_db["Things"] = {}
283 world_db["WORLD_ACTIVE"] = 1
285 for i in range(world_db["ThingTypes"][playertype]["TT_START_NUMBER"]):
286 id = id_setter(-1, "Things")
287 world_db["Things"][id] = new_Thing(playertype, free_pos())
288 if not world_db["Things"][0]["fovmap"]:
289 empty_fovmap = bytearray(b" " * world_db["MAP_LENGTH"] ** 2)
290 world_db["Things"][0]["fovmap"] = empty_fovmap
291 update_map_memory(world_db["Things"][0])
292 for type in world_db["ThingTypes"]:
293 for i in range(world_db["ThingTypes"][type]["TT_START_NUMBER"]):
294 if type != playertype:
295 id = id_setter(-1, "Things")
296 world_db["Things"][id] = new_Thing(type, free_pos())
297 from server.config.io import io_db
298 from server.io import strong_write
299 strong_write(io_db["file_out"], "NEW_WORLD\n")
303 """Run game world and its inhabitants until new player input expected."""
304 from server.config.actions import action_db, ai_func
307 while world_db["Things"][0]["T_LIFEPOINTS"]:
308 proliferable_map = world_db["MAP"][:]
309 for id in [id for id in world_db["Things"]
310 if not world_db["Things"][id]["carried"]]:
311 y = world_db["Things"][id]["T_POSY"]
312 x = world_db["Things"][id]["T_POSX"]
313 proliferable_map[y * world_db["MAP_LENGTH"] + x] = ord('X')
314 for id in [id for id in world_db["Things"]]: # Only what's from start!
315 if not id in world_db["Things"] or \
316 world_db["Things"][id]["carried"]: # May have been consumed or
317 continue # picked up during turn …
318 Thing = world_db["Things"][id]
319 if Thing["T_LIFEPOINTS"]:
320 if not Thing["T_COMMAND"]:
321 update_map_memory(Thing)
328 if Thing["T_LIFEPOINTS"]:
329 Thing["T_PROGRESS"] += 1
330 taid = [a for a in world_db["ThingActions"]
331 if a == Thing["T_COMMAND"]][0]
332 ThingAction = world_db["ThingActions"][taid]
333 if Thing["T_PROGRESS"] == ThingAction["TA_EFFORT"]:
334 action = action_db["actor_" + ThingAction["TA_NAME"]]
336 Thing["T_COMMAND"] = 0
337 Thing["T_PROGRESS"] = 0
338 thingproliferation(Thing, proliferable_map)
341 world_db["TURN"] += 1