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) 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)) objectives = db.relationship( 'Objective', lazy='select', backref=db.backref('game', lazy='joined'), cascade="save-update, merge, delete, delete-orphan") notifications = db.relationship( 'Notification', lazy='select', backref=db.backref('game', lazy='joined'), cascade="save-update, merge, delete, delete-orphan") def last_player_locations(self): # pylint: disable=not-an-iterable return [player.last_location() for player in self.players if player.user.locations] def last_locations(self, players): locations = [] for player in players: if isinstance(player, GamePlayer): player = player.user locations.append(player.last_location(self)) return locations def bunnies(self): # pylint: disable=not-an-iterable return [gameplayer for gameplayer in self.players if gameplayer.role == Role.bunny] 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.players if gameplayer.role == Role.owner]