Frontend - Add a simple timer and animate a match state history (#33)

This commit is contained in:
lucas authored and GitHub committed 2026-03-03 20:43:54 +01:00
1 parent 214e1bb3c4
commit 84e4fc4e5d
10 files changed
+319 -73

No files matched your search

+26 -59
View File
@@ -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 =
@@ -0,0 +1,15 @@
import { Actor, Engine } from "excalibur";
import { Clock } from "../Timers/Clock";
export class BaseActor extends Actor {
private _clocks = new Array<Clock>();
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);
}
}
+25
View File
@@ -0,0 +1,25 @@
import { Actor, Engine, Scene } from "excalibur";
import { Clock } from "../Timers/Clock";
export class BaseScene extends Scene {
private _clocks = new Array<Clock>();
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);
}
}
}
+2 -1
View File
@@ -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!;
+59 -10
View File
@@ -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<void> {
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);
}
}
+36
View File
@@ -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;
}
}
+77
View File
@@ -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<typeof TimerEvents> {
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<void> {
const promise = new Promise<void>((resolve) => {
this.on("end", () => resolve());
});
await promise;
}
async startAndWait(duration?: number): Promise<void> {
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", {});
}
}
}
}
+42
View File
@@ -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],
},
],
},
};
+29
View File
@@ -1,3 +1,5 @@
import { assertNotNull } from "./assertUtils";
export class Event {
constructor() {}
}
@@ -29,4 +31,31 @@ export class Evented<E extends Events> {
): void {
this._observers[eventName]?.forEach((observer) => observer(event));
}
once<K extends keyof EventHandlers<E>>(
eventName: K,
handler: EventHandlers<E>[K],
): void {
const observer = (this._observers[eventName] ??= []);
const wrappedHandler: EventHandlers<E>[K] = (e) => {
handler(e);
this.off(eventName, wrappedHandler);
};
observer.push(wrappedHandler);
}
off<K extends keyof EventHandlers<E>>(
eventName: K,
handler: EventHandlers<E>[K],
): void {
const observers = this._observers[eventName];
assertNotNull(observers);
const index = observers.findIndex((h) => h === handler);
if (index != null) {
observers.splice(index, 1);
}
}
}
+8 -3
View File
@@ -10,8 +10,13 @@ export function assertNull<T>(obj: T | null): asserts obj is null {
}
}
export function assertNotNull<T>(obj: T | null): asserts obj is T {
if (obj == null) {
throw new Error("Assertion failed");
export function assertNotNull<T>(
expression: T,
message?: string,
): asserts expression is NonNullable<T> {
if (expression == null) {
throw new Error(
`Assertion failed. Value is null or undefined. ${message ?? ""}`,
);
}
}