Frontend - Claude found some bugs (#41)

This commit is contained in:
lucas authored and GitHub committed 2026-05-04 20:06:36 +02:00
1 parent 72e6cb10ed
commit 9a3851f802
22 files changed
+168 -153

No files matched your search

+15 -7
View File
@@ -8,7 +8,6 @@ import { log } from "./utils/debugUtils";
import { Event, Evented } from "./utils/Evented"; import { Event, Evented } from "./utils/Evented";
import { MatchState } from "./MatchState"; import { MatchState } from "./MatchState";
import { BaseSocket, MessageEvent } from "./sockets/BaseSocket"; import { BaseSocket, MessageEvent } from "./sockets/BaseSocket";
import { MockSocket } from "./sockets/MockSocket";
import { Socket } from "./sockets/Socket"; import { Socket } from "./sockets/Socket";
type MessageType = "join" | "rejoin" | "toggleRole" | "toggleReady"; type MessageType = "join" | "rejoin" | "toggleRole" | "toggleReady";
@@ -33,10 +32,12 @@ interface RejoinRequest {
interface ToggleRoleRequest { interface ToggleRoleRequest {
messageType: "toggleRole"; messageType: "toggleRole";
messageContent: Record<string, never>;
} }
interface ToggleReadyRequest { interface ToggleReadyRequest {
messageType: "toggleReady"; messageType: "toggleReady";
messageContent: Record<string, never>;
} }
export class LobbyMessageEvent extends Event { export class LobbyMessageEvent extends Event {
@@ -71,7 +72,7 @@ export const ConnectionEvents = {
export class Connection extends Evented<typeof ConnectionEvents> { export class Connection extends Evented<typeof ConnectionEvents> {
private _socket: BaseSocket | null = null; private _socket: BaseSocket | null = null;
private _connected = false; private _wasConnected = false;
private _waitForJoin = false; private _waitForJoin = false;
private _client: Client | null = null; private _client: Client | null = null;
@@ -80,7 +81,8 @@ export class Connection extends Evented<typeof ConnectionEvents> {
return this._socket?.connected ?? false; return this._socket?.connected ?? false;
} }
connect(mock?: MockSocket): void { connect(mock?: BaseSocket): void {
this._socket?.offAll();
this._socket = mock ?? new Socket(); this._socket = mock ?? new Socket();
this._socket.on("open", () => this._onConnect()); this._socket.on("open", () => this._onConnect());
@@ -96,8 +98,14 @@ export class Connection extends Evented<typeof ConnectionEvents> {
const messageObject = JSON.parse(message.json); const messageObject = JSON.parse(message.json);
if (this._waitForJoin) { 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); storeClient(this._client);
this._waitForJoin = false; this._waitForJoin = false;
this.emit("joined", new JoinedEvent()); this.emit("joined", new JoinedEvent());
return; return;
@@ -129,7 +137,7 @@ export class Connection extends Evented<typeof ConnectionEvents> {
private _onConnect(): void { private _onConnect(): void {
log("Connection", "connected"); log("Connection", "connected");
this._connected = true; this._wasConnected = true;
this.emit("connect", new ConnectEvent()); this.emit("connect", new ConnectEvent());
this.emit("connect-or-disconnect", new ConnectOrDisconnectEvent(true)); this.emit("connect-or-disconnect", new ConnectOrDisconnectEvent(true));
@@ -140,8 +148,8 @@ export class Connection extends Evented<typeof ConnectionEvents> {
// The socket close event is also invoked when a connection attempt fails. // The socket close event is also invoked when a connection attempt fails.
// Only emit the disconnect event when we actually had a connection. // Only emit the disconnect event when we actually had a connection.
if (this._connected) { if (this._wasConnected) {
this._connected = false; this._wasConnected = false;
this.emit("disconnect", new DisconnectEvent()); this.emit("disconnect", new DisconnectEvent());
this.emit("connect-or-disconnect", new ConnectOrDisconnectEvent(false)); this.emit("connect-or-disconnect", new ConnectOrDisconnectEvent(false));
} }
+7 -7
View File
@@ -6,24 +6,24 @@ const margin = 2;
export class Cups extends ex.Graphic { export class Cups extends ex.Graphic {
protected _drawImage( protected _drawImage(
context: ex.ExcaliburGraphicsContext, context: ex.ExcaliburGraphicsContext,
x: number, _x: number,
y: number, y: number,
): void { ): void {
y += radius; let currentY = y + radius;
for (let r = 4; r > 0; r--) { for (let r = 4; r > 0; r--) {
x = -r * radius + radius; let currentX = -r * radius + radius;
for (let c = 0; c < r; c++) { for (let c = 0; c < r; c++) {
context.drawCircle( context.drawCircle(
ex.vec(x, y), ex.vec(currentX, currentY),
radius, radius,
ex.Color.Red, ex.Color.Red,
ex.Color.White, ex.Color.White,
2, 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(); return new Cups();
} }
get computeHeight(): number { get computedHeight(): number {
return 4 * 2 * radius + 3 * margin; return 4 * 2 * radius + 3 * margin;
} }
} }
+3 -37
View File
@@ -1,7 +1,6 @@
import { import {
ActorArgs, ActorArgs,
Circle, Circle,
clamp,
Color, Color,
Engine, Engine,
Graphic, Graphic,
@@ -10,10 +9,9 @@ import {
vec, vec,
Vector, Vector,
} from "excalibur"; } from "excalibur";
import { gravitationalConstant } from "../configs/physicsConstant";
import { Parabola as ParabolaJSON } from "../jsonTypes";
import { BallClock } from "../Timers/BallClock"; import { BallClock } from "../Timers/BallClock";
import { BaseActor } from "./BaseActor"; import { BaseActor } from "./BaseActor";
import { Parabola } from "./Parabola";
export const defaultBallConfiguration: BallConfiguration = { export const defaultBallConfiguration: BallConfiguration = {
color: Color.Orange, color: Color.Orange,
@@ -45,7 +43,7 @@ export class Ball extends BaseActor {
const { radius } = configuration; const { radius } = configuration;
const ballGraphic = new Circle({ const ballGraphic = new Circle({
radius: radius, radius,
color: configuration.color, color: configuration.color,
}); });
@@ -56,7 +54,7 @@ export class Ball extends BaseActor {
this._graphic = new GraphicsGroup({ this._graphic = new GraphicsGroup({
members: [ members: [
{ graphic: ballGraphic, offset: vec(0, 0) }, { graphic: ballGraphic, offset: Vector.Zero },
{ graphic: specularGraphic, offset: vec(radius / 2, radius / 2) }, { graphic: specularGraphic, offset: vec(radius / 2, radius / 2) },
], ],
}); });
@@ -83,35 +81,3 @@ export class Ball extends BaseActor {
this._clock.startWithParabola(parabola); 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);
}
}
+1 -1
View File
@@ -2,7 +2,7 @@ import { Actor, Engine } from "excalibur";
import { Clock } from "../Timers/Clock"; import { Clock } from "../Timers/Clock";
export class BaseActor extends Actor { export class BaseActor extends Actor {
private _clocks = new Array<Clock>(); private _clocks: Clock[] = [];
override update(engine: Engine, elapsed: number): void { override update(engine: Engine, elapsed: number): void {
super.update(engine, elapsed); super.update(engine, elapsed);
+35
View File
@@ -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);
}
}
+9 -9
View File
@@ -1,19 +1,19 @@
import { import {
Client, Client,
LobbyStateRawReadonly,
Id, Id,
LobbyStateRaw,
Player, Player,
Spectator, Spectator,
getClient, getClient,
} from "./jsonTypes"; } from "./jsonTypes";
import { maxPlayers } from "./main"; import { maxPlayers } from "./utils/constants";
import { log } from "./utils/debugUtils"; import { log } from "./utils/debugUtils";
export class LobbyState { export class LobbyState {
_errors: string[] = []; private _errors: string[] = [];
constructor( constructor(
public readonly lobbyStateRaw: LobbyStateRawReadonly, private readonly _lobbyStateRaw: LobbyStateRaw,
readonly client: Client, readonly client: Client,
) { ) {
this._validate(); this._validate();
@@ -34,11 +34,11 @@ export class LobbyState {
} }
get players(): Player[] { get players(): Player[] {
return this.lobbyStateRaw.messageContent.players; return this._lobbyStateRaw.messageContent.players;
} }
get spectators(): Spectator[] { get spectators(): Spectator[] {
return this.lobbyStateRaw.messageContent.spectators; return this._lobbyStateRaw.messageContent.spectators;
} }
get isFull(): boolean { get isFull(): boolean {
@@ -46,15 +46,15 @@ export class LobbyState {
} }
get isPlayer(): boolean { 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 { get isReady(): boolean {
return this.getPlayerById(this.client.id)!.ready; return this.getPlayerById(this.client.id)?.ready ?? false;
} }
get isSpectator(): boolean { 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 { getPlayerById(id: Id): Player | undefined {
+3 -3
View File
@@ -1,11 +1,11 @@
import { Client, MatchStateRawReadonly } from "./jsonTypes"; import { Client, MatchStateRaw } from "./jsonTypes";
import { log } from "./utils/debugUtils"; import { log } from "./utils/debugUtils";
export class MatchState { export class MatchState {
_errors: string[] = []; private _errors: string[] = [];
constructor( constructor(
public readonly matchStateRaw: MatchStateRawReadonly, public readonly matchStateRaw: MatchStateRaw,
readonly client: Client, readonly client: Client,
) { ) {
this._validate(); this._validate();
+2 -2
View File
@@ -9,8 +9,8 @@ export class BaseScene extends Scene {
this._clocks.forEach((clock) => clock.update(elapsed)); this._clocks.forEach((clock) => clock.update(elapsed));
} }
addClock(timer: Clock): void { addClock(clock: Clock): void {
this._clocks.push(timer); this._clocks.push(clock);
} }
protected updateActorVisibility(actor: Actor, visible: boolean): void { protected updateActorVisibility(actor: Actor, visible: boolean): void {
+32 -48
View File
@@ -9,9 +9,9 @@ import { Connection, LobbyMessageEvent } from "../Connection";
import { Title } from "../UIElements/Title"; import { Title } from "../UIElements/Title";
import { ErrorList } from "../UIElements/ErrorList"; import { ErrorList } from "../UIElements/ErrorList";
import { LobbyState } from "../LobbyState"; import { LobbyState } from "../LobbyState";
import { maxPlayers } from "../main";
import { Id } from "../jsonTypes"; import { Id } from "../jsonTypes";
import { BaseScene } from "./BaseScene"; import { BaseScene } from "./BaseScene";
import { maxPlayers } from "../utils/constants";
const tableWidth = 400; const tableWidth = 400;
@@ -41,20 +41,11 @@ export class LobbyScene extends BaseScene {
private _errorList: ErrorList = null!; private _errorList: ErrorList = null!;
private _noConnectionErrorHandle: (() => void) | null = null; private _noConnectionErrorHandle: (() => void) | null = null;
private _screen: "join" | "lobby" = "join"; private _screen: Screens = "join";
private _gameState?: LobbyState; private _gameState?: LobbyState;
constructor(private _connection: Connection) { constructor(private _connection: Connection) {
super(); 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 { onInitialize(engine: ex.Engine): void {
@@ -102,7 +93,7 @@ export class LobbyScene extends BaseScene {
this._joinPlayerButton = new Button({ this._joinPlayerButton = new Button({
text: "Join as player", text: "Join as player",
anchor: ex.vec(0.5, 0), anchor: ex.vec(0.5, 0),
onClick: () => this._joinAsPlayer(), onClick: () => this._connection.toggleRole(),
}); });
this._spectatorsList = new ClientListScreenElement("Spectators"); this._spectatorsList = new ClientListScreenElement("Spectators");
@@ -111,27 +102,27 @@ export class LobbyScene extends BaseScene {
this._joinSpectatorButton = new Button({ this._joinSpectatorButton = new Button({
text: "Join as spectator", text: "Join as spectator",
anchor: ex.vec(0.5, 0), anchor: ex.vec(0.5, 0),
onClick: () => this._joinAsSpectator(), onClick: () => this._connection.toggleRole(),
}); });
this._readyButton = new Button({ this._readyButton = new Button({
text: "I'm Ready", text: "I'm Ready",
anchor: ex.vec(0.5, 0), anchor: ex.vec(0.5, 0),
color: ex.Color.Green, color: ex.Color.Green,
onClick: () => this._ready(), onClick: () => this._connection.toggleReady(),
}); });
this._unreadyButton = new Button({ this._unreadyButton = new Button({
text: "Not Ready", text: "Not Ready",
anchor: ex.vec(0.5, 0), anchor: ex.vec(0.5, 0),
color: ex.Color.Red, color: ex.Color.Red,
onClick: () => this._unready(), onClick: () => this._connection.toggleReady(),
}); });
// Name input // Name input
this._playerNameInput = new PlayerNameInput( this._playerNameInput = new PlayerNameInput(
this._connection, this._connection,
(name: string) => this._join(name), (name: string) => this._connection.join(name),
(id: Id) => this._rejoin(id), (id: Id) => this._connection.rejoin(id),
); );
this._playerNameInput.anchor = ex.vec(0.5, 0); this._playerNameInput.anchor = ex.vec(0.5, 0);
@@ -145,12 +136,30 @@ export class LobbyScene extends BaseScene {
this.add(this._errorList); this.add(this._errorList);
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. // Wait for two seconds before displaying an error.
const errorTimeout = setTimeout(() => { errorTimeout = setTimeout(() => {
this._noConnectionErrorHandle = this._errorList.addError( this._noConnectionErrorHandle = this._errorList.addError(
"No server connection", "No server connection",
); );
}, 2000); }, 2000);
}
this._connection.on("connect-or-disconnect", ({ connected }) => { this._connection.on("connect-or-disconnect", ({ connected }) => {
if (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 // eslint-disable-next-line @typescript-eslint/no-unused-vars
@@ -194,9 +201,10 @@ export class LobbyScene extends BaseScene {
const isPlayer = gameState?.isPlayer ?? false; const isPlayer = gameState?.isPlayer ?? false;
const isSpectator = gameState?.isSpectator ?? false; const isSpectator = gameState?.isSpectator ?? false;
const isReadyVisible = isPlayer && (gameState?.isReady ?? false);
const isNotReadyVisible = const readyState = isPlayer ? (gameState?.isReady ?? false) : null;
isPlayer && ((gameState != null && !gameState.isReady) ?? false); const isReadyVisible = readyState === true;
const isNotReadyVisible = readyState === false;
const isLobbyFull = gameState?.isFull ?? false; const isLobbyFull = gameState?.isFull ?? false;
this.updateActorVisibility(this._playerNameInput, isJoinScreen); this.updateActorVisibility(this._playerNameInput, isJoinScreen);
@@ -231,7 +239,7 @@ export class LobbyScene extends BaseScene {
this._cups.pos = ex.vec(halfWidth, y); this._cups.pos = ex.vec(halfWidth, y);
const cups = this._cups.graphics.getGraphic("default") as Cups; const cups = this._cups.graphics.getGraphic("default") as Cups;
y += cups.computeHeight! + spacingM; y += cups.computedHeight + spacingM;
this._bar1.pos = ex.vec(halfWidth, y); this._bar1.pos = ex.vec(halfWidth, y);
y += this._bar1.height + spacingM; y += this._bar1.height + spacingM;
@@ -283,28 +291,4 @@ export class LobbyScene extends BaseScene {
this._updatePositions(); this._updatePositions();
this._updateVisibility(); 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();
}
} }
+9 -6
View File
@@ -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 { Champion } from "../GameElements/Champion";
import { Cup, defaultCupConfiguration } from "../GameElements/Cups"; import { Cup, defaultCupConfiguration } from "../GameElements/Cups";
import { Ground, groundColor } from "../GameElements/Ground"; import { Ground, groundColor } from "../GameElements/Ground";
@@ -17,6 +14,12 @@ import { assertNotNull, assertNull } from "../utils/assertUtils";
import { colorDistance } from "../utils/colorUtils"; import { colorDistance } from "../utils/colorUtils";
import { randomColor, randomInteger } from "../utils/randomUtils"; import { randomColor, randomInteger } from "../utils/randomUtils";
import { BaseScene } from "./BaseScene"; 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; const speedUpFactor = 3;
@@ -48,7 +51,7 @@ export class MatchScene extends BaseScene {
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars // 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.camera.pos.setTo(0, 0);
this._ground = new Ground(); this._ground = new Ground();
@@ -64,8 +67,8 @@ export class MatchScene extends BaseScene {
const tableHeight = this._table.configuration.height; const tableHeight = this._table.configuration.height;
const cupPositions = [ const cupPositions = [
...[54, 32, 10].map((v) => v - tableHalfWidth), ...cupOffsets.map((v) => v - tableHalfWidth),
...[54, 32, 10].map((v) => -v + tableHalfWidth), ...cupOffsets.map((v) => -v + tableHalfWidth),
]; ];
cupPositions.forEach((offsetX) => { cupPositions.forEach((offsetX) => {
const cup = new Cup( const cup = new Cup(
+2 -6
View File
@@ -58,7 +58,7 @@ export class Button extends ex.ScreenElement {
this.graphics.add( this.graphics.add(
"disabled", "disabled",
makeStyledRectangle(width, height, ex.Color.Gray, false), makeStyledRectangle(width, height, ex.Color.Gray, false),
); // this._createButtonGraphic(ex.Color.Gray)); );
this.graphics.add( this.graphics.add(
"clicked", "clicked",
makeStyledRectangle(width, height, hoverColor, true), makeStyledRectangle(width, height, hoverColor, true),
@@ -115,11 +115,7 @@ export class Button extends ex.ScreenElement {
} }
this._down = false; this._down = false;
this._onClick?.(event);
const { _onClick } = this;
if (_onClick != null) {
_onClick(event);
}
this._updateGraphic("hover"); this._updateGraphic("hover");
} }
+9 -2
View File
@@ -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 { Text } from "./Text";
import { paragraphFont } from "../utils/fontUtil"; import { paragraphFont } from "../utils/fontUtil";
import { spacingS } from "../utils/formattingUtils"; import { spacingS } from "../utils/formattingUtils";
@@ -8,7 +15,7 @@ interface ErrorScreenElementProperties {
width: number; width: number;
} }
type ConstructProperties = Partial<ex.ActorArgs> & ErrorScreenElementProperties; type ConstructProperties = Partial<ActorArgs> & ErrorScreenElementProperties;
export class ErrorScreenElement extends ScreenElement { export class ErrorScreenElement extends ScreenElement {
private _text: string; private _text: string;
@@ -31,7 +31,7 @@ export class PlayerListScreenElement extends ClientListScreenElement {
this.entities.push(label); this.entities.push(label);
const ready = new Checkbox({ checked: currentClient.ready }); 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); ready.pos = ex.vec(textWidth / 2 + spacingS, y);
this.addChild(ready); this.addChild(ready);
+2 -1
View File
@@ -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 { assertNotNull } from "../utils/assertUtils";
import { groundHeight } from "../configs/sceneConfiguration"; import { groundHeight } from "../configs/sceneConfiguration";
import { Clock } from "./Clock"; import { Clock } from "./Clock";
+1 -1
View File
@@ -46,7 +46,7 @@ export class Clock extends Evented<typeof TimerEvents> {
async whenEnd(): Promise<void> { async whenEnd(): Promise<void> {
const promise = new Promise<void>((resolve) => { const promise = new Promise<void>((resolve) => {
this.on("end", () => resolve()); this.once("end", () => resolve());
}); });
await promise; await promise;
} }
-4
View File
@@ -10,8 +10,6 @@ export interface LobbyStateRaw {
}; };
} }
export type LobbyStateRawReadonly = Readonly<LobbyStateRaw>;
export interface Player { export interface Player {
client: Client; client: Client;
ready: boolean; ready: boolean;
@@ -31,8 +29,6 @@ export interface MatchStateRaw {
}; };
} }
export type MatchStateRawReadonly = Readonly<MatchStateRaw>;
export interface Table { export interface Table {
cupsA: [boolean, boolean, boolean]; cupsA: [boolean, boolean, boolean];
cupsB: [boolean, boolean, boolean]; cupsB: [boolean, boolean, boolean];
+22 -10
View File
@@ -12,13 +12,11 @@ import { loadImages } from "./imageLoader";
const urlParams = new URLSearchParams(window.location.search); const urlParams = new URLSearchParams(window.location.search);
const mocked = urlParams.get("mock"); const mocked = urlParams.get("mock");
export const maxPlayers = 2;
(async () => { (async () => {
const connection = new Connection(); const connection = new Connection();
const mockSocket = new MockSocket(); const mockSocket = mocked != null ? new MockSocket() : undefined;
connection.connect(mocked != null ? mockSocket : undefined); connection.connect(mockSocket);
const lobbyScene = new LobbyScene(connection); const lobbyScene = new LobbyScene(connection);
const matchScene = new MatchScene(connection); const matchScene = new MatchScene(connection);
@@ -38,11 +36,25 @@ export const maxPlayers = 2;
connection.on("lobby-message", () => game.goToScene("lobby")); connection.on("lobby-message", () => game.goToScene("lobby"));
connection.on("match-message", () => game.goToScene("match")); connection.on("match-message", () => game.goToScene("match"));
if (mocked === "lobby") { if (mocked != null) {
connection.join("Dubbel"); runMockScenario(mocked, connection, mockSocket!);
mockSocket.sendToClient(mockLobbyMessage());
} else if (mocked === "match") {
connection.join("Dubbel");
mockSocket.sendToClient(mockGameMessage());
} }
})(); })();
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());
}
}
+2 -2
View File
@@ -21,6 +21,7 @@ import tableSchemaFile from "../../schema/match/table.json";
const ajv = new Ajv({ strict: true }); const ajv = new Ajv({ strict: true });
// Referenced by other schemas via $ref — must be registered before compile.
ajv.addSchema(clientSchemaFile, "client.json"); ajv.addSchema(clientSchemaFile, "client.json");
ajv.addSchema(playerSchemaFile, "player.json"); ajv.addSchema(playerSchemaFile, "player.json");
@@ -54,11 +55,10 @@ export function validate(
const valid = validateFunction(json); const valid = validateFunction(json);
if (!valid) { if (!valid) {
log("Connection", "invalid message received", { log("Validator", "invalid message received", {
json, json,
errors: validateFunction.errors, errors: validateFunction.errors,
}); });
console.log(validateFunction.errors);
} }
return valid; return valid;
+1 -1
View File
@@ -21,7 +21,7 @@ export class MockSocket
} }
send(message: string): void { send(message: string): void {
if (message.includes("join")) { if (JSON.parse(message).messageType === "join") {
this.sendToClient( this.sendToClient(
JSON.stringify({ JSON.stringify({
messageType: "joinResponse", messageType: "joinResponse",
+6 -4
View File
@@ -1,8 +1,6 @@
import { assertNotNull } from "./assertUtils"; import { assertNotNull } from "./assertUtils";
export class Event { export class Event {}
constructor() {}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
type EventCtor<T extends Event = Event> = abstract new (...args: any[]) => T; type EventCtor<T extends Event = Event> = abstract new (...args: any[]) => T;
@@ -54,8 +52,12 @@ export class Evented<E extends Events> {
const index = observers.findIndex((h) => h === handler); const index = observers.findIndex((h) => h === handler);
if (index != null) { if (index !== -1) {
observers.splice(index, 1); observers.splice(index, 1);
} }
} }
offAll(): void {
this._observers = {};
}
} }
+1
View File
@@ -0,0 +1 @@
export const maxPlayers = 2;
+5 -1
View File
@@ -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 // eslint-disable-next-line @typescript-eslint/no-explicit-any
export function log(source: LogSource, ...data: any[]): void { export function log(source: LogSource, ...data: any[]): void {