home · contact · privacy
Plugin: Don't use global on variables changed by plugin itself.
[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     from server.config.world_data import symbols_passable
266     from server.build_fov_map import build_fov_map
267     def decrement_lifepoints(t):
268         t["T_LIFEPOINTS"] -= 1
269         _id = [_id for _id in world_db["Things"] if world_db["Things"][_id] == t][0]
270         if 0 == t["T_LIFEPOINTS"]:
271             sadness = world_db["ThingTypes"][t["T_TYPE"]]["TT_LIFEPOINTS"]
272             for id in t["T_CARRIES"]:
273                 t["T_CARRIES"].remove(id)
274                 world_db["Things"][id]["T_POSY"] = t["T_POSY"]
275                 world_db["Things"][id]["T_POSX"] = t["T_POSX"]
276                 world_db["Things"][id]["carried"] = False
277             t["T_TYPE"] = world_db["ThingTypes"][t["T_TYPE"]]["TT_CORPSE_ID"]
278             if world_db["Things"][0] == t:
279                 t["fovmap"] = bytearray(b' ' * (world_db["MAP_LENGTH"] ** 2))
280                 log("You die.")
281                 log("See README on how to start over.")
282             else:
283                 t["fovmap"] = False
284                 t["T_MEMMAP"] = False
285                 t["T_MEMDEPTHMAP"] = False
286                 t["T_MEMTHING"] = []
287             log("BAR " + str(t["T_LIFEPOINTS"]))
288             return sadness 
289         return 0 
290     passable = False
291     move_result = mv_yx_in_dir_legal(chr(t["T_ARGUMENT"]),
292                                      t["T_POSY"], t["T_POSX"])
293     if 1 == move_result[0]:
294         pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
295         hitted = [id for id in world_db["Things"]
296                   if world_db["Things"][id] != t
297                   if world_db["Things"][id]["T_LIFEPOINTS"]
298                   if world_db["Things"][id]["T_POSY"] == move_result[1]
299                   if world_db["Things"][id]["T_POSX"] == move_result[2]]
300         if len(hitted):
301             hit_id = hitted[0]
302             if t == world_db["Things"][0]:
303                 hitted_type = world_db["Things"][hit_id]["T_TYPE"]
304                 hitted_name = world_db["ThingTypes"][hitted_type]["TT_NAME"]
305                 log("You WOUND " + hitted_name + ".")
306                 world_db["GOD_FAVOR"] -= 1
307             elif 0 == hit_id:
308                 hitter_name = world_db["ThingTypes"][t["T_TYPE"]]["TT_NAME"]
309                 log(hitter_name +" WOUNDS you.")
310             test = decrement_lifepoints(world_db["Things"][hit_id])
311             if test and t == world_db["Things"][0]:
312                 world_db["GOD_FAVOR"] -= test 
313             return
314         passable = chr(world_db["MAP"][pos]) in symbols_passable
315     dir = [dir for dir in directions_db
316            if directions_db[dir] == chr(t["T_ARGUMENT"])][0]
317     if passable:
318         t["T_POSY"] = move_result[1]
319         t["T_POSX"] = move_result[2]
320         for id in t["T_CARRIES"]:
321             world_db["Things"][id]["T_POSY"] = move_result[1]
322             world_db["Things"][id]["T_POSX"] = move_result[2]
323         build_fov_map(t)
324         if t == world_db["Things"][0]:
325             log("You MOVE " + dir + ".")
326
327 def command_ttid(id_string):
328     id = id_setter(id_string, "ThingTypes", command_ttid)
329     if None != id:
330         world_db["ThingTypes"][id] = {
331             "TT_NAME": "(none)",
332             "TT_TOOLPOWER": 0,
333             "TT_LIFEPOINTS": 0,
334             "TT_PROLIFERATE": 0,
335             "TT_START_NUMBER": 0,
336             "TT_STORAGE": 0,
337             "TT_SYMBOL": "?",
338             "TT_CORPSE_ID": id,
339             "TT_TOOL": ""
340         }
341
342 strong_write(io_db["file_out"], "PLUGIN PleaseTheIslandGod\n")
343
344 if not "GOD_FAVOR"  in world_db:
345     world_db["GOD_FAVOR"] = 0
346 io_db["worldstate_write_order"] += [["GOD_FAVOR", "world_int"]]
347
348 import server.config.world_data
349 server.config.world_data.symbols_passable += ":"
350
351 from server.config.world_data import thing_defaults
352 thing_defaults["T_PLAYERDROP"] = 0
353
354 import server.config.actions
355 server.config.actions.action_db["actor_move"] = actor_move
356 server.config.actions.action_db["actor_pickup"] = actor_pickup
357 server.config.actions.action_db["actor_drop"] = actor_drop
358 server.config.actions.ai_func = ai
359
360 from server.config.commands import commands_db
361 commands_db["TT_ID"] = (1, False, command_ttid)
362 commands_db["GOD_FAVOR"] = (1, False, setter(None, "GOD_FAVOR", -32768, 32767))
363 commands_db["TT_STORAGE"] = (1, False, setter("ThingType", "TT_STORAGE", 0, 255))
364 commands_db["T_PLAYERDROP"] = (1, False, setter("Thing", "T_PLAYERDROP", 0, 1))
365
366 import server.config.misc
367 server.config.misc.make_map_func = make_map
368 server.config.misc.thingproliferation_func = thingproliferation
369 server.config.misc.make_world = make_world