home · contact · privacy
40fa6937a491c5d48f9ef67d54e1d85321fcc0a0
[plomrogue] / plugins / server / PleaseTheIslandGod.py
1 from server.io import log, strong_write
2 from server.config.world_data import world_db, symbols_passable, directions_db
3 from server.utils import mv_yx_in_dir_legal, rand, id_setter
4 from server.config.io import io_db
5 from server.new_thing import new_Thing
6
7 def make_world(seed):
8     from server.update_map_memory import update_map_memory
9     from server.config.misc import make_map_func
10     from server.utils import libpr
11
12     def free_pos(plant=False):
13         i = 0
14         while 1:
15             err = "Space to put thing on too hard to find. Map too small?"
16             while 1:
17                 y = rand.next() % world_db["MAP_LENGTH"]
18                 x = rand.next() % world_db["MAP_LENGTH"]
19                 pos = y * world_db["MAP_LENGTH"] + x;
20                 if (not plant
21                     and "." == chr(world_db["MAP"][pos])) \
22                    or ":" == chr(world_db["MAP"][pos]):
23                     break
24                 i += 1
25                 if i == 65535:
26                     raise SystemExit(err)
27             pos_clear = (0 == len([id for id in world_db["Things"]
28                                    if world_db["Things"][id]["T_LIFEPOINTS"]
29                                    if world_db["Things"][id]["T_POSY"] == y
30                                    if world_db["Things"][id]["T_POSX"] == x]))
31             if pos_clear:
32                 break
33         return (y, x)
34
35     rand.seed = seed
36     if world_db["MAP_LENGTH"] < 1:
37         print("Ignoring: No map length >= 1 defined.")
38         return
39     libpr.set_maplength(world_db["MAP_LENGTH"])
40     player_will_be_generated = False
41     playertype = world_db["PLAYER_TYPE"]
42     for ThingType in world_db["ThingTypes"]:
43         if playertype == ThingType:
44             if 0 < world_db["ThingTypes"][ThingType]["TT_START_NUMBER"]:
45                 player_will_be_generated = True
46             break
47     if not player_will_be_generated:
48         print("Ignoring: No player type with start number >0 defined.")
49         return
50     wait_action = False
51     for ThingAction in world_db["ThingActions"]:
52         if "wait" == world_db["ThingActions"][ThingAction]["TA_NAME"]:
53             wait_action = True
54     if not wait_action:
55         print("Ignoring beyond SEED_MAP: " +
56               "No thing action with name 'wait' defined.")
57         return
58     #for name in specials:
59     #    if world_db[name] not in world_db["ThingTypes"]:
60     #        print("Ignoring: No valid " + name + " set.")
61     #        return
62     world_db["Things"] = {}
63     make_map()
64     world_db["WORLD_ACTIVE"] = 1
65     world_db["TURN"] = 1
66     for i in range(world_db["ThingTypes"][playertype]["TT_START_NUMBER"]):
67         id = id_setter(-1, "Things")
68         world_db["Things"][id] = new_Thing(playertype, free_pos())
69     if not world_db["Things"][0]["fovmap"]:
70         empty_fovmap = bytearray(b" " * world_db["MAP_LENGTH"] ** 2)
71         world_db["Things"][0]["fovmap"] = empty_fovmap
72     update_map_memory(world_db["Things"][0])
73     for type in world_db["ThingTypes"]:
74         for i in range(world_db["ThingTypes"][type]["TT_START_NUMBER"]):
75             if type != playertype:
76                 id = id_setter(-1, "Things")
77                 plantness = world_db["ThingTypes"][type]["TT_PROLIFERATE"]
78                 world_db["Things"][id] = new_Thing(type, free_pos(plantness))
79     strong_write(io_db["file_out"], "NEW_WORLD\n")
80
81 def thingproliferation(t, prol_map):
82     from server.new_thing import new_Thing
83     global directions_db, mv_yx_in_dir_legal
84     prolscore = world_db["ThingTypes"][t["T_TYPE"]]["TT_PROLIFERATE"]
85     if prolscore and \
86       (world_db["ThingTypes"][t["T_TYPE"]]["TT_LIFEPOINTS"] == 0 or
87        t["T_LIFEPOINTS"] >= 0.9 *
88                         world_db["ThingTypes"][t["T_TYPE"]]["TT_LIFEPOINTS"]) \
89        and \
90       (1 == prolscore or 1 == (rand.next() % prolscore)):
91         candidates = []
92         for dir in [directions_db[key] for key in directions_db]:
93             mv_result = mv_yx_in_dir_legal(dir, t["T_POSY"], t["T_POSX"])
94             pos = mv_result[1] * world_db["MAP_LENGTH"] + mv_result[2]
95             if mv_result[0] and \
96                (ord(":") == prol_map[pos]
97                 or (world_db["ThingTypes"][t["T_TYPE"]]["TT_LIFEPOINTS"]
98                     and ord(".") == prol_map[pos])):
99                 candidates.append((mv_result[1], mv_result[2]))
100         if len(candidates):
101             i = rand.next() % len(candidates)
102             id = id_setter(-1, "Things")
103             newT = new_Thing(t["T_TYPE"], (candidates[i][0], candidates[i][1]))
104             world_db["Things"][id] = newT
105             #if (world_db["FAVOR_STAGE"] > 0
106             #    and t["T_TYPE"] == world_db["PLANT_0"]):
107             #    world_db["GOD_FAVOR"] += 5
108             #elif t["T_TYPE"] == world_db["PLANT_1"];
109             #    world_db["GOD_FAVOR"] += 25
110             #elif world_db["FAVOR_STAGE"] >= 4 and \
111             #     t["T_TYPE"] == world_db["ANIMAL_1"]:
112             #    log("The Island God SMILES upon a new-born bear baby.")
113             #    world_db["GOD_FAVOR"] += 750
114
115 def make_map():
116     global rand
117
118     def is_neighbor(coordinates, type):
119         y = coordinates[0]
120         x = coordinates[1]
121         length = world_db["MAP_LENGTH"]
122         ind = y % 2
123         diag_west = x + (ind > 0)
124         diag_east = x + (ind < (length - 1))
125         pos = (y * length) + x
126         if (y > 0 and diag_east
127             and type == chr(world_db["MAP"][pos - length + ind])) \
128            or (x < (length - 1)
129                and type == chr(world_db["MAP"][pos + 1])) \
130            or (y < (length - 1) and diag_east
131                and type == chr(world_db["MAP"][pos + length + ind])) \
132            or (y > 0 and diag_west
133                and type == chr(world_db["MAP"][pos - length - (not ind)])) \
134            or (x > 0
135                and type == chr(world_db["MAP"][pos - 1])) \
136            or (y < (length - 1) and diag_west
137                and type == chr(world_db["MAP"][pos + length - (not ind)])):
138             return True
139         return False
140
141     world_db["MAP"] = bytearray(b'~' * (world_db["MAP_LENGTH"] ** 2))
142     length = world_db["MAP_LENGTH"]
143     add_half_width = (not (length % 2)) * int(length / 2)
144     world_db["MAP"][int((length ** 2) / 2) + add_half_width] = ord(".")
145     while (1):
146         y = rand.next() % length
147         x = rand.next() % length
148         pos = (y * length) + x
149         if "~" == chr(world_db["MAP"][pos]) and is_neighbor((y, x), "."):
150             if y == 0 or y == (length - 1) or x == 0 or x == (length - 1):
151                 break
152             world_db["MAP"][pos] = ord(".")
153     n_trees = int((length ** 2) / 16)
154     i_trees = 0
155     while (i_trees <= n_trees):
156         single_allowed = rand.next() % 32
157         y = rand.next() % length
158         x = rand.next() % length
159         pos = (y * length) + x
160         if "." == chr(world_db["MAP"][pos]) \
161           and ((not single_allowed) or is_neighbor((y, x), "X")):
162             world_db["MAP"][pos] = ord("X")
163             i_trees += 1
164     n_colons = int((length ** 2) / 16)
165     i_colons = 0
166     while (i_colons <= n_colons):
167         single_allowed = rand.next() % 256
168         y = rand.next() % length
169         x = rand.next() % length
170         pos = (y * length) + x
171         if ("." == chr(world_db["MAP"][pos])
172           and ((not single_allowed) or is_neighbor((y, x), ":"))):
173             world_db["MAP"][pos] = ord(":")
174             i_colons += 1
175     altar_placed = False
176     while not altar_placed:
177         y = rand.next() % length
178         x = rand.next() % length
179         pos = (y * length) + x
180         if (("." == chr(world_db["MAP"][pos]
181              or ":" == chr(world_db["MAP"][pos]))
182             and not is_neighbor((y, x), "X"))):
183             world_db["MAP"][pos] = ord("_")
184             world_db["altar"] = (y, x)
185             altar_placed = True
186
187 def ai(t):
188     from server.ai import get_dir_to_target, get_inventory_slot_to_consume, \
189         standing_on_food
190     t["T_COMMAND"] = [id for id in world_db["ThingActions"]
191                       if world_db["ThingActions"][id]["TA_NAME"] == "wait"][0]
192     eating = len([id for id in world_db["ThingActions"]
193                   if world_db["ThingActions"][id]["TA_NAME"] == "use"]) > 0
194     picking = len([id for id in world_db["ThingActions"]
195                    if world_db["ThingActions"][id]["TA_NAME"] == "pickup"]) > 0
196     if eating and picking:
197         if get_dir_to_target(t, "f"):
198             return
199         sel = get_inventory_slot_to_consume(t)
200         if -1 != sel:
201             t["T_COMMAND"] = [id for id in world_db["ThingActions"]
202                               if world_db["ThingActions"][id]["TA_NAME"]
203                                  == "use"][0]
204             t["T_ARGUMENT"] = sel
205         elif standing_on_food(t) and (len(t["T_CARRIES"]) <
206                 world_db["ThingTypes"][t["T_TYPE"]]["TT_STORAGE"]):
207                 t["T_COMMAND"] = [id for id in world_db["ThingActions"]
208                                   if world_db["ThingActions"][id]["TA_NAME"]
209                                   == "pickup"][0]
210         else:
211             going_to_known_food_spot = get_dir_to_target(t, "c")
212             if not going_to_known_food_spot:
213                 aiming_for_walking_food = get_dir_to_target(t, "a")
214                 if not aiming_for_walking_food:
215                     get_dir_to_target(t, "s")
216
217 def actor_pickup(t):
218     from server.ai import eat_vs_hunger_threshold
219     used_slots = len(t["T_CARRIES"])
220     if used_slots < world_db["ThingTypes"][t["T_TYPE"]]["TT_STORAGE"]:
221         ids = [id for id in world_db["Things"] if world_db["Things"][id] != t
222                if not world_db["Things"][id]["carried"]
223                if world_db["Things"][id]["T_POSY"] == t["T_POSY"]
224                if world_db["Things"][id]["T_POSX"] == t["T_POSX"]]
225         if len(ids):
226             lowest_tid = -1
227             eat_cost = eat_vs_hunger_threshold(t["T_TYPE"])
228             for iid in ids:
229                 tid = world_db["Things"][iid]["T_TYPE"] 
230                 if lowest_tid == -1 or tid < lowest_tid:
231                     if (t != world_db["Things"][0] and
232                         (world_db["ThingTypes"][tid]["TT_TOOL"] != "food"
233                          or (world_db["ThingTypes"][tid]["TT_TOOLPOWER"]
234                              <= eat_cost))):
235                         continue
236                     id = iid
237                     lowest_tid = tid
238             world_db["Things"][id]["carried"] = True
239             ty = world_db["Things"][id]["T_TYPE"]
240             if (t != world_db["Things"][0]
241                 and world_db["Things"][id]["T_PLAYERDROP"]
242                 and world_db["ThingTypes"][ty]["TT_TOOL"] == "food"):
243                 score = int(world_db["ThingTypes"][ty]["TT_TOOLPOWER"] / 32)
244                 world_db["GOD_FAVOR"] += score
245                 world_db["Things"][id]["T_PLAYERDROP"] = 0
246             t["T_CARRIES"].append(id)
247             if t == world_db["Things"][0]:
248                 log("You PICK UP an object.")
249     elif t == world_db["Things"][0]:
250         log("Can't pick up object: No storage room to carry more.")
251
252
253 def actor_drop(t):
254     """Make t rop Thing from inventory to ground indexed by T_ARGUMENT."""
255     if len(t["T_CARRIES"]):
256         id = t["T_CARRIES"][t["T_ARGUMENT"]]
257         t["T_CARRIES"].remove(id)
258         world_db["Things"][id]["carried"] = False
259         if t == world_db["Things"][0]:
260             log("You DROP an object.")
261             world_db["Things"][id]["T_PLAYERDROP"] = 1
262
263
264 def actor_move(t):
265
266     def enter_altar():
267         log("YOU ENTER SACRED GROUND.")
268
269     from server.config.world_data import symbols_passable
270     from server.build_fov_map import build_fov_map
271     def decrement_lifepoints(t):
272         t["T_LIFEPOINTS"] -= 1
273         _id = [_id for _id in world_db["Things"] if world_db["Things"][_id] == t][0]
274         if 0 == t["T_LIFEPOINTS"]:
275             sadness = world_db["ThingTypes"][t["T_TYPE"]]["TT_LIFEPOINTS"]
276             for id in t["T_CARRIES"]:
277                 t["T_CARRIES"].remove(id)
278                 world_db["Things"][id]["T_POSY"] = t["T_POSY"]
279                 world_db["Things"][id]["T_POSX"] = t["T_POSX"]
280                 world_db["Things"][id]["carried"] = False
281             t["T_TYPE"] = world_db["ThingTypes"][t["T_TYPE"]]["TT_CORPSE_ID"]
282             if world_db["Things"][0] == t:
283                 t["fovmap"] = bytearray(b' ' * (world_db["MAP_LENGTH"] ** 2))
284                 log("You die.")
285                 log("See README on how to start over.")
286             else:
287                 t["fovmap"] = False
288                 t["T_MEMMAP"] = False
289                 t["T_MEMDEPTHMAP"] = False
290                 t["T_MEMTHING"] = []
291             log("BAR " + str(t["T_LIFEPOINTS"]))
292             return sadness 
293         return 0 
294     passable = False
295     move_result = mv_yx_in_dir_legal(chr(t["T_ARGUMENT"]),
296                                      t["T_POSY"], t["T_POSX"])
297     if 1 == move_result[0]:
298         pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
299         hitted = [id for id in world_db["Things"]
300                   if world_db["Things"][id] != t
301                   if world_db["Things"][id]["T_LIFEPOINTS"]
302                   if world_db["Things"][id]["T_POSY"] == move_result[1]
303                   if world_db["Things"][id]["T_POSX"] == move_result[2]]
304         if len(hitted):
305             hit_id = hitted[0]
306             if t == world_db["Things"][0]:
307                 hitted_type = world_db["Things"][hit_id]["T_TYPE"]
308                 hitted_name = world_db["ThingTypes"][hitted_type]["TT_NAME"]
309                 log("You WOUND " + hitted_name + ".")
310                 world_db["GOD_FAVOR"] -= 1
311             elif 0 == hit_id:
312                 hitter_name = world_db["ThingTypes"][t["T_TYPE"]]["TT_NAME"]
313                 log(hitter_name +" WOUNDS you.")
314             test = decrement_lifepoints(world_db["Things"][hit_id])
315             if test and t == world_db["Things"][0]:
316                 world_db["GOD_FAVOR"] -= test 
317             return
318         passable = chr(world_db["MAP"][pos]) in symbols_passable
319     dir = [dir for dir in directions_db
320            if directions_db[dir] == chr(t["T_ARGUMENT"])][0]
321     if passable:
322         t["T_POSY"] = move_result[1]
323         t["T_POSX"] = move_result[2]
324         for id in t["T_CARRIES"]:
325             world_db["Things"][id]["T_POSY"] = move_result[1]
326             world_db["Things"][id]["T_POSX"] = move_result[2]
327         build_fov_map(t)
328         if t == world_db["Things"][0]:
329             log("You MOVE " + dir + ".")
330             if (move_result[1] == world_db["altar"][0] and
331                 move_result[2] == world_db["altar"][1]):
332                 enter_altar()
333
334 def command_ttid(id_string):
335     id = id_setter(id_string, "ThingTypes", command_ttid)
336     if None != id:
337         world_db["ThingTypes"][id] = {
338             "TT_NAME": "(none)",
339             "TT_TOOLPOWER": 0,
340             "TT_LIFEPOINTS": 0,
341             "TT_PROLIFERATE": 0,
342             "TT_START_NUMBER": 0,
343             "TT_STORAGE": 0,
344             "TT_SYMBOL": "?",
345             "TT_CORPSE_ID": id,
346             "TT_TOOL": ""
347         }
348
349 def command_worldactive(worldactive_string):
350     val = integer_test(worldactive_string, 0, 1)
351     if None != val:
352         if 0 != world_db["WORLD_ACTIVE"]:
353             if 0 == val:
354                 set_world_inactive()
355             else:
356                 print("World already active.")
357         elif 0 == world_db["WORLD_ACTIVE"]:
358             wait_exists = False
359             for ThingAction in world_db["ThingActions"]:
360                 if "wait" == world_db["ThingActions"][ThingAction]["TA_NAME"]:
361                     wait_exists = True
362                     break
363             player_exists = False
364             for Thing in world_db["Things"]:
365                 if 0 == Thing:
366                     player_exists = True
367                     break
368             altar_found = False
369             if world_db["MAP"]:
370                 pos = world_db["MAP"].find(b'_')
371                 if pos > 0:
372                     y = int(pos / world_db["MAP_LENGTH"])
373                     x = pos % world_db["MAP_LENGTH"]
374                     world_db["altar"] = (y, x)
375                     altar_found = True
376             if altar_found and wait_exists and player_exists and \
377                     world_db["MAP"]:
378                 for id in world_db["Things"]:
379                     if world_db["Things"][id]["T_LIFEPOINTS"]:
380                         build_fov_map(world_db["Things"][id])
381                         if 0 == id:
382                             update_map_memory(world_db["Things"][id], False)
383                 if not world_db["Things"][0]["T_LIFEPOINTS"]:
384                     empty_fovmap = bytearray(b" " * world_db["MAP_LENGTH"] ** 2)
385                     world_db["Things"][0]["fovmap"] = empty_fovmap
386                 world_db["WORLD_ACTIVE"] = 1
387             else:
388                 print("Ignoring: Not all conditions for world activation met.")
389
390 strong_write(io_db["file_out"], "PLUGIN PleaseTheIslandGod\n")
391
392 if not "GOD_FAVOR"  in world_db:
393     world_db["GOD_FAVOR"] = 0
394 io_db["worldstate_write_order"] += [["GOD_FAVOR", "world_int"]]
395
396 import server.config.world_data
397 server.config.world_data.symbols_passable += ":_"
398
399 from server.config.world_data import thing_defaults
400 thing_defaults["T_PLAYERDROP"] = 0
401
402 import server.config.actions
403 server.config.actions.action_db["actor_move"] = actor_move
404 server.config.actions.action_db["actor_pickup"] = actor_pickup
405 server.config.actions.action_db["actor_drop"] = actor_drop
406 server.config.actions.ai_func = ai
407
408 from server.config.commands import commands_db
409 commands_db["TT_ID"] = (1, False, command_ttid)
410 commands_db["GOD_FAVOR"] = (1, False, setter(None, "GOD_FAVOR", -32768, 32767))
411 commands_db["TT_STORAGE"] = (1, False, setter("ThingType", "TT_STORAGE", 0, 255))
412 commands_db["T_PLAYERDROP"] = (1, False, setter("Thing", "T_PLAYERDROP", 0, 1))
413 commands_db["WORLD_ACTIVE"] = (1, False, command_worldactive)
414
415 import server.config.misc
416 server.config.misc.make_map_func = make_map
417 server.config.misc.thingproliferation_func = thingproliferation
418 server.config.misc.make_world = make_world