From 72e6cb10ede7b9d20763b580a771b20b6882dab9 Mon Sep 17 00:00:00 2001 From: Denis <68426415+zoopsel@users.noreply.github.com> Date: Mon, 4 May 2026 20:00:44 +0200 Subject: [PATCH] Backend - Add match logic (#38) * add method to update server state * add draft test match unit test class * add join response message class * add lobby state message class * add spectator raw type * add start match json schema * add start match message class * add test client manager class * change client to return server responses as python classes * add start match test method * adapt old unit tests to use python message classes * shortcut two players join and ready protocol * fix wrong imports * add message to assertion * make broadcast function send message provided as argument * add match state message class * add match state json schema * add match utility class * add match state message class * extend test function with match state check * remove print statement * add missing match schemas to frontend and add id properties * make state keys unique * fix MockSocket * add basic match history funtionality * use Prettier formatter * fix typehint error --- src/backend/autobeerpong/match.py | 77 +++++++++++ .../autobeerpong/messages/lobby/join.py | 18 +-- .../messages/lobby/join_response.py | 17 +++ .../autobeerpong/messages/lobby/state.py | 21 +++ .../autobeerpong/messages/match/__init__.py | 0 .../messages/match/match_state.py | 17 +++ .../messages/match/start_match.py | 16 +++ src/backend/autobeerpong/server.py | 86 +++++++++---- src/backend/autobeerpong/types/raw.py | 1 + src/backend/tests/test_lobby.py | 121 +++++++++--------- src/backend/tests/test_match.py | 59 +++++++++ src/backend/tests/utils/client.py | 31 +++-- src/backend/tests/utils/manager.py | 42 ++++++ src/frontend/src/Scenes/MatchScene.ts | 2 +- src/frontend/src/schemaValidators.ts | 14 +- src/schema/archive/match_state_schema.json | 29 ----- .../action_schema.json => match/action.json} | 3 +- src/schema/match/start_match.json | 15 +++ src/schema/match/state.json | 31 +++++ .../table_schema.json => match/table.json} | 3 +- src/schema/message.json | 6 + 21 files changed, 474 insertions(+), 135 deletions(-) create mode 100644 src/backend/autobeerpong/match.py create mode 100644 src/backend/autobeerpong/messages/lobby/join_response.py create mode 100644 src/backend/autobeerpong/messages/lobby/state.py create mode 100644 src/backend/autobeerpong/messages/match/__init__.py create mode 100644 src/backend/autobeerpong/messages/match/match_state.py create mode 100644 src/backend/autobeerpong/messages/match/start_match.py create mode 100644 src/backend/tests/test_match.py create mode 100644 src/backend/tests/utils/manager.py delete mode 100644 src/schema/archive/match_state_schema.json rename src/schema/{archive/action_schema.json => match/action.json} (95%) create mode 100644 src/schema/match/start_match.json create mode 100644 src/schema/match/state.json rename src/schema/{archive/table_schema.json => match/table.json} (94%) diff --git a/src/backend/autobeerpong/match.py b/src/backend/autobeerpong/match.py new file mode 100644 index 0000000..3543911 --- /dev/null +++ b/src/backend/autobeerpong/match.py @@ -0,0 +1,77 @@ +from autobeerpong.types.raw import MessageRaw_T + + +class Team: + def __init__(self) -> None: + self.formation = [1, 2, 3] + self.cups = [True, True, True] + + def rotate(self) -> None: + self.formation.insert(0, self.formation.pop()) + + def hit_cup(self) -> None: + for _ in range(len(self.cups)): + pass + + +class Match: + def __init__(self) -> None: + self.turn = True + self.team_a = Team() + self.team_b = Team() + self.history: list[MessageRaw_T] = [] + + def get_table_state(self) -> MessageRaw_T: + return { + "cupsA": self.team_a.cups.copy(), + "cupsB": self.team_b.cups.copy(), + "teamA": self.team_a.formation.copy(), + "teamB": self.team_b.formation.copy(), + } + + def get_action(self) -> MessageRaw_T: + turn = "a" if self.turn else "b" + x_pos = -150 if self.turn else 150 + x_vel = 250 if self.turn else -250 + + # determine if hit + # is_hit = True if random.random() >= 0.5 else False + + return { + "turn": turn, + "parabola": { + "startPosition": [x_pos, -200], + "startVelocity": [x_vel, -300], + "stopTime": 900, + }, + } + + def match_not_over(self) -> bool: + return any(self.team_a.cups) and any(self.team_b.cups) + + def resolve(self) -> None: + # first send table state + self.history.append(self.get_table_state()) + + while self.match_not_over(): + # action + active_team = self.team_a if self.turn else self.team_b + other_team = self.team_a if not self.turn else self.team_b + + self.history.append(self.get_action()) + + for i in range(len(other_team.cups)): + if other_team.cups[i]: + other_team.cups[i] = False + break + + active_team.rotate() + # table state + self.history.append(self.get_table_state()) + self.turn = not self.turn + + def to_raw(self) -> MessageRaw_T: + return { + "messageType": "matchState", + "messageContent": {"history": self.history}, + } diff --git a/src/backend/autobeerpong/messages/lobby/join.py b/src/backend/autobeerpong/messages/lobby/join.py index 4a69da1..3b8cc42 100644 --- a/src/backend/autobeerpong/messages/lobby/join.py +++ b/src/backend/autobeerpong/messages/lobby/join.py @@ -1,4 +1,6 @@ -from autobeerpong.messages.message import Message, MessageRaw_T +from autobeerpong.messages.message import Message +from autobeerpong.messages.lobby.join_response import JoinResponseMessage +from autobeerpong.types.raw import MessageRaw_T from autobeerpong.client import Client from autobeerpong.contexts.server import ServerContext from autobeerpong.contexts.client import ClientContext @@ -42,11 +44,11 @@ class JoinMessage(Message): client_context.has_joined = True client_context.client_id = client_id - join_message_raw: MessageRaw_T = { - "messageType": "joinResponse", - "messageContent": {"client": client.as_raw()}, - } + join_message = JoinResponseMessage( + { + "messageType": "joinResponse", + "messageContent": {"client": client.as_raw()}, + } + ) - Message.validate(join_message_raw) - - await client.send(join_message_raw) + await client.send(join_message.to_raw()) diff --git a/src/backend/autobeerpong/messages/lobby/join_response.py b/src/backend/autobeerpong/messages/lobby/join_response.py new file mode 100644 index 0000000..7ae12d5 --- /dev/null +++ b/src/backend/autobeerpong/messages/lobby/join_response.py @@ -0,0 +1,17 @@ +from autobeerpong.messages.message import Message +from autobeerpong.types.raw import MessageRaw_T, ClientRaw_T + + +class JoinResponseMessage(Message): + has_direct_response = False + + def _contents_from_raw(self, message_raw: MessageRaw_T): + self.client_raw: ClientRaw_T = message_raw["messageContent"]["client"] + + def to_raw(self) -> MessageRaw_T: + msg_raw = super().to_raw() + msg_raw["messageContent"].update({"client": self.client_raw}) + + self.validate(msg_raw) + + return msg_raw diff --git a/src/backend/autobeerpong/messages/lobby/state.py b/src/backend/autobeerpong/messages/lobby/state.py new file mode 100644 index 0000000..82506dd --- /dev/null +++ b/src/backend/autobeerpong/messages/lobby/state.py @@ -0,0 +1,21 @@ +from autobeerpong.messages.message import Message +from autobeerpong.types.raw import MessageRaw_T, PlayerRaw_T, SpectatorRaw_T + + +class LobbyStateMessage(Message): + has_direct_response = False + + def _contents_from_raw(self, message_raw: MessageRaw_T): + self.players: list[PlayerRaw_T] = message_raw["messageContent"]["players"] + self.spectators: list[SpectatorRaw_T] = message_raw["messageContent"][ + "spectators" + ] + + def to_raw(self) -> MessageRaw_T: + msg_raw = super().to_raw() + msg_raw["messageContent"].update({"players": self.players}) + msg_raw["messageContent"].update({"spectators": self.spectators}) + + self.validate(msg_raw) + + return msg_raw diff --git a/src/backend/autobeerpong/messages/match/__init__.py b/src/backend/autobeerpong/messages/match/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/backend/autobeerpong/messages/match/match_state.py b/src/backend/autobeerpong/messages/match/match_state.py new file mode 100644 index 0000000..379773b --- /dev/null +++ b/src/backend/autobeerpong/messages/match/match_state.py @@ -0,0 +1,17 @@ +from autobeerpong.messages.message import Message +from autobeerpong.types.raw import MessageRaw_T + + +class MatchStateMessage(Message): + has_direct_response = False + + def _contents_from_raw(self, message_raw: MessageRaw_T) -> None: + self.history = message_raw["messageContent"]["history"] + + def to_raw(self) -> MessageRaw_T: + msg_raw = super().to_raw() + msg_raw["messageContent"].update({"history": self.history}) + + self.validate(msg_raw) + + return msg_raw diff --git a/src/backend/autobeerpong/messages/match/start_match.py b/src/backend/autobeerpong/messages/match/start_match.py new file mode 100644 index 0000000..2f1840f --- /dev/null +++ b/src/backend/autobeerpong/messages/match/start_match.py @@ -0,0 +1,16 @@ +from autobeerpong.messages.message import Message +from autobeerpong.types.raw import MessageRaw_T + + +class StartMatchMessage(Message): + has_direct_response = False + + def _contents_from_raw(self, message_raw: MessageRaw_T) -> None: + pass + + def to_raw(self) -> MessageRaw_T: + msg_raw = super().to_raw() + + self.validate(msg_raw) + + return msg_raw diff --git a/src/backend/autobeerpong/server.py b/src/backend/autobeerpong/server.py index 607c79c..a98a225 100644 --- a/src/backend/autobeerpong/server.py +++ b/src/backend/autobeerpong/server.py @@ -7,26 +7,76 @@ from websockets.exceptions import ConnectionClosedOK import autobeerpong.config as config from autobeerpong.messages.message import Message, MessageRaw_T from autobeerpong.messages.lobby.join import JoinMessage +from autobeerpong.messages.lobby.join_response import JoinResponseMessage from autobeerpong.messages.lobby.rejoin import RejoinMessage from autobeerpong.messages.lobby.toggle_ready import ToggleReadyMessage from autobeerpong.messages.lobby.toggle_role import ToggleRoleMessage +from autobeerpong.messages.lobby.state import LobbyStateMessage +from autobeerpong.messages.match.start_match import StartMatchMessage +from autobeerpong.messages.match.match_state import MatchStateMessage from autobeerpong.contexts.server import ServerContext from autobeerpong.contexts.client import ClientContext from autobeerpong.states.client import ClientState +from autobeerpong.states.server import ServerState +from autobeerpong.match import Match class AutobeerpongServer: message_map: dict[str, type[Message]] = { + # LOBBY "join": JoinMessage, + "joinResponse": JoinResponseMessage, "rejoin": RejoinMessage, "toggleReady": ToggleReadyMessage, "toggleRole": ToggleRoleMessage, + "lobbyState": LobbyStateMessage, + # MATCH + "startMatch": StartMatchMessage, + "matchState": MatchStateMessage, } def __init__(self) -> None: self.context = ServerContext() - async def broadcast(self): + async def broadcast(self, msg_raw: MessageRaw_T) -> None: + connected_clients = list( + filter( + lambda x: x.state is not ClientState.DISCONNECTED, + self.context.clients.values(), + ) + ) + + for client in connected_clients: + await client.send(msg_raw) + + async def update_server_state(self) -> None: + if self.context.state is ServerState.LOBBY: + players = list( + filter( + lambda x: x.state is ClientState.PLAYER, + self.context.clients.values(), + ) + ) + + if all([player.ready for player in players]): + # all players are ready, advance server state to match + self.context.state = ServerState.MATCH + # send match start message to all connected clients + start_match = StartMatchMessage( + {"messageType": "startMatch", "messageContent": {}} + ) + + await self.broadcast(start_match.to_raw()) + + match = Match() + match.resolve() + + await self.broadcast(match.to_raw()) + + elif self.context.state is ServerState.MATCH: + pass + + def get_lobby_state(self) -> LobbyStateMessage: players = list( filter( lambda x: x.state is ClientState.PLAYER, @@ -40,33 +90,22 @@ class AutobeerpongServer: ) ) - lobby_state_raw: MessageRaw_T = { - "messageType": "lobbyState", - "messageContent": { - "players": [player.as_raw_player() for player in players], - "spectators": [spectator.as_raw() for spectator in spectators], - }, - } - - # for validation - Message.validate(lobby_state_raw) - - connected_clients = list( - filter( - lambda x: x.state is not ClientState.DISCONNECTED, - self.context.clients.values(), - ) + return LobbyStateMessage( + { + "messageType": "lobbyState", + "messageContent": { + "players": [player.as_raw_player() for player in players], + "spectators": [spectator.as_raw() for spectator in spectators], + }, + } ) - for client in connected_clients: - await client.send(lobby_state_raw) - async def handler(self, websocket: ServerConnection) -> None: client_context = ClientContext(websocket) async for msg in websocket: message_raw: MessageRaw_T = json.loads(msg) - message_type: str = message_raw.get("messageType") + message_type = str(message_raw.get("messageType")) if message_type is None: raise Exception("Message has no messageType property.") @@ -83,12 +122,13 @@ class AutobeerpongServer: client_context=client_context, ) - await self.broadcast() + await self.broadcast(self.get_lobby_state().to_raw()) + await self.update_server_state() if client_context.has_joined: self.context.clients[client_context.get_client_id()].disconnect() try: - await self.broadcast() + await self.broadcast(self.get_lobby_state().to_raw()) except ConnectionClosedOK: pass diff --git a/src/backend/autobeerpong/types/raw.py b/src/backend/autobeerpong/types/raw.py index 26b3a70..ca6c851 100644 --- a/src/backend/autobeerpong/types/raw.py +++ b/src/backend/autobeerpong/types/raw.py @@ -4,3 +4,4 @@ _Raw_T = dict[str, Any] MessageRaw_T = _Raw_T ClientRaw_T = _Raw_T PlayerRaw_T = _Raw_T +SpectatorRaw_T = _Raw_T diff --git a/src/backend/tests/test_lobby.py b/src/backend/tests/test_lobby.py index 6763402..9f0dc1d 100644 --- a/src/backend/tests/test_lobby.py +++ b/src/backend/tests/test_lobby.py @@ -1,9 +1,11 @@ from unittest import IsolatedAsyncioTestCase from autobeerpong.messages.lobby.join import JoinMessage +from autobeerpong.messages.lobby.join_response import JoinResponseMessage from autobeerpong.messages.lobby.rejoin import RejoinMessage from autobeerpong.messages.lobby.toggle_ready import ToggleReadyMessage from autobeerpong.messages.lobby.toggle_role import ToggleRoleMessage +from autobeerpong.messages.lobby.state import LobbyStateMessage from autobeerpong.contexts.lobby import MAX_PLAYERS_IN_LOBBY from tests.utils.server import manage_server from tests.utils.client import TestClient @@ -27,26 +29,31 @@ class TestLobby(IsolatedAsyncioTestCase): self.assertEqual(len(client_b_responses), 2) response = client_a_responses[0] - self.assertEqual(response["messageType"], "joinResponse") - self.assertEqual(response["messageContent"]["client"]["name"], "Ruedi") + self.assertEqual(response.type, "joinResponse") + assert type(response) is JoinResponseMessage + self.assertEqual(response.client_raw["name"], "Ruedi") response = client_b_responses[0] - self.assertEqual(response["messageType"], "joinResponse") - self.assertEqual(response["messageContent"]["client"]["name"], "Hansi") + self.assertEqual(response.type, "joinResponse") + assert type(response) is JoinResponseMessage + self.assertEqual(response.client_raw["name"], "Hansi") response = client_a_responses[1] - self.assertEqual(response["messageType"], "lobbyState") - self.assertEqual(len(response["messageContent"]["players"]), 1) + self.assertEqual(response.type, "lobbyState") + assert type(response) is LobbyStateMessage + self.assertEqual(len(response.players), 1) response = client_b_responses[1] - self.assertEqual(response["messageType"], "lobbyState") - self.assertEqual(len(response["messageContent"]["players"]), 2) + self.assertEqual(response.type, "lobbyState") + assert type(response) is LobbyStateMessage + self.assertEqual(len(response.players), 2) response = client_a_responses[2] - self.assertEqual(response["messageType"], "lobbyState") - self.assertEqual(len(response["messageContent"]["players"]), 2) + self.assertEqual(response.type, "lobbyState") + assert type(response) is LobbyStateMessage + self.assertEqual(len(response.players), 2) - player_names = [p["client"]["name"] for p in response["messageContent"]["players"]] + player_names = [p["client"]["name"] for p in response.players] self.assertIn("Ruedi", player_names) self.assertIn("Hansi", player_names) @@ -88,8 +95,9 @@ class TestLobby(IsolatedAsyncioTestCase): client_a_responses.append(await client_a.get_response()) response = client_a_responses[3] - self.assertEqual(response["messageType"], "lobbyState") - players = response["messageContent"]["players"] + self.assertEqual(response.type, "lobbyState") + assert type(response) is LobbyStateMessage + players = response.players for player in players: if player["client"]["name"] == "Ruedi": @@ -97,11 +105,12 @@ class TestLobby(IsolatedAsyncioTestCase): elif player["client"]["name"] == "Hansi": self.assertEqual(player["ready"], False) - self.assertEqual(client_a_responses[3], client_b_responses[2]) + self.assertEqual(client_a_responses[3].to_raw(), client_b_responses[2].to_raw()) response = client_a_responses[4] - self.assertEqual(response["messageType"], "lobbyState") - players = response["messageContent"]["players"] + self.assertEqual(response.type, "lobbyState") + assert type(response) is LobbyStateMessage + players = response.players for player in players: if player["client"]["name"] == "Ruedi": @@ -109,7 +118,7 @@ class TestLobby(IsolatedAsyncioTestCase): elif player["client"]["name"] == "Hansi": self.assertEqual(player["ready"], True) - self.assertEqual(client_a_responses[4], client_b_responses[3]) + self.assertEqual(client_a_responses[4].to_raw(), client_b_responses[3].to_raw()) client_a.shutdown() client_b.shutdown() @@ -154,20 +163,23 @@ class TestLobby(IsolatedAsyncioTestCase): client_a_responses.append(await client_a.get_response()) response = client_a_responses[2] - self.assertEqual(response["messageType"], "lobbyState") - self.assertEqual(response, client_b_responses[1]) - self.assertEqual(len(response["messageContent"]["players"]), 2) + self.assertEqual(response.type, "lobbyState") + assert type(response) is LobbyStateMessage + self.assertEqual(response.to_raw(), client_b_responses[1].to_raw()) + self.assertEqual(len(response.players), 2) response = client_a_responses[3] - self.assertEqual(response, client_b_responses[2]) - self.assertEqual(len(response["messageContent"]["players"]), 1) - self.assertEqual(len(response["messageContent"]["spectators"]), 1) - self.assertEqual(response["messageContent"]["spectators"][0]["name"], "Ruedi") + assert type(response) is LobbyStateMessage + self.assertEqual(response.to_raw(), client_b_responses[2].to_raw()) + self.assertEqual(len(response.players), 1) + self.assertEqual(len(response.spectators), 1) + self.assertEqual(response.spectators[0]["name"], "Ruedi") response = client_a_responses[4] - self.assertEqual(response, client_b_responses[3]) - self.assertEqual(len(response["messageContent"]["players"]), 0) - self.assertEqual(len(response["messageContent"]["spectators"]), 2) + assert type(response) is LobbyStateMessage + self.assertEqual(response.to_raw(), client_b_responses[3].to_raw()) + self.assertEqual(len(response.players), 0) + self.assertEqual(len(response.spectators), 2) client_a.shutdown() client_b.shutdown() @@ -192,13 +204,12 @@ class TestLobby(IsolatedAsyncioTestCase): client_b_responses.append(await client_b.get_response()) response = client_a_responses[3] - self.assertEqual(response["messageType"], "lobbyState") - self.assertEqual(response, client_b_responses[2]) - self.assertEqual(response, client_c_responses[1]) - self.assertLessEqual( - len(response["messageContent"]["players"]), MAX_PLAYERS_IN_LOBBY - ) - self.assertEqual(response["messageContent"]["spectators"][0]["name"], "Fredi") + self.assertEqual(response.type, "lobbyState") + assert type(response) is LobbyStateMessage + self.assertEqual(response.to_raw(), client_b_responses[2].to_raw()) + self.assertEqual(response.to_raw(), client_c_responses[1].to_raw()) + self.assertLessEqual(len(response.players), MAX_PLAYERS_IN_LOBBY) + self.assertEqual(response.spectators[0]["name"], "Fredi") client_c_responses.extend( await client_c.send_messages( @@ -209,14 +220,13 @@ class TestLobby(IsolatedAsyncioTestCase): client_b_responses.append(await client_b.get_response()) response = client_a_responses[-1] - self.assertEqual(response["messageType"], "lobbyState") - self.assertEqual(response, client_b_responses[-1]) - self.assertEqual(response, client_c_responses[-1]) + self.assertEqual(response.type, "lobbyState") + assert type(response) is LobbyStateMessage + self.assertEqual(response.to_raw(), client_b_responses[-1].to_raw()) + self.assertEqual(response.to_raw(), client_c_responses[-1].to_raw()) - self.assertLessEqual( - len(response["messageContent"]["players"]), MAX_PLAYERS_IN_LOBBY - ) - self.assertEqual(response["messageContent"]["spectators"][0]["name"], "Fredi") + self.assertLessEqual(len(response.players), MAX_PLAYERS_IN_LOBBY) + self.assertEqual(response.spectators[0]["name"], "Fredi") client_a.shutdown() client_b.shutdown() @@ -235,7 +245,9 @@ class TestLobby(IsolatedAsyncioTestCase): ) client_a_responses.append(await client_a.get_response()) - client_b_id = client_b_responses[0]["messageContent"]["client"]["id"] + response = client_b_responses[0] + assert type(response) is JoinResponseMessage + client_b_id = response.client_raw["id"] client_b.shutdown() client_a_responses.append(await client_a.get_response()) @@ -261,14 +273,11 @@ class TestLobby(IsolatedAsyncioTestCase): ) 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]["messageContent"]["players"][0]["ready"], False - ) - self.assertEqual( - client_a_responses[-1]["messageContent"]["players"][1]["ready"], True - ) + response = client_a_responses[-1] + assert type(response) is LobbyStateMessage + self.assertEqual(response.to_raw(), client_b_responses[-1].to_raw()) + self.assertEqual(response.players[0]["ready"], False) + self.assertEqual(response.players[1]["ready"], True) client_a_responses.extend( await client_a.send_messages( @@ -281,14 +290,12 @@ class TestLobby(IsolatedAsyncioTestCase): ) client_b_responses.append(await client_b.get_response()) - self.assertEqual(client_a_responses[-1], client_b_responses[-1]) + response = client_a_responses[-1] + assert type(response) is LobbyStateMessage + self.assertEqual(response.to_raw(), client_b_responses[-1].to_raw()) - self.assertEqual( - client_a_responses[-1]["messageContent"]["players"][0]["ready"], True - ) - self.assertEqual( - client_a_responses[-1]["messageContent"]["players"][1]["ready"], True - ) + self.assertEqual(response.players[0]["ready"], True) + self.assertEqual(response.players[1]["ready"], True) client_a.shutdown() client_b.shutdown() diff --git a/src/backend/tests/test_match.py b/src/backend/tests/test_match.py new file mode 100644 index 0000000..d352c68 --- /dev/null +++ b/src/backend/tests/test_match.py @@ -0,0 +1,59 @@ +from unittest import IsolatedAsyncioTestCase + +from autobeerpong.messages.message import Message +from autobeerpong.messages.lobby.join import JoinMessage +from autobeerpong.messages.lobby.toggle_ready import ToggleReadyMessage +from tests.utils.server import manage_server +from tests.utils.client import TestClient +from tests.utils.manager import TestClientManager + + +def get_two_players_join_and_ready( + client_a: TestClient, client_b: TestClient +) -> list[tuple[TestClient, Message]]: + return [ + ( + client_a, + JoinMessage({"messageType": "join", "messageContent": {"name": "Ruedi"}}), + ), + ( + client_b, + JoinMessage({"messageType": "join", "messageContent": {"name": "Ueli"}}), + ), + ( + client_a, + ToggleReadyMessage({"messageType": "toggleReady", "messageContent": {}}), + ), + ( + client_b, + ToggleReadyMessage({"messageType": "toggleReady", "messageContent": {}}), + ), + ] + + +class TestMatch(IsolatedAsyncioTestCase): + @manage_server + async def test_match(self) -> None: + client_a = TestClient() + client_b = TestClient() + + client_manager = TestClientManager() + client_manager.register_test_client(client_a) + client_manager.register_test_client(client_b) + + await client_manager.send_messages( + get_two_players_join_and_ready(client_a, client_b) + ) + + await client_manager.collect_broadcast_messages() + + self.assertEqual(client_manager.response_map[client_a][-1].type, "startMatch") + self.assertEqual(client_manager.response_map[client_b][-1].type, "startMatch") + + await client_manager.collect_broadcast_messages() + + self.assertEqual(client_manager.response_map[client_a][-1].type, "matchState") + self.assertEqual(client_manager.response_map[client_b][-1].type, "matchState") + + client_a.shutdown() + client_b.shutdown() diff --git a/src/backend/tests/utils/client.py b/src/backend/tests/utils/client.py index bc19e09..62e16ca 100644 --- a/src/backend/tests/utils/client.py +++ b/src/backend/tests/utils/client.py @@ -1,11 +1,11 @@ import json import asyncio -from typing import Any from websockets.asyncio.client import connect import autobeerpong.config as config from autobeerpong.messages.message import MessageRaw_T, Message +from autobeerpong.server import AutobeerpongServer from tests.utils.task import ClientTask, SendMessageToServer, GetResponseFromServer from tests.utils.server import SERVER_RESPONSE_TIMEOUT @@ -13,7 +13,7 @@ from tests.utils.server import SERVER_RESPONSE_TIMEOUT class TestClient: def __init__(self) -> None: self.queue_send: asyncio.Queue[ClientTask] = asyncio.Queue() - self.queue_recv: asyncio.Queue[MessageRaw_T] = asyncio.Queue() + self.queue_recv: asyncio.Queue[Message] = asyncio.Queue() self._task = asyncio.create_task(self._client_task()) async def _client_task(self) -> None: @@ -30,7 +30,18 @@ class TestClient: response_raw = await asyncio.wait_for( websocket.recv(), timeout=SERVER_RESPONSE_TIMEOUT ) - await self.queue_recv.put(json.loads(response_raw)) + + message_raw: MessageRaw_T = json.loads(response_raw) + + assert ( + message_raw["messageType"] in AutobeerpongServer.message_map + ), f"Message type {message_raw['messageType']} not in message map!" + + MessageClass = AutobeerpongServer.message_map[ + message_raw["messageType"] + ] + + await self.queue_recv.put(MessageClass(message_raw)) else: raise Exception( @@ -39,23 +50,23 @@ class TestClient: self.queue_send.task_done() - async def send_message(self, message: Message): + async def send_message(self, message: Message) -> None: await self.queue_send.put(SendMessageToServer(message)) - async def get_response(self) -> dict[str, Any]: + async def get_response(self) -> Message: await self.queue_send.put(GetResponseFromServer()) - response_raw = await asyncio.wait_for( + response = await asyncio.wait_for( self.queue_recv.get(), timeout=SERVER_RESPONSE_TIMEOUT, ) self.queue_recv.task_done() - return response_raw + return response - async def send_messages(self, messages: list[Message]) -> list[MessageRaw_T]: - responses: list[MessageRaw_T] = [] + async def send_messages(self, messages: list[Message]) -> list[Message]: + responses: list[Message] = [] for message in messages: await self.send_message(message) @@ -70,7 +81,7 @@ class TestClient: return responses - def shutdown(self): + def shutdown(self) -> None: self.queue_send.shutdown() self.queue_recv.shutdown() self._task.cancel() diff --git a/src/backend/tests/utils/manager.py b/src/backend/tests/utils/manager.py new file mode 100644 index 0000000..0ffec68 --- /dev/null +++ b/src/backend/tests/utils/manager.py @@ -0,0 +1,42 @@ +from tests.utils.client import TestClient + +from autobeerpong.messages.message import Message + + +class TestClientManager: + def __init__(self) -> None: + self.response_map: dict[TestClient, list[Message]] = {} + self.joined_map: dict[TestClient, bool] = {} + + def register_test_client( + self, + test_client: TestClient, + ): + self.response_map[test_client]: list[Message] = [] + self.joined_map[test_client] = False + + async def collect_broadcast_messages(self) -> None: + for broadcast_client in self.response_map: + if not self.joined_map[broadcast_client]: + continue + + response = await broadcast_client.get_response() + self.response_map[broadcast_client].append(response) + + async def send_messages( + self, client_messages: list[tuple[TestClient, Message]] + ) -> None: + for client, message in client_messages: + assert client in self.response_map + + await client.send_message(message) + + if message.has_direct_response: + response = await client.get_response() + self.response_map[client].append(response) + + if response.type == "joinResponse": + self.joined_map[client] = True + + # collect broadcast responses + await self.collect_broadcast_messages() diff --git a/src/frontend/src/Scenes/MatchScene.ts b/src/frontend/src/Scenes/MatchScene.ts index e9872ef..68cdb23 100644 --- a/src/frontend/src/Scenes/MatchScene.ts +++ b/src/frontend/src/Scenes/MatchScene.ts @@ -119,7 +119,7 @@ export class MatchScene extends BaseScene { (resolve) => (resolver = resolve), ); - for (const actionOrTable of state.matchStateRaw.history) { + for (const actionOrTable of state.matchStateRaw.messageContent.history) { if ("cupsA" in actionOrTable) { this._updateFromTableState(actionOrTable); await this._matchClock.startAndWait(2000); diff --git a/src/frontend/src/schemaValidators.ts b/src/frontend/src/schemaValidators.ts index cbff554..94166be 100644 --- a/src/frontend/src/schemaValidators.ts +++ b/src/frontend/src/schemaValidators.ts @@ -14,9 +14,10 @@ import lobbyStateSchemaFile from "../../schema/lobby/state.json"; import toggleReadySchemaFile from "../../schema/lobby/toggle_ready.json"; import toggleRoleSchemaFile from "../../schema/lobby/toggle_role.json"; -// import matchStateSchemaFile from "../../schema//match/state.json"; -// import actionSchemaFile from "../../schema/match/action.json"; -// import tableSchemaFile from "../../schema/match/table_schema.json"; +import startMatchSchemaFile from "../../schema/match/start_match.json"; +import matchStateSchemaFile from "../../schema/match/state.json"; +import actionSchemaFile from "../../schema/match/action.json"; +import tableSchemaFile from "../../schema/match/table.json"; const ajv = new Ajv({ strict: true }); @@ -26,11 +27,14 @@ ajv.addSchema(playerSchemaFile, "player.json"); ajv.addSchema(joinSchemaFile, "join.json"); ajv.addSchema(joinResponseSchemaFile, "join_response.json"); ajv.addSchema(rejoinSchemaFile, "rejoin.json"); -ajv.addSchema(lobbyStateSchemaFile, "state.json"); +ajv.addSchema(lobbyStateSchemaFile, "lobby_state.json"); ajv.addSchema(toggleReadySchemaFile, "toggle_ready.json"); ajv.addSchema(toggleRoleSchemaFile, "toggle_role.json"); -// TODO: Match schemas +ajv.addSchema(startMatchSchemaFile, "start_match.json"); +ajv.addSchema(matchStateSchemaFile, "match_state.json"); +ajv.addSchema(actionSchemaFile, "action.json"); +ajv.addSchema(tableSchemaFile, "table.json"); const validateMessage = ajv.compile(messageSchemaFile); const validateClient = ajv.compile(clientSchemaFile); diff --git a/src/schema/archive/match_state_schema.json b/src/schema/archive/match_state_schema.json deleted file mode 100644 index 0d0ef9b..0000000 --- a/src/schema/archive/match_state_schema.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "title": "MatchState", - "type": "object", - "properties": { - "stateType": { - "enum": [ - "match" - ] - }, - "history": { - "type": "array", - "items": { - "anyOf": [ - { - "$ref": "./table_schema.json" - }, - { - "$ref": "./action_schema.json" - } - ] - } - } - }, - "required": [ - "stateType", - "history" - ], - "additionalProperties": false -} \ No newline at end of file diff --git a/src/schema/archive/action_schema.json b/src/schema/match/action.json similarity index 95% rename from src/schema/archive/action_schema.json rename to src/schema/match/action.json index 882940f..b717a86 100644 --- a/src/schema/archive/action_schema.json +++ b/src/schema/match/action.json @@ -1,6 +1,7 @@ { - "title": "Action", + "$id": "http://localhost/match/action.json", "type": "object", + "title": "Action", "properties": { "parabola": { "$ref": "#/$defs/parabola" diff --git a/src/schema/match/start_match.json b/src/schema/match/start_match.json new file mode 100644 index 0000000..06c2979 --- /dev/null +++ b/src/schema/match/start_match.json @@ -0,0 +1,15 @@ +{ + "$id": "http://localhost/match/start_match.json", + "type": "object", + "properties": { + "messageType": { + "const": "startMatch" + }, + "messageContent": { + "type": "object", + "properties": {}, + "required": [], + "additionalProperties": false + } + } +} \ No newline at end of file diff --git a/src/schema/match/state.json b/src/schema/match/state.json new file mode 100644 index 0000000..d1cc7d9 --- /dev/null +++ b/src/schema/match/state.json @@ -0,0 +1,31 @@ +{ + "$id": "http://localhost/match/state.json", + "type": "object", + "properties": { + "messageType": { + "const": "matchState" + }, + "messageContent": { + "type": "object", + "properties": { + "history": { + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "./table.json" + }, + { + "$ref": "./action.json" + } + ] + } + } + }, + "required": [ + "history" + ], + "additionalProperties": false + } + } +} \ No newline at end of file diff --git a/src/schema/archive/table_schema.json b/src/schema/match/table.json similarity index 94% rename from src/schema/archive/table_schema.json rename to src/schema/match/table.json index 1f7ecaf..aae6c80 100644 --- a/src/schema/archive/table_schema.json +++ b/src/schema/match/table.json @@ -1,6 +1,7 @@ { - "title": "Table", + "$id": "http://localhost/match/table.json", "type": "object", + "title": "Table", "properties": { "cupsA": { "$ref": "#/$defs/cups" diff --git a/src/schema/message.json b/src/schema/message.json index 968da2c..7ba5269 100644 --- a/src/schema/message.json +++ b/src/schema/message.json @@ -29,6 +29,12 @@ }, { "$ref": "./lobby/toggle_role.json" + }, + { + "$ref": "./match/start_match.json" + }, + { + "$ref": "./match/state.json" } ], "required": [