diff options
-rw-r--r-- | swiftstory/client.py | 14 | ||||
-rw-r--r-- | swiftstory/game.py | 6 | ||||
-rw-r--r-- | swiftstory/player.py | 14 |
3 files changed, 18 insertions, 16 deletions
diff --git a/swiftstory/client.py b/swiftstory/client.py index 527c9c6..c3a2aff 100644 --- a/swiftstory/client.py +++ b/swiftstory/client.py @@ -66,12 +66,16 @@ class Client: raise WrongAction('You have to join a game first') return self.game.try_view_black_card(self.player) - def register_notification(self, message): + def monitor_player(self) -> None: + """ Start monitoring the player for notifications and send them. """ async def f(): - try: - await self.socket.send(message) - except websockets.exceptions.ConnectionClosed: - logging.warning("Recipient has disconnected.") + assert self.player is not None + while True: + try: + notif = await self.player.notifications.get() + await self.socket.send(notif) + except websockets.exceptions.ConnectionClosed: + logging.warning("Recipient has disconnected.") asyncio.create_task(f()) diff --git a/swiftstory/game.py b/swiftstory/game.py index f48633b..8ed56fc 100644 --- a/swiftstory/game.py +++ b/swiftstory/game.py @@ -41,7 +41,7 @@ class Game: except IndexError: raise JoinError('not enough white cards for player') - player = Player(client) + player = Player() for card in cards: player.receive_card(card) @@ -49,6 +49,8 @@ class Game: client.player = player client.game = self + client.monitor_player() + self.players.append(player) for p in self.players: @@ -195,8 +197,6 @@ class Game: raise WrongAction('The black card has not been revealed yet') def disconnect(self, player): - player.client = None - if self.judge is player: self.judge = None diff --git a/swiftstory/player.py b/swiftstory/player.py index 7193b64..011ae51 100644 --- a/swiftstory/player.py +++ b/swiftstory/player.py @@ -1,18 +1,19 @@ +import asyncio import json +from typing import Any class Player: - def __init__(self, client): + def __init__(self): self.cards = {} self.next_idx = 0 - self.client = client - self.score = 0 self.has_played = False self.name = 'default' + self.notifications: asyncio.Queue = asyncio.Queue() def pop_card(self, card_id): return self.cards.pop(card_id) @@ -29,10 +30,7 @@ class Player: self.next_idx += 1 return self.next_idx - 1 - def register_notification(self, obj): - if self.client is None: - return - + def register_notification(self, obj: Any): message = json.dumps({'type': 'notification', 'content': obj}) - self.client.register_notification(message) + self.notifications.put_nowait(message) |