home · contact · privacy
93606f7305974f40db7e4a584f6b45ccfa190693
[plomrogue] / plugins / server / TheCrawlingEater.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.config.world_data import world_db
7
8
9 def command_help(str_int):
10     val = integer_test(str_int, 0, 4)
11     if None != val:
12         log(str_int)
13
14
15 def command_ai():
16     if not (world_db["WORLD_ACTIVE"]
17             and world_db["Things"][0]["T_LIFEPOINTS"] > 0):
18         return
19     world_db["ai"](world_db["Things"][0])
20     world_db["turn_over"]()
21
22
23 def play_drink():
24     if not (action_exists("drink") and world_db["WORLD_ACTIVE"]
25             and world_db["Things"][0]["T_LIFEPOINTS"] > 0):
26         return
27     pos = world_db["Things"][0]["pos"]
28     if not (chr(world_db["MAP"][pos]) in "0-+"
29             and world_db["wetmap"][pos] > ord("0")):
30         log("NOTHING to drink here.")
31         return
32     elif world_db["Things"][0]["T_KIDNEY"] >= 32:
33         log("You're too FULL to drink more.")
34         return
35     world_db["set_command"]("drink")
36
37
38 def actor_drink(t):
39     pos = t["pos"]
40     if chr(world_db["MAP"][pos]) in "0-+" and \
41                 world_db["wetmap"][pos] > ord("0") and t["T_KIDNEY"] < 32:
42         if world_db["Things"][0] == t:
43             log("You DRINK.")
44         t["T_KIDNEY"] += 1
45         world_db["wetmap"][pos] -= 1
46
47
48 def play_pee():
49     if not (action_exists("pee") and world_db["WORLD_ACTIVE"]
50             and world_db["Things"][0]["T_LIFEPOINTS"] > 0):
51         return
52     if world_db["Things"][0]["T_BLADDER"] < 1:
53         log("Nothing to drop from empty bladder.")
54         return
55     world_db["set_command"]("pee")
56
57
58 def actor_pee(t):
59     if t["T_BLADDER"] < 1:
60         return
61     if t == world_db["Things"][0]:
62         log("You LOSE fluid.")
63     if not world_db["test_air"](t):
64         return
65     t["T_BLADDER"] -= 1
66     world_db["wetmap"][t["pos"]] += 1
67
68
69 def play_drop():
70     if not (action_exists("drop") and world_db["WORLD_ACTIVE"]
71             and world_db["Things"][0]["T_LIFEPOINTS"] > 0):
72         return
73     if world_db["Things"][0]["T_BOWEL"] < 1:
74         log("Nothing to drop from empty bowel.")
75         return
76     world_db["set_command"]("drop")
77
78
79 def actor_drop(t):
80     if t["T_BOWEL"] < 1:
81         return
82     if t == world_db["Things"][0]:
83         log("You DROP waste.")
84     if not world_db["test_air"](t):
85         return
86     if world_db["MAP"][t["pos"]] == ord("+"):
87         world_db["MAP"][t["pos"]] = ord("-")
88     elif world_db["MAP"][t["pos"]] == ord("-"):
89         world_db["MAP"][t["pos"]] = ord("0")
90     else:
91         world_db["MAP"][t["pos"]] += 1
92     t["T_BOWEL"] -= 1
93
94
95 def play_move(str_arg):
96     if not (action_exists("move") and world_db["WORLD_ACTIVE"]
97             and world_db["Things"][0]["T_LIFEPOINTS"] > 0):
98         return
99     from server.config.world_data import directions_db, symbols_passable
100     t = world_db["Things"][0]
101     if not str_arg in directions_db:
102         print("Illegal move direction string.")
103         return
104     d = ord(directions_db[str_arg])
105     from server.utils import mv_yx_in_dir_legal
106     move_result = mv_yx_in_dir_legal(chr(d), t["T_POSY"], t["T_POSX"])
107     if 1 == move_result[0]:
108         pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
109         hitted = [tid for tid in world_db["Things"]
110                   if world_db["Things"][tid]["T_POSY"] == move_result[1]
111                   if world_db["Things"][tid]["T_POSX"] == move_result[2]]
112         if len(hitted) > 0:
113             if t["T_STOMACH"] >= 32 and t["T_KIDNEY"] >= 32:
114                 if t == world_db["Things"][0]:
115                     log("You're too FULL to suck from another creature.")
116                 return
117             world_db["Things"][0]["T_ARGUMENT"] = d
118             world_db["set_command"]("eat")
119             return
120         if chr(world_db["MAP"][pos]) in "34":
121             if t["T_STOMACH"] >= 32:
122                 if t == world_db["Things"][0]:
123                     log("You're too FULL to eat.")
124                 return
125             world_db["Things"][0]["T_ARGUMENT"] = d
126             world_db["set_command"]("eat")
127             return
128         if chr(world_db["MAP"][pos]) in symbols_passable:
129             world_db["Things"][0]["T_ARGUMENT"] = d
130             world_db["set_command"]("move")
131             return
132     log("You CAN'T eat your way through there.")
133
134
135 def actor_eat(t):
136     from server.utils import mv_yx_in_dir_legal, rand
137     from server.config.world_data import symbols_passable
138     passable = False
139     move_result = mv_yx_in_dir_legal(chr(t["T_ARGUMENT"]),
140                                      t["T_POSY"], t["T_POSX"])
141     if 1 == move_result[0]:
142         pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
143         hitted = [tid for tid in world_db["Things"]
144                   if world_db["Things"][tid]["T_POSY"] == move_result[1]
145                   if world_db["Things"][tid]["T_POSX"] == move_result[2]]
146         if len(hitted):
147             hit_id = hitted[0]
148             hitted_tid = world_db["Things"][hit_id]["T_TYPE"]
149             if t == world_db["Things"][0]:
150                 hitted_name = world_db["ThingTypes"][hitted_tid]["TT_NAME"]
151                 log("You SUCK from " + hitted_name + ".")
152             elif 0 == hit_id:
153                 hitter_name = world_db["ThingTypes"][t["T_TYPE"]]["TT_NAME"]
154                 log(hitter_name +" SUCKS from you.")
155             hitted = world_db["Things"][hit_id]
156             if t["T_STOMACH"] < 32:
157                 t["T_STOMACH"] = t["T_STOMACH"] + 1
158                 hitted["T_STOMACH"] -= 1
159             if t["T_KIDNEY"] < 32:
160                 t["T_KIDNEY"] = t["T_KIDNEY"] + 1
161                 hitted["T_KIDNEY"] -= 1
162             return
163         passable = chr(world_db["MAP"][pos]) in symbols_passable
164     if passable and t == world_db["Things"][0]:
165         log("You try to EAT, but fail.")
166     else:
167         height = world_db["MAP"][pos] - ord("0")
168         if t["T_STOMACH"] >= 32 or height == 5:
169             return
170         t["T_STOMACH"] += 1
171         if t == world_db["Things"][0]:
172             log("You EAT.")
173         eaten = (height == 3 and 0 == int(rand.next() % 2)) or \
174                 (height == 4 and 0 == int(rand.next() % 5))
175         if eaten:
176             world_db["MAP"][pos] = ord("0")
177             if t["T_STOMACH"] > 32:
178                 t["T_STOMACH"] = 32
179
180
181 def actor_move(t):
182     from server.build_fov_map import build_fov_map
183     from server.utils import mv_yx_in_dir_legal, rand
184     from server.config.world_data import symbols_passable
185     passable = False
186     move_result = mv_yx_in_dir_legal(chr(t["T_ARGUMENT"]),
187                                      t["T_POSY"], t["T_POSX"])
188     if 1 == move_result[0]:
189         pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
190         hitted = [tid for tid in world_db["Things"]
191                   if world_db["Things"][tid]["T_POSY"] == move_result[1]
192                   if world_db["Things"][tid]["T_POSX"] == move_result[2]]
193         if len(hitted):
194             hit_id = hitted[0]
195             hitted_tid = world_db["Things"][hit_id]["T_TYPE"]
196             if t == world_db["Things"][0]:
197                 hitted_name = world_db["ThingTypes"][hitted_tid]["TT_NAME"]
198                 log("You BUMP into " + hitted_name + ".")
199             elif 0 == hit_id:
200                 hitter_name = world_db["ThingTypes"][t["T_TYPE"]]["TT_NAME"]
201                 log(hitter_name +" BUMPS into you.")
202             return
203         passable = chr(world_db["MAP"][pos]) in symbols_passable
204     if passable:
205         t["T_POSY"] = move_result[1]
206         t["T_POSX"] = move_result[2]
207         t["pos"] = move_result[1] * world_db["MAP_LENGTH"] + move_result[2]
208         world_db["soundmap"][t["pos"]] = ord("9")
209     elif t == world_db["Things"][0]:
210         log("You try to MOVE there, but fail.")
211
212
213 def test_hole(t):
214     if world_db["MAP"][t["pos"]] == ord("&"):
215         world_db["die"](t, "YOU WIN, CONGRATULATIONS.")
216         return False
217     if chr(world_db["MAP"][t["pos"]]) in "*&":
218         world_db["die"](t, "You FALL in a hole, and die.")
219         return False
220     return True
221 world_db["test_hole"] = test_hole
222
223
224 def test_air(t):
225     if world_db["terrain_fullness"](t["pos"]) > 5:
226         world_db["die"](t, "You SUFFOCATE")
227         return False
228     return True
229 world_db["test_air"] = test_air
230
231
232 def die(t, message):
233     t["T_LIFEPOINTS"] = 0
234     if t == world_db["Things"][0]:
235         t["fovmap"] = bytearray(b' ' * (world_db["MAP_LENGTH"] ** 2))
236         t["T_MEMMAP"][t["pos"]] = ord("@")
237         log(message)
238     else:
239         world_db["MAP"][t["pos"]] = ord("5")
240         world_db["HUMILITY"] = t["T_KIDNEY"] + t["T_BLADDER"] + \
241             (world_db["wetmap"][t["pos"]] - ord("0"))
242         world_db["wetmap"][t["pos"]] = 0
243         tid = next(tid for tid in world_db["Things"]
244                    if world_db["Things"][tid] == t)
245         del world_db["Things"][tid]
246 world_db["die"] = die
247
248
249 def make_map():
250     from server.make_map import new_pos, is_neighbor
251     from server.utils import rand
252     world_db["MAP"] = bytearray(b'5' * (world_db["MAP_LENGTH"] ** 2))
253     length = world_db["MAP_LENGTH"]
254     add_half_width = (not (length % 2)) * int(length / 2)
255     world_db["MAP"][int((length ** 2) / 2) + add_half_width] = ord("4")
256     while (1):
257         y, x, pos = new_pos()
258         if "5" == chr(world_db["MAP"][pos]) and is_neighbor((y, x), "4"):
259             if y == 0 or y == (length - 1) or x == 0 or x == (length - 1):
260                 break
261             world_db["MAP"][pos] = ord("4")
262     n_ground = int((length ** 2) / 16)
263     i_ground = 0
264     while (i_ground <= n_ground):
265         single_allowed = rand.next() % 32
266         y, x, pos = new_pos()
267         if "4" == chr(world_db["MAP"][pos]) \
268                 and ((not single_allowed) or is_neighbor((y, x), "0")):
269             world_db["MAP"][pos] = ord("0")
270             i_ground += 1
271     n_water = int((length ** 2) / 32)
272     i_water = 0
273     while (i_water <= n_water):
274         y, x, pos = new_pos()
275         if ord("0") == world_db["MAP"][pos] and \
276                 ord("0") == world_db["wetmap"][pos]:
277             world_db["wetmap"][pos] = ord("3")
278             i_water += 1
279
280
281 def calc_effort(ta, t):
282     from server.utils import mv_yx_in_dir_legal
283     if ta["TA_NAME"] == "move":
284         move_result = mv_yx_in_dir_legal(chr(t["T_ARGUMENT"]),
285                                          t["T_POSY"], t["T_POSX"])
286         if 1 == move_result[0]:
287             pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
288             narrowness = world_db["MAP"][pos] - ord("0")
289             return 2 ** narrowness
290     return 1
291 world_db["calc_effort"] = calc_effort
292
293
294 def turn_over():
295     from server.ai import ai
296     from server.config.actions import action_db
297     from server.update_map_memory import update_map_memory
298     from server.io import try_worldstate_update
299     from server.config.io import io_db
300     from server.utils import rand
301     from server.build_fov_map import build_fov_map
302     while world_db["Things"][0]["T_LIFEPOINTS"]:
303         for tid in [tid for tid in world_db["Things"]]:
304             if not tid in world_db["Things"]:
305                 continue
306             t = world_db["Things"][tid]
307             if t["T_LIFEPOINTS"]:
308                 if not (world_db["test_air"](t) and world_db["test_hole"](t)):
309                     continue
310                 if not t["T_COMMAND"]:
311                     update_map_memory(t)
312                     build_fov_map(t)
313                     if 0 == tid:
314                         return
315                     world_db["ai"](t)
316                 if t["T_LIFEPOINTS"]:
317                     t["T_PROGRESS"] += 1
318                     taid = [a for a in world_db["ThingActions"]
319                               if a == t["T_COMMAND"]][0]
320                     ThingAction = world_db["ThingActions"][taid]
321                     effort = world_db["calc_effort"](ThingAction, t)
322                     if t["T_PROGRESS"] >= effort:
323                         action = action_db["actor_" + ThingAction["TA_NAME"]]
324                         action(t)
325                         t["T_COMMAND"] = 0
326                         t["T_PROGRESS"] = 0
327                     if t["T_BOWEL"] > 16:
328                         if 0 == (rand.next() % (33 - t["T_BOWEL"])):
329                             action_db["actor_drop"](t)
330                     if t["T_BLADDER"] > 16:
331                         if 0 == (rand.next() % (33 - t["T_BLADDER"])):
332                             action_db["actor_pee"](t)
333                     if 0 == world_db["TURN"] % 5:
334                         t["T_STOMACH"] -= 1
335                         t["T_BOWEL"] += 1
336                         t["T_KIDNEY"] -= 1
337                         t["T_BLADDER"] += 1
338                     if t["T_STOMACH"] <= 0:
339                         world_db["die"](t, "You DIE of hunger.")
340                     elif t["T_KIDNEY"] <= 0:
341                         world_db["die"](t, "You DIE of dehydration.")
342         mapsize = world_db["MAP_LENGTH"] ** 2
343         for pos in range(mapsize):
344             wetness = world_db["wetmap"][pos] - ord("0")
345             height = world_db["MAP"][pos] - ord("0")
346             if world_db["MAP"][pos] == ord("-"):
347                 height = -1
348             elif world_db["MAP"][pos] == ord("+"):
349                 height = -2
350             if height == -2 and wetness > 1 \
351                     and 0 == rand.next() % ((2 ** 11) / (2 ** wetness)):
352                 world_db["MAP"][pos] = ord("*")
353                 world_db["HUMIDITY"] += wetness
354             if height == -1 and wetness > 1 \
355                     and 0 == rand.next() % ((2 ** 10) / (2 ** wetness)):
356                 world_db["MAP"][pos] = ord("+")
357             if height == 0 and wetness > 1 \
358                     and 0 == rand.next() % ((2 ** 9) / (2 ** wetness)):
359                 world_db["MAP"][pos] = ord("-")
360             if ((wetness > 0 and height > 0) or wetness > 1) \
361                 and 0 == rand.next() % 5:
362                 world_db["wetmap"][pos] -= 1
363                 world_db["HUMIDITY"] += 1
364         if world_db["HUMIDITY"] > 0:
365             if world_db["HUMIDITY"] > 2 and 0 == rand.next() % 2:
366                 world_db["NEW_SPAWN"] += 1
367                 world_db["HUMIDITY"] -= 1
368             if world_db["NEW_SPAWN"] >= 16:
369                 world_db["NEW_SPAWN"] -= 16
370                 from server.new_thing import new_Thing
371                 while 1:
372                     y = rand.next() % world_db["MAP_LENGTH"]
373                     x = rand.next() % world_db["MAP_LENGTH"]
374                     if chr(world_db["MAP"][y * world_db["MAP_LENGTH"] + x]) !=\
375                         "5":
376                         from server.utils import id_setter
377                         tid = id_setter(-1, "Things")
378                         world_db["Things"][tid] = new_Thing(
379                             world_db["PLAYER_TYPE"], (y, x))
380                         pos = y * world_db["MAP_LENGTH"] + x
381                         break
382             positions_to_wet = []
383             for pos in range(mapsize):
384                 if chr(world_db["MAP"][pos]) in "0-+" \
385                         and world_db["wetmap"][pos] < ord("5"):
386                     positions_to_wet += [pos]
387             while world_db["HUMIDITY"] > 0 and len(positions_to_wet) > 0:
388                 select = rand.next() % len(positions_to_wet)
389                 pos = positions_to_wet[select]
390                 world_db["wetmap"][pos] += 1
391                 positions_to_wet.remove(pos)
392                 world_db["HUMIDITY"] -= 1
393         for pos in range(mapsize):
394             if world_db["soundmap"][pos] > ord("0"):
395                 world_db["soundmap"][pos] -= 1
396         from server.utils import libpr
397         libpr.init_score_map()
398         def set_map_score(pos, score):
399             test = libpr.set_map_score(pos, score)
400             if test:
401                 raise RuntimeError("No score map allocated for set_map_score().")
402         [set_map_score(pos, 1) for pos in range(mapsize)
403          if world_db["MAP"][pos] == ord("*")]
404         for pos in range(mapsize):
405             if world_db["MAP"][pos] == ord("*"):
406                 if libpr.ready_neighbor_scores(pos):
407                     raise RuntimeError("No score map allocated for " +
408                                        "ready_neighbor_scores.()")
409                 score = 0
410                 dirs = "edcxsw"
411                 for i in range(len(dirs)):
412                     score += libpr.get_neighbor_score(i)
413                 if score == 5 or score == 6:
414                     world_db["MAP"][pos] = ord("&")
415         libpr.free_score_map()
416         world_db["TURN"] += 1
417         io_db["worldstate_updateable"] = True
418         try_worldstate_update()
419 world_db["turn_over"] = turn_over
420
421
422 def set_command(action):
423     """Set player's T_COMMAND, then call turn_over()."""
424     tid = [x for x in world_db["ThingActions"]
425            if world_db["ThingActions"][x]["TA_NAME"] == action][0]
426     world_db["Things"][0]["T_COMMAND"] = tid
427     world_db["turn_over"]()
428 world_db["set_command"] = set_command
429
430
431 def play_wait():
432     """Try "wait" as player's T_COMMAND."""
433     if world_db["WORLD_ACTIVE"]:
434         world_db["set_command"]("wait")
435
436
437 def save_maps():
438     length = world_db["MAP_LENGTH"]
439     string = ""
440     for i in range(length):
441         line = world_db["wetmap"][i * length:(i * length) + length].decode()
442         string = string + "WETMAP" + " "  + str(i) + " " + line + "\n"
443     for i in range(length):
444         line = world_db["soundmap"][i * length:(i * length) + length].decode()
445         string = string + "SOUNDMAP" + " "  + str(i) + " " + line + "\n"
446     return string
447
448
449 def soundmapset(str_int, mapline):
450     def valid_map_line(str_int, mapline):
451         from server.utils import integer_test
452         val = integer_test(str_int, 0, 255)
453         if None != val:
454             if val >= world_db["MAP_LENGTH"]:
455                 print("Illegal value for map line number.")
456             elif len(mapline) != world_db["MAP_LENGTH"]:
457                 print("Map line length is unequal map width.")
458             else:
459                 return val
460         return None
461     val = valid_map_line(str_int, mapline)
462     if None != val:
463         length = world_db["MAP_LENGTH"]
464         if not world_db["soundmap"]:
465             m = bytearray(b' ' * (length ** 2))
466         else:
467             m = world_db["soundmap"]
468         m[val * length:(val * length) + length] = mapline.encode()
469         if not world_db["soundmap"]:
470             world_db["soundmap"] = m
471
472
473 def wetmapset(str_int, mapline):
474     def valid_map_line(str_int, mapline):
475         from server.utils import integer_test
476         val = integer_test(str_int, 0, 255)
477         if None != val:
478             if val >= world_db["MAP_LENGTH"]:
479                 print("Illegal value for map line number.")
480             elif len(mapline) != world_db["MAP_LENGTH"]:
481                 print("Map line length is unequal map width.")
482             else:
483                 return val
484         return None
485     val = valid_map_line(str_int, mapline)
486     if None != val:
487         length = world_db["MAP_LENGTH"]
488         if not world_db["wetmap"]:
489             m = bytearray(b' ' * (length ** 2))
490         else:
491             m = world_db["wetmap"]
492         m[val * length:(val * length) + length] = mapline.encode()
493         if not world_db["wetmap"]:
494             world_db["wetmap"] = m
495
496
497 def write_soundmap():
498     from server.worldstate_write_helpers import write_map
499     length = world_db["MAP_LENGTH"]
500     return write_map(world_db["soundmap"], world_db["MAP_LENGTH"])
501
502
503 def write_wetmap():
504     from server.worldstate_write_helpers import write_map
505     length = world_db["MAP_LENGTH"]
506     visible_wetmap = bytearray(b' ' * (length ** 2))
507     for i in range(length ** 2):
508         if world_db["Things"][0]["fovmap"][i] == ord('v'):
509             visible_wetmap[i] = world_db["wetmap"][i]
510     return write_map(visible_wetmap, world_db["MAP_LENGTH"])
511
512
513 def get_dir_to_target(t, target):
514
515     from server.utils import rand, libpr, c_pointer_to_bytearray
516     from server.config.world_data import symbols_passable
517
518     def get_map_score(pos):
519         result = libpr.get_map_score(pos)
520         if result < 0:
521             raise RuntimeError("No score map allocated for get_map_score().")
522         return result
523
524     def zero_score_map_where_char_on_memdepthmap(c):
525         map = c_pointer_to_bytearray(t["T_MEMDEPTHMAP"])
526         if libpr.zero_score_map_where_char_on_memdepthmap(c, map):
527             raise RuntimeError("No score map allocated for "
528                                "zero_score_map_where_char_on_memdepthmap().")
529
530     def set_map_score(pos, score):
531         test = libpr.set_map_score(pos, score)
532         if test:
533             raise RuntimeError("No score map allocated for set_map_score().")
534
535     def set_movement_cost_map():
536         copy_memmap = t["T_MEMMAP"][:]
537         copy_memmap.replace(b' ', b'4')
538         memmap = c_pointer_to_bytearray(copy_memmap)
539         if libpr.TCE_set_movement_cost_map(memmap):
540             raise RuntimeError("No movement cost map allocated for "
541                                "set_movement_cost_map().")
542
543     def animates_in_fov(maplength):
544         return [Thing for Thing in world_db["Things"].values()
545                 if Thing["T_LIFEPOINTS"] and 118 == t["fovmap"][Thing["pos"]]
546                 and (not Thing == t)]
547
548     def seeing_thing():
549         def exists(gen):
550             try:
551                 next(gen)
552             except StopIteration:
553                 return False
554             return True
555         mapsize = world_db["MAP_LENGTH"] ** 2
556         if target == "food" and t["T_MEMMAP"]:
557             return exists(pos for pos in range(mapsize)
558                            if ord("2") < t["T_MEMMAP"][pos] < ord("5"))
559         elif target == "fluid_certain" and t["fovmap"]:
560             return exists(pos for pos in range(mapsize)
561                            if t["fovmap"] == ord("v")
562                            if world_db["MAP"][pos] == ord("0")
563                            if world_db["wetmap"][pos] > ord("0"))
564         elif target == "crack" and t["T_MEMMAP"]:
565             return exists(pos for pos in range(mapsize)
566                            if t["T_MEMMAP"][pos] == ord("-"))
567         elif target == "fluid_potential" and t["T_MEMMAP"] and t["fovmap"]:
568             return exists(pos for pos in range(mapsize)
569                            if t["T_MEMMAP"][pos] == ord("0")
570                            if t["fovmap"] != ord("v"))
571         elif target == "space" and t["T_MEMMAP"] and t["fovmap"]:
572             return exists(pos for pos in range(mapsize)
573                           if ord("-") <= t["T_MEMMAP"][pos] <= ord("2")
574                           if (t["fovmap"] != ord("v")
575                               or world_db["terrain_fullness"](pos) < 5))
576         elif target in {"hunt", "flee"} and t["fovmap"]:
577             return exists(Thing for
578                           Thing in animates_in_fov(world_db["MAP_LENGTH"])) \
579                 or exists(pos for pos in range(mapsize)
580                           if world_db["soundmap"][pos] > ord("0")
581                           if t["fovmap"][pos] != ord("v"))
582         return False
583
584     def init_score_map():
585         mapsize = world_db["MAP_LENGTH"] ** 2
586         test = libpr.TCE_init_score_map()
587         [set_map_score(pos, 65535) for pos in range(mapsize)
588          if chr(t["T_MEMMAP"][pos]) in "5*&"]
589         set_movement_cost_map()
590         if test:
591             raise RuntimeError("Malloc error in init_score_map().")
592         if target == "food" and t["T_MEMMAP"]:
593             [set_map_score(pos, 0) for pos in range(mapsize)
594              if ord("2") < t["T_MEMMAP"][pos] < ord("5")]
595         elif target == "fluid_certain" and t["fovmap"]:
596             [set_map_score(pos, 0) for pos in range(mapsize)
597              if t["fovmap"] == ord("v")
598              if world_db["MAP"][pos] == ord("0")
599              if world_db["wetmap"][pos] > ord("0")]
600         elif target == "crack" and t["T_MEMMAP"]:
601             [set_map_score(pos, 0) for pos in range(mapsize)
602              if t["T_MEMMAP"][pos] == ord("-")]
603         elif target == "fluid_potential" and t["T_MEMMAP"] and t["fovmap"]:
604             [set_map_score(pos, 0) for pos in range(mapsize)
605              if t["T_MEMMAP"][pos] == ord("0")
606              if t["fovmap"] != ord("v")]
607         elif target == "space" and t["T_MEMMAP"] and t["fovmap"]:
608             [set_map_score(pos, 0) for pos in range(mapsize)
609              if ord("-") <= t["T_MEMMAP"][pos] <= ord("2")
610              if (t["fovmap"] != ord("v")
611                  or world_db["terrain_fullness"](pos) < 5)]
612         elif target == "search":
613             zero_score_map_where_char_on_memdepthmap(mem_depth_c[0])
614         elif target in {"hunt", "flee"}:
615             [set_map_score(Thing["pos"], 0) for
616              Thing in animates_in_fov(world_db["MAP_LENGTH"])]
617             [set_map_score(pos, 0) for pos in range(mapsize)
618              if world_db["soundmap"][pos] > ord("0")
619              if t["fovmap"][pos] != ord("v")]
620
621     def rand_target_dir(neighbors, cmp, dirs):
622         candidates = []
623         n_candidates = 0
624         for i in range(len(dirs)):
625             if cmp == neighbors[i]:
626                 candidates.append(dirs[i])
627                 n_candidates += 1
628         return candidates[rand.next() % n_candidates] if n_candidates else 0
629
630     def get_neighbor_scores(dirs, eye_pos):
631         scores = []
632         if libpr.ready_neighbor_scores(eye_pos):
633             raise RuntimeError("No score map allocated for " +
634                                "ready_neighbor_scores.()")
635         for i in range(len(dirs)):
636             scores.append(libpr.get_neighbor_score(i))
637         return scores
638
639     def get_dir_from_neighbors():
640         import math
641         dir_to_target = False
642         dirs = "edcxsw"
643         eye_pos = t["pos"]
644         neighbors = get_neighbor_scores(dirs, eye_pos)
645         minmax_start = 0 if "flee" == target else 65535 - 1
646         minmax_neighbor = minmax_start
647         for i in range(len(dirs)):
648             if ("flee" == target and get_map_score(t["pos"]) < neighbors[i] and
649                 minmax_neighbor < neighbors[i] and 65535 != neighbors[i]) \
650                or ("flee" != target and minmax_neighbor > neighbors[i]):
651                 minmax_neighbor = neighbors[i]
652         if minmax_neighbor != minmax_start:
653             dir_to_target = rand_target_dir(neighbors, minmax_neighbor, dirs)
654         if "flee" == target:
655             distance = get_map_score(t["pos"])
656             fear_distance = 5
657             attack_distance = 1
658             if not dir_to_target:
659                 if attack_distance >= distance:
660                     dir_to_target = rand_target_dir(neighbors,
661                                                     distance - 1, dirs)
662             elif dir_to_target and fear_distance < distance:
663                 dir_to_target = 0
664         return dir_to_target, minmax_neighbor
665
666     dir_to_target = False
667     mem_depth_c = b' '
668     run_i = 9 + 1 if "search" == target else 1
669     minmax_neighbor = 0
670     while run_i and not dir_to_target and \
671             ("search" == target or seeing_thing()):
672         run_i -= 1
673         init_score_map()
674         mem_depth_c = b'9' if b' ' == mem_depth_c \
675             else bytes([mem_depth_c[0] - 1])
676         if libpr.TCE_dijkstra_map_with_movement_cost():
677             raise RuntimeError("No score map allocated for dijkstra_map().")
678         dir_to_target, minmax_neighbor = get_dir_from_neighbors()
679         libpr.free_score_map()
680         if dir_to_target and str == type(dir_to_target):
681             action = "move"
682             from server.utils import mv_yx_in_dir_legal
683             move_result = mv_yx_in_dir_legal(dir_to_target, t["T_POSY"],
684                                                             t["T_POSX"])
685             if 1 != move_result[0]:
686                 return False, 0
687             pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
688             hitted = [tid for tid in world_db["Things"]
689                       if world_db["Things"][tid]["pos"] == pos]
690             if world_db["MAP"][pos] > ord("2") or len(hitted) > 0:
691                 action = "eat"
692             t["T_COMMAND"] = [taid for taid in world_db["ThingActions"]
693                               if world_db["ThingActions"][taid]["TA_NAME"]
694                               == action][0]
695             t["T_ARGUMENT"] = ord(dir_to_target)
696     return dir_to_target, minmax_neighbor
697 world_db["get_dir_to_target"] = get_dir_to_target
698
699
700 def terrain_fullness(pos):
701     wetness = world_db["wetmap"][pos] - ord("0")
702     if chr(world_db["MAP"][pos]) in "-+":
703         height = 0
704     else:
705         height = world_db["MAP"][pos] - ord("0")
706     return wetness + height
707 world_db["terrain_fullness"] = terrain_fullness
708
709
710 def ai(t):
711
712     if t["T_LIFEPOINTS"] == 0:
713         return
714
715     def standing_on_fluid(t):
716         if world_db["MAP"][t["pos"]] == ord("0") and \
717             world_db["wetmap"][t["pos"]] > ord("0"):
718                 return True
719         else:
720             return False
721
722     def thing_action_id(name):
723         return [taid for taid in world_db["ThingActions"]
724                 if world_db["ThingActions"][taid]
725                 ["TA_NAME"] == name][0]
726
727     t["T_COMMAND"] = thing_action_id("wait")
728     needs = {
729         "fix_cracks": 24,
730         "flee": 24,
731         "safe_pee": (world_db["terrain_fullness"](t["pos"]) * t["T_BLADDER"]) / 4,
732         "safe_drop": (world_db["terrain_fullness"](t["pos"]) * t["T_BOWEL"]) / 4,
733         "food": 33 - t["T_STOMACH"],
734         "fluid_certain": 33 - t["T_KIDNEY"],
735         "fluid_potential": 32 - t["T_KIDNEY"],
736         "search": 1,
737     }
738     from operator import itemgetter
739     needs = sorted(needs.items(), key=itemgetter(1,0))
740     needs.reverse()
741     for need in needs:
742         if need[1] > 0:
743             if need[0] == "fix_cracks":
744                 if world_db["MAP"][t["pos"]] == ord("-") and \
745                         t["T_BOWEL"] > 0 and \
746                         world_db["terrain_fullness"](t["pos"]) <= 3:
747                     t["T_COMMAND"] = thing_action_id("drop")
748                     return
749                 elif world_db["get_dir_to_target"](t, "crack"):
750                     return
751             if need[0] in {"fluid_certain", "fluid_potential"}:
752                 if standing_on_fluid(t):
753                     t["T_COMMAND"] = thing_action_id("drink")
754                     return
755                 elif t["T_BLADDER"] > 0 and \
756                          world_db["MAP"][t["pos"]] == ord("0"):
757                     t["T_COMMAND"] = thing_action_id("pee")
758                     return
759             elif need[0] in {"safe_pee", "safe_drop"}:
760                 action_name = need[0][len("safe_"):]
761                 if world_db["terrain_fullness"](t["pos"]) <= 3:
762                     t["T_COMMAND"] = thing_action_id(action_name)
763                     return
764                 test = world_db["get_dir_to_target"](t, "space")
765                 if test[0]:
766                     if test[1] < 5:
767                         return
768                     elif world_db["terrain_fullness"](t["pos"]) < 5:
769                         t["T_COMMAND"] = thing_action_id(action_name)
770                     return
771                 if t["T_STOMACH"] < 32 and \
772                         world_db["get_dir_to_target"](t, "food")[0]:
773                     return
774                 continue
775             if need[0] in {"fluid_certain", "fluid_potential", "food"}:
776                 if world_db["get_dir_to_target"](t, need[0])[0]:
777                     return
778                 elif world_db["get_dir_to_target"](t, "hunt")[0]:
779                     return
780                 elif need[0] != "food" and t["T_STOMACH"] < 32 and \
781                         world_db["get_dir_to_target"](t, "food")[0]:
782                     return
783             elif world_db["get_dir_to_target"](t, need[0])[0]:
784                 return
785 world_db["ai"] = ai
786
787
788 from server.config.io import io_db
789 io_db["worldstate_write_order"] += [["T_STOMACH", "player_int"]]
790 io_db["worldstate_write_order"] += [["T_KIDNEY", "player_int"]]
791 io_db["worldstate_write_order"] += [["T_BOWEL", "player_int"]]
792 io_db["worldstate_write_order"] += [["T_BLADDER", "player_int"]]
793 io_db["worldstate_write_order"] += [[write_wetmap, "func"]]
794 io_db["worldstate_write_order"] += [[write_soundmap, "func"]]
795 import server.config.world_data
796 server.config.world_data.symbols_hide = "345"
797 server.config.world_data.symbols_passable = "012-+*&"
798 server.config.world_data.thing_defaults["T_STOMACH"] = 16
799 server.config.world_data.thing_defaults["T_BOWEL"] = 0
800 server.config.world_data.thing_defaults["T_KIDNEY"] = 16
801 server.config.world_data.thing_defaults["T_BLADDER"] = 0
802 world_db["soundmap"] = bytearray(b"0" * world_db["MAP_LENGTH"] ** 2)
803 world_db["wetmap"] = bytearray(b"0" * world_db["MAP_LENGTH"] ** 2)
804 if not "NEW_SPAWN" in world_db:
805     world_db["NEW_SPAWN"] = 0
806 if not "HUMIDITY" in world_db:
807     world_db["HUMIDITY"] = 0
808 io_db["hook_save"] = save_maps
809 import server.config.make_world_helpers
810 server.config.make_world_helpers.make_map = make_map
811 from server.config.commands import commands_db
812 commands_db["THINGS_HERE"] = (2, True, lambda x, y: None)
813 commands_db["HELP"] = (1, False, command_help)
814 commands_db["ai"] = (0, False, command_ai)
815 commands_db["move"] = (1, False, play_move)
816 commands_db["eat"] = (1, False, play_move)
817 commands_db["wait"] = (0, False, play_wait)
818 commands_db["drop"] = (0, False, play_drop)
819 commands_db["drink"] = (0, False, play_drink)
820 commands_db["pee"] = (0, False, play_pee)
821 commands_db["use"] = (1, False, lambda x: None)
822 commands_db["pickup"] = (0, False, lambda: None)
823 commands_db["NEW_SPAWN"] = (1, False, setter(None, "NEW_SPAWN", 0, 255))
824 commands_db["HUMIDITY"] = (1, False, setter(None, "HUMIDITY", 0, 65535))
825 commands_db["T_STOMACH"] = (1, False, setter("Thing", "T_STOMACH", 0, 255))
826 commands_db["T_KIDNEY"] = (1, False, setter("Thing", "T_KIDNEY", 0, 255))
827 commands_db["T_BOWEL"] = (1, False, setter("Thing", "T_BOWEL", 0, 255))
828 commands_db["T_BLADDER"] = (1, False, setter("Thing", "T_BLADDER", 0, 255))
829 commands_db["WETMAP"] = (2, False, wetmapset)
830 commands_db["SOUNDMAP"] = (2, False, soundmapset)
831 from server.actions import actor_wait
832 import server.config.actions
833 server.config.actions.action_db = {
834     "actor_wait": actor_wait,
835     "actor_move": actor_move,
836     "actor_drop": actor_drop,
837     "actor_drink": actor_drink,
838     "actor_pee": actor_pee,
839     "actor_eat": actor_eat,
840 }
841
842 strong_write(io_db["file_out"], "PLUGIN TheCrawlingEater\n")