class GamePool: _awaiting: Game | None = None def __init__(self, player: Player): self._player: Player = player self._game: Game | None = None async def __aenter__(self) -> Game: if GamePool._awaiting: self._game, GamePool._awaiting = GamePool._awaiting, None self._game.add_player(self._player) self._game.toss() else: self._game = Game() self._game.add_player(self._player) GamePool._awaiting = self._game return self._game async def __aexit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> None: if GamePool._awaiting is self._game: GamePool._awaiting = None if self._game is not None: if self._game.status == GameStatus.in_progress: self._game.status = GameStatus.unfinished await publish_game_state(self._game) for player in self._game.players: await player.ws.close()
def test_toss(self): game = Game() ws = web.WebSocketResponse() game.add_player(Player(id=str(uuid.uuid4()), ws=ws)) game.add_player(Player(id=str(uuid.uuid4()), ws=ws)) game.toss() for player in game.players: self.assertNotEqual(player.box_type, BoxType.empty) self.assertIn(game.whose_turn, game.players) self.assertEqual(game.status, GameStatus.in_progress)
def test_turn(self): game = Game() ws = web.WebSocketResponse() game.add_player(Player(id=str(uuid.uuid4()), ws=ws)) game.add_player(Player(id=str(uuid.uuid4()), ws=ws)) game.toss() player = [p for p in game.players if p.id != game.whose_turn.id][0] with self.assertRaises(NotYourTurnError): game.turn(player, 0) player = game.whose_turn game.turn(player, 0) self.assertTrue(game.whose_turn.id != player.id) self.assertEqual(game.grid[0], player.box_type)