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