home · contact · privacy
Server: Fix AI bug (searching too costly consumable when not player).
[plomrogue] / server / commands.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 from server.config.io import io_db
8 from server.io import log, strong_write 
9 from server.utils import integer_test, id_setter
10 from server.world import set_world_inactive, turn_over
11 from server.update_map_memory import update_map_memory
12 from server.build_fov_map import build_fov_map
13
14
15 def command_plugin(str_plugin):
16     """Run code in plugins/[str_plugin]."""
17     import os
18     if (str_plugin.replace("_", "").isalnum()
19         and os.access("plugins/server/" + str_plugin + ".py", os.F_OK)):
20         exec(open("plugins/server/" + str_plugin + ".py").read())
21         world_db["PLUGIN"] += [str_plugin]
22         return
23     print("Bad plugin name:", str_plugin)
24
25
26 def command_ping():
27     """Send PONG line to server output file."""
28     strong_write(io_db["file_out"], "PONG\n")
29
30
31 def command_quit():
32     """Abort server process."""
33     from server.io import save_world, atomic_write
34     from server.utils import opts
35     if None == opts.replay:
36         if world_db["WORLD_ACTIVE"]:
37             save_world()
38         atomic_write(io_db["path_record"], io_db["record_chunk"],
39             do_append=True)
40     raise SystemExit("received QUIT command")
41
42
43 def command_thingshere(str_y, str_x):
44     """Write to out file list of Things known to player at coordinate y, x."""
45     if world_db["WORLD_ACTIVE"]:
46         y = integer_test(str_y, 0, 255)
47         x = integer_test(str_x, 0, 255)
48         length = world_db["MAP_LENGTH"]
49         if None != y and None != x and y < length and x < length:
50             pos = (y * world_db["MAP_LENGTH"]) + x
51             strong_write(io_db["file_out"], "THINGS_HERE START\n")
52             terrain = chr(world_db["Things"][0]["T_MEMMAP"][pos])
53             terrain_name = world_db["terrain_names"][terrain]
54             strong_write(io_db["file_out"], "terrain: " + terrain_name + "\n")
55             if "v" == chr(world_db["Things"][0]["fovmap"][pos]):
56                 for id in [id for tid in sorted(list(world_db["ThingTypes"]))
57                               for id in world_db["Things"]
58                               if not world_db["Things"][id]["carried"]
59                               if world_db["Things"][id]["T_TYPE"] == tid
60                               if y == world_db["Things"][id]["T_POSY"]
61                               if x == world_db["Things"][id]["T_POSX"]]:
62                     type = world_db["Things"][id]["T_TYPE"]
63                     name = world_db["ThingTypes"][type]["TT_NAME"]
64                     strong_write(io_db["file_out"], name + "\n")
65             else:
66                 for mt in [mt for tid in sorted(list(world_db["ThingTypes"]))
67                               for mt in world_db["Things"][0]["T_MEMTHING"]
68                               if mt[0] == tid if y == mt[1] if x == mt[2]]:
69                     name = world_db["ThingTypes"][mt[0]]["TT_NAME"]
70                     strong_write(io_db["file_out"], name + "\n")
71             strong_write(io_db["file_out"], "THINGS_HERE END\n")
72         else:
73             print("Ignoring: Invalid map coordinates.")
74     else:
75         print("Ignoring: Command only works on existing worlds.")
76
77
78 def command_seedrandomness(seed_string):
79     """Set rand seed to int(seed_string)."""
80     from server.utils import rand
81     val = integer_test(seed_string, 0, 4294967295)
82     if None != val:
83         rand.seed = val
84
85
86 def command_makeworld(seed_string):
87     """Call make_world()."""
88     val = integer_test(seed_string, 0, 4294967295)
89     if None != val:
90         from server.make_world import make_world
91         make_world(val)
92
93
94 def command_maplength(maplength_string):
95     """Redefine map length. Invalidate map, therefore lose all things on it."""
96     val = integer_test(maplength_string, 1, 256)
97     if None != val:
98         from server.utils import libpr
99         world_db["MAP_LENGTH"] = val
100         world_db["MAP"] = False
101         set_world_inactive()
102         world_db["Things"] = {}
103         libpr.set_maplength(val)
104
105
106 def command_worldactive(worldactive_string):
107     """Toggle world_db["WORLD_ACTIVE"] if possible.
108
109     An active world can always be set inactive. An inactive world can only be
110     set active with a "wait" ThingAction, and a player Thing (of ID 0), and a
111     map. On activation, rebuild all Things' FOVs, and the player's map memory.
112     """
113     val = integer_test(worldactive_string, 0, 1)
114     if None != val:
115         if 0 != world_db["WORLD_ACTIVE"]:
116             if 0 == val:
117                 set_world_inactive()
118             else:
119                 print("World already active.")
120         elif 0 == world_db["WORLD_ACTIVE"]:
121             for ThingAction in world_db["ThingActions"]:
122                 if "wait" == world_db["ThingActions"][ThingAction]["TA_NAME"]:
123                     break
124             else:
125                 print("Ignored: No wait action defined for world to activate.")
126                 return
127             for Thing in world_db["Things"]:
128                 if 0 == Thing:
129                     break
130             else:
131                 print("Ignored: No player defined for world to activate.")
132                 return
133             if not world_db["MAP"]:
134                 print("Ignoring: No map defined for world to activate.")
135                 return
136             from server.config.commands import command_worldactive_test_hook
137             if not command_worldactive_test_hook():
138                 return
139             for tid in world_db["Things"]:
140                 if world_db["Things"][tid]["T_LIFEPOINTS"]:
141                     build_fov_map(world_db["Things"][tid])
142                     if 0 == tid:
143                         update_map_memory(world_db["Things"][tid], False)
144             if not world_db["Things"][0]["T_LIFEPOINTS"]:
145                 empty_fovmap = bytearray(b" " * world_db["MAP_LENGTH"] ** 2)
146                 world_db["Things"][0]["fovmap"] = empty_fovmap
147             world_db["WORLD_ACTIVE"] = 1
148
149
150 def command_tid(id_string):
151     """Set ID of Thing to manipulate. ID unused? Create new one.
152
153     Default new Thing's type to the first available ThingType, others: zero.
154     """
155     tid = id_setter(id_string, "Things", command_tid)
156     if None != tid:
157         if world_db["ThingTypes"] == {}:
158             print("Ignoring: No ThingType to settle new Thing in.")
159             return
160         ty = list(world_db["ThingTypes"].keys())[0]
161         from server.new_thing import new_Thing
162         world_db["Things"][tid] = new_Thing(ty)
163
164
165 def command_ttid(id_string):
166     """Set ID of ThingType to manipulate. ID unused? Create new one.
167
168     Set new type's TT_CORPSE_ID to self, other fields to thingtype_defaults.
169     """
170     ttid = id_setter(id_string, "ThingTypes", command_ttid)
171     if None != ttid:
172         from server.config.world_data import thingtype_defaults
173         world_db["ThingTypes"][ttid] = {}
174         for key in thingtype_defaults:
175             world_db["ThingTypes"][ttid][key] = thingtype_defaults[key]
176         world_db["ThingTypes"][ttid]["TT_CORPSE_ID"] = ttid
177
178
179 def command_taid(id_string):
180     """Set ID of ThingAction to manipulate. ID unused? Create new one.
181
182     Default new ThingAction's TA_EFFORT to 1, its TA_NAME to "wait".
183     """
184     taid = id_setter(id_string, "ThingActions", command_taid, True)
185     if None != taid:
186         world_db["ThingActions"][taid] = {
187             "TA_EFFORT": 1,
188             "TA_NAME": "wait"
189         }
190
191
192 def test_for_id_maker(object, category):
193     """Return decorator testing for object having "id" attribute."""
194     def decorator(f):
195         def helper(*args):
196             if hasattr(object, "id"):
197                 f(*args)
198             else:
199                 print("Ignoring: No " + category +
200                       " defined to manipulate yet.")
201         return helper
202     return decorator
203
204
205 test_Thing_id = test_for_id_maker(command_tid, "Thing")
206 test_ThingType_id = test_for_id_maker(command_ttid, "ThingType")
207 test_ThingAction_id = test_for_id_maker(command_taid, "ThingAction")
208
209
210 @test_Thing_id
211 def command_tcommand(str_int):
212     """Set T_COMMAND of selected Thing."""
213     val = integer_test(str_int, 0)
214     if None != val:
215         if 0 == val or val in world_db["ThingActions"]:
216             world_db["Things"][command_tid.id]["T_COMMAND"] = val
217         else:
218             print("Ignoring: ThingAction ID belongs to no known ThingAction.")
219
220
221 @test_Thing_id
222 def command_ttype(str_int):
223     """Set T_TYPE of selected Thing."""
224     val = integer_test(str_int, 0)
225     if None != val:
226         if val in world_db["ThingTypes"]:
227             world_db["Things"][command_tid.id]["T_TYPE"] = val
228         else:
229             print("Ignoring: ThingType ID belongs to no known ThingType.")
230
231
232 @test_Thing_id
233 def command_tcarries(str_int):
234     """Append int(str_int) to T_CARRIES of selected Thing.
235
236     The ID int(str_int) must not be of the selected Thing, and must belong to a
237     Thing with unset "carried" flag. Its "carried" flag will be set on owning.
238     """
239     val = integer_test(str_int, 0)
240     if None != val:
241         if val == command_tid.id:
242             print("Ignoring: Thing cannot carry itself.")
243         elif val in world_db["Things"] \
244                 and not world_db["Things"][val]["carried"]:
245             world_db["Things"][command_tid.id]["T_CARRIES"].append(val)
246             world_db["Things"][val]["carried"] = True
247         else:
248             print("Ignoring: Thing not available for carrying.")
249     # Note that the whole carrying structure is different from the C version:
250     # Carried-ness is marked by a "carried" flag, not by Things containing
251     # Things internally.
252
253
254 @test_Thing_id
255 def command_tmemthing(str_t, str_y, str_x):
256     """Add (int(str_t), int(str_y), int(str_x)) to selected Thing's T_MEMTHING.
257
258     The type must fit to an existing ThingType, and the position into the map.
259     """
260     type = integer_test(str_t, 0)
261     posy = integer_test(str_y, 0, 255)
262     posx = integer_test(str_x, 0, 255)
263     if None != type and None != posy and None != posx:
264         if type not in world_db["ThingTypes"] \
265            or posy >= world_db["MAP_LENGTH"] or posx >= world_db["MAP_LENGTH"]:
266             print("Ignoring: Illegal value for thing type or position.")
267         else:
268             memthing = (type, posy, posx)
269             world_db["Things"][command_tid.id]["T_MEMTHING"].append(memthing)
270
271
272 @test_ThingType_id
273 def command_ttname(name):
274     """Set TT_NAME of selected ThingType."""
275     world_db["ThingTypes"][command_ttid.id]["TT_NAME"] = name
276
277
278 @test_ThingType_id
279 def command_tttool(name):
280     """Set TT_TOOL of selected ThingType."""
281     world_db["ThingTypes"][command_ttid.id]["TT_TOOL"] = name
282
283
284 @test_ThingType_id
285 def command_ttsymbol(char):
286     """Set TT_SYMBOL of selected ThingType. """
287     if 1 == len(char):
288         world_db["ThingTypes"][command_ttid.id]["TT_SYMBOL"] = char
289     else:
290         print("Ignoring: Argument must be single character.")
291
292
293 @test_ThingType_id
294 def command_ttcorpseid(str_int):
295     """Set TT_CORPSE_ID of selected ThingType."""
296     val = integer_test(str_int, 0)
297     if None != val:
298         if val in world_db["ThingTypes"]:
299             world_db["ThingTypes"][command_ttid.id]["TT_CORPSE_ID"] = val
300         else:
301             print("Ignoring: Corpse ID belongs to no known ThignType.")
302
303
304 @test_ThingAction_id
305 def command_taname(name):
306     """Set TA_NAME of selected ThingAction.
307
308     The name must match a valid thing action function. If after the name
309     setting no ThingAction with name "wait" remains, call set_world_inactive().
310     """
311     if name == "wait" or name == "move" or name == "use" or name == "drop" \
312        or name == "pickup":
313         world_db["ThingActions"][command_taid.id]["TA_NAME"] = name
314         if 1 == world_db["WORLD_ACTIVE"]:
315             for id in world_db["ThingActions"]:
316                 if "wait" == world_db["ThingActions"][id]["TA_NAME"]:
317                     break
318             else:
319                 set_world_inactive()
320     else:
321         print("Ignoring: Invalid action name.")
322
323
324 def setter(category, key, min, max=None):
325     """Build setter for world_db([category + "s"][id])[key] to >=min/<=max."""
326     if category is None:
327         def f(val_string):
328             val = integer_test(val_string, min, max)
329             if None != val:
330                 world_db[key] = val
331     else:
332         if category == "Thing":
333             id_store = command_tid
334             decorator = test_Thing_id
335         elif category == "ThingType":
336             id_store = command_ttid
337             decorator = test_ThingType_id
338         elif category == "ThingAction":
339             id_store = command_taid
340             decorator = test_ThingAction_id
341
342         @decorator
343         def f(val_string):
344             val = integer_test(val_string, min, max)
345             if None != val:
346                 world_db[category + "s"][id_store.id][key] = val
347     return f
348
349
350 def setter_map(maptype):
351     """Set (world or Thing's) map of maptype's int(str_int)-th line to mapline.
352
353     If no map of maptype exists yet, initialize it with ' ' bytes first.
354     """
355
356     def valid_map_line(str_int, mapline):
357         val = integer_test(str_int, 0, 255)
358         if None != val:
359             if val >= world_db["MAP_LENGTH"]:
360                 print("Illegal value for map line number.")
361             elif len(mapline) != world_db["MAP_LENGTH"]:
362                 print("Map line length is unequal map width.")
363             else:
364                 return val
365         return None
366
367     def nonThingMap_helper(str_int, mapline):
368         val = valid_map_line(str_int, mapline)
369         if None != val:
370             length = world_db["MAP_LENGTH"]
371             if not world_db["MAP"]:
372                 map = bytearray(b' ' * (length ** 2))
373             else:
374                 map = world_db["MAP"]
375             map[val * length:(val * length) + length] = mapline.encode()
376             if not world_db["MAP"]:
377                 world_db["MAP"] = map
378
379     @test_Thing_id
380     def ThingMap_helper(str_int, mapline):
381         val = valid_map_line(str_int, mapline)
382         if None != val:
383             length = world_db["MAP_LENGTH"]
384             if not world_db["Things"][command_tid.id][maptype]:
385                 map = bytearray(b' ' * (length ** 2))
386             else:
387                 map = world_db["Things"][command_tid.id][maptype]
388             map[val * length:(val * length) + length] = mapline.encode()
389             if not world_db["Things"][command_tid.id][maptype]:
390                 world_db["Things"][command_tid.id][maptype] = map
391
392     return nonThingMap_helper if maptype == "MAP" else ThingMap_helper
393
394
395
396 def setter_tpos(axis):
397     """Generate setter for T_POSX or  T_POSY of selected Thing.
398
399     If world is active, rebuilds animate things' fovmap, player's memory map.
400     """
401     @test_Thing_id
402     def helper(str_int):
403         val = integer_test(str_int, 0, 255)
404         if None != val:
405             if val < world_db["MAP_LENGTH"]:
406                 world_db["Things"][command_tid.id]["T_POS" + axis] = val
407                 if world_db["WORLD_ACTIVE"] \
408                    and world_db["Things"][command_tid.id]["T_LIFEPOINTS"]:
409                     build_fov_map(world_db["Things"][command_tid.id])
410                     if 0 == command_tid.id:
411                         update_map_memory(world_db["Things"][command_tid.id])
412             else:
413                 print("Ignoring: Position is outside of map.")
414     return helper
415
416
417 def set_command(action):
418     """Set player's T_COMMAND, then call turn_over()."""
419     id = [x for x in world_db["ThingActions"]
420           if world_db["ThingActions"][x]["TA_NAME"] == action][0]
421     world_db["Things"][0]["T_COMMAND"] = id
422     turn_over()
423
424
425 def play_wait():
426     """Try "wait" as player's T_COMMAND."""
427     set_command("wait")
428
429
430 def action_exists(action):
431     matching_actions = [x for x in world_db["ThingActions"]
432                         if world_db["ThingActions"][x]["TA_NAME"] == action]
433     if len(matching_actions) >= 1:
434         return True
435     print("No appropriate ThingAction defined.")
436     return False
437
438
439 def play_pickup():
440     """Try "pickup" as player's T_COMMAND"."""
441     if action_exists("pickup"):
442         t = world_db["Things"][0]
443         ids = [tid for tid in world_db["Things"] if tid
444                if not world_db["Things"][tid]["carried"]
445                if world_db["Things"][tid]["T_POSY"] == t["T_POSY"]
446                if world_db["Things"][tid]["T_POSX"] == t["T_POSX"]]
447         from server.config.commands import play_pickup_attempt_hook
448         if not len(ids):
449              log("NOTHING to pick up.")
450         elif play_pickup_attempt_hook(t):
451             set_command("pickup")
452
453
454 def play_drop(str_arg):
455     """Try "drop" as player's T_COMMAND, int(str_arg) as T_ARGUMENT / slot."""
456     if action_exists("drop"):
457         t = world_db["Things"][0]
458         if 0 == len(t["T_CARRIES"]):
459             log("You have NOTHING to drop in your inventory.")
460         else:
461             val = integer_test(str_arg, 0, 255)
462             if None != val and val < len(t["T_CARRIES"]):
463                 world_db["Things"][0]["T_ARGUMENT"] = val
464                 set_command("drop")
465             else:
466                 print("Illegal inventory index.")
467
468
469 def play_use(str_arg):
470     """Try "use" as player's T_COMMAND, int(str_arg) as T_ARGUMENT / slot."""
471     if action_exists("use"):
472         t = world_db["Things"][0]
473         if 0 == len(t["T_CARRIES"]):
474             log("You have NOTHING to use in your inventory.")
475         else:
476             val = integer_test(str_arg, 0, 255)
477             if None != val and val < len(t["T_CARRIES"]):
478                 tid = t["T_CARRIES"][val]
479                 tt = world_db["ThingTypes"][world_db["Things"][tid]["T_TYPE"]]
480                 from server.config.commands import play_use_attempt_hook
481                 hook_test = play_use_attempt_hook(t, tt)
482                 if not (tt["TT_TOOL"] == "food" or hook_test):
483                     if hook_test != False:
484                         log("You CAN'T use this thing.")
485                     return
486                 world_db["Things"][0]["T_ARGUMENT"] = val
487                 set_command("use")
488             else:
489                 print("Illegal inventory index.")
490
491
492 def play_move(str_arg):
493     """Try "move" as player's T_COMMAND, str_arg as T_ARGUMENT / direction."""
494     if action_exists("move"):
495         from server.config.world_data import directions_db, symbols_passable
496         t = world_db["Things"][0]
497         if not str_arg in directions_db:
498             print("Illegal move direction string.")
499             return
500         d = ord(directions_db[str_arg])
501         from server.utils import mv_yx_in_dir_legal
502         move_result = mv_yx_in_dir_legal(chr(d), t["T_POSY"], t["T_POSX"])
503         if 1 == move_result[0]:
504             pos = (move_result[1] * world_db["MAP_LENGTH"]) + move_result[2]
505             if ord("~") == world_db["MAP"][pos]:
506                 log("You can't SWIM.")
507                 return
508             from server.config.commands import play_move_attempt_hook
509             if play_move_attempt_hook(t, d, pos):
510                 return
511             if chr(world_db["MAP"][pos]) in symbols_passable:
512                 world_db["Things"][0]["T_ARGUMENT"] = d
513                 set_command("move")
514                 return
515         log("You CAN'T move there.")
516
517
518 def command_ai():
519     """Call ai() on player Thing, then turn_over()."""
520     from server.ai import ai
521     ai(world_db["Things"][0])
522     turn_over()