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, cmd_MAP,
5 cmd_TURN, cmd_MAP_LINE, 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
19 self.map_geometry = MapGeometrySquare(YX(24, 40))
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.commands = {'QUERY': cmd_QUERY,
50 'MAP_LINE': cmd_MAP_LINE,
51 'GET_ANNOTATION': cmd_GET_ANNOTATION,
53 'GET_GAMESTATE': cmd_GET_GAMESTATE,
54 'ANNOTATE': cmd_ANNOTATE,
57 self.thing_type = Thing
58 self.thing_types = {'player': ThingPlayer}
60 self.map = Map(self.map_geometry.size)
63 if os.path.exists(self.io.save_file):
64 if not os.path.isfile(self.io.save_file):
65 raise GameError('save file path refers to non-file')
67 with open(self.io.save_file, 'r') as f:
69 for i in range(len(lines)):
71 print("FILE INPUT LINE %5s: %s" % (i, line), end='')
72 self.io.handle_input(line, god_mode=True)
74 def get_string_options(self, string_option_type):
76 if string_option_type == 'direction':
77 return self.map_geometry.get_directions()
78 elif string_option_type == 'char':
80 string.digits + string.ascii_letters + string.punctuation + ' ']
81 elif string_option_type == 'map_geometry':
82 return ['Hex', 'Square']
85 def get_map_geometry_shape(self):
86 return self.map_geometry.__class__.__name__[len('MapGeometry'):]
88 def send_gamestate(self, connection_id=None):
89 """Send out game state data relevant to clients."""
91 def send_thing(thing):
92 self.io.send('THING_POS %s %s' % (thing.id_, t.position))
93 if hasattr(thing, 'nickname'):
94 self.io.send('THING_NAME %s %s' % (thing.id_, quote(t.nickname)))
96 self.io.send('TURN ' + str(self.turn))
99 self.io.send('MAP %s %s %s' % (self.get_map_geometry_shape(),
100 self.map_geometry.size, quote(self.map.terrain)))
101 for yx in self.portals:
102 self.io.send('PORTAL %s %s' % (yx, quote(self.portals[yx])))
103 self.io.send('GAME_STATE_COMPLETE')
107 for connection_id in self.sessions:
108 connection_id_found = False
109 for server in self.io.servers:
110 if connection_id in server.clients:
111 connection_id_found = True
113 if not connection_id_found:
114 t = self.get_thing(self.sessions[connection_id], create_unfound=False)
115 self.things.remove(t)
116 to_delete += [connection_id]
117 for connection_id in to_delete:
118 del self.sessions[connection_id]
120 for t in [t for t in self.things]:
124 except GameError as e:
125 for connection_id in [c_id for c_id in self.sessions
126 if self.sessions[c_id] == t.id_]:
127 self.io.send('GAME_ERROR ' + quote(str(e)), connection_id)
128 except PlayError as e:
129 for connection_id in [c_id for c_id in self.sessions
130 if self.sessions[c_id] == t.id_]:
131 self.io.send('PLAY_ERROR ' + quote(str(e)), connection_id)
134 self.send_gamestate()
138 def get_command(self, command_name):
140 def partial_with_attrs(f, *args, **kwargs):
141 from functools import partial
142 p = partial(f, *args, **kwargs)
143 p.__dict__.update(f.__dict__)
146 def cmd_TASK_colon(task_name, game, *args, connection_id):
147 if connection_id not in game.sessions:
148 raise GameError('Not registered as player.')
149 t = game.get_thing(game.sessions[connection_id], create_unfound=False)
150 t.set_next_task(task_name, args)
152 def task_prefixed(command_name, task_prefix, task_command):
153 if command_name.startswith(task_prefix):
154 task_name = command_name[len(task_prefix):]
155 if task_name in self.tasks:
156 f = partial_with_attrs(task_command, task_name, self)
157 task = self.tasks[task_name]
158 f.argtypes = task.argtypes
162 command = task_prefixed(command_name, 'TASK:', cmd_TASK_colon)
165 if command_name in self.commands:
166 f = partial_with_attrs(self.commands[command_name], self)
170 def new_thing_id(self):
171 if len(self.things) == 0:
173 # DANGEROUS – if anywhere we append a thing to the list of lower
174 # ID than the highest-value ID, this might lead to re-using an
175 # already active ID. This condition /should/ not be fulfilled
176 # anywhere in the code, but if it does, trouble here is one of
177 # the more obvious indicators that it does – that's why there's
178 # no safeguard here against this.
179 return self.things[-1].id_ + 1
186 with open(self.io.save_file, 'w') as f:
187 write(f, 'TURN %s' % self.turn)
188 map_geometry_shape = self.get_map_geometry_shape()
189 write(f, 'MAP %s %s' % (map_geometry_shape, self.map_geometry.size,))
190 for y, line in self.map.lines():
191 write(f, 'MAP_LINE %5s %s' % (y, quote(line)))
192 for yx in self.annotations:
193 write(f, 'ANNOTATE %s %s' % (yx, quote(self.annotations[yx])))
194 for yx in self.portals:
195 write(f, 'PORTAL %s %s' % (yx, quote(self.portals[yx])))
197 def new_world(self, map_geometry):
198 self.map_geometry = map_geometry
199 self.map = Map(self.map_geometry.size)
200 self.annotations = {}