From 214e1bb3c4dfa0df5b9ad29b288c266e996e386c Mon Sep 17 00:00:00 2001 From: Lucas Habersaat Date: Mon, 2 Feb 2026 21:00:56 +0100 Subject: [PATCH] Add json schemas and match scene to frontend (#29) - Add json schemas for lobby and match state messages - I did a few changes: Player and spectator each have a property client, which has the id/name. - Add the separatio between lobby and match for messages - Put the socket api into our own wrapper, to easily have a `MockSocket` to use in tests. - Rename gamescene to matchscene. - Add the url param `?mock=lobby` or `?mock=match` to jump to lobby or match with mocked data. --- src/frontend/package-lock.json | 97 ++++++++++++++++--- src/frontend/package.json | 1 + src/frontend/src/Connection.ts | 93 ++++++++++++------ src/frontend/src/GameStateRaw.ts | 22 ----- .../src/{GameState.ts => LobbyState.ts} | 22 ++--- src/frontend/src/MatchState.ts | 21 ++++ src/frontend/src/Scenes/GameStateScene.ts | 7 -- src/frontend/src/Scenes/LobbyScene.ts | 29 ++++-- .../Scenes/{GameScene.ts => MatchScene.ts} | 6 +- .../ScreenElements/ClientListScreenElement.ts | 6 +- .../ScreenElements/PlayerListScreenElement.ts | 4 +- .../src/UIElements/PlayerNameInput.ts | 2 +- src/frontend/src/jsonTypes.ts | 54 +++++++++++ src/frontend/src/main.ts | 50 ++++------ src/frontend/src/schemaValidators.ts | 50 ++++++++++ src/frontend/src/sockets/BaseSocket.ts | 20 ++++ src/frontend/src/sockets/MockSocket.ts | 63 ++++++++++++ src/frontend/src/sockets/Socket.ts | 32 ++++++ src/frontend/src/utils/debugUtils.ts | 2 +- src/schema/action_schema.json | 29 ++++++ src/schema/client_schema.json | 15 +++ src/schema/lobby_state_schema.json | 21 ++++ src/schema/match_state_schema.json | 18 ++++ src/schema/message_schema.json | 14 +++ src/schema/player_schema.json | 14 +++ src/schema/spectator_schema.json | 11 +++ src/schema/table_schema.json | 26 +++++ 27 files changed, 598 insertions(+), 131 deletions(-) delete mode 100644 src/frontend/src/GameStateRaw.ts rename src/frontend/src/{GameState.ts => LobbyState.ts} (66%) create mode 100644 src/frontend/src/MatchState.ts delete mode 100644 src/frontend/src/Scenes/GameStateScene.ts rename src/frontend/src/Scenes/{GameScene.ts => MatchScene.ts} (91%) create mode 100644 src/frontend/src/jsonTypes.ts create mode 100644 src/frontend/src/schemaValidators.ts create mode 100644 src/frontend/src/sockets/BaseSocket.ts create mode 100644 src/frontend/src/sockets/MockSocket.ts create mode 100644 src/frontend/src/sockets/Socket.ts create mode 100644 src/schema/action_schema.json create mode 100644 src/schema/client_schema.json create mode 100644 src/schema/lobby_state_schema.json create mode 100644 src/schema/match_state_schema.json create mode 100644 src/schema/message_schema.json create mode 100644 src/schema/player_schema.json create mode 100644 src/schema/spectator_schema.json create mode 100644 src/schema/table_schema.json diff --git a/src/frontend/package-lock.json b/src/frontend/package-lock.json index 8a34b51..3a1c994 100644 --- a/src/frontend/package-lock.json +++ b/src/frontend/package-lock.json @@ -8,6 +8,7 @@ "name": "frontend", "version": "0.0.0", "dependencies": { + "ajv": "^8.17.1", "excalibur": "^0.30.3" }, "devDependencies": { @@ -570,6 +571,30 @@ "url": "https://opencollective.com/eslint" } }, + "node_modules/@eslint/eslintrc/node_modules/ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/@eslint/eslintrc/node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, "node_modules/@eslint/js": { "version": "9.39.1", "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.39.1.tgz", @@ -1261,16 +1286,15 @@ } }, "node_modules/ajv": { - "version": "6.12.6", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", - "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", - "dev": true, + "version": "8.17.1", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz", + "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", "license": "MIT", "dependencies": { - "fast-deep-equal": "^3.1.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" }, "funding": { "type": "github", @@ -1604,6 +1628,30 @@ "url": "https://opencollective.com/eslint" } }, + "node_modules/eslint/node_modules/ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/eslint/node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, "node_modules/espree": { "version": "10.4.0", "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz", @@ -1678,7 +1726,6 @@ "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "dev": true, "license": "MIT" }, "node_modules/fast-diff": { @@ -1702,6 +1749,22 @@ "dev": true, "license": "MIT" }, + "node_modules/fast-uri": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz", + "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, "node_modules/file-entry-cache": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", @@ -1899,10 +1962,9 @@ "license": "MIT" }, "node_modules/json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true, + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", "license": "MIT" }, "node_modules/json-stable-stringify-without-jsonify": { @@ -2173,6 +2235,15 @@ "node": ">=6" } }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/resolve-from": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", diff --git a/src/frontend/package.json b/src/frontend/package.json index ba79b52..ba7748c 100644 --- a/src/frontend/package.json +++ b/src/frontend/package.json @@ -12,6 +12,7 @@ "dev": "vite" }, "dependencies": { + "ajv": "^8.17.1", "excalibur": "^0.30.3" }, "devDependencies": { diff --git a/src/frontend/src/Connection.ts b/src/frontend/src/Connection.ts index db5e284..2824a0c 100644 --- a/src/frontend/src/Connection.ts +++ b/src/frontend/src/Connection.ts @@ -1,7 +1,15 @@ -import { GameState } from "./GameState"; -import { Client, GameStateRaw, Id } from "./GameStateRaw"; +import { LobbyState } from "./LobbyState"; +import { Client, Id } from "./jsonTypes"; +import { + validateClientSchema, + validateMessageSchema, +} from "./schemaValidators"; import { log } from "./utils/debugUtils"; import { Event, Evented } from "./utils/Evented"; +import { MatchState } from "./MatchState"; +import { BaseSocket, MessageEvent } from "./sockets/BaseSocket"; +import { MockSocket } from "./sockets/MockSocket"; +import { Socket } from "./sockets/Socket"; type Action = "join" | "rejoin" | "toggleRole" | "toggleReady"; @@ -27,8 +35,14 @@ interface ToggleReadyRequest { action: "toggleReady"; } -export class GameMessageEvent extends Event { - constructor(public gameState: GameState) { +export class LobbyMessageEvent extends Event { + constructor(public lobbyState: LobbyState) { + super(); + } +} + +export class MatchMessageEvent extends Event { + constructor(public matchState: MatchState) { super(); } } @@ -43,7 +57,8 @@ export class ConnectOrDisconnectEvent extends Event { } export const ConnectionEvents = { - "game-message": GameMessageEvent, + "lobby-message": LobbyMessageEvent, + "match-message": MatchMessageEvent, joined: JoinedEvent, connect: ConnectEvent, disconnect: DisconnectEvent, @@ -51,30 +66,30 @@ export const ConnectionEvents = { } as const; export class Connection extends Evented { - private _socket: WebSocket | null = null; + private _socket: BaseSocket | null = null; private _connected = false; private _waitForJoin = false; private _client: Client | null = null; get connected(): boolean { - const { _socket } = this; - return _socket !== null && _socket.readyState === _socket.OPEN; + return this._socket?.connected ?? false; } - connect(): void { - this._socket = new WebSocket("ws://127.0.0.1:8888"); + connect(mock?: MockSocket): void { + this._socket = mock ?? new Socket(); - this._socket.onopen = () => this._onConnect(); - this._socket.onmessage = (event) => this._onMessage(event); - this._socket.onerror = (event) => this._onError(event); - this._socket.onclose = () => this._onDisconnect(); + this._socket.on("open", () => this._onConnect()); + this._socket.on("close", () => this._onDisconnect()); + this._socket.on("error", (event) => this._onError(event)); + this._socket.on("message", (event) => this._onMessage(event)); } - private _onMessage(event: MessageEvent): void { - log("Connection", "received", event); + private _onMessage(message: MessageEvent): void { + log("Connection", "received", message); - const messageObject = JSON.parse(event.data); + // TODO: Print error if not valid json. + const messageObject = JSON.parse(message.json); if (this._waitForJoin) { this._client = messageObject.player as Client; @@ -84,13 +99,30 @@ export class Connection extends Evented { return; } - // We only emit game message events when we have joined. + // We only accept state messages events when we have joined. if (this._client) { - const gameState: GameStateRaw = messageObject.gamestate; - const gameMessage = new GameMessageEvent( - new GameState(gameState, this._client), - ); - this.emit("game-message", gameMessage); + const validated = validateMessageSchema(messageObject); + if (!validated) { + return; + } + + switch (messageObject.state.stateType) { + case "lobby": + this.emit( + "lobby-message", + new LobbyMessageEvent( + new LobbyState(messageObject.state, this._client), + ), + ); + break; + case "match": + this.emit( + "match-message", + new MatchMessageEvent( + new MatchState(messageObject.state, this._client), + ), + ); + } } } @@ -169,15 +201,20 @@ export class Connection extends Evented { } export function storedClient(): Client | null { - const clientRaw = localStorage.getItem("client"); - if (clientRaw == null) { + const clientString = localStorage.getItem("client"); + if (clientString == null) { return null; } try { - // TODO: Do schema check. - return JSON.parse(clientRaw) as Client; - } catch { + const clientRaw = JSON.parse(clientString) as Client; + if (!validateClientSchema(clientRaw)) { + return null; + } + + return clientRaw; + } catch (error) { + log("Connection", error); return null; } } diff --git a/src/frontend/src/GameStateRaw.ts b/src/frontend/src/GameStateRaw.ts deleted file mode 100644 index 2bb1dd6..0000000 --- a/src/frontend/src/GameStateRaw.ts +++ /dev/null @@ -1,22 +0,0 @@ -export type Id = number; - -export interface GameStateRaw { - players: Player[]; - spectators: Spectator[]; -} - -export type GameStateRawReadonly = Readonly; - -export interface Player { - player: Client; - ready: boolean; -} - -export interface Spectator { - player: Client; -} - -export interface Client { - id: Id; - name: string; -} diff --git a/src/frontend/src/GameState.ts b/src/frontend/src/LobbyState.ts similarity index 66% rename from src/frontend/src/GameState.ts rename to src/frontend/src/LobbyState.ts index b7c7292..ddd1520 100644 --- a/src/frontend/src/GameState.ts +++ b/src/frontend/src/LobbyState.ts @@ -1,18 +1,18 @@ import { Client, - GameStateRawReadonly, + LobbyStateRawReadonly, Id, Player, Spectator, -} from "./GameStateRaw"; +} from "./jsonTypes"; import { maxPlayers } from "./main"; import { log } from "./utils/debugUtils"; -export class GameState { +export class LobbyState { _errors: string[] = []; constructor( - public readonly gameStateRaw: GameStateRawReadonly, + public readonly lobbyStateRaw: LobbyStateRawReadonly, readonly client: Client, ) { this._validate(); @@ -28,16 +28,16 @@ export class GameState { } if (this._errors.length > 0) { - log("GameState", this._errors); + log("LobbyState", this._errors); } } get players(): Player[] { - return this.gameStateRaw.players; + return this.lobbyStateRaw.players; } get spectators(): Spectator[] { - return this.gameStateRaw.spectators; + return this.lobbyStateRaw.spectators; } get isFull(): boolean { @@ -45,7 +45,7 @@ export class GameState { } get isPlayer(): boolean { - return this.players.map((p) => p.player.id).includes(this.client.id); + return this.players.map((p) => p.client.id).includes(this.client.id); } get isReady(): boolean { @@ -53,14 +53,14 @@ export class GameState { } get isSpectator(): boolean { - return this.spectators.map((p) => p.player.id).includes(this.client.id); + return this.spectators.map((p) => p.client.id).includes(this.client.id); } getPlayerById(id: Id): Player | undefined { - return this.players.find((p) => p.player.id === id); + return this.players.find((p) => p.client.id === id); } getSpectatorById(id: Id): Spectator | undefined { - return this.spectators.find((p) => p.player.id === id); + return this.spectators.find((p) => p.client.id === id); } } diff --git a/src/frontend/src/MatchState.ts b/src/frontend/src/MatchState.ts new file mode 100644 index 0000000..1d0b61b --- /dev/null +++ b/src/frontend/src/MatchState.ts @@ -0,0 +1,21 @@ +import { Client, MatchStateRawReadonly } from "./jsonTypes"; +import { log } from "./utils/debugUtils"; + +export class MatchState { + _errors: string[] = []; + + constructor( + public readonly matchStateRaw: MatchStateRawReadonly, + readonly client: Client, + ) { + this._validate(); + } + + private _validate(): void { + if (this._errors.length > 0) { + log("MatchState", this._errors); + } + } + + // WIP more utility functions. +} diff --git a/src/frontend/src/Scenes/GameStateScene.ts b/src/frontend/src/Scenes/GameStateScene.ts deleted file mode 100644 index 1adef05..0000000 --- a/src/frontend/src/Scenes/GameStateScene.ts +++ /dev/null @@ -1,7 +0,0 @@ -import * as ex from "excalibur"; -import { GameState } from "../GameState"; - -export class GameStateScene extends ex.Scene { - // eslint-disable-next-line @typescript-eslint/no-unused-vars - public updateFromGameState(_gameState: GameState): void {} -} diff --git a/src/frontend/src/Scenes/LobbyScene.ts b/src/frontend/src/Scenes/LobbyScene.ts index 10c6c0e..b41937e 100644 --- a/src/frontend/src/Scenes/LobbyScene.ts +++ b/src/frontend/src/Scenes/LobbyScene.ts @@ -1,23 +1,22 @@ import * as ex from "excalibur"; import { spacingL, spacingM } from "../utils/formattingUtils"; import { Cups } from "../Cups"; -import { GameStateScene } from "./GameStateScene"; import { PlayerListScreenElement } from "../ScreenElements/PlayerListScreenElement"; import { ClientListScreenElement } from "../ScreenElements/ClientListScreenElement"; import { Button } from "../ScreenElements/Button"; import { PlayerNameInput } from "../UIElements/PlayerNameInput"; -import { Connection, GameMessageEvent } from "../Connection"; +import { Connection, LobbyMessageEvent } from "../Connection"; import { Title } from "../UIElements/Title"; import { ErrorList } from "../UIElements/ErrorList"; -import { GameState } from "../GameState"; +import { LobbyState } from "../LobbyState"; import { maxPlayers } from "../main"; -import { Id } from "../GameStateRaw"; +import { Id } from "../jsonTypes"; const tableWidth = 400; export type Screens = "join" | "lobby"; -export class LobbyScene extends GameStateScene { +export class LobbyScene extends ex.Scene { private _table: ex.ScreenElement = null!; private _cups: ex.ScreenElement = null!; @@ -39,7 +38,7 @@ export class LobbyScene extends GameStateScene { private _playerNameInput: PlayerNameInput = null!; private _errorList: ErrorList = null!; - private _noConnectionErrorHandle: (() => void) | undefined; + private _noConnectionErrorHandle: (() => void) | null = null; private _screen: "join" | "lobby" = "join"; @@ -51,8 +50,8 @@ export class LobbyScene extends GameStateScene { this._playerNameInput.clear(); this.setScreen("join"); }); - this._connection.on("game-message", (e: GameMessageEvent) => - this.updateFromGameState(e.gameState), + this._connection.on("lobby-message", (e: LobbyMessageEvent) => + this.updateFromMessage(e.lobbyState), ); } @@ -144,9 +143,18 @@ export class LobbyScene extends GameStateScene { this.add(this._errorList); + // Wait for two seconds before displaying an error. + const errorTimeout = setTimeout(() => { + this._noConnectionErrorHandle = this._errorList.addError( + "No server connection", + ); + }, 2000); + this._connection.on("connect-or-disconnect", ({ connected }) => { if (connected) { + clearTimeout(errorTimeout); this._noConnectionErrorHandle?.(); + this._noConnectionErrorHandle = null; } else if (this._noConnectionErrorHandle == null) { this._noConnectionErrorHandle = this._errorList.addError( "No server connection", @@ -178,7 +186,7 @@ export class LobbyScene extends GameStateScene { return bar; } - private _updateVisibility(gameState?: GameState): void { + private _updateVisibility(gameState?: LobbyState): void { const isJoinScreen = this._screen === "join"; const setVisible = (g: ex.Actor, visible: boolean): void => { if (visible) { @@ -252,7 +260,7 @@ export class LobbyScene extends GameStateScene { } } - public updateFromGameState(gameState: GameState): void { + public updateFromMessage(gameState: LobbyState): void { this._playerList.updateFromGameState(gameState.players, gameState.client); this._spectatorsList.updateFromGameState( gameState.spectators, @@ -265,6 +273,7 @@ export class LobbyScene extends GameStateScene { public setScreen(screen: Screens): void { this._screen = screen; this._updatePositions(); + this._updateVisibility(); } private _join(name: string): void { diff --git a/src/frontend/src/Scenes/GameScene.ts b/src/frontend/src/Scenes/MatchScene.ts similarity index 91% rename from src/frontend/src/Scenes/GameScene.ts rename to src/frontend/src/Scenes/MatchScene.ts index 73f2120..0371862 100644 --- a/src/frontend/src/Scenes/GameScene.ts +++ b/src/frontend/src/Scenes/MatchScene.ts @@ -1,16 +1,15 @@ import { Connection } from "../Connection"; -import { GameStateScene } from "./GameStateScene"; import { Ground, groundColor } from "../GameElements/Ground"; import { defaultTableConfiguration, Table } from "../GameElements/Table"; import { Cup, defaultCupConfiguration } from "../GameElements/Cups"; -import { Color, vec } from "excalibur"; +import { Color, Scene, vec } from "excalibur"; import { Ball, defaultBallConfiguration } from "../GameElements/Ball"; import { groundHeight } from "../utils/physicsConstant"; import { Champion } from "../GameElements/Champion"; import { randomColor } from "../utils/randomUtils"; import { colorDistance } from "../utils/colorUtils"; -export class GameScene extends GameStateScene { +export class MatchScene extends Scene { private _ground: Ground = null!; private _table: Table = null!; private _ball: Ball = null!; @@ -18,7 +17,6 @@ export class GameScene extends GameStateScene { private _cups: Cup[] = []; private _champions: Champion[] = []; - // eslint-disable-next-line @typescript-eslint/no-unused-vars constructor(private _connection: Connection) { super(); } diff --git a/src/frontend/src/ScreenElements/ClientListScreenElement.ts b/src/frontend/src/ScreenElements/ClientListScreenElement.ts index 0ed3088..ada3172 100644 --- a/src/frontend/src/ScreenElements/ClientListScreenElement.ts +++ b/src/frontend/src/ScreenElements/ClientListScreenElement.ts @@ -3,7 +3,7 @@ import * as ex from "excalibur"; import { spacingS } from "../utils/formattingUtils"; import { headingFont, paragraphFont } from "../utils/fontUtil"; import { Text } from "./Text"; -import { Client, Player, Spectator } from "../GameStateRaw"; +import { Client, Player, Spectator } from "../jsonTypes"; const clientColor = ex.Color.fromHex("40E0D0"); @@ -51,7 +51,7 @@ export class ClientListScreenElement extends ex.ScreenElement { let y = headingFont.size + spacingS; for (const currentClient of this._clients) { - const isClient = currentClient.player.id === this._client?.id; + const isClient = currentClient.client.id === this._client?.id; const label = this.createLabel(currentClient, y, isClient); y += label.font.size + spacingS; @@ -77,7 +77,7 @@ export class ClientListScreenElement extends ex.ScreenElement { isClient: boolean, ): Text { const color = isClient ? clientColor : undefined; - const { name } = client.player; + const { name } = client.client; const label = new Text({ text: name, font: paragraphFont, diff --git a/src/frontend/src/ScreenElements/PlayerListScreenElement.ts b/src/frontend/src/ScreenElements/PlayerListScreenElement.ts index f114c54..6041318 100644 --- a/src/frontend/src/ScreenElements/PlayerListScreenElement.ts +++ b/src/frontend/src/ScreenElements/PlayerListScreenElement.ts @@ -3,7 +3,7 @@ import { spacingS } from "../utils/formattingUtils"; import { disabledFont } from "../utils/fontUtil"; import { Text } from "./Text"; import { Checkbox } from "./Checkbox"; -import { Player } from "../GameStateRaw"; +import { Player } from "../jsonTypes"; import { ClientListScreenElement } from "./ClientListScreenElement"; export class PlayerListScreenElement extends ClientListScreenElement { @@ -23,7 +23,7 @@ export class PlayerListScreenElement extends ClientListScreenElement { const clients = this._clients.slice(0, this._maxPlayers); for (const currentClient of clients) { - const { name, id } = currentClient.player; + const { name, id } = currentClient.client; const isClient = id === this._client?.id; const label = this.createLabel(currentClient, y, isClient); diff --git a/src/frontend/src/UIElements/PlayerNameInput.ts b/src/frontend/src/UIElements/PlayerNameInput.ts index 75565eb..5e06157 100644 --- a/src/frontend/src/UIElements/PlayerNameInput.ts +++ b/src/frontend/src/UIElements/PlayerNameInput.ts @@ -5,7 +5,7 @@ import { paragraphFont } from "../utils/fontUtil"; import { Text } from "../ScreenElements/Text"; import { spacingM } from "../utils/formattingUtils"; import { Connection, storedClient } from "../Connection"; -import { Id } from "../GameStateRaw"; +import { Id } from "../jsonTypes"; export class PlayerNameInput extends ex.ScreenElement { private _nameLabel: Text = null!; diff --git a/src/frontend/src/jsonTypes.ts b/src/frontend/src/jsonTypes.ts new file mode 100644 index 0000000..5d510a5 --- /dev/null +++ b/src/frontend/src/jsonTypes.ts @@ -0,0 +1,54 @@ +export type Id = number; + +export interface MessageRaw { + state: LobbyStateRaw | MatchStateRaw; +} + +export interface LobbyStateRaw { + stateType: "lobby"; + players: Player[]; + spectators: Spectator[]; +} + +export type LobbyStateRawReadonly = Readonly; + +export interface Player { + client: Client; + ready: boolean; +} + +export interface Spectator { + client: Client; +} + +export interface Client { + id: Id; + name: string; +} + +export interface MatchStateRaw { + stateType: "match"; + history: (Table | Action)[]; +} + +export type MatchStateRawReadonly = Readonly; + +export interface Table { + cupsA: [boolean, boolean, boolean]; + cupsB: [boolean, boolean, boolean]; + teamA: [Id, Id, Id]; + teamB: [Id, Id, Id]; +} + +export interface Action { + turn: "a" | "b"; + parabola: Parabola; +} + +export interface Parabola { + startPosition: Vector2; + startVelocity: Vector2; + stopTime: number; +} + +export type Vector2 = [number, number]; diff --git a/src/frontend/src/main.ts b/src/frontend/src/main.ts index c0b928b..e3301e2 100644 --- a/src/frontend/src/main.ts +++ b/src/frontend/src/main.ts @@ -1,25 +1,30 @@ import * as ex from "excalibur"; import { LobbyScene } from "./Scenes/LobbyScene"; import { Connection } from "./Connection"; -import { GameStateRaw } from "./GameStateRaw"; -import { GameState } from "./GameState"; -import { GameScene } from "./Scenes/GameScene"; +import { MatchScene } from "./Scenes/MatchScene"; +import { + mockGameMessage, + mockLobbyMessage, + MockSocket, +} from "./sockets/MockSocket"; const urlParams = new URLSearchParams(window.location.search); -const debugSkipTo = urlParams.get("skipTo"); +const mocked = urlParams.get("mock"); export const maxPlayers = 2; (async () => { const connection = new Connection(); - connection.connect(); + + const mockSocket = new MockSocket(); + connection.connect(mocked != null ? mockSocket : undefined); const lobbyScene = new LobbyScene(connection); - const gameScene = new GameScene(connection); + const matchScene = new MatchScene(connection); const game = new ex.Engine({ displayMode: ex.DisplayMode.FillScreen, - scenes: { lobby: lobbyScene, game: gameScene }, + scenes: { lobby: lobbyScene, match: matchScene }, backgroundColor: ex.Color.fromHex("23213b"), }); game.toggleDebug(); @@ -27,27 +32,14 @@ export const maxPlayers = 2; await game.start(); await game.goToScene("lobby"); - if (debugSkipTo === "lobby") { - lobbyScene.setScreen("lobby"); - lobbyScene.updateFromGameState(dummyGameState()); - } else if (debugSkipTo === "game") { - await game.goToScene("game"); + connection.on("lobby-message", () => game.goToScene("lobby")); + connection.on("match-message", () => game.goToScene("match")); + + if (mocked === "lobby") { + connection.join("Dubbel"); + mockSocket.sendToClient(mockLobbyMessage()); + } else if (mocked === "match") { + connection.join("Dubbel"); + mockSocket.sendToClient(mockGameMessage()); } })(); - -function dummyGameState(): GameState { - const you = { name: "Dubbel", id: 0 }; - - const dummyState: GameStateRaw = { - players: [ - { player: { name: "Dubbel", id: 0 }, ready: true }, - { player: { name: "Yeah", id: 1 }, ready: false }, - ], - spectators: [ - { player: { name: "Dubbel", id: 2 } }, - { player: { name: "Cocksucker", id: 3 } }, - ], - }; - - return new GameState(dummyState, you); -} diff --git a/src/frontend/src/schemaValidators.ts b/src/frontend/src/schemaValidators.ts new file mode 100644 index 0000000..0205987 --- /dev/null +++ b/src/frontend/src/schemaValidators.ts @@ -0,0 +1,50 @@ +import Ajv, { ValidateFunction } from "ajv"; + +import { log } from "./utils/debugUtils"; +import { Client, MessageRaw } from "./jsonTypes"; +import messageSchemaFile from "../../schema/message_schema.json"; +import clientSchemaFile from "../../schema/client_schema.json"; +import lobbyStateSchemaFile from "../../schema/lobby_state_schema.json"; +import matchStateSchemaFile from "../../schema/match_state_schema.json"; +import actionSchemaFile from "../../schema/action_schema.json"; +import playerSchemaFile from "../../schema/player_schema.json"; +import spectatorSchemaFile from "../../schema/spectator_schema.json"; +import tableSchemaFile from "../../schema/table_schema.json"; + +const ajv = new Ajv({ strict: true }); + +ajv.addSchema(lobbyStateSchemaFile, "lobby_state_schema.json"); +ajv.addSchema(matchStateSchemaFile, "match_state_schema.json"); +ajv.addSchema(actionSchemaFile, "action_schema.json"); +ajv.addSchema(clientSchemaFile, "client_schema.json"); +ajv.addSchema(playerSchemaFile, "player_schema.json"); +ajv.addSchema(spectatorSchemaFile, "spectator_schema.json"); +ajv.addSchema(tableSchemaFile, "table_schema.json"); + +const validateMessage = ajv.compile(messageSchemaFile); +const validateClient = ajv.compile(clientSchemaFile); + +export function validateMessageSchema(json: unknown): json is MessageRaw { + return validate(json, validateMessage); +} + +export function validateClientSchema(json: unknown): json is Client { + return validate(json, validateClient); +} + +export function validate( + json: unknown, + validateFunction: ValidateFunction, +): boolean { + const valid = validateFunction(json); + + if (!valid) { + log("Connection", "invalid message received", { + json, + errors: validateFunction.errors, + }); + console.log(validateFunction.errors); + } + + return valid; +} diff --git a/src/frontend/src/sockets/BaseSocket.ts b/src/frontend/src/sockets/BaseSocket.ts new file mode 100644 index 0000000..ce89f4e --- /dev/null +++ b/src/frontend/src/sockets/BaseSocket.ts @@ -0,0 +1,20 @@ +import { Event, Evented } from "../utils/Evented"; + +export class MessageEvent extends Event { + // TODO: Turn into union of all possible messages. + constructor(public json: string) { + super(); + } +} + +export const BaseSocketEvents = { + open: Event, + close: Event, + error: globalThis.Event, + message: MessageEvent, +}; + +export interface BaseSocket extends Evented { + send: (message: string) => void; + connected: boolean; +} diff --git a/src/frontend/src/sockets/MockSocket.ts b/src/frontend/src/sockets/MockSocket.ts new file mode 100644 index 0000000..9866af9 --- /dev/null +++ b/src/frontend/src/sockets/MockSocket.ts @@ -0,0 +1,63 @@ +import { Evented } from "../utils/Evented"; +import { BaseSocket, BaseSocketEvents } from "./BaseSocket"; + +export class MockSocket + extends Evented + implements BaseSocket +{ + constructor() { + super(); + setTimeout(() => { + this.emit("open", {}); + }, 500); + } + + get connected(): boolean { + return true; + } + + sendToClient(json: string): void { + this.emit("message", { json }); + } + + send(message: string): void { + if (message.includes("join")) { + this.sendToClient(JSON.stringify({ player: { id: 0, name: "Dubbel" } })); + } + } +} + +export function mockLobbyMessage(): string { + const lobbyUpdate = { + state: { + stateType: "lobby", + players: [ + { client: { name: "Dubbel", id: 0 }, ready: true }, + { client: { name: "Yeah", id: 1 }, ready: false }, + ], + spectators: [ + { client: { name: "Dubbel", id: 2 } }, + { client: { name: "Cocksucker", id: 3 } }, + { client: { name: "Cocksucker 2", id: 4 } }, + ], + }, + }; + return JSON.stringify(lobbyUpdate); +} + +export function mockGameMessage(): string { + const matchUpdate = { + state: { + stateType: "match", + history: [ + { + cupsA: [true, true, true], + cupsB: [true, true, true], + teamA: [0, 1, 2], + teamB: [3, 1, 4], + }, + ], + }, + }; + return JSON.stringify(matchUpdate); +} diff --git a/src/frontend/src/sockets/Socket.ts b/src/frontend/src/sockets/Socket.ts new file mode 100644 index 0000000..f354a9f --- /dev/null +++ b/src/frontend/src/sockets/Socket.ts @@ -0,0 +1,32 @@ +import { assert } from "../utils/assertUtils"; +import { Evented } from "../utils/Evented"; +import { BaseSocket, BaseSocketEvents } from "./BaseSocket"; + +export class Socket + extends Evented + implements BaseSocket +{ + private _webSocket: WebSocket; + + constructor() { + super(); + + this._webSocket = new WebSocket("ws://127.0.0.1:8888"); + + this._webSocket.onopen = () => this.emit("open", {}); + this._webSocket.onclose = () => this.emit("close", {}); + this._webSocket.onerror = (event) => this.emit("error", event); + this._webSocket.onmessage = (event) => { + assert(typeof event.data === "string"); + this.emit("message", { json: event.data }); + }; + } + + get connected(): boolean { + return this._webSocket.readyState === this._webSocket.OPEN; + } + + send(message: string): void { + this._webSocket.send(message); + } +} diff --git a/src/frontend/src/utils/debugUtils.ts b/src/frontend/src/utils/debugUtils.ts index d700cc3..ad1cc7d 100644 --- a/src/frontend/src/utils/debugUtils.ts +++ b/src/frontend/src/utils/debugUtils.ts @@ -1,4 +1,4 @@ -export type LogSource = "Connection" | "GameState"; +export type LogSource = "Connection" | "LobbyState" | "MatchState"; // eslint-disable-next-line @typescript-eslint/no-explicit-any export function log(source: LogSource, ...data: any[]): void { diff --git a/src/schema/action_schema.json b/src/schema/action_schema.json new file mode 100644 index 0000000..00da8c1 --- /dev/null +++ b/src/schema/action_schema.json @@ -0,0 +1,29 @@ +{ + "title": "Action", + "type": "object", + "properties": { + "parabola": { "$ref": "#/$defs/parabola" }, + "turn": { "$ref": "#/$defs/turn" } + }, + "required": ["parabola", "turn"], + "additionalProperties": false, + "$defs": { + "turn": { + "enum": ["a", "b"] + }, + "parabola": { + "type": "object", + "properties": { + "startPosition": { "$ref": "#/$defs/vector2" }, + "startVelocity": { "$ref": "#/$defs/vector2" }, + "stopTime": { "type": "number" } + } + }, + "vector2": { + "type": "array", + "items": { "type": "number" }, + "minItems": 2, + "maxItems": 2 + } + } +} diff --git a/src/schema/client_schema.json b/src/schema/client_schema.json new file mode 100644 index 0000000..d62d0e1 --- /dev/null +++ b/src/schema/client_schema.json @@ -0,0 +1,15 @@ +{ + "title": "Client", + "type": "object", + "properties": { + "id": { + "type": "number", + "minimum": 0 + }, + "name": { + "type": "string" + } + }, + "required": ["id", "name"], + "additionalProperties": false +} diff --git a/src/schema/lobby_state_schema.json b/src/schema/lobby_state_schema.json new file mode 100644 index 0000000..f325a46 --- /dev/null +++ b/src/schema/lobby_state_schema.json @@ -0,0 +1,21 @@ +{ + "title": "LobbyState", + "type": "object", + "properties": { + "stateType": { "enum": ["lobby"] }, + "players": { + "type": "array", + "items": { + "$ref": "./player_schema.json" + } + }, + "spectators": { + "type": "array", + "items": { + "$ref": "./spectator_schema.json" + } + } + }, + "required": ["stateType", "players", "spectators"], + "additionalProperties": false +} diff --git a/src/schema/match_state_schema.json b/src/schema/match_state_schema.json new file mode 100644 index 0000000..4379975 --- /dev/null +++ b/src/schema/match_state_schema.json @@ -0,0 +1,18 @@ +{ + "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 +} diff --git a/src/schema/message_schema.json b/src/schema/message_schema.json new file mode 100644 index 0000000..a12c6e3 --- /dev/null +++ b/src/schema/message_schema.json @@ -0,0 +1,14 @@ +{ + "title": "Message", + "type": "object", + "properties": { + "state": { + "anyOf": [ + { "$ref": "./lobby_state_schema.json"}, + { "$ref": "./match_state_schema.json"} + ] + } + }, + "required": ["state"], + "additionalProperties": false +} diff --git a/src/schema/player_schema.json b/src/schema/player_schema.json new file mode 100644 index 0000000..63601c6 --- /dev/null +++ b/src/schema/player_schema.json @@ -0,0 +1,14 @@ +{ + "title": "Player", + "type": "object", + "properties": { + "client": { + "$ref": "./client_schema.json" + }, + "ready": { + "type": "boolean" + } + }, + "required": ["client", "ready"], + "additionalProperties": false +} diff --git a/src/schema/spectator_schema.json b/src/schema/spectator_schema.json new file mode 100644 index 0000000..4fe7531 --- /dev/null +++ b/src/schema/spectator_schema.json @@ -0,0 +1,11 @@ +{ + "title": "Spectator", + "type": "object", + "properties": { + "client": { + "$ref": "./client_schema.json" + } + }, + "required": ["client"], + "additionalProperties": false +} diff --git a/src/schema/table_schema.json b/src/schema/table_schema.json new file mode 100644 index 0000000..5565c20 --- /dev/null +++ b/src/schema/table_schema.json @@ -0,0 +1,26 @@ +{ + "title": "Table", + "type": "object", + "properties": { + "cupsA": { "$ref": "#/$defs/cups" }, + "cupsB": { "$ref": "#/$defs/cups" }, + "teamA": { "$ref": "#/$defs/team" }, + "teamB": { "$ref": "#/$defs/team" } + }, + "required": ["cupsA", "cupsB", "teamA", "teamB"], + "additionalProperties": false, + "$defs": { + "cups": { + "type": "array", + "items": { "type": "boolean" }, + "minItems": 3, + "maxItems": 3 + }, + "team": { + "type": "array", + "items": { "type": "number" }, + "minItems": 3, + "maxItems": 3 + } + } +}