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