def attack(self, me: PlayerLogic, defender: PlayerLogic): if defender is None: raise UserError("Игрок не найден!") if defender.model.game != me.model.game: raise UserError("Игрок не найден!") if not self.can_attack(me, defender): raise UserError("Сейчас нельзя атаковать этого игрока") self.set_dirty() cur_battle = self.get_player_battle(me) if cur_battle is not None: cur_battle.defendingPlayer = defender.model else: battle = self.start_battle(me) battle.defendingPlayer = defender.model
def join_player(self, player: PlayerLogic, is_admin: bool) -> None: if self.get_state() != GameLogic.State.WAITROOM: raise UserError("Невозможно присоединиться к запущенной игре", error_type=UserError.ErrorType.INVALID_GAME) if is_admin: player.make_admin() self.set_dirty()
def complete_battle(self, battle: BattleLogic, bypass=False): if not bypass: self.assert_running() self.set_dirty() btl_model = battle.model if not bypass and btl_model.offensiveCard is None: raise UserError("Нельзя завершить битву без карты атаки!") if not bypass: self.calculate_battle_falsics(battle) btl_model.isComplete = True if self.cur_round.isAccidentComplete: next_player = self.get_neighbour( PlayerLogic(self.db, btl_model.offendingPlayer)) if next_player != self.get_players(True)[0].model: self.start_battle(PlayerLogic(self.db, next_player)) if all(map(lambda b: b.model.isComplete, self.get_battles())): if btl_model.offensiveCard is not None and btl_model.offensiveCard.type.enumType == CardTypeEnum.ACCIDENT: print("Round", self.cur_round.roundNo, "has accident completed") self.on_accident_played() else: print("Round", self.cur_round.roundNo, "is complete") self.on_round_completed() if not self.is_complete(): self.new_round()
def end_battle(self, player: PlayerLogic): self.assert_running() self.set_dirty() battle = self.get_player_battle(player) if battle is None or battle.defendingPlayer != player.model: raise UserError("Нельзя завершить раунд, если Вы не защищаетесь!") self.complete_battle(BattleLogic(self.db, battle))
def get_game(self, game_key: str, optional=False) -> GameLogic: game = Game.query.filter_by(uniqueCode=game_key).first() if game is None and not optional: raise UserError( "К сожалению, такая игра не найдена. Проверьте уникальный код.", UserError.ErrorType.INVALID_GAME) if game is None: return None return GameLogic(self.db, game)
def play_card(self, card: CardLogic, player: PlayerLogic): if not self.can_play_card(card, player): raise UserError("Сейчас нельзя сыграть эту карту") self.set_dirty() battle = self.get_player_battle(player) if battle.offendingPlayer == player.model: battle.offensiveCard = card.model else: BattleLogic(self.db, battle).add_defensive_card(card) player.drop_card(card)
def delete_player(self, player: PlayerLogic): try: if player is not None: self.db.session.delete(player.model) self.db.session.commit() except IntegrityError as e: print("Player deletion problem: " + str(e)) self.db.session.rollback() raise UserError("Не удалось удалить игрока из игры. По идее, вы не должны видеть эту ошибку", UserError.ErrorType.INVALID_DELITION)
def delete_game(self, game: GameLogic): try: self.db.session.delete(game.model) self.db.session.commit() except IntegrityError as e: print("Game deletion problem: " + str(e)) self.db.session.rollback() # TODO: Fix "NOT NULL constraint failed: deckentry.gameId": Cascade delete? raise UserError( "Не удалось удалить игру. По идее, вы не должны видеть эту ошибку", UserError.ErrorType.INVALID_GAME_DELETION)
def start_game(): gm = get_game_manager() pm = get_player_manager() game = g.game if not game.is_waitroom(): raise UserError("Игра не может быть начата без комнаты ожидания!") if not game.can_start(pm.get_my_player()): raise HackAttemptError( "Попытка начать игру игроком, который не может этого делать!") game.start() return True
def create_player(self, name: str, game: 'GameLogic') -> PlayerLogic: player = Player(name=name, game=game.model, money=0, isAdmin=False, isOnline=False) self.db.session.add(player) try: self.db.session.commit() except IntegrityError as e: print("Player creation problem: " + str(e)) self.db.session.rollback() raise UserError("Игрок с таким именем уже существует. Пожалуйста, измените имя.", UserError.ErrorType.INVALID_NAME) return PlayerLogic(self.db, player)
def subscribe(): if g.game is not None and g.game.model is not None: join_room(g.game.model.uniqueCode) else: raise UserError("Ошибка подписки на события - нет игры")
def assert_has_game(): if g.game is None: raise UserError("Игра не найдена")
def assert_running(self): if self.get_state() != GameLogic.State.RUNNING: raise UserError( "Невозможно выполнить действие, если игра не запущена")