1 from plomrogue.tasks import (Task_WAIT, Task_MOVE, Task_WRITE,
2 Task_FLATTEN_SURROUNDINGS)
3 from plomrogue.errors import GameError, PlayError
4 from plomrogue.commands import (cmd_ALL, cmd_LOGIN, cmd_QUERY, cmd_PING,
5 cmd_TURN, cmd_MAP_LINE, cmd_MAP, cmd_GET_ANNOTATION,
6 cmd_ANNOTATE, cmd_PORTAL, cmd_GET_GAMESTATE)
7 from plomrogue.io import GameIO
8 from plomrogue.misc import quote
9 from plomrogue.things import Thing, ThingPlayer
10 from plomrogue.mapping import YX, MapGeometrySquare, Map
21 def get_thing(self, id_, create_unfound):
22 # No default for create_unfound because every call to get_thing
23 # should be accompanied by serious consideration whether to use it.
24 for thing in self.things:
28 t = self.thing_type(self, id_)
37 def __init__(self, save_file, *args, **kwargs):
39 super().__init__(*args, **kwargs)
41 self.io = GameIO(self, save_file)
42 self.tasks = {'WAIT': Task_WAIT,
45 'FLATTEN_SURROUNDINGS': Task_FLATTEN_SURROUNDINGS}
46 self.map_geometry = MapGeometrySquare(YX(24, 40))
47 self.commands = {'QUERY': cmd_QUERY,
51 'MAP_LINE': cmd_MAP_LINE,
52 'GET_ANNOTATION': cmd_GET_ANNOTATION,
54 'GET_GAMESTATE': cmd_GET_GAMESTATE,
55 'ANNOTATE': cmd_ANNOTATE,
58 self.thing_type = Thing
59 self.thing_types = {'player': ThingPlayer}
61 self.map = Map(self.map_geometry.size)
64 if os.path.exists(self.io.save_file):
65 if not os.path.isfile(self.io.save_file):
66 raise GameError('save file path refers to non-file')
68 with open(self.io.save_file, 'r') as f:
70 for i in range(len(lines)):
72 print("FILE INPUT LINE %5s: %s" % (i, line), end='')
73 self.io.handle_input(line, god_mode=True)
75 def get_string_options(self, string_option_type):
77 if string_option_type == 'direction':
78 return self.map_geometry.get_directions()
79 if string_option_type == 'char':
81 string.digits + string.ascii_letters + string.punctuation + ' ']
84 def send_gamestate(self, connection_id=None):
85 """Send out game state data relevant to clients."""
87 def send_thing(thing):
88 self.io.send('THING_POS %s %s' % (thing.id_, t.position))
90 self.io.send('TURN ' + str(self.turn))
93 self.io.send('MAP %s %s' % (self.map_geometry.size, quote(self.map.terrain)))
94 for yx in self.portals:
95 self.io.send('PORTAL %s %s' % (yx, self.portals[yx]))
96 self.io.send('GAME_STATE_COMPLETE')
100 for connection_id in self.sessions:
101 connection_id_found = False
102 for server in self.io.servers:
103 if connection_id in server.clients:
104 connection_id_found = True
106 if not connection_id_found:
107 t = self.get_thing(self.sessions[connection_id], create_unfound=False)
108 self.things.remove(t)
109 to_delete += [connection_id]
110 for connection_id in to_delete:
111 del self.sessions[connection_id]
113 for t in [t for t in self.things]:
117 except GameError as e:
118 for connection_id in [c_id for c_id in self.sessions
119 if self.sessions[c_id] == t.id_]:
120 self.io.send('GAME_ERROR ' + quote(str(e)), connection_id)
121 except PlayError as e:
122 for connection_id in [c_id for c_id in self.sessions
123 if self.sessions[c_id] == t.id_]:
124 self.io.send('PLAY_ERROR ' + quote(str(e)), connection_id)
127 self.send_gamestate()
131 def get_command(self, command_name):
133 def partial_with_attrs(f, *args, **kwargs):
134 from functools import partial
135 p = partial(f, *args, **kwargs)
136 p.__dict__.update(f.__dict__)
139 def cmd_TASK_colon(task_name, game, *args, connection_id):
140 if connection_id not in game.sessions:
141 raise GameError('Not registered as player.')
142 t = game.get_thing(game.sessions[connection_id], create_unfound=False)
143 t.set_next_task(task_name, args)
145 def task_prefixed(command_name, task_prefix, task_command):
146 if command_name.startswith(task_prefix):
147 task_name = command_name[len(task_prefix):]
148 if task_name in self.tasks:
149 f = partial_with_attrs(task_command, task_name, self)
150 task = self.tasks[task_name]
151 f.argtypes = task.argtypes
155 command = task_prefixed(command_name, 'TASK:', cmd_TASK_colon)
158 if command_name in self.commands:
159 f = partial_with_attrs(self.commands[command_name], self)
163 def new_thing_id(self):
164 if len(self.things) == 0:
166 # DANGEROUS – if anywhere we append a thing to the list of lower
167 # ID than the highest-value ID, this might lead to re-using an
168 # already active ID. This condition /should/ not be fulfilled
169 # anywhere in the code, but if it does, trouble here is one of
170 # the more obvious indicators that it does – that's why there's
171 # no safeguard here against this.
172 return self.things[-1].id_ + 1
179 with open(self.io.save_file, 'w') as f:
180 write(f, 'TURN %s' % self.turn)
181 write(f, 'MAP %s' % (self.map_geometry.size,))
182 for y, line in self.map.lines():
183 write(f, 'MAP_LINE %5s %s' % (y, quote(line)))
184 for yx in self.annotations:
185 write(f, 'ANNOTATE %s %s' % (yx, quote(self.annotations[yx])))
186 for yx in self.portals:
187 write(f, 'PORTAL %s %s' % (yx, self.portals[yx]))
189 def new_world(self, size):
190 self.map_geometry = MapGeometrySquare(YX(size.y, size.x))
191 self.map = Map(self.map_geometry.size)
192 self.annotations = {}