From 84e4fc4e5db19cc85e4eff159ccfcb794eccb649 Mon Sep 17 00:00:00 2001 From: Lucas Habersaat Date: Tue, 3 Mar 2026 20:43:54 +0100 Subject: [PATCH] Frontend - Add a simple timer and animate a match state history (#33) --- src/frontend/src/GameElements/Ball.ts | 85 +++++++--------------- src/frontend/src/GameElements/BaseActor.ts | 15 ++++ src/frontend/src/Scenes/BaseScene.ts | 25 +++++++ src/frontend/src/Scenes/LobbyScene.ts | 3 +- src/frontend/src/Scenes/MatchScene.ts | 69 +++++++++++++++--- src/frontend/src/Timers/BallClock.ts | 36 +++++++++ src/frontend/src/Timers/Clock.ts | 77 ++++++++++++++++++++ src/frontend/src/sockets/MockSocket.ts | 42 +++++++++++ src/frontend/src/utils/Evented.ts | 29 ++++++++ src/frontend/src/utils/assertUtils.ts | 11 ++- 10 files changed, 319 insertions(+), 73 deletions(-) create mode 100644 src/frontend/src/GameElements/BaseActor.ts create mode 100644 src/frontend/src/Scenes/BaseScene.ts create mode 100644 src/frontend/src/Timers/BallClock.ts create mode 100644 src/frontend/src/Timers/Clock.ts diff --git a/src/frontend/src/GameElements/Ball.ts b/src/frontend/src/GameElements/Ball.ts index 2ff1a4b..383bc90 100644 --- a/src/frontend/src/GameElements/Ball.ts +++ b/src/frontend/src/GameElements/Ball.ts @@ -1,7 +1,7 @@ import { - Actor, ActorArgs, Circle, + clamp, Color, Engine, Graphic, @@ -10,8 +10,10 @@ import { vec, Vector, } from "excalibur"; -import { assertNotNull, assertNull } from "../utils/assertUtils"; -import { gravitationalConstant, groundHeight } from "../utils/physicsConstant"; +import { gravitationalConstant } from "../utils/physicsConstant"; +import { Parabola as ParabolaJSON } from "../jsonTypes"; +import { BallClock } from "../Timers/BallClock"; +import { BaseActor } from "./BaseActor"; export const defaultBallConfiguration: BallConfiguration = { color: Color.Orange, @@ -25,15 +27,17 @@ export interface BallConfiguration { const random = new Random(); -export class Ball extends Actor { +export class Ball extends BaseActor { private _graphic: Graphic = null!; - private _animation: BallAnimation = new BallAnimation(this); + private _clock: BallClock = new BallClock(this); constructor( actorArgs: ActorArgs, public readonly configuration: BallConfiguration, ) { super(actorArgs); + + this.addClock(this._clock); } onInitialize(engine: Engine): void { @@ -71,62 +75,12 @@ export class Ball extends Actor { }); } - public update(engine: Engine, elapsed: number): void { - super.update(engine, elapsed); - this._animation.update(elapsed); + get clock(): BallClock { + return this._clock; } startParabolaAnimation(parabola: Parabola): void { - this._animation.start(parabola); - } -} - -class BallAnimation { - private _running: boolean = false; - private _parabola: Parabola | null = null; - private _elapsedTime: number | null = null; - - constructor(private _ball: Ball) {} - - get running(): boolean { - return this._running; - } - - start(parabola: Parabola): void { - this.reset(); - this._parabola = parabola; - this._running = true; - } - - reset(): void { - this._parabola = null; - this._running = false; - this._elapsedTime = null; - - // TODO: Reset ball position? - } - - update(elapsed: number): void { - if (!this.running) { - assertNull(this._parabola); - assertNull(this._elapsedTime); - return; - } - - assertNotNull(this._parabola); - - if (this._elapsedTime == null) { - this._elapsedTime = 0; - } - this._elapsedTime += elapsed; - - const newPosition = this._parabola.position(this._elapsedTime); - - // Collide with ground - const yMin = groundHeight - this._ball.configuration.radius; - newPosition.y = Math.min(yMin, newPosition.y); - - this._ball.pos = newPosition; + this._clock.startWithParabola(parabola); } } @@ -134,10 +88,23 @@ 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 = time / 1000; + const timeSeconds = clamp(time / 1000, 0, this.stopTime ?? Infinity); const x = this.startPos.x + this.startVelocity.x * timeSeconds; const y = diff --git a/src/frontend/src/GameElements/BaseActor.ts b/src/frontend/src/GameElements/BaseActor.ts new file mode 100644 index 0000000..2ba1922 --- /dev/null +++ b/src/frontend/src/GameElements/BaseActor.ts @@ -0,0 +1,15 @@ +import { Actor, Engine } from "excalibur"; +import { Clock } from "../Timers/Clock"; + +export class BaseActor extends Actor { + private _clocks = new Array(); + + override update(engine: Engine, elapsed: number): void { + super.update(engine, elapsed); + this._clocks.forEach((clock) => clock.update(elapsed)); + } + + protected addClock(timer: Clock): void { + this._clocks.push(timer); + } +} diff --git a/src/frontend/src/Scenes/BaseScene.ts b/src/frontend/src/Scenes/BaseScene.ts new file mode 100644 index 0000000..f7bfdd8 --- /dev/null +++ b/src/frontend/src/Scenes/BaseScene.ts @@ -0,0 +1,25 @@ +import { Actor, Engine, Scene } from "excalibur"; +import { Clock } from "../Timers/Clock"; + +export class BaseScene extends Scene { + private _clocks = new Array(); + + override update(engine: Engine, elapsed: number): void { + super.update(engine, elapsed); + this._clocks.forEach((clock) => clock.update(elapsed)); + } + + protected addClock(timer: Clock): void { + this._clocks.push(timer); + } + + protected updateActorVisibility(actor: Actor, visible: boolean): void { + const previousVisible = this.actors.includes(actor); + + if (visible && !previousVisible) { + this.add(actor); + } else if (!visible && previousVisible) { + this.remove(actor); + } + } +} diff --git a/src/frontend/src/Scenes/LobbyScene.ts b/src/frontend/src/Scenes/LobbyScene.ts index b41937e..a5c7c39 100644 --- a/src/frontend/src/Scenes/LobbyScene.ts +++ b/src/frontend/src/Scenes/LobbyScene.ts @@ -11,12 +11,13 @@ import { ErrorList } from "../UIElements/ErrorList"; import { LobbyState } from "../LobbyState"; import { maxPlayers } from "../main"; import { Id } from "../jsonTypes"; +import { BaseScene } from "./BaseScene"; const tableWidth = 400; export type Screens = "join" | "lobby"; -export class LobbyScene extends ex.Scene { +export class LobbyScene extends BaseScene { private _table: ex.ScreenElement = null!; private _cups: ex.ScreenElement = null!; diff --git a/src/frontend/src/Scenes/MatchScene.ts b/src/frontend/src/Scenes/MatchScene.ts index 0371862..c36678f 100644 --- a/src/frontend/src/Scenes/MatchScene.ts +++ b/src/frontend/src/Scenes/MatchScene.ts @@ -1,24 +1,45 @@ -import { Connection } from "../Connection"; +import { Connection, MatchMessageEvent } from "../Connection"; import { Ground, groundColor } from "../GameElements/Ground"; -import { defaultTableConfiguration, Table } from "../GameElements/Table"; +import { + defaultTableConfiguration, + Table as TableElement, +} from "../GameElements/Table"; import { Cup, defaultCupConfiguration } from "../GameElements/Cups"; -import { Color, Scene, vec } from "excalibur"; -import { Ball, defaultBallConfiguration } from "../GameElements/Ball"; +import { Color, vec } from "excalibur"; +import { Ball, defaultBallConfiguration, Parabola } from "../GameElements/Ball"; import { groundHeight } from "../utils/physicsConstant"; import { Champion } from "../GameElements/Champion"; import { randomColor } from "../utils/randomUtils"; import { colorDistance } from "../utils/colorUtils"; +import { MatchState } from "../MatchState"; +import { Action, Table } from "../jsonTypes"; +import { assertNotNull } from "../utils/assertUtils"; +import { Clock } from "../Timers/Clock"; +import { BaseScene } from "./BaseScene"; -export class MatchScene extends Scene { +export class MatchScene extends BaseScene { private _ground: Ground = null!; - private _table: Table = null!; + private _table: TableElement = null!; private _ball: Ball = null!; private _cups: Cup[] = []; private _champions: Champion[] = []; + private _matchClock = new Clock(); + constructor(private _connection: Connection) { super(); + + this.addClock(this._matchClock); + + this._connection.on("match-message", (e: MatchMessageEvent) => { + if (!this.isInitialized) { + this.once("initialize", () => this._playFroMatchState(e.matchState)); + return; + } + + this._playFroMatchState(e.matchState); + }); } // eslint-disable-next-line @typescript-eslint/no-unused-vars @@ -28,7 +49,7 @@ export class MatchScene extends Scene { this._ground = new Ground(); this.add(this._ground); - this._table = new Table( + this._table = new TableElement( { pos: vec(0, groundHeight) }, defaultTableConfiguration, ); @@ -38,8 +59,8 @@ export class MatchScene extends Scene { const tableHeight = this._table.configuration.height; const cupPositions = [ - ...[10, 32, 54].map((v) => v - tableHalfWidth), - ...[10, 32, 54].map((v) => -v + tableHalfWidth), + ...[54, 32, 10].map((v) => v - tableHalfWidth), + ...[54, 32, 10].map((v) => -v + tableHalfWidth), ]; cupPositions.forEach((offsetX) => { const cup = new Cup( @@ -68,7 +89,35 @@ export class MatchScene extends Scene { }); this._ball = new Ball({}, defaultBallConfiguration); - this.add(this._ball); + } + + private async _playFroMatchState(state: MatchState): Promise { + for (const actionOrTable of state.matchStateRaw.history) { + if ("cupsA" in actionOrTable) { + this._updateFromTableState(actionOrTable); + await this._matchClock.startAndWait(2000); + } else { + this.updateActorVisibility(this._ball, true); + this._updateFromActionState(actionOrTable); + await this._ball.clock.whenEnd(); + await this._matchClock.startAndWait(1000); + this.updateActorVisibility(this._ball, false); + } + } + } + + private _updateFromTableState(table: Table): void { + const cups = [...table.cupsA, ...table.cupsB]; + cups.forEach((visible, index) => { + const cup = this._cups[index]; + assertNotNull(cup); + this.updateActorVisibility(cup, visible); + }); + } + + private _updateFromActionState(action: Action): void { + const parabola = Parabola.fromJSON(action.parabola); + this._ball.startParabolaAnimation(parabola); } } diff --git a/src/frontend/src/Timers/BallClock.ts b/src/frontend/src/Timers/BallClock.ts new file mode 100644 index 0000000..69781da --- /dev/null +++ b/src/frontend/src/Timers/BallClock.ts @@ -0,0 +1,36 @@ +import { Ball, Parabola } from "../GameElements/Ball"; +import { assertNotNull } from "../utils/assertUtils"; +import { groundHeight } from "../utils/physicsConstant"; +import { Clock } from "./Clock"; + +export class BallClock extends Clock { + private _parabola: Parabola | null = null; + + constructor(private _ball: Ball) { + super(); + } + + startWithParabola(parabola: Parabola): void { + this.start(parabola.stopTime); + this._parabola = parabola; + } + + update(elapsed: number): void { + super.update(elapsed); + + if (!this.running) { + return; + } + + assertNotNull(this._parabola); + + assertNotNull(this._elapsedTime); + const newPosition = this._parabola.position(this._elapsedTime); + + // Collide with ground + const yMin = groundHeight - this._ball.configuration.radius; + newPosition.y = Math.min(yMin, newPosition.y); + + this._ball.pos = newPosition; + } +} diff --git a/src/frontend/src/Timers/Clock.ts b/src/frontend/src/Timers/Clock.ts new file mode 100644 index 0000000..6e57201 --- /dev/null +++ b/src/frontend/src/Timers/Clock.ts @@ -0,0 +1,77 @@ +import { assertNull } from "../utils/assertUtils"; +import { Event, Evented } from "../utils/Evented"; + +export const TimerEvents = { + start: Event, + stop: Event, + end: Event, + reset: Event, +}; + +export class Clock extends Evented { + private _running: boolean = false; + protected _elapsedTime: number | null = null; + + private _duration?: number; + + constructor(duration?: number) { + super(); + this._duration = duration; + } + + get running(): boolean { + return this._running; + } + + start(duration?: number): void { + this.reset(); + if (duration != null) { + this._duration = duration; + } + this._running = true; + this.emit("start", {}); + } + + stop(): void { + this._running = false; + this._elapsedTime = null; + this.emit("stop", {}); + } + + reset(): void { + this._running = false; + this._elapsedTime = null; + this.emit("reset", {}); + } + + async whenEnd(): Promise { + const promise = new Promise((resolve) => { + this.on("end", () => resolve()); + }); + await promise; + } + + async startAndWait(duration?: number): Promise { + this.start(duration); + await this.whenEnd(); + } + + update(elapsed: number): void { + if (!this.running) { + assertNull(this._elapsedTime); + return; + } + + if (this._elapsedTime == null) { + this._elapsedTime = 0; + } + this._elapsedTime += elapsed; + + if (this._duration != null) { + if (this._elapsedTime > this._duration) { + this.stop(); + this.emit("end", {}); + } + } + } +} diff --git a/src/frontend/src/sockets/MockSocket.ts b/src/frontend/src/sockets/MockSocket.ts index 9866af9..5f02fe6 100644 --- a/src/frontend/src/sockets/MockSocket.ts +++ b/src/frontend/src/sockets/MockSocket.ts @@ -56,6 +56,48 @@ export function mockGameMessage(): string { teamA: [0, 1, 2], teamB: [3, 1, 4], }, + { + turn: "b", + parabola: { + startPosition: [150, -200], + startVelocity: [-300, -300], + stopTime: 900, + }, + }, + { + cupsA: [true, true, false], + cupsB: [true, true, true], + teamA: [0, 1, 2], + teamB: [3, 1, 4], + }, + { + turn: "a", + parabola: { + startPosition: [-150, -200], + startVelocity: [300, -300], + stopTime: 900, + }, + }, + { + cupsA: [true, true, false], + cupsB: [true, true, false], + teamA: [0, 1, 2], + teamB: [3, 1, 4], + }, + { + turn: "b", + parabola: { + startPosition: [150, -200], + startVelocity: [-250, -300], + stopTime: 900, + }, + }, + { + cupsA: [false, true, false], + cupsB: [true, true, false], + teamA: [0, 1, 2], + teamB: [3, 1, 4], + }, ], }, }; diff --git a/src/frontend/src/utils/Evented.ts b/src/frontend/src/utils/Evented.ts index b973f0e..c54b1e5 100644 --- a/src/frontend/src/utils/Evented.ts +++ b/src/frontend/src/utils/Evented.ts @@ -1,3 +1,5 @@ +import { assertNotNull } from "./assertUtils"; + export class Event { constructor() {} } @@ -29,4 +31,31 @@ export class Evented { ): void { this._observers[eventName]?.forEach((observer) => observer(event)); } + + once>( + eventName: K, + handler: EventHandlers[K], + ): void { + const observer = (this._observers[eventName] ??= []); + const wrappedHandler: EventHandlers[K] = (e) => { + handler(e); + this.off(eventName, wrappedHandler); + }; + + observer.push(wrappedHandler); + } + + off>( + eventName: K, + handler: EventHandlers[K], + ): void { + const observers = this._observers[eventName]; + assertNotNull(observers); + + const index = observers.findIndex((h) => h === handler); + + if (index != null) { + observers.splice(index, 1); + } + } } diff --git a/src/frontend/src/utils/assertUtils.ts b/src/frontend/src/utils/assertUtils.ts index 0598d2f..7628cc9 100644 --- a/src/frontend/src/utils/assertUtils.ts +++ b/src/frontend/src/utils/assertUtils.ts @@ -10,8 +10,13 @@ export function assertNull(obj: T | null): asserts obj is null { } } -export function assertNotNull(obj: T | null): asserts obj is T { - if (obj == null) { - throw new Error("Assertion failed"); +export function assertNotNull( + expression: T, + message?: string, +): asserts expression is NonNullable { + if (expression == null) { + throw new Error( + `Assertion failed. Value is null or undefined. ${message ?? ""}`, + ); } }