fix multiple clients bug (#16)

* switch to relative imports for DIY files

* fix player instance always belonging to last joined client
This commit is contained in:
Denis authored and GitHub committed 2025-10-20 20:13:17 +02:00
1 parent 2b1bb586c9
commit fb74527e82
1 file changed
+17 -9
+17 -9
View File
@@ -9,7 +9,7 @@ T_PlayerStateDict = dict[str, T_PlayerDict | bool]
T_SpectatorStateDict = dict[str, T_PlayerDict] T_SpectatorStateDict = dict[str, T_PlayerDict]
MAX_PLAYERS = 2 MAX_PLAYERS = 2
PLAYERS: set[Player] = set() PLAYERS: list[Player] = []
def num_players() -> int: def num_players() -> int:
@@ -62,11 +62,6 @@ async def broadcast(message):
async def handler(websocket: ServerConnection): async def handler(websocket: ServerConnection):
# client_id = next(CLIENT_IDS)
# CLIENTS.add(Client(websocket))
player: Player | None = None
try: try:
async for msg in websocket: async for msg in websocket:
raw_action = json.loads(msg) raw_action = json.loads(msg)
@@ -75,7 +70,7 @@ async def handler(websocket: ServerConnection):
if raw_action["action"] == "join": if raw_action["action"] == "join":
name = raw_action["name"] name = raw_action["name"]
player = Player(websocket, name, is_spectator()) player = Player(websocket, name, is_spectator())
PLAYERS.add(player) PLAYERS.append(player)
await player.send_message({"player": player.as_dict()}) await player.send_message({"player": player.as_dict()})
@@ -97,8 +92,21 @@ async def handler(websocket: ServerConnection):
await player.send_message({"player": player.as_dict()}) await player.send_message({"player": player.as_dict()})
else: else:
if player is None: query = list(
raise Exception("Player has not joined.") filter(
lambda player: player.websocket is not None
and player.websocket.id == websocket.id,
PLAYERS,
)
)
if len(query) == 0:
raise Exception("Player did not join yet.")
player = query[0]
if player.is_disconnected:
raise Exception("Player is not connected.")
if raw_action["action"] == "toggleRole": if raw_action["action"] == "toggleRole":
if player.is_spectator: if player.is_spectator: