From 9a3851f802297d6c577217dbe0fc92ebddbc6a41 Mon Sep 17 00:00:00 2001 From: Lucas Habersaat Date: Mon, 4 May 2026 20:06:36 +0200 Subject: [PATCH] Frontend - Claude found some bugs (#41) --- src/frontend/src/Connection.ts | 22 +++-- src/frontend/src/Cups.ts | 14 +-- src/frontend/src/GameElements/Ball.ts | 40 +-------- src/frontend/src/GameElements/BaseActor.ts | 2 +- src/frontend/src/GameElements/Parabola.ts | 35 ++++++++ src/frontend/src/LobbyState.ts | 18 ++-- src/frontend/src/MatchState.ts | 6 +- src/frontend/src/Scenes/BaseScene.ts | 4 +- src/frontend/src/Scenes/LobbyScene.ts | 90 ++++++++----------- src/frontend/src/Scenes/MatchScene.ts | 15 ++-- src/frontend/src/ScreenElements/Button.ts | 8 +- src/frontend/src/ScreenElements/Error.ts | 11 ++- .../ScreenElements/PlayerListScreenElement.ts | 2 +- src/frontend/src/Timers/BallClock.ts | 3 +- src/frontend/src/Timers/Clock.ts | 2 +- src/frontend/src/jsonTypes.ts | 4 - src/frontend/src/main.ts | 32 ++++--- src/frontend/src/schemaValidators.ts | 4 +- src/frontend/src/sockets/MockSocket.ts | 2 +- src/frontend/src/utils/Evented.ts | 10 ++- src/frontend/src/utils/constants.ts | 1 + src/frontend/src/utils/debugUtils.ts | 6 +- 22 files changed, 173 insertions(+), 158 deletions(-) create mode 100644 src/frontend/src/GameElements/Parabola.ts create mode 100644 src/frontend/src/utils/constants.ts diff --git a/src/frontend/src/Connection.ts b/src/frontend/src/Connection.ts index c6a5edc..996bc00 100644 --- a/src/frontend/src/Connection.ts +++ b/src/frontend/src/Connection.ts @@ -8,7 +8,6 @@ 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 MessageType = "join" | "rejoin" | "toggleRole" | "toggleReady"; @@ -33,10 +32,12 @@ interface RejoinRequest { interface ToggleRoleRequest { messageType: "toggleRole"; + messageContent: Record; } interface ToggleReadyRequest { messageType: "toggleReady"; + messageContent: Record; } export class LobbyMessageEvent extends Event { @@ -71,7 +72,7 @@ export const ConnectionEvents = { export class Connection extends Evented { private _socket: BaseSocket | null = null; - private _connected = false; + private _wasConnected = false; private _waitForJoin = false; private _client: Client | null = null; @@ -80,7 +81,8 @@ export class Connection extends Evented { return this._socket?.connected ?? false; } - connect(mock?: MockSocket): void { + connect(mock?: BaseSocket): void { + this._socket?.offAll(); this._socket = mock ?? new Socket(); this._socket.on("open", () => this._onConnect()); @@ -96,8 +98,14 @@ export class Connection extends Evented { const messageObject = JSON.parse(message.json); if (this._waitForJoin) { - this._client = messageObject.messageContent.client as Client; + const client = messageObject.messageContent.client; + if (!validateClientSchema(client)) { + return; + } + this._client = client; + storeClient(this._client); + this._waitForJoin = false; this.emit("joined", new JoinedEvent()); return; @@ -129,7 +137,7 @@ export class Connection extends Evented { private _onConnect(): void { log("Connection", "connected"); - this._connected = true; + this._wasConnected = true; this.emit("connect", new ConnectEvent()); this.emit("connect-or-disconnect", new ConnectOrDisconnectEvent(true)); @@ -140,8 +148,8 @@ export class Connection extends Evented { // The socket close event is also invoked when a connection attempt fails. // Only emit the disconnect event when we actually had a connection. - if (this._connected) { - this._connected = false; + if (this._wasConnected) { + this._wasConnected = false; this.emit("disconnect", new DisconnectEvent()); this.emit("connect-or-disconnect", new ConnectOrDisconnectEvent(false)); } diff --git a/src/frontend/src/Cups.ts b/src/frontend/src/Cups.ts index ac89ca0..839fa37 100644 --- a/src/frontend/src/Cups.ts +++ b/src/frontend/src/Cups.ts @@ -6,24 +6,24 @@ const margin = 2; export class Cups extends ex.Graphic { protected _drawImage( context: ex.ExcaliburGraphicsContext, - x: number, + _x: number, y: number, ): void { - y += radius; + let currentY = y + radius; for (let r = 4; r > 0; r--) { - x = -r * radius + radius; + let currentX = -r * radius + radius; for (let c = 0; c < r; c++) { context.drawCircle( - ex.vec(x, y), + ex.vec(currentX, currentY), radius, ex.Color.Red, ex.Color.White, 2, ); - x += radius * 2 + margin; + currentX += radius * 2 + margin; } - y += radius * 2 + margin; + currentY += radius * 2 + margin; } } @@ -31,7 +31,7 @@ export class Cups extends ex.Graphic { return new Cups(); } - get computeHeight(): number { + get computedHeight(): number { return 4 * 2 * radius + 3 * margin; } } diff --git a/src/frontend/src/GameElements/Ball.ts b/src/frontend/src/GameElements/Ball.ts index f7781b8..0b7879a 100644 --- a/src/frontend/src/GameElements/Ball.ts +++ b/src/frontend/src/GameElements/Ball.ts @@ -1,7 +1,6 @@ import { ActorArgs, Circle, - clamp, Color, Engine, Graphic, @@ -10,10 +9,9 @@ import { vec, Vector, } from "excalibur"; -import { gravitationalConstant } from "../configs/physicsConstant"; -import { Parabola as ParabolaJSON } from "../jsonTypes"; import { BallClock } from "../Timers/BallClock"; import { BaseActor } from "./BaseActor"; +import { Parabola } from "./Parabola"; export const defaultBallConfiguration: BallConfiguration = { color: Color.Orange, @@ -45,7 +43,7 @@ export class Ball extends BaseActor { const { radius } = configuration; const ballGraphic = new Circle({ - radius: radius, + radius, color: configuration.color, }); @@ -56,7 +54,7 @@ export class Ball extends BaseActor { this._graphic = new GraphicsGroup({ members: [ - { graphic: ballGraphic, offset: vec(0, 0) }, + { graphic: ballGraphic, offset: Vector.Zero }, { graphic: specularGraphic, offset: vec(radius / 2, radius / 2) }, ], }); @@ -83,35 +81,3 @@ export class Ball extends BaseActor { this._clock.startWithParabola(parabola); } } - -export class Parabola { - constructor( - readonly startPos: Vector, - readonly startVelocity: Vector, - readonly stopTime?: number, - ) {} - - static fromJSON(parabolaJSON: ParabolaJSON) { - const { - startPosition: start, - startVelocity: velocity, - stopTime, - } = parabolaJSON; - - const startPosition = new Vector(start[0], start[1]); - const startVelocity = new Vector(velocity[0], velocity[1]); - return new Parabola(startPosition, startVelocity, stopTime); - } - - position(time: number): Vector { - const timeSeconds = clamp(time / 1000, 0, this.stopTime ?? Infinity); - - const x = this.startPos.x + this.startVelocity.x * timeSeconds; - const y = - this.startVelocity.y * timeSeconds + - (gravitationalConstant / 2) * timeSeconds ** 2 + - this.startPos.y; - - return new Vector(x, y); - } -} diff --git a/src/frontend/src/GameElements/BaseActor.ts b/src/frontend/src/GameElements/BaseActor.ts index 2ba1922..7c93801 100644 --- a/src/frontend/src/GameElements/BaseActor.ts +++ b/src/frontend/src/GameElements/BaseActor.ts @@ -2,7 +2,7 @@ import { Actor, Engine } from "excalibur"; import { Clock } from "../Timers/Clock"; export class BaseActor extends Actor { - private _clocks = new Array(); + private _clocks: Clock[] = []; override update(engine: Engine, elapsed: number): void { super.update(engine, elapsed); diff --git a/src/frontend/src/GameElements/Parabola.ts b/src/frontend/src/GameElements/Parabola.ts new file mode 100644 index 0000000..8eb9074 --- /dev/null +++ b/src/frontend/src/GameElements/Parabola.ts @@ -0,0 +1,35 @@ +import { Vector, clamp } from "excalibur"; +import { Parabola as ParabolaJSON } from "../jsonTypes"; +import { gravitationalConstant } from "../configs/physicsConstant"; + +export class Parabola { + constructor( + readonly startPos: Vector, + readonly startVelocity: Vector, + readonly stopTime?: number, + ) {} + + static fromJSON(parabolaJSON: ParabolaJSON): Parabola { + const { + startPosition: start, + startVelocity: velocity, + stopTime, + } = parabolaJSON; + + const startPosition = new Vector(start[0], start[1]); + const startVelocity = new Vector(velocity[0], velocity[1]); + return new Parabola(startPosition, startVelocity, stopTime); + } + + position(time: number): Vector { + const timeSeconds = clamp(time / 1000, 0, this.stopTime ?? Infinity); + + const x = this.startPos.x + this.startVelocity.x * timeSeconds; + const y = + this.startVelocity.y * timeSeconds + + (gravitationalConstant / 2) * timeSeconds ** 2 + + this.startPos.y; + + return new Vector(x, y); + } +} diff --git a/src/frontend/src/LobbyState.ts b/src/frontend/src/LobbyState.ts index f2b8be9..551723d 100644 --- a/src/frontend/src/LobbyState.ts +++ b/src/frontend/src/LobbyState.ts @@ -1,19 +1,19 @@ import { Client, - LobbyStateRawReadonly, Id, + LobbyStateRaw, Player, Spectator, getClient, } from "./jsonTypes"; -import { maxPlayers } from "./main"; +import { maxPlayers } from "./utils/constants"; import { log } from "./utils/debugUtils"; export class LobbyState { - _errors: string[] = []; + private _errors: string[] = []; constructor( - public readonly lobbyStateRaw: LobbyStateRawReadonly, + private readonly _lobbyStateRaw: LobbyStateRaw, readonly client: Client, ) { this._validate(); @@ -34,11 +34,11 @@ export class LobbyState { } get players(): Player[] { - return this.lobbyStateRaw.messageContent.players; + return this._lobbyStateRaw.messageContent.players; } get spectators(): Spectator[] { - return this.lobbyStateRaw.messageContent.spectators; + return this._lobbyStateRaw.messageContent.spectators; } get isFull(): boolean { @@ -46,15 +46,15 @@ export class LobbyState { } get isPlayer(): boolean { - return this.players.map((p) => p.client.id).includes(this.client.id); + return this.players.some((p) => p.client.id === this.client.id); } get isReady(): boolean { - return this.getPlayerById(this.client.id)!.ready; + return this.getPlayerById(this.client.id)?.ready ?? false; } get isSpectator(): boolean { - return this.spectators.map((p) => getClient(p).id).includes(this.client.id); + return this.spectators.some((p) => getClient(p).id === this.client.id); } getPlayerById(id: Id): Player | undefined { diff --git a/src/frontend/src/MatchState.ts b/src/frontend/src/MatchState.ts index 1d0b61b..d7bb11e 100644 --- a/src/frontend/src/MatchState.ts +++ b/src/frontend/src/MatchState.ts @@ -1,11 +1,11 @@ -import { Client, MatchStateRawReadonly } from "./jsonTypes"; +import { Client, MatchStateRaw } from "./jsonTypes"; import { log } from "./utils/debugUtils"; export class MatchState { - _errors: string[] = []; + private _errors: string[] = []; constructor( - public readonly matchStateRaw: MatchStateRawReadonly, + public readonly matchStateRaw: MatchStateRaw, readonly client: Client, ) { this._validate(); diff --git a/src/frontend/src/Scenes/BaseScene.ts b/src/frontend/src/Scenes/BaseScene.ts index 8bb825e..541ffa9 100644 --- a/src/frontend/src/Scenes/BaseScene.ts +++ b/src/frontend/src/Scenes/BaseScene.ts @@ -9,8 +9,8 @@ export class BaseScene extends Scene { this._clocks.forEach((clock) => clock.update(elapsed)); } - addClock(timer: Clock): void { - this._clocks.push(timer); + addClock(clock: Clock): void { + this._clocks.push(clock); } protected updateActorVisibility(actor: Actor, visible: boolean): void { diff --git a/src/frontend/src/Scenes/LobbyScene.ts b/src/frontend/src/Scenes/LobbyScene.ts index 49fba67..29ac143 100644 --- a/src/frontend/src/Scenes/LobbyScene.ts +++ b/src/frontend/src/Scenes/LobbyScene.ts @@ -9,9 +9,9 @@ import { Connection, LobbyMessageEvent } from "../Connection"; import { Title } from "../UIElements/Title"; import { ErrorList } from "../UIElements/ErrorList"; import { LobbyState } from "../LobbyState"; -import { maxPlayers } from "../main"; import { Id } from "../jsonTypes"; import { BaseScene } from "./BaseScene"; +import { maxPlayers } from "../utils/constants"; const tableWidth = 400; @@ -41,20 +41,11 @@ export class LobbyScene extends BaseScene { private _errorList: ErrorList = null!; private _noConnectionErrorHandle: (() => void) | null = null; - private _screen: "join" | "lobby" = "join"; + private _screen: Screens = "join"; private _gameState?: LobbyState; constructor(private _connection: Connection) { super(); - - this._connection.on("joined", () => this.setScreen("lobby")); - this._connection.on("disconnect", () => { - this._playerNameInput.clear(); - this.setScreen("join"); - }); - this._connection.on("lobby-message", (e: LobbyMessageEvent) => - this.updateFromMessage(e.lobbyState), - ); } onInitialize(engine: ex.Engine): void { @@ -102,7 +93,7 @@ export class LobbyScene extends BaseScene { this._joinPlayerButton = new Button({ text: "Join as player", anchor: ex.vec(0.5, 0), - onClick: () => this._joinAsPlayer(), + onClick: () => this._connection.toggleRole(), }); this._spectatorsList = new ClientListScreenElement("Spectators"); @@ -111,27 +102,27 @@ export class LobbyScene extends BaseScene { this._joinSpectatorButton = new Button({ text: "Join as spectator", anchor: ex.vec(0.5, 0), - onClick: () => this._joinAsSpectator(), + onClick: () => this._connection.toggleRole(), }); this._readyButton = new Button({ text: "I'm Ready", anchor: ex.vec(0.5, 0), color: ex.Color.Green, - onClick: () => this._ready(), + onClick: () => this._connection.toggleReady(), }); this._unreadyButton = new Button({ text: "Not Ready", anchor: ex.vec(0.5, 0), color: ex.Color.Red, - onClick: () => this._unready(), + onClick: () => this._connection.toggleReady(), }); // Name input this._playerNameInput = new PlayerNameInput( this._connection, - (name: string) => this._join(name), - (id: Id) => this._rejoin(id), + (name: string) => this._connection.join(name), + (id: Id) => this._connection.rejoin(id), ); this._playerNameInput.anchor = ex.vec(0.5, 0); @@ -145,12 +136,30 @@ export class LobbyScene extends BaseScene { 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._setupConnectionHandles(); + + engine.screen.events.on("resize", () => this._updatePositions()); + } + + private _setupConnectionHandles(): void { + this._connection.on("joined", () => this.setScreen("lobby")); + this._connection.on("disconnect", () => { + this._playerNameInput.clear(); + this.setScreen("join"); + }); + this._connection.on("lobby-message", (e: LobbyMessageEvent) => + this.updateFromMessage(e.lobbyState), + ); + + let errorTimeout = undefined; + if (!this._connection.connected) { + // Wait for two seconds before displaying an error. + errorTimeout = setTimeout(() => { + this._noConnectionErrorHandle = this._errorList.addError( + "No server connection", + ); + }, 2000); + } this._connection.on("connect-or-disconnect", ({ connected }) => { if (connected) { @@ -163,8 +172,6 @@ export class LobbyScene extends BaseScene { ); } }); - - engine.screen.events.on("resize", () => this._updatePositions()); } // eslint-disable-next-line @typescript-eslint/no-unused-vars @@ -194,9 +201,10 @@ export class LobbyScene extends BaseScene { const isPlayer = gameState?.isPlayer ?? false; const isSpectator = gameState?.isSpectator ?? false; - const isReadyVisible = isPlayer && (gameState?.isReady ?? false); - const isNotReadyVisible = - isPlayer && ((gameState != null && !gameState.isReady) ?? false); + + const readyState = isPlayer ? (gameState?.isReady ?? false) : null; + const isReadyVisible = readyState === true; + const isNotReadyVisible = readyState === false; const isLobbyFull = gameState?.isFull ?? false; this.updateActorVisibility(this._playerNameInput, isJoinScreen); @@ -231,7 +239,7 @@ export class LobbyScene extends BaseScene { this._cups.pos = ex.vec(halfWidth, y); const cups = this._cups.graphics.getGraphic("default") as Cups; - y += cups.computeHeight! + spacingM; + y += cups.computedHeight + spacingM; this._bar1.pos = ex.vec(halfWidth, y); y += this._bar1.height + spacingM; @@ -283,28 +291,4 @@ export class LobbyScene extends BaseScene { this._updatePositions(); this._updateVisibility(); } - - private _join(name: string): void { - this._connection.join(name); - } - - private _rejoin(id: Id): void { - this._connection.rejoin(id); - } - - private _joinAsPlayer(): void { - this._connection.toggleRole(); - } - - private _joinAsSpectator(): void { - this._connection.toggleRole(); - } - - private _ready(): void { - this._connection.toggleReady(); - } - - private _unready(): void { - this._connection.toggleReady(); - } } diff --git a/src/frontend/src/Scenes/MatchScene.ts b/src/frontend/src/Scenes/MatchScene.ts index 68cdb23..51c4576 100644 --- a/src/frontend/src/Scenes/MatchScene.ts +++ b/src/frontend/src/Scenes/MatchScene.ts @@ -1,6 +1,3 @@ -import { Color, vec } from "excalibur"; -import { Connection, MatchMessageEvent } from "../Connection"; -import { Ball, defaultBallConfiguration, Parabola } from "../GameElements/Ball"; import { Champion } from "../GameElements/Champion"; import { Cup, defaultCupConfiguration } from "../GameElements/Cups"; import { Ground, groundColor } from "../GameElements/Ground"; @@ -17,6 +14,12 @@ import { assertNotNull, assertNull } from "../utils/assertUtils"; import { colorDistance } from "../utils/colorUtils"; import { randomColor, randomInteger } from "../utils/randomUtils"; import { BaseScene } from "./BaseScene"; +import { Parabola } from "../GameElements/Parabola"; +import { Engine, vec, Color } from "excalibur"; +import { Connection, MatchMessageEvent } from "../Connection"; +import { Ball, defaultBallConfiguration } from "../GameElements/Ball"; + +const cupOffsets = [54, 32, 10]; const speedUpFactor = 3; @@ -48,7 +51,7 @@ export class MatchScene extends BaseScene { } // eslint-disable-next-line @typescript-eslint/no-unused-vars - onInitialize(_engine: ex.Engine): void { + onInitialize(_engine: Engine): void { this.camera.pos.setTo(0, 0); this._ground = new Ground(); @@ -64,8 +67,8 @@ export class MatchScene extends BaseScene { const tableHeight = this._table.configuration.height; const cupPositions = [ - ...[54, 32, 10].map((v) => v - tableHalfWidth), - ...[54, 32, 10].map((v) => -v + tableHalfWidth), + ...cupOffsets.map((v) => v - tableHalfWidth), + ...cupOffsets.map((v) => -v + tableHalfWidth), ]; cupPositions.forEach((offsetX) => { const cup = new Cup( diff --git a/src/frontend/src/ScreenElements/Button.ts b/src/frontend/src/ScreenElements/Button.ts index a844d8c..495e519 100644 --- a/src/frontend/src/ScreenElements/Button.ts +++ b/src/frontend/src/ScreenElements/Button.ts @@ -58,7 +58,7 @@ export class Button extends ex.ScreenElement { this.graphics.add( "disabled", makeStyledRectangle(width, height, ex.Color.Gray, false), - ); // this._createButtonGraphic(ex.Color.Gray)); + ); this.graphics.add( "clicked", makeStyledRectangle(width, height, hoverColor, true), @@ -115,11 +115,7 @@ export class Button extends ex.ScreenElement { } this._down = false; - - const { _onClick } = this; - if (_onClick != null) { - _onClick(event); - } + this._onClick?.(event); this._updateGraphic("hover"); } diff --git a/src/frontend/src/ScreenElements/Error.ts b/src/frontend/src/ScreenElements/Error.ts index 880e9d4..754f2c5 100644 --- a/src/frontend/src/ScreenElements/Error.ts +++ b/src/frontend/src/ScreenElements/Error.ts @@ -1,4 +1,11 @@ -import { Color, Engine, Rectangle, ScreenElement, vec } from "excalibur"; +import { + ActorArgs, + Color, + Engine, + Rectangle, + ScreenElement, + vec, +} from "excalibur"; import { Text } from "./Text"; import { paragraphFont } from "../utils/fontUtil"; import { spacingS } from "../utils/formattingUtils"; @@ -8,7 +15,7 @@ interface ErrorScreenElementProperties { width: number; } -type ConstructProperties = Partial & ErrorScreenElementProperties; +type ConstructProperties = Partial & ErrorScreenElementProperties; export class ErrorScreenElement extends ScreenElement { private _text: string; diff --git a/src/frontend/src/ScreenElements/PlayerListScreenElement.ts b/src/frontend/src/ScreenElements/PlayerListScreenElement.ts index 6041318..85cb010 100644 --- a/src/frontend/src/ScreenElements/PlayerListScreenElement.ts +++ b/src/frontend/src/ScreenElements/PlayerListScreenElement.ts @@ -31,7 +31,7 @@ export class PlayerListScreenElement extends ClientListScreenElement { this.entities.push(label); const ready = new Checkbox({ checked: currentClient.ready }); - const textWidth = label.font.measureTextWithoutCache(name ?? "").width; + const textWidth = label.font.measureTextWithoutCache(name).width; ready.pos = ex.vec(textWidth / 2 + spacingS, y); this.addChild(ready); diff --git a/src/frontend/src/Timers/BallClock.ts b/src/frontend/src/Timers/BallClock.ts index d9cc0c0..5d0ec90 100644 --- a/src/frontend/src/Timers/BallClock.ts +++ b/src/frontend/src/Timers/BallClock.ts @@ -1,4 +1,5 @@ -import { Ball, Parabola } from "../GameElements/Ball"; +import { Ball } from "../GameElements/Ball"; +import { Parabola } from "../GameElements/Parabola"; import { assertNotNull } from "../utils/assertUtils"; import { groundHeight } from "../configs/sceneConfiguration"; import { Clock } from "./Clock"; diff --git a/src/frontend/src/Timers/Clock.ts b/src/frontend/src/Timers/Clock.ts index 9838b82..0965fb9 100644 --- a/src/frontend/src/Timers/Clock.ts +++ b/src/frontend/src/Timers/Clock.ts @@ -46,7 +46,7 @@ export class Clock extends Evented { async whenEnd(): Promise { const promise = new Promise((resolve) => { - this.on("end", () => resolve()); + this.once("end", () => resolve()); }); await promise; } diff --git a/src/frontend/src/jsonTypes.ts b/src/frontend/src/jsonTypes.ts index 809363b..426e120 100644 --- a/src/frontend/src/jsonTypes.ts +++ b/src/frontend/src/jsonTypes.ts @@ -10,8 +10,6 @@ export interface LobbyStateRaw { }; } -export type LobbyStateRawReadonly = Readonly; - export interface Player { client: Client; ready: boolean; @@ -31,8 +29,6 @@ export interface MatchStateRaw { }; } -export type MatchStateRawReadonly = Readonly; - export interface Table { cupsA: [boolean, boolean, boolean]; cupsB: [boolean, boolean, boolean]; diff --git a/src/frontend/src/main.ts b/src/frontend/src/main.ts index 06fd7ee..704eace 100644 --- a/src/frontend/src/main.ts +++ b/src/frontend/src/main.ts @@ -12,13 +12,11 @@ import { loadImages } from "./imageLoader"; const urlParams = new URLSearchParams(window.location.search); const mocked = urlParams.get("mock"); -export const maxPlayers = 2; - (async () => { const connection = new Connection(); - const mockSocket = new MockSocket(); - connection.connect(mocked != null ? mockSocket : undefined); + const mockSocket = mocked != null ? new MockSocket() : undefined; + connection.connect(mockSocket); const lobbyScene = new LobbyScene(connection); const matchScene = new MatchScene(connection); @@ -38,11 +36,25 @@ export const maxPlayers = 2; 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()); + if (mocked != null) { + runMockScenario(mocked, connection, mockSocket!); } })(); + +function runMockScenario( + mocked: string, + connection: Connection, + mockSocket: MockSocket, +): void { + if (mocked == null) { + return; + } + + connection.join("Dubbel"); + + if (mocked === "lobby") { + mockSocket.sendToClient(mockLobbyMessage()); + } else if (mocked === "match") { + mockSocket.sendToClient(mockGameMessage()); + } +} diff --git a/src/frontend/src/schemaValidators.ts b/src/frontend/src/schemaValidators.ts index 94166be..6df7aee 100644 --- a/src/frontend/src/schemaValidators.ts +++ b/src/frontend/src/schemaValidators.ts @@ -21,6 +21,7 @@ import tableSchemaFile from "../../schema/match/table.json"; const ajv = new Ajv({ strict: true }); +// Referenced by other schemas via $ref — must be registered before compile. ajv.addSchema(clientSchemaFile, "client.json"); ajv.addSchema(playerSchemaFile, "player.json"); @@ -54,11 +55,10 @@ export function validate( const valid = validateFunction(json); if (!valid) { - log("Connection", "invalid message received", { + log("Validator", "invalid message received", { json, errors: validateFunction.errors, }); - console.log(validateFunction.errors); } return valid; diff --git a/src/frontend/src/sockets/MockSocket.ts b/src/frontend/src/sockets/MockSocket.ts index e3d0c88..ff56b0b 100644 --- a/src/frontend/src/sockets/MockSocket.ts +++ b/src/frontend/src/sockets/MockSocket.ts @@ -21,7 +21,7 @@ export class MockSocket } send(message: string): void { - if (message.includes("join")) { + if (JSON.parse(message).messageType === "join") { this.sendToClient( JSON.stringify({ messageType: "joinResponse", diff --git a/src/frontend/src/utils/Evented.ts b/src/frontend/src/utils/Evented.ts index c54b1e5..9eb8dbf 100644 --- a/src/frontend/src/utils/Evented.ts +++ b/src/frontend/src/utils/Evented.ts @@ -1,8 +1,6 @@ import { assertNotNull } from "./assertUtils"; -export class Event { - constructor() {} -} +export class Event {} // eslint-disable-next-line @typescript-eslint/no-explicit-any type EventCtor = abstract new (...args: any[]) => T; @@ -54,8 +52,12 @@ export class Evented { const index = observers.findIndex((h) => h === handler); - if (index != null) { + if (index !== -1) { observers.splice(index, 1); } } + + offAll(): void { + this._observers = {}; + } } diff --git a/src/frontend/src/utils/constants.ts b/src/frontend/src/utils/constants.ts new file mode 100644 index 0000000..8438b6a --- /dev/null +++ b/src/frontend/src/utils/constants.ts @@ -0,0 +1 @@ +export const maxPlayers = 2; diff --git a/src/frontend/src/utils/debugUtils.ts b/src/frontend/src/utils/debugUtils.ts index ad1cc7d..be39221 100644 --- a/src/frontend/src/utils/debugUtils.ts +++ b/src/frontend/src/utils/debugUtils.ts @@ -1,4 +1,8 @@ -export type LogSource = "Connection" | "LobbyState" | "MatchState"; +export type LogSource = + | "Connection" + | "Validator" + | "LobbyState" + | "MatchState"; // eslint-disable-next-line @typescript-eslint/no-explicit-any export function log(source: LogSource, ...data: any[]): void {