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.mapping import YX, MapGeometrySquare, Map
16 self.map_geometry = MapGeometrySquare(YX(24, 40))
19 def get_thing(self, id_):
20 for thing in self.things:
25 def _register_object(self, obj, obj_type_desc, prefix):
26 if not obj.__name__.startswith(prefix):
27 raise GameError('illegal %s object name: %s' % (obj_type_desc, obj.__name__))
28 obj_name = obj.__name__[len(prefix):]
29 d = getattr(self, obj_type_desc + 's')
32 def register_command(self, command):
33 self._register_object(command, 'command', 'cmd_')
40 def __init__(self, save_file, *args, **kwargs):
41 super().__init__(*args, **kwargs)
43 self.io = GameIO(self, save_file)
47 self.map = Map(self.map_geometry.size)
48 self.map_control = Map(self.map_geometry.size)
49 self.map_control_passwords = {}
52 self.player_chars = string.digits + string.ascii_letters
53 self.player_char_i = -1
54 if os.path.exists(self.io.save_file):
55 if not os.path.isfile(self.io.save_file):
56 raise GameError('save file path refers to non-file')
58 def register_thing_type(self, thing_type):
59 self._register_object(thing_type, 'thing_type', 'Thing_')
61 def register_task(self, task):
62 self._register_object(task, 'task', 'Task_')
64 def read_savefile(self):
65 if os.path.exists(self.io.save_file):
66 with open(self.io.save_file, 'r') as f:
68 for i in range(len(lines)):
70 print("FILE INPUT LINE %5s: %s" % (i, line), end='')
71 self.io.handle_input(line, god_mode=True)
73 def can_do_tile_with_pw(self, yx, pw):
74 tile_class = self.map_control[yx]
75 if tile_class in self.map_control_passwords:
76 tile_pw = self.map_control_passwords[tile_class]
81 def get_string_options(self, string_option_type):
82 if string_option_type == 'direction':
83 return self.map_geometry.get_directions()
84 elif string_option_type == 'char':
86 string.digits + string.ascii_letters + string.punctuation + ' ']
87 elif string_option_type == 'map_geometry':
88 return ['Hex', 'Square']
89 elif string_option_type == 'thing_type':
90 return self.thing_types.keys()
93 def get_map_geometry_shape(self):
94 return self.map_geometry.__class__.__name__[len('MapGeometry'):]
96 def send_gamestate(self, connection_id=None):
97 """Send out game state data relevant to clients."""
99 self.io.send('TURN ' + str(self.turn))
100 for c_id in self.sessions:
101 player = self.get_thing(self.sessions[c_id])
102 visible_terrain = player.fov_stencil_map(self.map)
103 self.io.send('FOV %s' % quote(player.fov_stencil.terrain), c_id)
104 self.io.send('MAP %s %s %s' % (self.get_map_geometry_shape(),
105 self.map_geometry.size,
106 quote(visible_terrain)), c_id)
107 visible_control = player.fov_stencil_map(self.map_control)
108 self.io.send('MAP_CONTROL %s' % quote(visible_control), c_id)
109 for t in [t for t in self.things
110 if player.fov_stencil[t.position] == '.']:
111 self.io.send('THING %s %s %s' % (t.position, t.type_, t.id_), c_id)
112 if hasattr(t, 'nickname'):
113 self.io.send('THING_NAME %s %s' % (t.id_,
114 quote(t.nickname)), c_id)
115 if hasattr(t, 'player_char'):
116 self.io.send('THING_CHAR %s %s' % (t.id_,
117 quote(t.player_char)), c_id)
118 for yx in [yx for yx in self.portals
119 if player.fov_stencil[yx] == '.']:
120 self.io.send('PORTAL %s %s' % (yx, quote(self.portals[yx])), c_id)
121 self.io.send('GAME_STATE_COMPLETE')
125 for connection_id in self.sessions:
126 connection_id_found = False
127 for server in self.io.servers:
128 if connection_id in server.clients:
129 connection_id_found = True
131 if not connection_id_found:
132 t = self.get_thing(self.sessions[connection_id])
133 if hasattr(t, 'nickname'):
134 self.io.send('CHAT ' + quote(t.nickname + ' left the map.'))
135 self.things.remove(t)
136 to_delete += [connection_id]
137 for connection_id in to_delete:
138 del self.sessions[connection_id]
140 for t in [t for t in self.things]:
144 except GameError as e:
145 for connection_id in [c_id for c_id in self.sessions
146 if self.sessions[c_id] == t.id_]:
147 self.io.send('GAME_ERROR ' + quote(str(e)), connection_id)
148 except PlayError as e:
149 for connection_id in [c_id for c_id in self.sessions
150 if self.sessions[c_id] == t.id_]:
151 self.io.send('PLAY_ERROR ' + quote(str(e)), connection_id)
154 self.send_gamestate()
158 def get_command(self, command_name):
160 def partial_with_attrs(f, *args, **kwargs):
161 from functools import partial
162 p = partial(f, *args, **kwargs)
163 p.__dict__.update(f.__dict__)
166 def cmd_TASK_colon(task_name, game, *args, connection_id):
167 if connection_id not in game.sessions:
168 raise GameError('Not registered as player.')
169 t = game.get_thing(game.sessions[connection_id])
170 t.set_next_task(task_name, args)
172 def task_prefixed(command_name, task_prefix, task_command):
173 if command_name.startswith(task_prefix):
174 task_name = command_name[len(task_prefix):]
175 if task_name in self.tasks:
176 f = partial_with_attrs(task_command, task_name, self)
177 task = self.tasks[task_name]
178 f.argtypes = task.argtypes
182 command = task_prefixed(command_name, 'TASK:', cmd_TASK_colon)
185 if command_name in self.commands:
186 f = partial_with_attrs(self.commands[command_name], self)
190 def new_thing_id(self):
191 if len(self.things) == 0:
193 return max([t.id_ for t in self.things]) + 1
195 def get_next_player_char(self):
196 self.player_char_i += 1
197 if self.player_char_i >= len(self.player_chars):
198 self.player_char_i = 0
199 return self.player_chars[self.player_char_i]
206 with open(self.io.save_file, 'w') as f:
208 write(f, 'TURN %s' % self.turn)
209 map_geometry_shape = self.get_map_geometry_shape()
210 write(f, 'MAP %s %s' % (map_geometry_shape, self.map_geometry.size,))
211 for y, line in self.map.lines():
212 write(f, 'MAP_LINE %5s %s' % (y, quote(line)))
213 for yx in self.annotations:
214 write(f, 'GOD_ANNOTATE %s %s' % (yx, quote(self.annotations[yx])))
215 for yx in self.portals:
216 write(f, 'GOD_PORTAL %s %s' % (yx, quote(self.portals[yx])))
217 for y, line in self.map_control.lines():
218 write(f, 'MAP_CONTROL_LINE %5s %s' % (y, quote(line)))
219 for tile_class in self.map_control_passwords:
220 write(f, 'MAP_CONTROL_PW %s %s' % (tile_class,
221 self.map_control_passwords[tile_class]))
222 for t in [t for t in self.things if not t.type_ == 'Player']:
223 write(f, 'THING %s %s %s' % (t.position, t.type_, t.id_))
225 def new_world(self, map_geometry):
226 self.map_geometry = map_geometry
227 self.map = Map(self.map_geometry.size)
228 self.map_control = Map(self.map_geometry.size)
229 self.annotations = {}