diff --git a/src/backend/autobeerpong/lobby.py b/src/backend/autobeerpong/lobby.py index 2c7338c..eaf6d36 100644 --- a/src/backend/autobeerpong/lobby.py +++ b/src/backend/autobeerpong/lobby.py @@ -2,32 +2,56 @@ from typing import Any, Callable from websockets.asyncio.server import ServerConnection from autobeerpong.client import Client, ClientRole -from autobeerpong.action import JoinAction +from autobeerpong.action import JoinAction, RejoinAction + + +MAX_PLAYERS_IN_LOBBY = 2 class AutobeerpongLobby: - MAX_PLAYERS = 2 + MAX_PLAYERS = MAX_PLAYERS_IN_LOBBY def __init__(self): self.clients: dict[int, Client] = {} async def broadcast(self) -> None: - for client in self.clients.values(): + for client in filter( + lambda c: c.role is not ClientRole.DISCONNECTED, self.clients.values() + ): await client.send(self.as_dict()) async def process_join( - self, websocket: ServerConnection, action: JoinAction + self, client_id: int, websocket: ServerConnection, action: JoinAction ) -> None: - client = Client(websocket.id.int, websocket, action.name) + client = Client(client_id=client_id, websocket=websocket, name=action.name) + + if self.is_players_full(): + client.role = ClientRole.SPECTATOR + self.add_client(client) await client.send({"player": client.as_dict()}) + async def process_rejoin( + self, websocket: ServerConnection, action: RejoinAction + ) -> None: + client = self.clients.get(action.client_id) + + if client is None: + print(f"No client found for id {action.client_id}") + return + + if self.is_players_full(): + client.role = ClientRole.SPECTATOR + else: + client.role = ClientRole.PLAYER + + client.websocket = websocket + + await client.send({"player": client.as_dict()}) + async def process_toggle_role(self, client: Client) -> None: - if ( - client.role is ClientRole.SPECTATOR - and self.get_num_players() < self.MAX_PLAYERS - ): + if client.role is ClientRole.SPECTATOR and not self.is_players_full(): client.role = ClientRole.PLAYER elif client.role is ClientRole.PLAYER: client.role = ClientRole.SPECTATOR @@ -36,27 +60,18 @@ class AutobeerpongLobby: if client.role is ClientRole.PLAYER: client.ready = not client.ready - async def process( - self, websocket: ServerConnection, action_dict: dict[str, Any] - ) -> None: + async def process(self, client_id: int, action_dict: dict[str, Any]) -> None: action_name = action_dict["action"] - if action_name == "join": - await self.process_join(websocket, JoinAction(name=action_dict["name"])) - elif action_name == "rejoin": - pass - else: - client = self.clients.get(websocket.id.int) + client = self.clients.get(client_id) - if client is None: - raise Exception("Client has not joined.") + if client is None: + raise Exception("Client has not joined.") - if action_name == "toggleRole": - await self.process_toggle_role(client) - elif action_name == "toggleReady": - await self.process_toggle_ready(client) - - await self.broadcast() + if action_name == "toggleRole": + await self.process_toggle_role(client) + elif action_name == "toggleReady": + await self.process_toggle_ready(client) def add_client(self, client: Client): self.clients[client.id] = client @@ -73,6 +88,9 @@ class AutobeerpongLobby: def get_spectators(self) -> list[Client]: return self.filter_clients(lambda x: x.role is ClientRole.SPECTATOR) + def is_players_full(self) -> bool: + return self.get_num_players() >= self.MAX_PLAYERS + def as_dict(self) -> dict[str, Any]: players = self.get_players() spectators = self.get_spectators() diff --git a/src/backend/autobeerpong/player.py b/src/backend/autobeerpong/player.py deleted file mode 100644 index fbaca7c..0000000 --- a/src/backend/autobeerpong/player.py +++ /dev/null @@ -1,58 +0,0 @@ -from __future__ import annotations - -import json - -from typing import Any -from websockets.asyncio.server import ServerConnection - - -T_PlayerDict = dict[str, str | int] - - -class Player: - def __init__( - self, - websocket: ServerConnection | None, - player_id: int, - name: str, - is_spectator: bool, - is_ready: bool = False, - ) -> None: - self.id = player_id - self.name = name - self.websocket: ServerConnection | None = websocket - self.is_spectator = is_spectator - self.is_ready = is_ready - self.is_disconnected = False - - def disconnect(self) -> None: - self.is_disconnected = True - self.is_spectator = True - self.is_ready = False - self.websocket = None - - def reconnect(self, websocket: ServerConnection) -> None: - self.is_disconnected = False - self.websocket = websocket - - async def send_message(self, message) -> None: - if not self.is_disconnected and self.websocket is not None: - await self.websocket.send(json.dumps(message)) - - def as_dict(self) -> T_PlayerDict: - return {"id": self.id, "name": self.name} - - @classmethod - def from_dict( - cls, player_dict: dict[str, Any], is_ready: bool, is_spectator: bool - ) -> Player: - player_id: int = player_dict["id"] - name: str = player_dict["name"] - - return Player( - websocket=None, - player_id=player_id, - name=name, - is_spectator=is_spectator, - is_ready=is_ready, - ) diff --git a/src/backend/autobeerpong/server.py b/src/backend/autobeerpong/server.py index 55ef8e8..2dc6640 100644 --- a/src/backend/autobeerpong/server.py +++ b/src/backend/autobeerpong/server.py @@ -1,8 +1,10 @@ +import websockets +from autobeerpong.action import JoinAction, RejoinAction import json import asyncio from enum import Enum, auto - +from itertools import count from websockets.asyncio.server import serve, ServerConnection from autobeerpong.lobby import AutobeerpongLobby @@ -15,16 +17,40 @@ class ServerState(Enum): class AutobeerpongServer: def __init__(self) -> None: + self.client_ids = count() self.server_state = ServerState.LOBBY self.lobby = AutobeerpongLobby() async def handler(self, websocket: ServerConnection): + client_id = None + try: async for msg in websocket: action_dict = json.loads(msg) if self.server_state is ServerState.LOBBY: - await self.lobby.process(websocket, action_dict) + action_name = action_dict["action"] + + if action_name == "join": + client_id = next(self.client_ids) + await self.lobby.process_join( + client_id=client_id, + websocket=websocket, + action=JoinAction(action_dict["name"]), + ) + + elif action_name == "rejoin": + client_id = action_dict["client_id"] + await self.lobby.process_rejoin( + websocket=websocket, action=RejoinAction(client_id) + ) + + else: + if client_id is not None: + await self.lobby.process(client_id, action_dict) + + await self.lobby.broadcast() + elif self.server_state is ServerState.MATCH: pass @@ -32,13 +58,24 @@ class AutobeerpongServer: print(str(exception)) await websocket.close(1011) else: - client = self.lobby.clients.get(websocket.id.int) + if client_id is not None: + client = self.lobby.clients.get(client_id) if client is not None: client.disconnect() await websocket.close(1000) + if self.server_state is ServerState.LOBBY: + # Hacky solution to keep test cases from failing gracefully + # at the end of the tests, when all clients disconnect. + try: + await self.lobby.broadcast() + except websockets.exceptions.ConnectionClosedOK: + pass + except Exception as exception: + raise (exception) + async def _start(self) -> None: async with serve(self.handler, "localhost", 8888) as server: await server.serve_forever() diff --git a/src/backend/tests/test_lobby.py b/src/backend/tests/test_lobby.py index e6c6117..0ad99b3 100644 --- a/src/backend/tests/test_lobby.py +++ b/src/backend/tests/test_lobby.py @@ -5,7 +5,14 @@ from typing import Any from unittest import IsolatedAsyncioTestCase from websockets.asyncio.client import connect -from autobeerpong.action import Action, JoinAction, ToggleReadyAction, ToggleRoleAction +from autobeerpong.action import ( + Action, + JoinAction, + RejoinAction, + ToggleReadyAction, + ToggleRoleAction, +) +from autobeerpong.lobby import MAX_PLAYERS_IN_LOBBY from tests.utils.server import manage_server, SERVER_ADDRESS, SERVER_PORT @@ -57,7 +64,12 @@ class TestClient: async def get_response(self) -> dict[str, Any]: await self.queue_send.put(GetResponseFromServer()) - response_raw = await self.queue_recv.get() + + response_raw = await asyncio.wait_for( + self.queue_recv.get(), + timeout=SERVER_RESPONSE_TIMEOUT, + ) + self.queue_recv.task_done() return response_raw @@ -157,3 +169,130 @@ class TestLobby(IsolatedAsyncioTestCase): client_a.shutdown() client_b.shutdown() + + @manage_server + async def test_toggle_role(self): + client_a = TestClient() + client_b = TestClient() + + client_a_responses = await client_a.send_actions([JoinAction("Ruedi")]) + client_b_responses = await client_b.send_actions([JoinAction("Hansi")]) + client_a_responses.append(await client_a.get_response()) + client_a_responses.extend(await client_a.send_actions([ToggleRoleAction()])) + client_b_responses.append(await client_b.get_response()) + client_b_responses.extend(await client_b.send_actions([ToggleRoleAction()])) + client_a_responses.append(await client_a.get_response()) + + response = client_a_responses[2] + + self.assertEqual(response, client_b_responses[1]) + self.assertEqual(len(response["gamestate"]["players"]), 2) + + response = client_a_responses[3] + + self.assertEqual(response, client_b_responses[2]) + self.assertEqual(len(response["gamestate"]["players"]), 1) + self.assertEqual(len(response["gamestate"]["spectators"]), 1) + self.assertEqual( + response["gamestate"]["spectators"][0]["player"]["name"], "Ruedi" + ) + + response = client_a_responses[4] + + self.assertEqual(response, client_b_responses[3]) + self.assertEqual(len(response["gamestate"]["players"]), 0) + self.assertEqual(len(response["gamestate"]["spectators"]), 2) + + client_a.shutdown() + client_b.shutdown() + + @manage_server + async def test_toggle_role_max_players(self): + client_a = TestClient() + client_b = TestClient() + client_c = TestClient() + + client_a_responses = await client_a.send_actions([JoinAction("Ruedi")]) + client_b_responses = await client_b.send_actions([JoinAction("Hansi")]) + client_a_responses.append(await client_a.get_response()) + client_c_responses = await client_c.send_actions([JoinAction("Fredi")]) + client_a_responses.append(await client_a.get_response()) + client_b_responses.append(await client_b.get_response()) + + response = client_a_responses[3] + + self.assertEqual(response, client_b_responses[2]) + self.assertEqual(response, client_c_responses[1]) + self.assertLessEqual( + len(response["gamestate"]["players"]), MAX_PLAYERS_IN_LOBBY + ) + self.assertEqual( + response["gamestate"]["spectators"][0]["player"]["name"], "Fredi" + ) + + client_c_responses.extend(await client_c.send_actions([ToggleRoleAction()])) + client_a_responses.append(await client_a.get_response()) + client_b_responses.append(await client_b.get_response()) + + response = client_a_responses[-1] + self.assertEqual(response, client_b_responses[-1]) + self.assertEqual(response, client_c_responses[-1]) + + self.assertLessEqual( + len(response["gamestate"]["players"]), MAX_PLAYERS_IN_LOBBY + ) + self.assertEqual( + response["gamestate"]["spectators"][0]["player"]["name"], "Fredi" + ) + + client_a.shutdown() + client_b.shutdown() + client_c.shutdown() + + @manage_server + async def test_rejoin(self): + client_a = TestClient() + client_b = TestClient() + + client_a_responses = await client_a.send_actions([JoinAction("Ruedi")]) + client_b_responses = await client_b.send_actions([JoinAction("Hansi")]) + client_a_responses.append(await client_a.get_response()) + + client_b_id = client_b_responses[0]["player"]["id"] + + client_b.shutdown() + + client_a_responses.append(await client_a.get_response()) + + client_b = TestClient() + client_b_responses = await client_b.send_actions( + [RejoinAction(client_id=client_b_id)] + ) + client_a_responses.append(await client_a.get_response()) + + client_b_responses.extend(await client_b.send_actions([ToggleReadyAction()])) + client_a_responses.append(await client_a.get_response()) + + self.assertEqual(client_a_responses[-1], client_b_responses[-1]) + + self.assertEqual( + client_a_responses[-1]["gamestate"]["players"][0]["ready"], False + ) + self.assertEqual( + client_a_responses[-1]["gamestate"]["players"][1]["ready"], True + ) + + client_a_responses.extend(await client_a.send_actions([ToggleReadyAction()])) + client_b_responses.append(await client_b.get_response()) + + self.assertEqual(client_a_responses[-1], client_b_responses[-1]) + + self.assertEqual( + client_a_responses[-1]["gamestate"]["players"][0]["ready"], True + ) + self.assertEqual( + client_a_responses[-1]["gamestate"]["players"][1]["ready"], True + ) + + client_a.shutdown() + client_b.shutdown()