from sqlalchemy.ext.associationproxy import association_proxy from app import db from .game_state import GameState from .game_player import GamePlayer from .role import 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") players = association_proxy('game_players', 'user', creator=lambda user: GamePlayer(user=user)) users = association_proxy('game_players', 'user', creator=lambda user: GamePlayer(user=user)) 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 [user.last_location(self) for user in self.players if user.locations] def bunnies(self): # pylint: disable=not-an-iterable return [gameplayer.user 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, user): # pylint: disable=not-an-iterable '''given user is an owner of this game''' return user in [gameplayer.user for gameplayer in self.game_players if gameplayer.role == Role.owner]