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.io import GameIO
5 from plomrogue.misc import quote
6 from plomrogue.things import Thing, ThingPlayer
7 from plomrogue.mapping import YX, MapGeometrySquare, Map
16 self.map_geometry = MapGeometrySquare(YX(24, 40))
19 def get_thing(self, id_, create_unfound):
20 # No default for create_unfound because every call to get_thing
21 # should be accompanied by serious consideration whether to use it.
22 for thing in self.things:
26 t = self.thing_type(self, id_)
31 def register_command(self, command):
33 if not command.__name__.startswith(prefix):
34 raise GameError('illegal command object name: %s' % command.__name__)
35 command_name = command.__name__[len(prefix):]
36 self.commands[command_name] = command
43 def __init__(self, save_file, *args, **kwargs):
44 super().__init__(*args, **kwargs)
46 self.io = GameIO(self, save_file)
48 self.thing_type = Thing
49 self.thing_types = {'player': ThingPlayer}
51 self.map = Map(self.map_geometry.size)
52 self.map_control = Map(self.map_geometry.size)
53 self.map_control_passwords = {}
56 if os.path.exists(self.io.save_file):
57 if not os.path.isfile(self.io.save_file):
58 raise GameError('save file path refers to non-file')
60 def register_task(self, task):
62 if not task.__name__.startswith(prefix):
63 raise GameError('illegal task object name: %s' % task.__name__)
64 task_name = task.__name__[len(prefix):]
65 self.tasks[task_name] = task
67 def read_savefile(self):
68 if os.path.exists(self.io.save_file):
69 with open(self.io.save_file, 'r') as f:
71 for i in range(len(lines)):
73 print("FILE INPUT LINE %5s: %s" % (i, line), end='')
74 self.io.handle_input(line, god_mode=True)
76 def get_string_options(self, string_option_type):
78 if string_option_type == 'direction':
79 return self.map_geometry.get_directions()
80 elif string_option_type == 'char':
82 string.digits + string.ascii_letters + string.punctuation + ' ']
83 elif string_option_type == 'map_geometry':
84 return ['Hex', 'Square']
87 def get_map_geometry_shape(self):
88 return self.map_geometry.__class__.__name__[len('MapGeometry'):]
90 def send_gamestate(self, connection_id=None):
91 """Send out game state data relevant to clients."""
93 def send_thing(thing):
94 self.io.send('THING_POS %s %s' % (thing.id_, t.position))
95 if hasattr(thing, 'nickname'):
96 self.io.send('THING_NAME %s %s' % (thing.id_, quote(t.nickname)))
98 self.io.send('TURN ' + str(self.turn))
101 self.io.send('MAP %s %s %s' % (self.get_map_geometry_shape(),
102 self.map_geometry.size, quote(self.map.terrain)))
103 self.io.send('MAP_CONTROL %s' % quote(self.map_control.terrain))
104 for yx in self.portals:
105 self.io.send('PORTAL %s %s' % (yx, quote(self.portals[yx])))
106 self.io.send('GAME_STATE_COMPLETE')
110 for connection_id in self.sessions:
111 connection_id_found = False
112 for server in self.io.servers:
113 if connection_id in server.clients:
114 connection_id_found = True
116 if not connection_id_found:
117 t = self.get_thing(self.sessions[connection_id], create_unfound=False)
118 if hasattr(t, 'nickname'):
119 self.io.send('CHAT ' + quote(t.nickname + ' left the map.'))
120 self.things.remove(t)
121 to_delete += [connection_id]
122 for connection_id in to_delete:
123 del self.sessions[connection_id]
125 for t in [t for t in self.things]:
129 except GameError as e:
130 for connection_id in [c_id for c_id in self.sessions
131 if self.sessions[c_id] == t.id_]:
132 self.io.send('GAME_ERROR ' + quote(str(e)), connection_id)
133 except PlayError as e:
134 for connection_id in [c_id for c_id in self.sessions
135 if self.sessions[c_id] == t.id_]:
136 self.io.send('PLAY_ERROR ' + quote(str(e)), connection_id)
139 self.send_gamestate()
143 def get_command(self, command_name):
145 def partial_with_attrs(f, *args, **kwargs):
146 from functools import partial
147 p = partial(f, *args, **kwargs)
148 p.__dict__.update(f.__dict__)
151 def cmd_TASK_colon(task_name, game, *args, connection_id):
152 if connection_id not in game.sessions:
153 raise GameError('Not registered as player.')
154 t = game.get_thing(game.sessions[connection_id], create_unfound=False)
155 t.set_next_task(task_name, args)
157 def task_prefixed(command_name, task_prefix, task_command):
158 if command_name.startswith(task_prefix):
159 task_name = command_name[len(task_prefix):]
160 if task_name in self.tasks:
161 f = partial_with_attrs(task_command, task_name, self)
162 task = self.tasks[task_name]
163 f.argtypes = task.argtypes
167 command = task_prefixed(command_name, 'TASK:', cmd_TASK_colon)
170 if command_name in self.commands:
171 f = partial_with_attrs(self.commands[command_name], self)
175 def new_thing_id(self):
176 if len(self.things) == 0:
178 # DANGEROUS – if anywhere we append a thing to the list of lower
179 # ID than the highest-value ID, this might lead to re-using an
180 # already active ID. This condition /should/ not be fulfilled
181 # anywhere in the code, but if it does, trouble here is one of
182 # the more obvious indicators that it does – that's why there's
183 # no safeguard here against this.
184 return self.things[-1].id_ + 1
191 with open(self.io.save_file, 'w') as f:
193 write(f, 'TURN %s' % self.turn)
194 map_geometry_shape = self.get_map_geometry_shape()
195 write(f, 'MAP %s %s' % (map_geometry_shape, self.map_geometry.size,))
196 for y, line in self.map.lines():
197 write(f, 'MAP_LINE %5s %s' % (y, quote(line)))
198 for yx in self.annotations:
199 write(f, 'ANNOTATE %s %s' % (yx, quote(self.annotations[yx])))
200 for yx in self.portals:
201 write(f, 'PORTAL %s %s' % (yx, quote(self.portals[yx])))
202 for y, line in self.map_control.lines():
203 write(f, 'MAP_CONTROL_LINE %5s %s' % (y, quote(line)))
204 for tile_class in self.map_control_passwords:
205 write(f, 'MAP_CONTROL_PW %s %s' % (tile_class,
206 self.map_control_passwords[tile_class]))
208 def new_world(self, map_geometry):
209 self.map_geometry = map_geometry
210 self.map = Map(self.map_geometry.size)
211 self.map_control = Map(self.map_geometry.size)
212 self.annotations = {}