home · contact · privacy
Plugin: Add endgame.
[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     if not world_db["SLIPPERS"] in world_db["ThingTypes"]:
59         print("Ignoring: No valid SLIPPERS set.")
60         return
61     #for name in specials:
62     #    if world_db[name] not in world_db["ThingTypes"]:
63     #        print("Ignoring: No valid " + name + " set.")
64     #        return
65     world_db["Things"] = {}
66     make_map()
67     world_db["WORLD_ACTIVE"] = 1
68     world_db["TURN"] = 1
69     for i in range(world_db["ThingTypes"][playertype]["TT_START_NUMBER"]):
70         id = id_setter(-1, "Things")
71         world_db["Things"][id] = new_Thing(playertype, free_pos())
72     if not world_db["Things"][0]["fovmap"]:
73         empty_fovmap = bytearray(b" " * world_db["MAP_LENGTH"] ** 2)
74         world_db["Things"][0]["fovmap"] = empty_fovmap
75     update_map_memory(world_db["Things"][0])
76     for type in world_db["ThingTypes"]:
77         for i in range(world_db["ThingTypes"][type]["TT_START_NUMBER"]):
78             if type != playertype:
79                 id = id_setter(-1, "Things")
80                 plantness = world_db["ThingTypes"][type]["TT_PROLIFERATE"]
81                 world_db["Things"][id] = new_Thing(type, free_pos(plantness))
82     strong_write(io_db["file_out"], "NEW_WORLD\n")
83
84 def thingproliferation(t, prol_map):
85     from server.new_thing import new_Thing
86     global directions_db, mv_yx_in_dir_legal
87     prolscore = world_db["ThingTypes"][t["T_TYPE"]]["TT_PROLIFERATE"]
88     if prolscore and \
89       (world_db["ThingTypes"][t["T_TYPE"]]["TT_LIFEPOINTS"] == 0 or
90        t["T_LIFEPOINTS"] >= 0.9 *
91                         world_db["ThingTypes"][t["T_TYPE"]]["TT_LIFEPOINTS"]) \
92        and \
93       (1 == prolscore or 1 == (rand.next() % prolscore)):
94         candidates = []
95         for dir in [directions_db[key] for key in directions_db]:
96             mv_result = mv_yx_in_dir_legal(dir, t["T_POSY"], t["T_POSX"])
97             pos = mv_result[1] * world_db["MAP_LENGTH"] + mv_result[2]
98             if mv_result[0] and \
99                (ord(":") == prol_map[pos]
100                 or (world_db["ThingTypes"][t["T_TYPE"]]["TT_LIFEPOINTS"]
101                     and ord(".") == prol_map[pos])):
102                 candidates.append((mv_result[1], mv_result[2]))
103         if len(candidates):
104             i = rand.next() % len(candidates)
105             id = id_setter(-1, "Things")
106             newT = new_Thing(t["T_TYPE"], (candidates[i][0], candidates[i][1]))
107             world_db["Things"][id] = newT
108             #if (world_db["FAVOR_STAGE"] > 0
109             #    and t["T_TYPE"] == world_db["PLANT_0"]):
110             #    world_db["GOD_FAVOR"] += 5
111             #elif t["T_TYPE"] == world_db["PLANT_1"];
112             #    world_db["GOD_FAVOR"] += 25
113             #elif world_db["FAVOR_STAGE"] >= 4 and \
114             #     t["T_TYPE"] == world_db["ANIMAL_1"]:
115             #    log("The Island God SMILES upon a new-born bear baby.")
116             #    world_db["GOD_FAVOR"] += 750
117
118 def make_map():
119     global rand
120
121     def is_neighbor(coordinates, type):
122         y = coordinates[0]
123         x = coordinates[1]
124         length = world_db["MAP_LENGTH"]
125         ind = y % 2
126         diag_west = x + (ind > 0)
127         diag_east = x + (ind < (length - 1))
128         pos = (y * length) + x
129         if (y > 0 and diag_east
130             and type == chr(world_db["MAP"][pos - length + ind])) \
131            or (x < (length - 1)
132                and type == chr(world_db["MAP"][pos + 1])) \
133            or (y < (length - 1) and diag_east
134                and type == chr(world_db["MAP"][pos + length + ind])) \
135            or (y > 0 and diag_west
136                and type == chr(world_db["MAP"][pos - length - (not ind)])) \
137            or (x > 0
138                and type == chr(world_db["MAP"][pos - 1])) \
139            or (y < (length - 1) and diag_west
140                and type == chr(world_db["MAP"][pos + length - (not ind)])):
141             return True
142         return False
143
144     world_db["MAP"] = bytearray(b'~' * (world_db["MAP_LENGTH"] ** 2))
145     length = world_db["MAP_LENGTH"]
146     add_half_width = (not (length % 2)) * int(length / 2)
147     world_db["MAP"][int((length ** 2) / 2) + add_half_width] = ord(".")
148     while (1):
149         y = rand.next() % length
150         x = rand.next() % length
151         pos = (y * length) + x
152         if "~" == chr(world_db["MAP"][pos]) and is_neighbor((y, x), "."):
153             if y == 0 or y == (length - 1) or x == 0 or x == (length - 1):
154                 break
155             world_db["MAP"][pos] = ord(".")
156     n_trees = int((length ** 2) / 16)
157     i_trees = 0
158     while (i_trees <= n_trees):
159         single_allowed = rand.next() % 32
160         y = rand.next() % length
161         x = rand.next() % length
162         pos = (y * length) + x
163         if "." == chr(world_db["MAP"][pos]) \
164           and ((not single_allowed) or is_neighbor((y, x), "X")):
165             world_db["MAP"][pos] = ord("X")
166             i_trees += 1
167     n_colons = int((length ** 2) / 16)
168     i_colons = 0
169     while (i_colons <= n_colons):
170         single_allowed = rand.next() % 256
171         y = rand.next() % length
172         x = rand.next() % length
173         pos = (y * length) + x
174         if ("." == chr(world_db["MAP"][pos])
175           and ((not single_allowed) or is_neighbor((y, x), ":"))):
176             world_db["MAP"][pos] = ord(":")
177             i_colons += 1
178     altar_placed = False
179     while not altar_placed:
180         y = rand.next() % length
181         x = rand.next() % length
182         pos = (y * length) + x
183         if (("." == chr(world_db["MAP"][pos]
184              or ":" == chr(world_db["MAP"][pos]))
185             and not is_neighbor((y, x), "X"))):
186             world_db["MAP"][pos] = ord("_")
187             world_db["altar"] = (y, x)
188             altar_placed = True
189
190 def ai(t):
191     from server.ai import get_dir_to_target, get_inventory_slot_to_consume, \
192         standing_on_food
193     t["T_COMMAND"] = [id for id in world_db["ThingActions"]
194                       if world_db["ThingActions"][id]["TA_NAME"] == "wait"][0]
195     eating = len([id for id in world_db["ThingActions"]
196                   if world_db["ThingActions"][id]["TA_NAME"] == "use"]) > 0
197     picking = len([id for id in world_db["ThingActions"]
198                    if world_db["ThingActions"][id]["TA_NAME"] == "pickup"]) > 0
199     if eating and picking:
200         if get_dir_to_target(t, "f"):
201             return
202         sel = get_inventory_slot_to_consume(t)
203         if -1 != sel:
204             t["T_COMMAND"] = [id for id in world_db["ThingActions"]
205                               if world_db["ThingActions"][id]["TA_NAME"]
206                                  == "use"][0]
207             t["T_ARGUMENT"] = sel
208         elif standing_on_food(t) and (len(t["T_CARRIES"]) <
209                 world_db["ThingTypes"][t["T_TYPE"]]["TT_STORAGE"]):
210                 t["T_COMMAND"] = [id for id in world_db["ThingActions"]
211                                   if world_db["ThingActions"][id]["TA_NAME"]
212                                   == "pickup"][0]
213         else:
214             going_to_known_food_spot = get_dir_to_target(t, "c")
215             if not going_to_known_food_spot:
216                 aiming_for_walking_food = get_dir_to_target(t, "a")
217                 if not aiming_for_walking_food:
218                     get_dir_to_target(t, "s")
219
220 def actor_pickup(t):
221     from server.ai import eat_vs_hunger_threshold
222     used_slots = len(t["T_CARRIES"])
223     if used_slots < world_db["ThingTypes"][t["T_TYPE"]]["TT_STORAGE"]:
224         ids = [id for id in world_db["Things"] if world_db["Things"][id] != t
225                if not world_db["Things"][id]["carried"]
226                if world_db["Things"][id]["T_POSY"] == t["T_POSY"]
227                if world_db["Things"][id]["T_POSX"] == t["T_POSX"]]
228         if len(ids):
229             lowest_tid = -1
230             eat_cost = eat_vs_hunger_threshold(t["T_TYPE"])
231             for iid in ids:
232                 tid = world_db["Things"][iid]["T_TYPE"] 
233                 if lowest_tid == -1 or tid < lowest_tid:
234                     if (t != world_db["Things"][0] and
235                         (world_db["ThingTypes"][tid]["TT_TOOL"] != "food"
236                          or (world_db["ThingTypes"][tid]["TT_TOOLPOWER"]
237                              <= eat_cost))):
238                         continue
239                     id = iid
240                     lowest_tid = tid
241             world_db["Things"][id]["carried"] = True
242             ty = world_db["Things"][id]["T_TYPE"]
243             if (t != world_db["Things"][0]
244                 and world_db["Things"][id]["T_PLAYERDROP"]
245                 and world_db["ThingTypes"][ty]["TT_TOOL"] == "food"):
246                 score = int(world_db["ThingTypes"][ty]["TT_TOOLPOWER"] / 32)
247                 world_db["GOD_FAVOR"] += score
248                 world_db["Things"][id]["T_PLAYERDROP"] = 0
249             t["T_CARRIES"].append(id)
250             if t == world_db["Things"][0]:
251                 log("You PICK UP an object.")
252     elif t == world_db["Things"][0]:
253         log("Can't pick up object: No storage room to carry more.")
254
255
256 def actor_drop(t):
257     """Make t rop Thing from inventory to ground indexed by T_ARGUMENT."""
258     if len(t["T_CARRIES"]):
259         id = t["T_CARRIES"][t["T_ARGUMENT"]]
260         t["T_CARRIES"].remove(id)
261         world_db["Things"][id]["carried"] = False
262         if t == world_db["Things"][0]:
263             log("You DROP an object.")
264             world_db["Things"][id]["T_PLAYERDROP"] = 1
265
266
267 def actor_use(t):
268     if len(t["T_CARRIES"]):
269         id = t["T_CARRIES"][t["T_ARGUMENT"]]
270         type = world_db["Things"][id]["T_TYPE"]
271         if type == world_db["SLIPPERS"]:
272             if t == world_db["Things"][0]:
273                 log("You use the " + world_db["ThingTypes"][type]["TT_NAME"]
274                     + ". It glows in wondrous colors, and emits a sound as if "
275                     + "from a dying cat. The Island God laughs.\n")
276             t["T_LIFEPOINTS"] = 1
277             decrement_lifepoints(t)
278         elif world_db["ThingTypes"][type]["TT_TOOL"] == "food":
279             t["T_CARRIES"].remove(id)
280             del world_db["Things"][id]
281             t["T_SATIATION"] += world_db["ThingTypes"][type]["TT_TOOLPOWER"]
282             if t == world_db["Things"][0]:
283                 log("You CONSUME this object.")
284         elif t == world_db["Things"][0]:
285             log("You try to use this object, but FAIL.")
286
287 def actor_move(t):
288
289     def enter_altar():
290         if world_db["GAME_WON"]:
291            log("You step on a soul-less slab of stone.")
292            return
293         log("YOU ENTER SACRED GROUND.")
294         if world_db["GOD_FAVOR"] > 9000:
295             world_db["GAME_WON"] = 1
296             log("The Island God speaks to you: \"You have proven yourself wort"
297                  + "hy of my respect. You were a good citizen to the island, a"
298                  + "nd sometimes a better steward to its inhabitants than me. "
299                  + "The island shall miss you when you leave. But you have ear"
300                  + "ned the right to do so. Take this "
301                  + world_db["ThingTypes"][world_db["SLIPPERS"]]["TT_NAME"]
302                  + " and USE it when you please. It will take you to where you"
303                  + " came from. (But do feel free to stay here as long as you "
304                  + "like.)\"")
305             id = id_setter(-1, "Things")
306             world_db["Things"][id] = new_Thing(world_db["SLIPPERS"],
307                                                world_db["altar"])
308
309     from server.config.world_data import symbols_passable
310     from server.build_fov_map import build_fov_map
311     def decrement_lifepoints(t):
312         t["T_LIFEPOINTS"] -= 1
313         _id = [_id for _id in world_db["Things"] if world_db["Things"][_id] == t][0]
314         if 0 == t["T_LIFEPOINTS"]:
315             sadness = world_db["ThingTypes"][t["T_TYPE"]]["TT_LIFEPOINTS"]
316             for id in t["T_CARRIES"]:
317                 t["T_CARRIES"].remove(id)
318                 world_db["Things"][id]["T_POSY"] = t["T_POSY"]
319                 world_db["Things"][id]["T_POSX"] = t["T_POSX"]
320                 world_db["Things"][id]["carried"] = False
321             t["T_TYPE"] = world_db["ThingTypes"][t["T_TYPE"]]["TT_CORPSE_ID"]
322             if world_db["Things"][0] == t:
323                 t["fovmap"] = bytearray(b' ' * (world_db["MAP_LENGTH"] ** 2))
324                 log("You die.")
325                 log("See README on how to start over.")
326             else:
327                 t["fovmap"] = False
328                 t["T_MEMMAP"] = False
329                 t["T_MEMDEPTHMAP"] = False
330                 t["T_MEMTHING"] = []
331             log("BAR " + str(t["T_LIFEPOINTS"]))
332             return sadness 
333         return 0 
334     passable = False
335     move_result = mv_yx_in_dir_legal(chr(t["T_ARGUMENT"]),
336                                      t["T_POSY"], t["T_POSX"])
337     if 1 == move_result[0]:
338         pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
339         hitted = [id for id in world_db["Things"]
340                   if world_db["Things"][id] != t
341                   if world_db["Things"][id]["T_LIFEPOINTS"]
342                   if world_db["Things"][id]["T_POSY"] == move_result[1]
343                   if world_db["Things"][id]["T_POSX"] == move_result[2]]
344         if len(hitted):
345             hit_id = hitted[0]
346             if t == world_db["Things"][0]:
347                 hitted_type = world_db["Things"][hit_id]["T_TYPE"]
348                 hitted_name = world_db["ThingTypes"][hitted_type]["TT_NAME"]
349                 log("You WOUND " + hitted_name + ".")
350                 world_db["GOD_FAVOR"] -= 1
351             elif 0 == hit_id:
352                 hitter_name = world_db["ThingTypes"][t["T_TYPE"]]["TT_NAME"]
353                 log(hitter_name +" WOUNDS you.")
354             test = decrement_lifepoints(world_db["Things"][hit_id])
355             if test and t == world_db["Things"][0]:
356                 world_db["GOD_FAVOR"] -= test 
357             return
358         passable = chr(world_db["MAP"][pos]) in symbols_passable
359     dir = [dir for dir in directions_db
360            if directions_db[dir] == chr(t["T_ARGUMENT"])][0]
361     if passable:
362         t["T_POSY"] = move_result[1]
363         t["T_POSX"] = move_result[2]
364         for id in t["T_CARRIES"]:
365             world_db["Things"][id]["T_POSY"] = move_result[1]
366             world_db["Things"][id]["T_POSX"] = move_result[2]
367         build_fov_map(t)
368         if t == world_db["Things"][0]:
369             log("You MOVE " + dir + ".")
370             if (move_result[1] == world_db["altar"][0] and
371                 move_result[2] == world_db["altar"][1]):
372                 enter_altar()
373
374 def command_ttid(id_string):
375     id = id_setter(id_string, "ThingTypes", command_ttid)
376     if None != id:
377         world_db["ThingTypes"][id] = {
378             "TT_NAME": "(none)",
379             "TT_TOOLPOWER": 0,
380             "TT_LIFEPOINTS": 0,
381             "TT_PROLIFERATE": 0,
382             "TT_START_NUMBER": 0,
383             "TT_STORAGE": 0,
384             "TT_SYMBOL": "?",
385             "TT_CORPSE_ID": id,
386             "TT_TOOL": ""
387         }
388
389 def command_worldactive(worldactive_string):
390     val = integer_test(worldactive_string, 0, 1)
391     if None != val:
392         if 0 != world_db["WORLD_ACTIVE"]:
393             if 0 == val:
394                 set_world_inactive()
395             else:
396                 print("World already active.")
397         elif 0 == world_db["WORLD_ACTIVE"]:
398             wait_exists = False
399             for ThingAction in world_db["ThingActions"]:
400                 if "wait" == world_db["ThingActions"][ThingAction]["TA_NAME"]:
401                     wait_exists = True
402                     break
403             player_exists = False
404             for Thing in world_db["Things"]:
405                 if 0 == Thing:
406                     player_exists = True
407                     break
408             altar_found = False
409             if world_db["MAP"]:
410                 pos = world_db["MAP"].find(b'_')
411                 if pos > 0:
412                     y = int(pos / world_db["MAP_LENGTH"])
413                     x = pos % world_db["MAP_LENGTH"]
414                     world_db["altar"] = (y, x)
415                     altar_found = True
416             valid_slippers = world_db["SLIPPERS"] in world_db["ThingTypes"]
417             if altar_found and wait_exists and player_exists and \
418                     world_db["MAP"] and valid_slippers:
419                 for id in world_db["Things"]:
420                     if world_db["Things"][id]["T_LIFEPOINTS"]:
421                         build_fov_map(world_db["Things"][id])
422                         if 0 == id:
423                             update_map_memory(world_db["Things"][id], False)
424                 if not world_db["Things"][0]["T_LIFEPOINTS"]:
425                     empty_fovmap = bytearray(b" " * world_db["MAP_LENGTH"] ** 2)
426                     world_db["Things"][0]["fovmap"] = empty_fovmap
427                 world_db["WORLD_ACTIVE"] = 1
428             else:
429                 print("Ignoring: Not all conditions for world activation met.")
430
431 def command_slippers(str_int):
432     val = integer_test(str_int, 0)
433     if None != val:
434         world_db["SLIPPERS"] = val
435         if world_db["WORLD_ACTIVE"] and \
436            world_db["SLIPPERS"] not in world_db["ThingTypes"]:
437             print(world_db["ThingTypes"])
438             print(":::" + str(world_db["SLIPPERS"]))
439             world_db["WORLD_ACTIVE"] = 0
440             print("SLIPPERS matches no known ThingTypes, deactivating world.")
441
442 strong_write(io_db["file_out"], "PLUGIN PleaseTheIslandGod\n")
443
444 if not "GOD_FAVOR" in world_db:
445     world_db["GOD_FAVOR"] = 0
446 if not "GAME_WON" in world_db:
447     world_db["GAME_WON"] = 0
448 if not "SLIPPERS" in world_db:
449     world_db["SLIPPERS"] = 0
450 io_db["worldstate_write_order"] += [["GOD_FAVOR", "world_int"]]
451
452 import server.config.world_data
453 server.config.world_data.symbols_passable += ":_"
454
455 from server.config.world_data import thing_defaults
456 thing_defaults["T_PLAYERDROP"] = 0
457
458 import server.config.actions
459 server.config.actions.action_db["actor_move"] = actor_move
460 server.config.actions.action_db["actor_pickup"] = actor_pickup
461 server.config.actions.action_db["actor_drop"] = actor_drop
462 server.config.actions.ai_func = ai
463
464 from server.config.commands import commands_db
465 commands_db["TT_ID"] = (1, False, command_ttid)
466 commands_db["GOD_FAVOR"] = (1, False, setter(None, "GOD_FAVOR", -32768, 32767))
467 commands_db["TT_STORAGE"] = (1, False, setter("ThingType", "TT_STORAGE", 0, 255))
468 commands_db["T_PLAYERDROP"] = (1, False, setter("Thing", "T_PLAYERDROP", 0, 1))
469 commands_db["WORLD_ACTIVE"] = (1, False, command_worldactive)
470 commands_db["GAME_WON"] = (1, False, setter(None, "GAME_WON", 0, 1))
471 commands_db["SLIPPERS"] = (1, False, command_slippers)
472
473 import server.config.misc
474 server.config.misc.make_map_func = make_map
475 server.config.misc.thingproliferation_func = thingproliferation
476 server.config.misc.make_world = make_world