home · contact · privacy
TCE: Prefix hole creation with crack hierarchy, fix some bugs.
[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 FALL in a hole, and die.")
216         return False
217     return True
218 world_db["test_hole"] = test_hole
219
220
221 def test_air(t):
222     if world_db["terrain_fullness"](t["pos"]) > 5:
223         world_db["die"](t, "You SUFFOCATE")
224         return False
225     return True
226 world_db["test_air"] = test_air
227
228
229 def die(t, message):
230     t["T_LIFEPOINTS"] = 0
231     if t == world_db["Things"][0]:
232         t["fovmap"] = bytearray(b' ' * (world_db["MAP_LENGTH"] ** 2))
233         t["T_MEMMAP"][t["pos"]] = ord("@")
234         log(message)
235     else:
236         world_db["MAP"][t["pos"]] = ord("5")
237         world_db["HUMILITY"] = t["T_KIDNEY"] + t["T_BLADDER"] + \
238             (world_db["wetmap"][t["pos"]] - ord("0"))
239         world_db["wetmap"][t["pos"]] = 0
240         tid = next(tid for tid in world_db["Things"]
241                    if world_db["Things"][tid] == t)
242         del world_db["Things"][tid]
243 world_db["die"] = die
244
245
246 def make_map():
247     from server.make_map import new_pos, is_neighbor
248     from server.utils import rand
249     world_db["MAP"] = bytearray(b'5' * (world_db["MAP_LENGTH"] ** 2))
250     length = world_db["MAP_LENGTH"]
251     add_half_width = (not (length % 2)) * int(length / 2)
252     world_db["MAP"][int((length ** 2) / 2) + add_half_width] = ord("4")
253     while (1):
254         y, x, pos = new_pos()
255         if "5" == chr(world_db["MAP"][pos]) and is_neighbor((y, x), "4"):
256             if y == 0 or y == (length - 1) or x == 0 or x == (length - 1):
257                 break
258             world_db["MAP"][pos] = ord("4")
259     n_ground = int((length ** 2) / 16)
260     i_ground = 0
261     while (i_ground <= n_ground):
262         single_allowed = rand.next() % 32
263         y, x, pos = new_pos()
264         if "4" == chr(world_db["MAP"][pos]) \
265                 and ((not single_allowed) or is_neighbor((y, x), "0")):
266             world_db["MAP"][pos] = ord("0")
267             i_ground += 1
268     n_water = int((length ** 2) / 32)
269     i_water = 0
270     while (i_water <= n_water):
271         y, x, pos = new_pos()
272         if ord("0") == world_db["MAP"][pos] and \
273                 ord("0") == world_db["wetmap"][pos]:
274             world_db["wetmap"][pos] = ord("3")
275             i_water += 1
276
277
278 def calc_effort(ta, t):
279     from server.utils import mv_yx_in_dir_legal
280     if ta["TA_NAME"] == "move":
281         move_result = mv_yx_in_dir_legal(chr(t["T_ARGUMENT"]),
282                                          t["T_POSY"], t["T_POSX"])
283         if 1 == move_result[0]:
284             pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
285             narrowness = world_db["MAP"][pos] - ord("0")
286             return 2 ** narrowness
287     return 1
288 world_db["calc_effort"] = calc_effort
289
290
291 def turn_over():
292     from server.ai import ai
293     from server.config.actions import action_db
294     from server.update_map_memory import update_map_memory
295     from server.io import try_worldstate_update
296     from server.config.io import io_db
297     from server.utils import rand
298     from server.build_fov_map import build_fov_map
299     while world_db["Things"][0]["T_LIFEPOINTS"]:
300         for tid in [tid for tid in world_db["Things"]]:
301             if not tid in world_db["Things"]:
302                 continue
303             t = world_db["Things"][tid]
304             if t["T_LIFEPOINTS"]:
305                 if not (world_db["test_air"](t) and world_db["test_hole"](t)):
306                     continue
307                 if not t["T_COMMAND"]:
308                     update_map_memory(t)
309                     build_fov_map(t)
310                     if 0 == tid:
311                         return
312                     world_db["ai"](t)
313                 if t["T_LIFEPOINTS"]:
314                     t["T_PROGRESS"] += 1
315                     taid = [a for a in world_db["ThingActions"]
316                               if a == t["T_COMMAND"]][0]
317                     ThingAction = world_db["ThingActions"][taid]
318                     effort = world_db["calc_effort"](ThingAction, t)
319                     if t["T_PROGRESS"] >= effort:
320                         action = action_db["actor_" + ThingAction["TA_NAME"]]
321                         action(t)
322                         t["T_COMMAND"] = 0
323                         t["T_PROGRESS"] = 0
324                     if t["T_BOWEL"] > 16:
325                         if 0 == (rand.next() % (33 - t["T_BOWEL"])):
326                             action_db["actor_drop"](t)
327                     if t["T_BLADDER"] > 16:
328                         if 0 == (rand.next() % (33 - t["T_BLADDER"])):
329                             action_db["actor_pee"](t)
330                     if 0 == world_db["TURN"] % 5:
331                         t["T_STOMACH"] -= 1
332                         t["T_BOWEL"] += 1
333                         t["T_KIDNEY"] -= 1
334                         t["T_BLADDER"] += 1
335                     if t["T_STOMACH"] <= 0:
336                         world_db["die"](t, "You DIE of hunger.")
337                     elif t["T_KIDNEY"] <= 0:
338                         world_db["die"](t, "You DIE of dehydration.")
339         for pos in range(world_db["MAP_LENGTH"] ** 2):
340             wetness = world_db["wetmap"][pos] - ord("0")
341             height = world_db["MAP"][pos] - ord("0")
342             if world_db["MAP"][pos] == ord("-"):
343                 height = -1
344             elif world_db["MAP"][pos] == ord("+"):
345                 height = -2
346             if height == -2 and wetness > 1 \
347                     and 0 == rand.next() % ((2 ** 11) / (2 ** wetness)):
348                 world_db["MAP"][pos] = ord("*")
349                 world_db["HUMIDITY"] += wetness
350             if height == -1 and wetness > 1 \
351                     and 0 == rand.next() % ((2 ** 10) / (2 ** wetness)):
352                 world_db["MAP"][pos] = ord("+")
353             if height == 0 and wetness > 1 \
354                     and 0 == rand.next() % ((2 ** 9) / (2 ** wetness)):
355                 world_db["MAP"][pos] = ord("-")
356             if ((wetness > 0 and height > 0) or wetness > 1) \
357                 and 0 == rand.next() % 5:
358                 world_db["wetmap"][pos] -= 1
359                 world_db["HUMIDITY"] += 1
360         if world_db["HUMIDITY"] > 0:
361             if world_db["HUMIDITY"] > 2 and 0 == rand.next() % 2:
362                 world_db["NEW_SPAWN"] += 1
363                 world_db["HUMIDITY"] -= 1
364             if world_db["NEW_SPAWN"] >= 16:
365                 world_db["NEW_SPAWN"] -= 16
366                 from server.new_thing import new_Thing
367                 while 1:
368                     y = rand.next() % world_db["MAP_LENGTH"]
369                     x = rand.next() % world_db["MAP_LENGTH"]
370                     if chr(world_db["MAP"][y * world_db["MAP_LENGTH"] + x]) !=\
371                         "5":
372                         from server.utils import id_setter
373                         tid = id_setter(-1, "Things")
374                         world_db["Things"][tid] = new_Thing(
375                             world_db["PLAYER_TYPE"], (y, x))
376                         pos = y * world_db["MAP_LENGTH"] + x
377                         break
378             positions_to_wet = []
379             for pos in range(world_db["MAP_LENGTH"] ** 2):
380                 if chr(world_db["MAP"][pos]) in "0-+" \
381                         and world_db["wetmap"][pos] < ord("5"):
382                     positions_to_wet += [pos]
383             while world_db["HUMIDITY"] > 0 and len(positions_to_wet) > 0:
384                 select = rand.next() % len(positions_to_wet)
385                 pos = positions_to_wet[select]
386                 world_db["wetmap"][pos] += 1
387                 positions_to_wet.remove(pos)
388                 world_db["HUMIDITY"] -= 1
389         for pos in range(world_db["MAP_LENGTH"] ** 2):
390             if world_db["soundmap"][pos] > ord("0"):
391                 world_db["soundmap"][pos] -= 1
392         log("TURN " + str(world_db["TURN"]))
393         world_db["TURN"] += 1
394         io_db["worldstate_updateable"] = True
395         try_worldstate_update()
396 world_db["turn_over"] = turn_over
397
398
399 def set_command(action):
400     """Set player's T_COMMAND, then call turn_over()."""
401     tid = [x for x in world_db["ThingActions"]
402            if world_db["ThingActions"][x]["TA_NAME"] == action][0]
403     world_db["Things"][0]["T_COMMAND"] = tid
404     world_db["turn_over"]()
405 world_db["set_command"] = set_command
406
407
408 def play_wait():
409     """Try "wait" as player's T_COMMAND."""
410     if world_db["WORLD_ACTIVE"]:
411         world_db["set_command"]("wait")
412
413
414 def save_maps():
415     length = world_db["MAP_LENGTH"]
416     string = ""
417     for i in range(length):
418         line = world_db["wetmap"][i * length:(i * length) + length].decode()
419         string = string + "WETMAP" + " "  + str(i) + " " + line + "\n"
420     for i in range(length):
421         line = world_db["soundmap"][i * length:(i * length) + length].decode()
422         string = string + "SOUNDMAP" + " "  + str(i) + " " + line + "\n"
423     return string
424
425
426 def soundmapset(str_int, mapline):
427     def valid_map_line(str_int, mapline):
428         from server.utils import integer_test
429         val = integer_test(str_int, 0, 255)
430         if None != val:
431             if val >= world_db["MAP_LENGTH"]:
432                 print("Illegal value for map line number.")
433             elif len(mapline) != world_db["MAP_LENGTH"]:
434                 print("Map line length is unequal map width.")
435             else:
436                 return val
437         return None
438     val = valid_map_line(str_int, mapline)
439     if None != val:
440         length = world_db["MAP_LENGTH"]
441         if not world_db["soundmap"]:
442             m = bytearray(b' ' * (length ** 2))
443         else:
444             m = world_db["soundmap"]
445         m[val * length:(val * length) + length] = mapline.encode()
446         if not world_db["soundmap"]:
447             world_db["soundmap"] = m
448
449
450 def wetmapset(str_int, mapline):
451     def valid_map_line(str_int, mapline):
452         from server.utils import integer_test
453         val = integer_test(str_int, 0, 255)
454         if None != val:
455             if val >= world_db["MAP_LENGTH"]:
456                 print("Illegal value for map line number.")
457             elif len(mapline) != world_db["MAP_LENGTH"]:
458                 print("Map line length is unequal map width.")
459             else:
460                 return val
461         return None
462     val = valid_map_line(str_int, mapline)
463     if None != val:
464         length = world_db["MAP_LENGTH"]
465         if not world_db["wetmap"]:
466             m = bytearray(b' ' * (length ** 2))
467         else:
468             m = world_db["wetmap"]
469         m[val * length:(val * length) + length] = mapline.encode()
470         if not world_db["wetmap"]:
471             world_db["wetmap"] = m
472
473
474 def write_soundmap():
475     from server.worldstate_write_helpers import write_map
476     length = world_db["MAP_LENGTH"]
477     return write_map(world_db["soundmap"], world_db["MAP_LENGTH"])
478
479
480 def write_wetmap():
481     from server.worldstate_write_helpers import write_map
482     length = world_db["MAP_LENGTH"]
483     visible_wetmap = bytearray(b' ' * (length ** 2))
484     for i in range(length ** 2):
485         if world_db["Things"][0]["fovmap"][i] == ord('v'):
486             visible_wetmap[i] = world_db["wetmap"][i]
487     return write_map(visible_wetmap, world_db["MAP_LENGTH"])
488
489
490 def get_dir_to_target(t, target):
491
492     from server.utils import rand, libpr, c_pointer_to_bytearray
493     from server.config.world_data import symbols_passable
494
495     def get_map_score(pos):
496         result = libpr.get_map_score(pos)
497         if result < 0:
498             raise RuntimeError("No score map allocated for get_map_score().")
499         return result
500
501     def zero_score_map_where_char_on_memdepthmap(c):
502         map = c_pointer_to_bytearray(t["T_MEMDEPTHMAP"])
503         if libpr.zero_score_map_where_char_on_memdepthmap(c, map):
504             raise RuntimeError("No score map allocated for "
505                                "zero_score_map_where_char_on_memdepthmap().")
506
507     def set_map_score(pos, score):
508         test = libpr.set_map_score(pos, score)
509         if test:
510             raise RuntimeError("No score map allocated for set_map_score().")
511
512     def set_movement_cost_map():
513         copy_memmap = t["T_MEMMAP"][:]
514         copy_memmap.replace(b' ', b'4')
515         memmap = c_pointer_to_bytearray(copy_memmap)
516         if libpr.TCE_set_movement_cost_map(memmap):
517             raise RuntimeError("No movement cost map allocated for "
518                                "set_movement_cost_map().")
519
520     def animates_in_fov(maplength):
521         return [Thing for Thing in world_db["Things"].values()
522                 if Thing["T_LIFEPOINTS"] and 118 == t["fovmap"][Thing["pos"]]
523                 and (not Thing == t)]
524
525     def seeing_thing():
526         def exists(gen):
527             try:
528                 next(gen)
529             except StopIteration:
530                 return False
531             return True
532         mapsize = world_db["MAP_LENGTH"] ** 2
533         if target == "food" and t["T_MEMMAP"]:
534             return exists(pos for pos in range(mapsize)
535                            if ord("2") < t["T_MEMMAP"][pos] < ord("5"))
536         elif target == "fluid_certain" and t["fovmap"]:
537             return exists(pos for pos in range(mapsize)
538                            if t["fovmap"] == ord("v")
539                            if world_db["MAP"][pos] == ord("0")
540                            if world_db["wetmap"][pos] > ord("0"))
541         elif target == "crack" and t["T_MEMMAP"]:
542             return exists(pos for pos in range(mapsize)
543                            if t["T_MEMMAP"][pos] == ord("-"))
544         elif target == "fluid_potential" and t["T_MEMMAP"] and t["fovmap"]:
545             return exists(pos for pos in range(mapsize)
546                            if t["T_MEMMAP"][pos] == ord("0")
547                            if t["fovmap"] != ord("v"))
548         elif target == "space" and t["T_MEMMAP"] and t["fovmap"]:
549             return exists(pos for pos in range(mapsize)
550                           if ord("-") <= t["T_MEMMAP"][pos] <= ord("2")
551                           if (t["fovmap"] != ord("v")
552                               or world_db["terrain_fullness"](pos) < 5))
553         elif target in {"hunt", "flee"} and t["fovmap"]:
554             return exists(Thing for
555                           Thing in animates_in_fov(world_db["MAP_LENGTH"])) \
556                 or exists(pos for pos in range(mapsize)
557                           if world_db["soundmap"][pos] > ord("0")
558                           if t["fovmap"][pos] != ord("v"))
559         return False
560
561     def init_score_map():
562         mapsize = world_db["MAP_LENGTH"] ** 2
563         test = libpr.TCE_init_score_map()
564         [set_map_score(pos, 65535) for pos in range(mapsize)
565          if chr(t["T_MEMMAP"][pos]) in "5*"]
566         set_movement_cost_map()
567         if test:
568             raise RuntimeError("Malloc error in init_score_map().")
569         if target == "food" and t["T_MEMMAP"]:
570             [set_map_score(pos, 0) for pos in range(mapsize)
571              if ord("2") < t["T_MEMMAP"][pos] < ord("5")]
572         elif target == "fluid_certain" and t["fovmap"]:
573             [set_map_score(pos, 0) for pos in range(mapsize)
574              if t["fovmap"] == ord("v")
575              if world_db["MAP"][pos] == ord("0")
576              if world_db["wetmap"][pos] > ord("0")]
577         elif target == "crack" and t["T_MEMMAP"]:
578             [set_map_score(pos, 0) for pos in range(mapsize)
579              if t["T_MEMMAP"][pos] == ord("-")]
580         elif target == "fluid_potential" and t["T_MEMMAP"] and t["fovmap"]:
581             [set_map_score(pos, 0) for pos in range(mapsize)
582              if t["T_MEMMAP"][pos] == ord("0")
583              if t["fovmap"] != ord("v")]
584         elif target == "space" and t["T_MEMMAP"] and t["fovmap"]:
585             [set_map_score(pos, 0) for pos in range(mapsize)
586              if ord("-") <= t["T_MEMMAP"][pos] <= ord("2")
587              if (t["fovmap"] != ord("v")
588                  or world_db["terrain_fullness"](pos) < 5)]
589         elif target == "search":
590             zero_score_map_where_char_on_memdepthmap(mem_depth_c[0])
591         elif target in {"hunt", "flee"}:
592             [set_map_score(Thing["pos"], 0) for
593              Thing in animates_in_fov(world_db["MAP_LENGTH"])]
594             [set_map_score(pos, 0) for pos in range(mapsize)
595              if world_db["soundmap"][pos] > ord("0")
596              if t["fovmap"][pos] != ord("v")]
597
598     def rand_target_dir(neighbors, cmp, dirs):
599         candidates = []
600         n_candidates = 0
601         for i in range(len(dirs)):
602             if cmp == neighbors[i]:
603                 candidates.append(dirs[i])
604                 n_candidates += 1
605         return candidates[rand.next() % n_candidates] if n_candidates else 0
606
607     def get_neighbor_scores(dirs, eye_pos):
608         scores = []
609         if libpr.ready_neighbor_scores(eye_pos):
610             raise RuntimeError("No score map allocated for " +
611                                "ready_neighbor_scores.()")
612         for i in range(len(dirs)):
613             scores.append(libpr.get_neighbor_score(i))
614         return scores
615
616     def get_dir_from_neighbors():
617         import math
618         dir_to_target = False
619         dirs = "edcxsw"
620         eye_pos = t["pos"]
621         neighbors = get_neighbor_scores(dirs, eye_pos)
622         minmax_start = 0 if "flee" == target else 65535 - 1
623         minmax_neighbor = minmax_start
624         for i in range(len(dirs)):
625             if ("flee" == target and get_map_score(t["pos"]) < neighbors[i] and
626                 minmax_neighbor < neighbors[i] and 65535 != neighbors[i]) \
627                or ("flee" != target and minmax_neighbor > neighbors[i]):
628                 minmax_neighbor = neighbors[i]
629         if minmax_neighbor != minmax_start:
630             dir_to_target = rand_target_dir(neighbors, minmax_neighbor, dirs)
631         if "flee" == target:
632             distance = get_map_score(t["pos"])
633             fear_distance = 5
634             attack_distance = 1
635             if not dir_to_target:
636                 if attack_distance >= distance:
637                     dir_to_target = rand_target_dir(neighbors,
638                                                     distance - 1, dirs)
639             elif dir_to_target and fear_distance < distance:
640                 dir_to_target = 0
641         return dir_to_target, minmax_neighbor
642
643     dir_to_target = False
644     mem_depth_c = b' '
645     run_i = 9 + 1 if "search" == target else 1
646     minmax_neighbor = 0
647     while run_i and not dir_to_target and \
648             ("search" == target or seeing_thing()):
649         run_i -= 1
650         init_score_map()
651         mem_depth_c = b'9' if b' ' == mem_depth_c \
652             else bytes([mem_depth_c[0] - 1])
653         if libpr.TCE_dijkstra_map_with_movement_cost():
654             raise RuntimeError("No score map allocated for dijkstra_map().")
655         dir_to_target, minmax_neighbor = get_dir_from_neighbors()
656         libpr.free_score_map()
657         if dir_to_target and str == type(dir_to_target):
658             action = "move"
659             from server.utils import mv_yx_in_dir_legal
660             move_result = mv_yx_in_dir_legal(dir_to_target, t["T_POSY"],
661                                                             t["T_POSX"])
662             if 1 != move_result[0]:
663                 return False, 0
664             pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
665             hitted = [tid for tid in world_db["Things"]
666                       if world_db["Things"][tid]["pos"] == pos]
667             if world_db["MAP"][pos] > ord("2") or len(hitted) > 0:
668                 action = "eat"
669             t["T_COMMAND"] = [taid for taid in world_db["ThingActions"]
670                               if world_db["ThingActions"][taid]["TA_NAME"]
671                               == action][0]
672             t["T_ARGUMENT"] = ord(dir_to_target)
673     return dir_to_target, minmax_neighbor
674 world_db["get_dir_to_target"] = get_dir_to_target
675
676
677 def terrain_fullness(pos):
678     wetness = world_db["wetmap"][pos] - ord("0")
679     if chr(world_db["MAP"][pos]) in "-+":
680         height = 0
681     else:
682         height = world_db["MAP"][pos] - ord("0")
683     return wetness + height
684 world_db["terrain_fullness"] = terrain_fullness
685
686
687 def ai(t):
688
689     if t["T_LIFEPOINTS"] == 0:
690         return
691
692     def standing_on_fluid(t):
693         if world_db["MAP"][t["pos"]] == ord("0") and \
694             world_db["wetmap"][t["pos"]] > ord("0"):
695                 return True
696         else:
697             return False
698
699     def thing_action_id(name):
700         return [taid for taid in world_db["ThingActions"]
701                 if world_db["ThingActions"][taid]
702                 ["TA_NAME"] == name][0]
703
704     t["T_COMMAND"] = thing_action_id("wait")
705     needs = {
706         "fix_cracks": 24,
707         "flee": 24,
708         "safe_pee": (world_db["terrain_fullness"](t["pos"]) * t["T_BLADDER"]) / 4,
709         "safe_drop": (world_db["terrain_fullness"](t["pos"]) * t["T_BOWEL"]) / 4,
710         "food": 33 - t["T_STOMACH"],
711         "fluid_certain": 33 - t["T_KIDNEY"],
712         "fluid_potential": 32 - t["T_KIDNEY"],
713         "search": 1,
714     }
715     from operator import itemgetter
716     needs = sorted(needs.items(), key=itemgetter(1,0))
717     needs.reverse()
718     for need in needs:
719         if need[1] > 0:
720             if need[0] == "fix_cracks":
721                 if world_db["MAP"][t["pos"]] == ord("-") and \
722                         t["T_BOWEL"] > 0 and \
723                         world_db["terrain_fullness"](t["pos"]) <= 3:
724                     t["T_COMMAND"] = thing_action_id("drop")
725                     return
726                 elif world_db["get_dir_to_target"](t, "crack"):
727                     return
728             if need[0] in {"fluid_certain", "fluid_potential"}:
729                 if standing_on_fluid(t):
730                     t["T_COMMAND"] = thing_action_id("drink")
731                     return
732                 elif t["T_BLADDER"] > 0 and \
733                          world_db["MAP"][t["pos"]] == ord("0"):
734                     t["T_COMMAND"] = thing_action_id("pee")
735                     return
736             elif need[0] in {"safe_pee", "safe_drop"}:
737                 action_name = need[0][len("safe_"):]
738                 if world_db["terrain_fullness"](t["pos"]) <= 3:
739                     t["T_COMMAND"] = thing_action_id(action_name)
740                     return
741                 test = world_db["get_dir_to_target"](t, "space")
742                 if test[0]:
743                     if test[1] < 5:
744                         return
745                     elif world_db["terrain_fullness"](t["pos"]) < 5:
746                         t["T_COMMAND"] = thing_action_id(action_name)
747                     return
748                 if t["T_STOMACH"] < 32 and \
749                         world_db["get_dir_to_target"](t, "food")[0]:
750                     return
751                 continue
752             if need[0] in {"fluid_certain", "fluid_potential", "food"}:
753                 if world_db["get_dir_to_target"](t, need[0])[0]:
754                     return
755                 elif world_db["get_dir_to_target"](t, "hunt")[0]:
756                     return
757                 elif need[0] != "food" and t["T_STOMACH"] < 32 and \
758                         world_db["get_dir_to_target"](t, "food")[0]:
759                     return
760             elif world_db["get_dir_to_target"](t, need[0])[0]:
761                 return
762 world_db["ai"] = ai
763
764
765 from server.config.io import io_db
766 io_db["worldstate_write_order"] += [["T_STOMACH", "player_int"]]
767 io_db["worldstate_write_order"] += [["T_KIDNEY", "player_int"]]
768 io_db["worldstate_write_order"] += [["T_BOWEL", "player_int"]]
769 io_db["worldstate_write_order"] += [["T_BLADDER", "player_int"]]
770 io_db["worldstate_write_order"] += [[write_wetmap, "func"]]
771 io_db["worldstate_write_order"] += [[write_soundmap, "func"]]
772 import server.config.world_data
773 server.config.world_data.symbols_hide = "345"
774 server.config.world_data.symbols_passable = "012-+*"
775 server.config.world_data.thing_defaults["T_STOMACH"] = 16
776 server.config.world_data.thing_defaults["T_BOWEL"] = 0
777 server.config.world_data.thing_defaults["T_KIDNEY"] = 16
778 server.config.world_data.thing_defaults["T_BLADDER"] = 0
779 world_db["soundmap"] = bytearray(b"0" * world_db["MAP_LENGTH"] ** 2)
780 world_db["wetmap"] = bytearray(b"0" * world_db["MAP_LENGTH"] ** 2)
781 if not "NEW_SPAWN" in world_db:
782     world_db["NEW_SPAWN"] = 0
783 if not "HUMIDITY" in world_db:
784     world_db["HUMIDITY"] = 0
785 io_db["hook_save"] = save_maps
786 import server.config.make_world_helpers
787 server.config.make_world_helpers.make_map = make_map
788 from server.config.commands import commands_db
789 commands_db["THINGS_HERE"] = (2, True, lambda x, y: None)
790 commands_db["HELP"] = (1, False, command_help)
791 commands_db["ai"] = (0, False, command_ai)
792 commands_db["move"] = (1, False, play_move)
793 commands_db["eat"] = (1, False, play_move)
794 commands_db["wait"] = (0, False, play_wait)
795 commands_db["drop"] = (0, False, play_drop)
796 commands_db["drink"] = (0, False, play_drink)
797 commands_db["pee"] = (0, False, play_pee)
798 commands_db["use"] = (1, False, lambda x: None)
799 commands_db["pickup"] = (0, False, lambda: None)
800 commands_db["NEW_SPAWN"] = (1, False, setter(None, "NEW_SPAWN", 0, 255))
801 commands_db["HUMIDITY"] = (1, False, setter(None, "HUMIDITY", 0, 65535))
802 commands_db["T_STOMACH"] = (1, False, setter("Thing", "T_STOMACH", 0, 255))
803 commands_db["T_KIDNEY"] = (1, False, setter("Thing", "T_KIDNEY", 0, 255))
804 commands_db["T_BOWEL"] = (1, False, setter("Thing", "T_BOWEL", 0, 255))
805 commands_db["T_BLADDER"] = (1, False, setter("Thing", "T_BLADDER", 0, 255))
806 commands_db["WETMAP"] = (2, False, wetmapset)
807 commands_db["SOUNDMAP"] = (2, False, soundmapset)
808 from server.actions import actor_wait
809 import server.config.actions
810 server.config.actions.action_db = {
811     "actor_wait": actor_wait,
812     "actor_move": actor_move,
813     "actor_drop": actor_drop,
814     "actor_drink": actor_drink,
815     "actor_pee": actor_pee,
816     "actor_eat": actor_eat,
817 }
818
819 strong_write(io_db["file_out"], "PLUGIN TheCrawlingEater\n")