home · contact · privacy
d126c41c0e46bc215be45431ff58f4fd6bd86320
[plomrogue] / plugins / server / PleaseTheIslandGod.py
1 # This file is part of PlomRogue. PlomRogue is licensed under the GPL version 3
2 # or any later version. For details on its copyright, license, and warranties,
3 # see the file NOTICE in the root directory of the PlomRogue source package.
4
5
6 from server.io import log, strong_write
7 from server.config.world_data import world_db, symbols_passable, directions_db
8 from server.utils import mv_yx_in_dir_legal, rand, id_setter
9 from server.config.io import io_db
10 from server.new_thing import new_Thing
11
12 def make_world(seed):
13     from server.update_map_memory import update_map_memory
14     from server.config.misc import make_map_func
15     from server.utils import libpr
16
17     def free_pos(plant=False):
18         i = 0
19         while 1:
20             err = "Space to put thing on too hard to find. Map too small?"
21             while 1:
22                 y = rand.next() % world_db["MAP_LENGTH"]
23                 x = rand.next() % world_db["MAP_LENGTH"]
24                 pos = y * world_db["MAP_LENGTH"] + x;
25                 if (not plant
26                     and "." == chr(world_db["MAP"][pos])) \
27                    or ":" == chr(world_db["MAP"][pos]):
28                     break
29                 i += 1
30                 if i == 65535:
31                     raise SystemExit(err)
32             pos_clear = (0 == len([id for id in world_db["Things"]
33                                    if world_db["Things"][id]["T_LIFEPOINTS"]
34                                    if world_db["Things"][id]["T_POSY"] == y
35                                    if world_db["Things"][id]["T_POSX"] == x]))
36             if pos_clear:
37                 break
38         return (y, x)
39
40     rand.seed = seed
41     if world_db["MAP_LENGTH"] < 1:
42         print("Ignoring: No map length >= 1 defined.")
43         return
44     libpr.set_maplength(world_db["MAP_LENGTH"])
45     player_will_be_generated = False
46     playertype = world_db["PLAYER_TYPE"]
47     for ThingType in world_db["ThingTypes"]:
48         if playertype == ThingType:
49             if 0 < world_db["ThingTypes"][ThingType]["TT_START_NUMBER"]:
50                 player_will_be_generated = True
51             break
52     if not player_will_be_generated:
53         print("Ignoring: No player type with start number >0 defined.")
54         return
55     wait_action = False
56     for ThingAction in world_db["ThingActions"]:
57         if "wait" == world_db["ThingActions"][ThingAction]["TA_NAME"]:
58             wait_action = True
59     if not wait_action:
60         print("Ignoring beyond SEED_MAP: " +
61               "No thing action with name 'wait' defined.")
62         return
63     for name in world_db["specials"]:
64         if world_db[name] not in world_db["ThingTypes"]:
65             print("Ignoring: No valid " + name + " set.")
66             return
67     world_db["Things"] = {}
68     make_map_func()
69     world_db["WORLD_ACTIVE"] = 1
70     world_db["TURN"] = 1
71     for i in range(world_db["ThingTypes"][playertype]["TT_START_NUMBER"]):
72         id = id_setter(-1, "Things")
73         world_db["Things"][id] = new_Thing(playertype, free_pos())
74     if not world_db["Things"][0]["fovmap"]:
75         empty_fovmap = bytearray(b" " * world_db["MAP_LENGTH"] ** 2)
76         world_db["Things"][0]["fovmap"] = empty_fovmap
77     update_map_memory(world_db["Things"][0])
78     for type in world_db["ThingTypes"]:
79         for i in range(world_db["ThingTypes"][type]["TT_START_NUMBER"]):
80             if type != playertype:
81                 id = id_setter(-1, "Things")
82                 plantness = world_db["ThingTypes"][type]["TT_PROLIFERATE"]
83                 world_db["Things"][id] = new_Thing(type, free_pos(plantness))
84     strong_write(io_db["file_out"], "NEW_WORLD\n")
85
86 def thingproliferation(t, prol_map):
87     from server.new_thing import new_Thing
88     global directions_db, mv_yx_in_dir_legal, rand
89     prolscore = world_db["ThingTypes"][t["T_TYPE"]]["TT_PROLIFERATE"]
90     if prolscore and \
91       (world_db["ThingTypes"][t["T_TYPE"]]["TT_LIFEPOINTS"] == 0 or
92        t["T_LIFEPOINTS"] >= 0.9 *
93                         world_db["ThingTypes"][t["T_TYPE"]]["TT_LIFEPOINTS"]) \
94        and \
95       (1 == prolscore or 1 == (rand.next() % prolscore)):
96         candidates = []
97         for dir in [directions_db[key] for key in directions_db]:
98             mv_result = mv_yx_in_dir_legal(dir, t["T_POSY"], t["T_POSX"])
99             pos = mv_result[1] * world_db["MAP_LENGTH"] + mv_result[2]
100             if mv_result[0] and \
101                (ord(":") == prol_map[pos]
102                 or (world_db["ThingTypes"][t["T_TYPE"]]["TT_LIFEPOINTS"]
103                     and ord(".") == prol_map[pos])):
104                 candidates.append((mv_result[1], mv_result[2]))
105         if len(candidates):
106             i = rand.next() % len(candidates)
107             id = id_setter(-1, "Things")
108             newT = new_Thing(t["T_TYPE"], (candidates[i][0], candidates[i][1]))
109             world_db["Things"][id] = newT
110             if (world_db["FAVOR_STAGE"] > 0
111                 and t["T_TYPE"] == world_db["PLANT_0"]):
112                 world_db["GOD_FAVOR"] += 5
113             elif t["T_TYPE"] == world_db["PLANT_1"]:
114                 world_db["GOD_FAVOR"] += 25
115             elif world_db["FAVOR_STAGE"] >= 4 and \
116                 t["T_TYPE"] == world_db["ANIMAL_1"]:
117                 log("The Island God SMILES upon a new-born bear baby.")
118                 world_db["GOD_FAVOR"] += 750
119
120 def make_map():
121     from server.make_map import make_map, is_neighbor, new_pos
122     global rand
123     make_map()
124     length = world_db["MAP_LENGTH"]
125     n_colons = int((length ** 2) / 16)
126     i_colons = 0
127     while (i_colons <= n_colons):
128         single_allowed = rand.next() % 256
129         y, x, pos = new_pos()
130         if ("." == chr(world_db["MAP"][pos])
131           and ((not single_allowed) or is_neighbor((y, x), ":"))):
132             world_db["MAP"][pos] = ord(":")
133             i_colons += 1
134     altar_placed = False
135     while not altar_placed:
136         y, x, pos = new_pos()
137         if (("." == chr(world_db["MAP"][pos]
138              or ":" == chr(world_db["MAP"][pos]))
139             and not is_neighbor((y, x), "X"))):
140             world_db["MAP"][pos] = ord("_")
141             world_db["altar"] = (y, x)
142             altar_placed = True
143
144 def ai(t):
145     from server.ai import get_dir_to_target, get_inventory_slot_to_consume, \
146         standing_on_food
147     t["T_COMMAND"] = [id for id in world_db["ThingActions"]
148                       if world_db["ThingActions"][id]["TA_NAME"] == "wait"][0]
149     eating = len([id for id in world_db["ThingActions"]
150                   if world_db["ThingActions"][id]["TA_NAME"] == "use"]) > 0
151     picking = len([id for id in world_db["ThingActions"]
152                    if world_db["ThingActions"][id]["TA_NAME"] == "pickup"]) > 0
153     if eating and picking:
154         if get_dir_to_target(t, "f"):
155             return
156         sel = get_inventory_slot_to_consume(t)
157         if -1 != sel:
158             t["T_COMMAND"] = [id for id in world_db["ThingActions"]
159                               if world_db["ThingActions"][id]["TA_NAME"]
160                                  == "use"][0]
161             t["T_ARGUMENT"] = sel
162         elif standing_on_food(t) and (len(t["T_CARRIES"]) <
163                 world_db["ThingTypes"][t["T_TYPE"]]["TT_STORAGE"]):
164                 t["T_COMMAND"] = [id for id in world_db["ThingActions"]
165                                   if world_db["ThingActions"][id]["TA_NAME"]
166                                   == "pickup"][0]
167         else:
168             going_to_known_food_spot = get_dir_to_target(t, "c")
169             if not going_to_known_food_spot:
170                 aiming_for_walking_food = get_dir_to_target(t, "a")
171                 if not aiming_for_walking_food:
172                     get_dir_to_target(t, "s")
173
174 def actor_pickup(t):
175     from server.ai import eat_vs_hunger_threshold
176     used_slots = len(t["T_CARRIES"])
177     if used_slots < world_db["ThingTypes"][t["T_TYPE"]]["TT_STORAGE"]:
178         ids = [id for id in world_db["Things"] if world_db["Things"][id] != t
179                if not world_db["Things"][id]["carried"]
180                if world_db["Things"][id]["T_POSY"] == t["T_POSY"]
181                if world_db["Things"][id]["T_POSX"] == t["T_POSX"]]
182         if len(ids):
183             lowest_tid = -1
184             eat_cost = eat_vs_hunger_threshold(t["T_TYPE"])
185             for iid in ids:
186                 tid = world_db["Things"][iid]["T_TYPE"] 
187                 if lowest_tid == -1 or tid < lowest_tid:
188                     if (t != world_db["Things"][0] and
189                         (world_db["ThingTypes"][tid]["TT_TOOL"] != "food"
190                          or (world_db["ThingTypes"][tid]["TT_TOOLPOWER"]
191                              <= eat_cost))):
192                         continue
193                     id = iid
194                     lowest_tid = tid
195             world_db["Things"][id]["carried"] = True
196             ty = world_db["Things"][id]["T_TYPE"]
197             if (t != world_db["Things"][0]
198                 and world_db["Things"][id]["T_PLAYERDROP"]
199                 and world_db["ThingTypes"][ty]["TT_TOOL"] == "food"):
200                 score = int(world_db["ThingTypes"][ty]["TT_TOOLPOWER"] / 32)
201                 world_db["GOD_FAVOR"] += score
202                 world_db["Things"][id]["T_PLAYERDROP"] = 0
203             t["T_CARRIES"].append(id)
204             if t == world_db["Things"][0]:
205                 log("You PICK UP an object.")
206     elif t == world_db["Things"][0]:
207         log("CAN'T pick up object: No storage room to carry more.")
208
209
210 def actor_drop(t):
211     """Make t rop Thing from inventory to ground indexed by T_ARGUMENT."""
212     if len(t["T_CARRIES"]):
213         id = t["T_CARRIES"][t["T_ARGUMENT"]]
214         t["T_CARRIES"].remove(id)
215         world_db["Things"][id]["carried"] = False
216         if t == world_db["Things"][0]:
217             log("You DROP an object.")
218             world_db["Things"][id]["T_PLAYERDROP"] = 1
219
220
221 def actor_use(t):
222     if len(t["T_CARRIES"]):
223         id = t["T_CARRIES"][t["T_ARGUMENT"]]
224         type = world_db["Things"][id]["T_TYPE"]
225         if type == world_db["SLIPPERS"]:
226             if t == world_db["Things"][0]:
227                 log("You use the " + world_db["ThingTypes"][type]["TT_NAME"] +
228                     ". It glows in wondrous colors, and emits a sound as if fr"
229                     "om a dying cat. The Island God laughs.\n")
230             t["T_LIFEPOINTS"] = 1
231             from server.config.misc import decrement_lifepoints_func
232             decrement_lifepoints_func(t)
233         elif (world_db["ThingTypes"][type]["TT_TOOL"] == "carpentry"):
234             pos = t["T_POSY"] * world_db["MAP_LENGTH"] + t["T_POSX"]
235             if (world_db["MAP"][pos] == ord("X")
236                 or world_db["MAP"][pos] == ord("|")):
237                 return
238             for id in [id for id in world_db["Things"]
239                        if not world_db["Things"][id] == t
240                        if not world_db["Things"][id]["carried"]
241                        if world_db["Things"][id]["T_POSY"] == t["T_POSY"]
242                        if world_db["Things"][id]["T_POSX"] == t["T_POSX"]]:
243                  return
244             wood_id = None
245             for id in t["T_CARRIES"]:
246                 type_material = world_db["Things"][id]["T_TYPE"]
247                 if (world_db["ThingTypes"][type_material]["TT_TOOL"]
248                     == "wood"):
249                     wood_id = id
250                     break
251             if wood_id != None:
252                 t["T_CARRIES"].remove(wood_id)
253                 del world_db["Things"][wood_id]
254                 world_db["MAP"][pos] = ord("|")
255                 log("With your " + world_db["ThingTypes"][type]["TT_NAME"]
256                     + " you build a WOODEN BARRIER from your "
257                     + world_db["ThingTypes"][type_material]["TT_NAME"] + ".")
258         elif world_db["ThingTypes"][type]["TT_TOOL"] == "fertilizer":
259             pos = t["T_POSY"] * world_db["MAP_LENGTH"] + t["T_POSX"]
260             if world_db["MAP"][pos] == ord("."):
261                 log("You create SOIL.")
262                 world_db["MAP"][pos] = ord(":")
263         elif world_db["ThingTypes"][type]["TT_TOOL"] == "food":
264             t["T_CARRIES"].remove(id)
265             del world_db["Things"][id]
266             t["T_SATIATION"] += world_db["ThingTypes"][type]["TT_TOOLPOWER"]
267             if t == world_db["Things"][0]:
268                 log("You CONSUME this thing.")
269         elif t == world_db["Things"][0]:
270             log("You try to use this object, but FAIL.")
271
272 def decrement_lifepoints(t):
273     t["T_LIFEPOINTS"] -= 1
274     live_type = t["T_TYPE"]
275     _id = [_id for _id in world_db["Things"] if world_db["Things"][_id] == t][0]
276     if 0 == t["T_LIFEPOINTS"]:
277         for id in t["T_CARRIES"]:
278             t["T_CARRIES"].remove(id)
279             world_db["Things"][id]["T_POSY"] = t["T_POSY"]
280             world_db["Things"][id]["T_POSX"] = t["T_POSX"]
281             world_db["Things"][id]["carried"] = False
282         t["T_TYPE"] = world_db["ThingTypes"][t["T_TYPE"]]["TT_CORPSE_ID"]
283         if world_db["Things"][0] == t:
284             t["fovmap"] = bytearray(b' ' * (world_db["MAP_LENGTH"] ** 2))
285             log("You die.")
286             log("See README on how to start over.")
287         else:
288             t["fovmap"] = False
289             t["T_MEMMAP"] = False
290             t["T_MEMDEPTHMAP"] = False
291             t["T_MEMTHING"] = []
292             n_species = len([id for id in world_db["Things"]
293                              if world_db["Things"][id]["T_TYPE"] == live_type])
294             if 0 == n_species:
295                 from server.new_thing import new_Thing
296                 if world_db["FAVOR_STAGE"] >= 3 and \
297                     live_type == world_db["ANIMAL_0"]:
298                     world_db["GOD_FAVOR"] += 3000
299                     log("CONGRATULATIONS! The "
300                         + world_db["ThingTypes"][live_type]["TT_NAME"]
301                         + " species has died out. The Island God is pleased.")
302                 else:
303                     id = id_setter(-1, "Things")
304                     world_db["Things"][id] = new_Thing(live_type,
305                                                        world_db["altar"])
306                     log("The "
307                         + world_db["ThingTypes"][live_type]["TT_NAME"]
308                         + " species has temporarily died out. "
309                         + "One new-born is spawned at the altar.")
310         return world_db["ThingTypes"][t["T_TYPE"]]["TT_LIFEPOINTS"]
311     return 0
312
313 def actor_move(t):
314
315     def altar_msg_wait(limit):
316             log("The Island God will talk again when it favors you to >=" +
317                 str(limit) + " points.")
318
319     altar_msg_0 = "The Island God speaks to you: \"I don't trust you. You in" \
320     "trude on the island's affairs. I think you're a nuisance at best, and a" \
321     " danger to my children at worst. I will give you a chance to lighten my" \
322     " mood, however: For a while now, I've been trying to spread the plant " \
323     + world_db["ThingTypes"][world_db["PLANT_0"]]["TT_NAME"] + " (\"" + \
324     world_db["ThingTypes"][world_db["PLANT_0"]]["TT_SYMBOL"] + "\"). I have " \
325     "not been very successful so far. Maybe you can make yourself useful the" \
326     "re. I will count each further " + \
327     world_db["ThingTypes"][world_db["PLANT_0"]]["TT_NAME"] + " that grows to" \
328     " your favor.\""
329
330     altar_msg_1 = "The Island God speaks to you: \"You could have done worse" \
331     " so far. Maybe you are not the worst to happen to this island since the" \
332     " metal birds threw the great lightning ball. Maybe you can help me spre" \
333     "ad another plant. It multiplies faster,and it is highly nutritious: " + \
334     world_db["ThingTypes"][world_db["PLANT_1"]]["TT_NAME"] + " (\"" + \
335     world_db["ThingTypes"][world_db["PLANT_1"]]["TT_SYMBOL"] + "\"). It is n" \
336     "ew. I give you the only example. Be very careful with it! I also give y" \
337     "ou another tool that may be helpful.\""
338
339     altar_msg_2 = "The Island God speaks to you: \"I am greatly disappointed" \
340     " that you lost all " + \
341     world_db["ThingTypes"][world_db["PLANT_1"]]["TT_NAME"] + " this island h" \
342     "ad. Here is another one. It cost me great work. Be more careful this ti" \
343     "me when planting it.\""
344
345     altar_msg_3 = "The Island God speaks to you: \"The " + \
346     world_db["ThingTypes"][world_db["ANIMAL_0"]]["TT_NAME"] + " has lately b" \
347     "ecome a pest. These creatures do not please me as much as they used to " \
348     "do. Exterminate them all. I will count each kill to your favor. To help" \
349     " you with the hunting, I grant you the empathy and knowledge to read an" \
350     "imals.\""
351
352     altar_msg_4 = "You will now see animals' health bars, and activities (\"" \
353     "m\": moving (maybe for an attack), \"u\": eating, \"p\": picking someth" \
354     "ing up; no letter: waiting)."
355
356     altar_msg_5 = "The Island God speaks to you: \"You know what animal I fi" \
357     "nd the cutest? The " + \
358     world_db["ThingTypes"][world_db["ANIMAL_1"]]["TT_NAME"] + "! I think wha" \
359     "t this islands clearly needs more of is " + \
360     world_db["ThingTypes"][world_db["ANIMAL_1"]]["TT_NAME"] + "s. Why don't " \
361     "you help? Support them. Make sure they are well, and they will multiply" \
362     " faster. From now on, I will count each new-born " + \
363     world_db["ThingTypes"][world_db["ANIMAL_1"]]["TT_NAME"] + \
364     " (not spawned by me due to undo an extinction event) greatly to your fa" \
365     "vor. To help you with the feeding, here is something to make the ground" \
366     " bear more consumables."
367
368     altar_msg_6 = "The Island God speaks to you: \"You have proven yourself " \
369     "worthy of my respect. You were a good citizen to the island, and someti" \
370     "mes a better steward to its inhabitants than me. The island shall miss " \
371     "you when you leave. But you have earned the right to do so. Take this" + \
372     world_db["ThingTypes"][world_db["SLIPPERS"]]["TT_NAME"] + " and USE it w" \
373     "hen you please. It will take you to where you came from. (But do feel f" \
374     "ree to stay here as long as you like.)\""
375
376     def enter_altar():
377         from server.new_thing import new_Thing
378         if world_db["FAVOR_STAGE"] > 9000:
379            log("You step on a soul-less slab of stone.")
380            return
381         log("YOU ENTER SACRED GROUND.")
382         if world_db["FAVOR_STAGE"] == 0:
383             world_db["FAVOR_STAGE"] = 1
384             log(altar_msg_0)
385         elif world_db["FAVOR_STAGE"] == 1 and world_db["GOD_FAVOR"] < 100:
386             altar_msg_wait(100)
387         elif world_db["FAVOR_STAGE"] == 1 and world_db["GOD_FAVOR"] >= 100:
388             world_db["FAVOR_STAGE"] = 2
389             log(altar_msg_2)
390             id = id_setter(-1, "Things")
391             world_db["Things"][id] = new_Thing(world_db["PLANT_1"],
392                                                world_db["altar"])
393             id = id_setter(-1, "Things")
394             world_db["Things"][id] = new_Thing(world_db["TOOL_0"],
395                                                world_db["altar"])
396         elif world_db["FAVOR_STAGE"] == 2 and \
397             0 == len([id for id in world_db["Things"]
398                       if world_db["Things"][id]["T_TYPE"]
399                          == world_db["PLANT_1"]]):
400             log(altar_msg_2)
401             id = id_setter(-1, "Things")
402             world_db["Things"][id] = new_Thing(world_db["PLANT_1"],
403                                                world_db["altar"])
404             world_db["GOD_FAVOR"] -= 250
405         elif world_db["FAVOR_STAGE"] == 2 and world_db["GOD_FAVOR"] < 500:
406             altar_msg_wait(500)
407         elif world_db["FAVOR_STAGE"] == 2 and world_db["GOD_FAVOR"] >= 500:
408             world_db["FAVOR_STAGE"] = 3
409             log(altar_msg_3)
410             log(altar_msg_4)
411             world_db["EMPATHY"] = 1
412         elif world_db["FAVOR_STAGE"] == 3 and world_db["GOD_FAVOR"] < 5000:
413             altar_msg_wait(5000)
414         elif world_db["FAVOR_STAGE"] == 3 and world_db["GOD_FAVOR"] >= 5000:
415             world_db["FAVOR_STAGE"] = 4
416             log(altar_msg_5)
417             id = id_setter(-1, "Things")
418             world_db["Things"][id] = new_Thing(world_db["TOOL_1"],
419                                                world_db["altar"])
420         elif world_db["GOD_FAVOR"] < 20000:
421             altar_msg_wait(20000)
422         elif world_db["GOD_FAVOR"] > 20000:
423             world_db["FAVOR_STAGE"] = 9001
424             log(altar_msg_6)
425             id = id_setter(-1, "Things")
426             world_db["Things"][id] = new_Thing(world_db["SLIPPERS"],
427                                                world_db["altar"])
428
429     from server.config.world_data import symbols_passable
430     from server.build_fov_map import build_fov_map
431     from server.config.misc import decrement_lifepoints_func
432     from server.new_thing import new_Thing
433     passable = False
434     move_result = mv_yx_in_dir_legal(chr(t["T_ARGUMENT"]),
435                                      t["T_POSY"], t["T_POSX"])
436     if 1 == move_result[0]:
437         pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
438         hitted = [id for id in world_db["Things"]
439                   if world_db["Things"][id] != t
440                   if world_db["Things"][id]["T_LIFEPOINTS"]
441                   if world_db["Things"][id]["T_POSY"] == move_result[1]
442                   if world_db["Things"][id]["T_POSX"] == move_result[2]]
443         if len(hitted):
444             hit_id = hitted[0]
445             hitted_type = world_db["Things"][hit_id]["T_TYPE"]
446             if t == world_db["Things"][0]:
447                 hitted_name = world_db["ThingTypes"][hitted_type]["TT_NAME"]
448                 log("You WOUND " + hitted_name + ".")
449                 world_db["GOD_FAVOR"] -= 1
450             elif 0 == hit_id:
451                 hitter_name = world_db["ThingTypes"][t["T_TYPE"]]["TT_NAME"]
452                 log(hitter_name +" WOUNDS you.")
453             test = decrement_lifepoints_func(world_db["Things"][hit_id])
454             if test and world_db["FAVOR_STAGE"] >= 3 and \
455                hitted_type == world_db["ANIMAL_0"]:
456                 world_db["GOD_FAVOR"] += 125
457             elif test and t == world_db["Things"][0]:
458                 world_db["GOD_FAVOR"] -= 2 * test
459             return
460         if (ord("X") == world_db["MAP"][pos]
461             or ord("|") == world_db["MAP"][pos]):
462             for id in t["T_CARRIES"]:
463                 type = world_db["Things"][id]["T_TYPE"]
464                 if world_db["ThingTypes"][type]["TT_TOOL"] == "axe":
465                     axe_name = world_db["ThingTypes"][type]["TT_NAME"]
466                     if t == world_db["Things"][0]:
467                         log("With your " + axe_name + ", you chop!")
468                         if ord("X") == world_db["MAP"][pos]:
469                             world_db["GOD_FAVOR"] -= 1
470                     chop_power = world_db["ThingTypes"][type]["TT_TOOLPOWER"]
471
472                     case_X = world_db["MAP"][pos] == ord("X")
473                     if (chop_power > 0
474                         and ((case_X and
475                               0 == int(rand.next() / chop_power))
476                         or (not case_X and
477                                  0 == int(rand.next() / (3 * chop_power))))):
478                         if t == world_db["Things"][0]:
479                             log("You chop it DOWN.")
480                             if ord("X") == world_db["MAP"][pos]:
481                                 world_db["GOD_FAVOR"] -= 10
482                         world_db["MAP"][pos] = ord(".")
483                         i = 3 if case_X else 1
484                         for i in range(i):
485                             id = id_setter(-1, "Things")
486                             world_db["Things"][id] = \
487                               new_Thing(world_db["LUMBER"],
488                                         (move_result[1], move_result[2]))
489                         build_fov_map(t)
490                     return
491         passable = chr(world_db["MAP"][pos]) in symbols_passable
492     dir = [dir for dir in directions_db
493            if directions_db[dir] == chr(t["T_ARGUMENT"])][0]
494     if passable:
495         t["T_POSY"] = move_result[1]
496         t["T_POSX"] = move_result[2]
497         for id in t["T_CARRIES"]:
498             world_db["Things"][id]["T_POSY"] = move_result[1]
499             world_db["Things"][id]["T_POSX"] = move_result[2]
500         build_fov_map(t)
501         if t == world_db["Things"][0]:
502             log("You MOVE " + dir + ".")
503             if (move_result[1] == world_db["altar"][0] and
504                 move_result[2] == world_db["altar"][1]):
505                 enter_altar()
506
507 def command_ttid(id_string):
508     id = id_setter(id_string, "ThingTypes", command_ttid)
509     if None != id:
510         world_db["ThingTypes"][id] = {
511             "TT_NAME": "(none)",
512             "TT_TOOLPOWER": 0,
513             "TT_LIFEPOINTS": 0,
514             "TT_PROLIFERATE": 0,
515             "TT_START_NUMBER": 0,
516             "TT_STORAGE": 0,
517             "TT_SYMBOL": "?",
518             "TT_CORPSE_ID": id,
519             "TT_TOOL": ""
520         }
521
522 def command_worldactive(worldactive_string):
523     val = integer_test(worldactive_string, 0, 1)
524     if None != val:
525         if 0 != world_db["WORLD_ACTIVE"]:
526             if 0 == val:
527                 set_world_inactive()
528             else:
529                 print("World already active.")
530         elif 0 == world_db["WORLD_ACTIVE"]:
531             for ThingAction in world_db["ThingActions"]:
532                 if "wait" == world_db["ThingActions"][ThingAction]["TA_NAME"]:
533                     break
534             else:
535                 print("Ignored: No wait action defined for world to activate.")
536                 return
537             for Thing in world_db["Things"]:
538                 if 0 == Thing:
539                     break
540             else:
541                 print("Ignored: No player defined for world to activate.")
542                 return
543             if world_db["MAP"]:
544                 pos = world_db["MAP"].find(b'_')
545                 if pos > 0:
546                     y = int(pos / world_db["MAP_LENGTH"])
547                     x = pos % world_db["MAP_LENGTH"]
548                     world_db["altar"] = (y, x)
549                 else:
550                     print("Ignored: No altar defined for world to activate.")
551                     return
552             else:
553                 print("Ignored: No map defined for world to activate.")
554                 return
555             for name in world_db["specials"]:
556                 if world_db[name] not in world_db["ThingTypes"]:
557                     print("Ignored: Not all specials set for world to "
558                           "activate.")
559                     return
560             for id in world_db["Things"]:
561                 if world_db["Things"][id]["T_LIFEPOINTS"]:
562                     build_fov_map(world_db["Things"][id])
563                     if 0 == id:
564                         update_map_memory(world_db["Things"][id], False)
565             if not world_db["Things"][0]["T_LIFEPOINTS"]:
566                 empty_fovmap = bytearray(b" " * world_db["MAP_LENGTH"] ** 2)
567                 world_db["Things"][0]["fovmap"] = empty_fovmap
568             world_db["WORLD_ACTIVE"] = 1
569
570 def play_move(str_arg):
571     if action_exists("move"):
572         from server.config.world_data import directions_db, symbols_passable
573         t = world_db["Things"][0]
574         if not str_arg in directions_db:
575             print("Illegal move direction string.")
576             return
577         dir = ord(directions_db[str_arg])
578         from server.utils import mv_yx_in_dir_legal
579         move_result = mv_yx_in_dir_legal(chr(dir), t["T_POSY"], t["T_POSX"])
580         if 1 == move_result[0]:
581             pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
582             if ord("~") == world_db["MAP"][pos]:
583                 log("You can't SWIM.")
584                 return
585             if (ord("X") == world_db["MAP"][pos]
586                 or ord("|") == world_db["MAP"][pos]):
587                 carries_axe = False
588                 for id in t["T_CARRIES"]:
589                     type = world_db["Things"][id]["T_TYPE"]
590                     if world_db["ThingTypes"][type]["TT_TOOL"] == "axe":
591                         world_db["Things"][0]["T_ARGUMENT"] = dir
592                         set_command("move")
593                         return
594             if chr(world_db["MAP"][pos]) in symbols_passable:
595                 world_db["Things"][0]["T_ARGUMENT"] = dir
596                 set_command("move")
597                 return
598         log("You CAN'T move there.")
599
600 def play_use(str_arg):
601     if action_exists("use"):
602         t = world_db["Things"][0]
603         if 0 == len(t["T_CARRIES"]):
604             log("You have NOTHING to use in your inventory.")
605         else:
606             val = integer_test(str_arg, 0, 255)
607             if None != val and val < len(t["T_CARRIES"]):
608                 id = t["T_CARRIES"][val]
609                 type = world_db["Things"][id]["T_TYPE"]
610                 if (world_db["ThingTypes"][type]["TT_TOOL"] == "axe"
611                       and t == world_db["Things"][0]):
612                     log("To use this item for chopping, move towards a tree "
613                         "while carrying it in your inventory.")
614                     return
615                 elif (world_db["ThingTypes"][type]["TT_TOOL"] == "carpentry"):
616                     pos = t["T_POSY"] * world_db["MAP_LENGTH"] + t["T_POSX"]
617                     if (world_db["MAP"][pos] == ord("X")
618                         or world_db["MAP"][pos] == ord("|")):
619                         log("CAN'T build when standing on barrier.")
620                         return
621                     for id in [id for id in world_db["Things"]
622                                if not world_db["Things"][id] == t
623                                if not world_db["Things"][id]["carried"]
624                                if world_db["Things"][id]["T_POSY"] == t["T_POSY"]
625                                if world_db["Things"][id]["T_POSX"] == t["T_POSX"]]:
626                          log("CAN'T build when standing objects.")
627                          return
628                     wood_id = None
629                     for id in t["T_CARRIES"]:
630                         type_material = world_db["Things"][id]["T_TYPE"]
631                         if (world_db["ThingTypes"][type_material]["TT_TOOL"]
632                             == "wood"):
633                             wood_id = id
634                             break
635                     if wood_id == None:
636                         log("You CAN'T use a "
637                             + world_db["ThingTypes"][type]["TT_NAME"]
638                             + " without some wood in your inventory.")
639                         return
640                 elif world_db["ThingTypes"][type]["TT_TOOL"] == "fertilizer":
641                     pos = t["T_POSY"] * world_db["MAP_LENGTH"] + t["T_POSX"]
642                     if not world_db["MAP"][pos] == ord("."):
643                         log("Can only make soil out of NON-SOIL earth.")
644                         return
645                 elif world_db["ThingTypes"][type]["TT_TOOL"] == "wood":
646                         log("To use wood, you NEED a carpentry tool.")
647                         return
648                 elif type != world_db["SLIPPERS"] and not \
649                         world_db["ThingTypes"][type]["TT_TOOL"] == "food":
650                     log("You CAN'T consume this thing.")
651                     return
652                 world_db["Things"][0]["T_ARGUMENT"] = val
653                 set_command("use")
654             else:
655                 print("Illegal inventory index.")
656
657 def specialtypesetter(name):
658     def helper(str_int):
659         val = integer_test(str_int, 0)
660         if None != val:
661             world_db[name] = val
662             if world_db["WORLD_ACTIVE"] \
663                and world_db[name] not in world_db["ThingTypes"]:
664                 world_db["WORLD_ACTIVE"] = 0
665                 print(name + " fits no known ThingType, deactivating world.")
666     return helper
667
668 def write_metamap_A():
669     from server.worldstate_write_helpers import write_map
670     ord_v = ord("v")
671     length = world_db["MAP_LENGTH"]
672     metamapA = bytearray(b'0' * (length ** 2))
673     for id in [id for id in world_db["Things"]
674                   if not world_db["Things"][id]["carried"]
675                   if world_db["Things"][id]["T_LIFEPOINTS"]
676                   if world_db["Things"][0]["fovmap"][
677                        world_db["Things"][id]["T_POSY"] * length
678                        + world_db["Things"][id]["T_POSX"]] == ord_v]:
679         pos = (world_db["Things"][id]["T_POSY"] * length
680               + world_db["Things"][id]["T_POSX"])
681         if id == 0 or world_db["EMPATHY"]:
682             type = world_db["Things"][id]["T_TYPE"]
683             max_hp = world_db["ThingTypes"][type]["TT_LIFEPOINTS"]
684             third_of_hp = max_hp / 3
685             hp = world_db["Things"][id]["T_LIFEPOINTS"]
686             add = 0
687             if hp > 2 * third_of_hp:
688                  add = 2
689             elif hp > third_of_hp:
690                 add = 1
691             metamapA[pos] = ord('a') + add
692         else:
693             metamapA[pos] = ord('X')
694     for mt in world_db["Things"][0]["T_MEMTHING"]:
695         pos = mt[1] * length + mt[2]
696         if metamapA[pos] < ord('2'):
697             metamapA[pos] += 1
698     return write_map(metamapA, length)
699
700 def write_metamap_B():
701     from server.worldstate_write_helpers import write_map
702     ord_v = ord("v")
703     length = world_db["MAP_LENGTH"]
704     metamapB = bytearray(b' ' * (length ** 2))
705     for id in [id for id in world_db["Things"]
706                   if not world_db["Things"][id]["carried"]
707                   if world_db["Things"][id]["T_LIFEPOINTS"]
708                   if world_db["Things"][0]["fovmap"][
709                        world_db["Things"][id]["T_POSY"] * length
710                        + world_db["Things"][id]["T_POSX"]] == ord_v]:
711         pos = (world_db["Things"][id]["T_POSY"] * length
712               + world_db["Things"][id]["T_POSX"])
713         if id == 0 or world_db["EMPATHY"]:
714             action = world_db["Things"][id]["T_COMMAND"]
715             if 0 != action:
716                 name = world_db["ThingActions"][action]["TA_NAME"]
717             else:
718                 name = " "
719             metamapB[pos] = ord(name[0])
720     return write_map(metamapB, length)
721
722 def calc_effort(thing_action, thing):
723     from math import sqrt
724     effort = thing_action["TA_EFFORT"]
725     if thing_action["TA_NAME"] == "move":
726         typ = thing["T_TYPE"]
727         max_hp = (world_db["ThingTypes"][typ]["TT_LIFEPOINTS"])
728         effort = int(effort / sqrt(max_hp))
729         effort = 1 if effort == 0 else effort
730     return effort
731
732 def play_pickup():
733     """Try "pickup" as player's T_COMMAND"."""
734     if action_exists("pickup"):
735         t = world_db["Things"][0]
736         ids = [id for id in world_db["Things"] if id
737                if not world_db["Things"][id]["carried"]
738                if world_db["Things"][id]["T_POSY"] == t["T_POSY"]
739                if world_db["Things"][id]["T_POSX"] == t["T_POSX"]]
740         if not len(ids):
741             log("NOTHING to pick up.")
742         elif len(t["T_CARRIES"]) >= world_db["ThingTypes"][t["T_TYPE"]] \
743                 ["TT_STORAGE"]:
744             log("CAN'T pick up: No storage room to carry anything more.")
745         else:
746             set_command("pickup")
747
748 strong_write(io_db["file_out"], "PLUGIN PleaseTheIslandGod\n")
749
750 def set_zero_if_undefined(key):
751     if not key in world_db:
752         world_db[key] = 0
753
754 set_zero_if_undefined("GOD_FAVOR")
755 set_zero_if_undefined("FAVOR_STAGE")
756 set_zero_if_undefined("EMPATHY")
757 world_db["specials"] = ["SLIPPERS", "PLANT_0", "PLANT_1", "TOOL_0", "TOOL_1",
758     "LUMBER", "ANIMAL_0", "ANIMAL_1"]
759 for key in world_db["specials"]:
760     set_zero_if_undefined(key)
761
762 world_db["terrain_names"][":"] = "SOIL"
763 world_db["terrain_names"]["|"] = "WALL"
764 world_db["terrain_names"]["_"] = "ALTAR"
765 io_db["worldstate_write_order"] += [["GOD_FAVOR", "world_int"]]
766 io_db["worldstate_write_order"] += [[write_metamap_A, "func"]]
767 io_db["worldstate_write_order"] += [[write_metamap_B, "func"]]
768
769 import server.config.world_data
770 server.config.world_data.symbols_passable += ":_"
771
772 from server.config.world_data import thing_defaults
773 thing_defaults["T_PLAYERDROP"] = 0
774
775 import server.config.actions
776 server.config.actions.action_db["actor_move"] = actor_move
777 server.config.actions.action_db["actor_pickup"] = actor_pickup
778 server.config.actions.action_db["actor_drop"] = actor_drop
779 server.config.actions.action_db["actor_use"] = actor_use
780 server.config.actions.ai_func = ai
781
782 from server.config.commands import commands_db
783 commands_db["TT_ID"] = (1, False, command_ttid)
784 commands_db["GOD_FAVOR"] = (1, False, setter(None, "GOD_FAVOR", -32768, 32767))
785 commands_db["TT_STORAGE"] = (1, False, setter("ThingType", "TT_STORAGE", 0, 255))
786 commands_db["T_PLAYERDROP"] = (1, False, setter("Thing", "T_PLAYERDROP", 0, 1))
787 commands_db["WORLD_ACTIVE"] = (1, False, command_worldactive)
788 commands_db["FAVOR_STAGE"] = (1, False, setter(None, "FAVOR_STAGE", 0, 1))
789 commands_db["SLIPPERS"] = (1, False, specialtypesetter("SLIPPERS"))
790 commands_db["TOOL_0"] = (1, False, specialtypesetter("TOOL_0"))
791 commands_db["TOOL_1"] = (1, False, specialtypesetter("TOOL_1"))
792 commands_db["ANIMAL_0"] = (1, False, specialtypesetter("ANIMAL_0"))
793 commands_db["ANIMAL_1"] = (1, False, specialtypesetter("ANIMAL_1"))
794 commands_db["PLANT_0"] = (1, False, specialtypesetter("PLANT_0"))
795 commands_db["PLANT_1"] = (1, False, specialtypesetter("PLANT_1"))
796 commands_db["LUMBER"] = (1, False, specialtypesetter("LUMBER"))
797 commands_db["EMPATHY"] = (1, False, setter(None, "EMPATHY", 0, 1))
798 commands_db["use"] = (1, False, play_use)
799 commands_db["move"] = (1, False, play_move)
800 commands_db["pickup"] = (0, False, play_pickup)
801
802 import server.config.misc
803 server.config.misc.make_map_func = make_map
804 server.config.misc.thingproliferation_func = thingproliferation
805 server.config.misc.make_world = make_world
806 server.config.misc.decrement_lifepoints_func = decrement_lifepoints
807 server.config.misc.calc_effort_func = calc_effort