from sqlalchemy.ext.associationproxy import association_proxy from app import db from app.models import GameState, GamePlayer, Role class Game(db.Model): __tablename__ = 'game' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), index=True, unique=True, nullable=False) state = db.Column(db.Enum(GameState), server_default=GameState(1).name, nullable=False) start_time = db.Column(db.DateTime) end_time = db.Column(db.DateTime) game_players = db.relationship( 'GamePlayer', back_populates='game', cascade="save-update, merge, delete, delete-orphan") users = association_proxy('game_players', 'user', creator=lambda user: GamePlayer(user=user)) # to enable game.players.append(player) objectives = db.relationship( 'Objective', lazy='select', backref=db.backref('game', lazy='joined')) notifications = db.relationship( 'Notification', lazy='select', backref=db.backref('game', lazy='joined')) def last_player_locations(self): return [player.last_location(self) for player in self.users if player.locations] def bunnies(self): # pylint: disable=not-an-iterable return [gameplayer.player for gameplayer in self.game_players if gameplayer.role == Role.bunny] def last_locations(self, players): locations = [] for player in players: locations.append(player.last_location(self)) return locations def owned_by(self, player): # pylint: disable=not-an-iterable '''given player is an owner of game''' return player in [gameplayer.player for gameplayer in self.game_players if gameplayer.role == Role.owner]