home · contact · privacy
Plugin: Clean up imports.
[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     global directions_db, new_Thing, mv_yx_in_dir_legal
83     prolscore = world_db["ThingTypes"][t["T_TYPE"]]["TT_PROLIFERATE"]
84     if prolscore and \
85       (world_db["ThingTypes"][t["T_TYPE"]]["TT_LIFEPOINTS"] == 0 or
86        t["T_LIFEPOINTS"] >= 0.9 *
87                         world_db["ThingTypes"][t["T_TYPE"]]["TT_LIFEPOINTS"]) \
88        and \
89       (1 == prolscore or 1 == (rand.next() % prolscore)):
90         candidates = []
91         for dir in [directions_db[key] for key in directions_db]:
92             mv_result = mv_yx_in_dir_legal(dir, t["T_POSY"], t["T_POSX"])
93             pos = mv_result[1] * world_db["MAP_LENGTH"] + mv_result[2]
94             if mv_result[0] and \
95                (ord(":") == prol_map[pos]
96                 or (world_db["ThingTypes"][t["T_TYPE"]]["TT_LIFEPOINTS"]
97                     and ord(".") == prol_map[pos])):
98                 candidates.append((mv_result[1], mv_result[2]))
99         if len(candidates):
100             i = rand.next() % len(candidates)
101             id = id_setter(-1, "Things")
102             newT = new_Thing(t["T_TYPE"], (candidates[i][0], candidates[i][1]))
103             world_db["Things"][id] = newT
104             #if (world_db["FAVOR_STAGE"] > 0
105             #    and t["T_TYPE"] == world_db["PLANT_0"]):
106             #    world_db["GOD_FAVOR"] += 5
107             #elif t["T_TYPE"] == world_db["PLANT_1"];
108             #    world_db["GOD_FAVOR"] += 25
109             #elif world_db["FAVOR_STAGE"] >= 4 and \
110             #     t["T_TYPE"] == world_db["ANIMAL_1"]:
111             #    log("The Island God SMILES upon a new-born bear baby.")
112             #    world_db["GOD_FAVOR"] += 750
113
114 def make_map():
115     global rand
116
117     def is_neighbor(coordinates, type):
118         y = coordinates[0]
119         x = coordinates[1]
120         length = world_db["MAP_LENGTH"]
121         ind = y % 2
122         diag_west = x + (ind > 0)
123         diag_east = x + (ind < (length - 1))
124         pos = (y * length) + x
125         if (y > 0 and diag_east
126             and type == chr(world_db["MAP"][pos - length + ind])) \
127            or (x < (length - 1)
128                and type == chr(world_db["MAP"][pos + 1])) \
129            or (y < (length - 1) and diag_east
130                and type == chr(world_db["MAP"][pos + length + ind])) \
131            or (y > 0 and diag_west
132                and type == chr(world_db["MAP"][pos - length - (not ind)])) \
133            or (x > 0
134                and type == chr(world_db["MAP"][pos - 1])) \
135            or (y < (length - 1) and diag_west
136                and type == chr(world_db["MAP"][pos + length - (not ind)])):
137             return True
138         return False
139
140     world_db["MAP"] = bytearray(b'~' * (world_db["MAP_LENGTH"] ** 2))
141     length = world_db["MAP_LENGTH"]
142     add_half_width = (not (length % 2)) * int(length / 2)
143     world_db["MAP"][int((length ** 2) / 2) + add_half_width] = ord(".")
144     while (1):
145         y = rand.next() % length
146         x = rand.next() % length
147         pos = (y * length) + x
148         if "~" == chr(world_db["MAP"][pos]) and is_neighbor((y, x), "."):
149             if y == 0 or y == (length - 1) or x == 0 or x == (length - 1):
150                 break
151             world_db["MAP"][pos] = ord(".")
152     n_trees = int((length ** 2) / 16)
153     i_trees = 0
154     while (i_trees <= n_trees):
155         single_allowed = rand.next() % 32
156         y = rand.next() % length
157         x = rand.next() % length
158         pos = (y * length) + x
159         if "." == chr(world_db["MAP"][pos]) \
160           and ((not single_allowed) or is_neighbor((y, x), "X")):
161             world_db["MAP"][pos] = ord("X")
162             i_trees += 1
163     n_colons = int((length ** 2) / 16)
164     i_colons = 0
165     while (i_colons <= n_colons):
166         single_allowed = rand.next() % 256
167         y = rand.next() % length
168         x = rand.next() % length
169         pos = (y * length) + x
170         if ("." == chr(world_db["MAP"][pos])
171           and ((not single_allowed) or is_neighbor((y, x), ":"))):
172             world_db["MAP"][pos] = ord(":")
173             i_colons += 1
174     #altar_placed = False
175     #while not altar_placed:
176     #    y = rand.next() % length
177     #    x = rand.next() % length
178     #    pos = (y * length) + x
179     #    if (("." == chr(world_db["MAP"][pos]
180     #         or ":" == chr(world_db["MAP"][pos]))
181     #        and not is_neighbor((y, x), "X"))):
182     #        world_db["MAP"][pos] = ord("_")
183     #        world_db["altar"] = (y, x)
184     #        altar_placed = True
185
186 def ai(t):
187     from server.ai import get_dir_to_target, get_inventory_slot_to_consume, \
188         standing_on_food
189     t["T_COMMAND"] = [id for id in world_db["ThingActions"]
190                       if world_db["ThingActions"][id]["TA_NAME"] == "wait"][0]
191     eating = len([id for id in world_db["ThingActions"]
192                   if world_db["ThingActions"][id]["TA_NAME"] == "use"]) > 0
193     picking = len([id for id in world_db["ThingActions"]
194                    if world_db["ThingActions"][id]["TA_NAME"] == "pickup"]) > 0
195     if eating and picking:
196         if get_dir_to_target(t, "f"):
197             return
198         sel = get_inventory_slot_to_consume(t)
199         if -1 != sel:
200             t["T_COMMAND"] = [id for id in world_db["ThingActions"]
201                               if world_db["ThingActions"][id]["TA_NAME"]
202                                  == "use"][0]
203             t["T_ARGUMENT"] = sel
204         elif standing_on_food(t) and (len(t["T_CARRIES"]) <
205                 world_db["ThingTypes"][t["T_TYPE"]]["TT_STORAGE"]):
206                 t["T_COMMAND"] = [id for id in world_db["ThingActions"]
207                                   if world_db["ThingActions"][id]["TA_NAME"]
208                                   == "pickup"][0]
209         else:
210             going_to_known_food_spot = get_dir_to_target(t, "c")
211             if not going_to_known_food_spot:
212                 aiming_for_walking_food = get_dir_to_target(t, "a")
213                 if not aiming_for_walking_food:
214                     get_dir_to_target(t, "s")
215
216 def actor_pickup(t):
217     from server.ai import eat_vs_hunger_threshold
218     used_slots = len(t["T_CARRIES"])
219     if used_slots < world_db["ThingTypes"][t["T_TYPE"]]["TT_STORAGE"]:
220         ids = [id for id in world_db["Things"] if world_db["Things"][id] != t
221                if not world_db["Things"][id]["carried"]
222                if world_db["Things"][id]["T_POSY"] == t["T_POSY"]
223                if world_db["Things"][id]["T_POSX"] == t["T_POSX"]]
224         if len(ids):
225             lowest_tid = -1
226             eat_cost = eat_vs_hunger_threshold(t["T_TYPE"])
227             for iid in ids:
228                 tid = world_db["Things"][iid]["T_TYPE"] 
229                 if lowest_tid == -1 or tid < lowest_tid:
230                     if (t != world_db["Things"][0] and
231                         (world_db["ThingTypes"][tid]["TT_TOOL"] != "food"
232                          or (world_db["ThingTypes"][tid]["TT_TOOLPOWER"]
233                              <= eat_cost))):
234                         continue
235                     id = iid
236                     lowest_tid = tid
237             world_db["Things"][id]["carried"] = True
238             ty = world_db["Things"][id]["T_TYPE"]
239             if (t != world_db["Things"][0]
240                 and world_db["Things"][id]["T_PLAYERDROP"]
241                 and world_db["ThingTypes"][ty]["TT_TOOL"] == "food"):
242                 score = int(world_db["ThingTypes"][ty]["TT_TOOLPOWER"] / 32)
243                 world_db["GOD_FAVOR"] += score
244                 world_db["Things"][id]["T_PLAYERDROP"] = 0
245             t["T_CARRIES"].append(id)
246             if t == world_db["Things"][0]:
247                 log("You PICK UP an object.")
248     elif t == world_db["Things"][0]:
249         log("Can't pick up object: No storage room to carry more.")
250
251
252 def actor_drop(t):
253     """Make t rop Thing from inventory to ground indexed by T_ARGUMENT."""
254     if len(t["T_CARRIES"]):
255         id = t["T_CARRIES"][t["T_ARGUMENT"]]
256         t["T_CARRIES"].remove(id)
257         world_db["Things"][id]["carried"] = False
258         if t == world_db["Things"][0]:
259             log("You DROP an object.")
260             world_db["Things"][id]["T_PLAYERDROP"] = 1
261
262
263 def actor_move(t):
264     global symbols_passable
265     from server.build_fov_map import build_fov_map
266     def decrement_lifepoints(t):
267         t["T_LIFEPOINTS"] -= 1
268         _id = [_id for _id in world_db["Things"] if world_db["Things"][_id] == t][0]
269         if 0 == t["T_LIFEPOINTS"]:
270             sadness = world_db["ThingTypes"][t["T_TYPE"]]["TT_LIFEPOINTS"]
271             for id in t["T_CARRIES"]:
272                 t["T_CARRIES"].remove(id)
273                 world_db["Things"][id]["T_POSY"] = t["T_POSY"]
274                 world_db["Things"][id]["T_POSX"] = t["T_POSX"]
275                 world_db["Things"][id]["carried"] = False
276             t["T_TYPE"] = world_db["ThingTypes"][t["T_TYPE"]]["TT_CORPSE_ID"]
277             if world_db["Things"][0] == t:
278                 t["fovmap"] = bytearray(b' ' * (world_db["MAP_LENGTH"] ** 2))
279                 log("You die.")
280                 log("See README on how to start over.")
281             else:
282                 t["fovmap"] = False
283                 t["T_MEMMAP"] = False
284                 t["T_MEMDEPTHMAP"] = False
285                 t["T_MEMTHING"] = []
286             log("BAR " + str(t["T_LIFEPOINTS"]))
287             return sadness 
288         return 0 
289     passable = False
290     move_result = mv_yx_in_dir_legal(chr(t["T_ARGUMENT"]),
291                                      t["T_POSY"], t["T_POSX"])
292     if 1 == move_result[0]:
293         pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
294         hitted = [id for id in world_db["Things"]
295                   if world_db["Things"][id] != t
296                   if world_db["Things"][id]["T_LIFEPOINTS"]
297                   if world_db["Things"][id]["T_POSY"] == move_result[1]
298                   if world_db["Things"][id]["T_POSX"] == move_result[2]]
299         if len(hitted):
300             hit_id = hitted[0]
301             if t == world_db["Things"][0]:
302                 hitted_type = world_db["Things"][hit_id]["T_TYPE"]
303                 hitted_name = world_db["ThingTypes"][hitted_type]["TT_NAME"]
304                 log("You WOUND " + hitted_name + ".")
305                 world_db["GOD_FAVOR"] -= 1
306             elif 0 == hit_id:
307                 hitter_name = world_db["ThingTypes"][t["T_TYPE"]]["TT_NAME"]
308                 log(hitter_name +" WOUNDS you.")
309             test = decrement_lifepoints(world_db["Things"][hit_id])
310             if test and t == world_db["Things"][0]:
311                 world_db["GOD_FAVOR"] -= test 
312             return
313         passable = chr(world_db["MAP"][pos]) in symbols_passable
314     dir = [dir for dir in directions_db
315            if directions_db[dir] == chr(t["T_ARGUMENT"])][0]
316     if passable:
317         t["T_POSY"] = move_result[1]
318         t["T_POSX"] = move_result[2]
319         for id in t["T_CARRIES"]:
320             world_db["Things"][id]["T_POSY"] = move_result[1]
321             world_db["Things"][id]["T_POSX"] = move_result[2]
322         build_fov_map(t)
323         if t == world_db["Things"][0]:
324             log("You MOVE " + dir + ".")
325
326 def command_ttid(id_string):
327     id = id_setter(id_string, "ThingTypes", command_ttid)
328     if None != id:
329         world_db["ThingTypes"][id] = {
330             "TT_NAME": "(none)",
331             "TT_TOOLPOWER": 0,
332             "TT_LIFEPOINTS": 0,
333             "TT_PROLIFERATE": 0,
334             "TT_START_NUMBER": 0,
335             "TT_STORAGE": 0,
336             "TT_SYMBOL": "?",
337             "TT_CORPSE_ID": id,
338             "TT_TOOL": ""
339         }
340
341 strong_write(io_db["file_out"], "PLUGIN PleaseTheIslandGod\n")
342
343 if not "GOD_FAVOR"  in world_db:
344     world_db["GOD_FAVOR"] = 0
345 io_db["worldstate_write_order"] += [["GOD_FAVOR", "world_int"]]
346
347 import server.config.world_data
348 server.config.world_data.symbols_passable += ":"
349
350 from server.config.world_data import thing_defaults
351 thing_defaults["T_PLAYERDROP"] = 0
352
353 import server.config.actions
354 server.config.actions.action_db["actor_move"] = actor_move
355 server.config.actions.action_db["actor_pickup"] = actor_pickup
356 server.config.actions.action_db["actor_drop"] = actor_drop
357 server.config.actions.ai_func = ai
358
359 from server.config.commands import commands_db
360 commands_db["TT_ID"] = (1, False, command_ttid)
361 commands_db["GOD_FAVOR"] = (1, False, setter(None, "GOD_FAVOR", -32768, 32767))
362 commands_db["TT_STORAGE"] = (1, False, setter("ThingType", "TT_STORAGE", 0, 255))
363 commands_db["T_PLAYERDROP"] = (1, False, setter("Thing", "T_PLAYERDROP", 0, 1))
364
365 import server.config.misc
366 server.config.misc.make_map_func = make_map
367 server.config.misc.thingproliferation_func = thingproliferation
368 server.config.misc.make_world = make_world