+ def quoted(self, string):
+ """Quote and escape string so client interprets it as single token."""
+ quoted = []
+ quoted += ['"']
+ for c in string:
+ if c in {'"', '\\'}:
+ quoted += ['\\']
+ quoted += [c]
+ quoted += ['"']
+ return ''.join(quoted)
+
+ def send_all_gamestate(self):
+ """Send out game state data relevant to clients."""
+ self.send_all('NEW_TURN ' + str(self.world.turn))
+ self.send_all('MAP_SIZE ' + self.stringify_yx(self.world.map_size))
+ for y in range(self.world.map_size[0]):
+ width = self.world.map_size[1]
+ terrain_line = self.world.map_[y * width:(y + 1) * width]
+ self.send_all('TERRAIN_LINE %5s %s' % (y, self.quoted(terrain_line)))
+ for thing in self.world.things:
+ self.send_all('THING TYPE:' + thing.type_ + ' '
+ + self.stringify_yx(thing.position))
+
+ def proceed(self):
+ """Send turn finish signal, run game world, send new world data.
+
+ First sends 'TURN_FINISHED' message, then runs game world
+ until new player input is needed, then sends game state.
+ """
+ self.send_all('TURN_FINISHED ' + str(self.world.turn))
+ self.world.proceed_to_next_player_turn()
+ self.send_all_gamestate()
+
+ def cmd_MOVE(self, direction, connection_id):
+ """Set player task to 'move' with direction arg, finish player turn."""
+ if direction not in {'UP', 'DOWN', 'RIGHT', 'LEFT'}:
+ raise ArgError('Move argument must be one of: '
+ 'UP, DOWN, RIGHT, LEFT')
+ self.world.player.set_task('move', direction=direction)
+ self.proceed()
+ cmd_MOVE.argtypes = 'string'
+
+ def cmd_WAIT(self, connection_id):
+ """Set player task to 'wait', finish player turn."""
+ self.world.player.set_task('wait')
+ self.proceed()
+
+ def cmd_GET_TURN(self, connection_id):
+ """Send world.turn to caller."""
+ self.send_to(connection_id, str(self.world.turn))
+
+ def cmd_ECHO(self, msg, connection_id):
+ """Send msg to caller."""
+ self.send_to(connection_id, msg)
+ cmd_ECHO.argtypes = 'string'
+
+ def cmd_ALL(self, msg, connection_id):
+ """Send msg to all clients."""
+ self.send_all(msg)
+ cmd_ALL.argtypes = 'string'
+
+ def cmd_FIB(self, numbers, connection_id):