refactor(lobby): sendall

parent c7c10c0b
import asyncio
import json
import sys
from sys import stderr
from typing import List, Dict, Optional
......@@ -47,6 +46,7 @@ class LobbyManager(ClientManager):
self.metadata[player.name] = Metadata(sid=sid)
print(f"Added {player} to a lobby with {len(self.lobby)} players.")
await self.send(to=player, message=MessageToPlayer.Welcome, extras={"name": player.name})
await self.sendall(MessageToPlayer.NewPlayer, but=player)
async def player_left(self, sid: str) -> None:
""" Reports the disconnection of a player, both internally and to other players."""
......@@ -57,9 +57,9 @@ class LobbyManager(ClientManager):
player = self.lobby.pop(name)
self.players.remove(player)
for p in self.players:
await self.send(p, MessageToPlayer.Disconnected, extras={"justLeft": name})
self.metadata.pop(name)
await self.sendall(MessageToPlayer.Disconnected, extras={"justLeft": name})
return
print(f"No player for sid {sid}...", file=stderr)
......@@ -70,6 +70,8 @@ class LobbyManager(ClientManager):
self.metadata[player.name].ready = True
print(f"Lobby | {player} wants to play!")
self.sendall(MessageToPlayer.PlayerReady, extras={"wantsToPlay": player.name}, but=player)
ready = self.players_ready
return ready
......@@ -104,6 +106,7 @@ class LobbyManager(ClientManager):
games = len(self.games)
msg = f"Resetting! sorry for the {players} players / {games} games..."
print(msg)
for p in self.players:
m = self.metadata[p.name]
await self.send(p, MessageToPlayer.Reset)
......@@ -114,6 +117,17 @@ class LobbyManager(ClientManager):
self.games.clear()
return msg
async def sendall(self, message: MessageToPlayer, extras=None,
to: List[Player] = None,
but: Optional[Player] = None):
if to is None:
to = self.players
for p in to:
if but and p.name == but.name:
continue
self.send(p, message, extras)
async def send(self, to: Player, message: MessageToPlayer, extras=None) -> None:
sid: str = "?"
......@@ -121,7 +135,7 @@ class LobbyManager(ClientManager):
sid = self.metadata[to.name].sid
except KeyError as e:
print(f"Error: Cannot send message to player {to.name}", file=stderr)
return # TODO: Warn other players and kill game
return # TODO: Warn other players and kill game
game: Game = self.game_with(to)
......@@ -227,5 +241,4 @@ class LobbyManager(ClientManager):
await self.send(player, MessageToPlayer.YourTurn, extras)
extras["waitingFor"] = player.name
for p in [p for p in game.players if p != player]:
await self.send(p, MessageToPlayer.Waiting, extras)
await self.sendall(MessageToPlayer.Waiting, extras, but=player)
......@@ -8,6 +8,8 @@ class MessageToPlayer(Enum):
NewGame = "NEW_GAME"
GiveHand = "GIVE_HAND"
WaitTurn = "WAITING_TURN"
NewPlayer = "NEW_PLAYER"
PlayerReady = "PLAYER_READY"
YourTurn = "YOUR_TURN"
WrongAnnounce = "WRONG_ANNOUNCE"
Announce = "ANNOUNCE"
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment