diff --git a/src/frontend/public/assets/berset_idle.png b/src/frontend/public/assets/berset_idle.png new file mode 100644 index 0000000..9570e20 Binary files /dev/null and b/src/frontend/public/assets/berset_idle.png differ diff --git a/src/frontend/public/assets/berset_shoot.png b/src/frontend/public/assets/berset_shoot.png new file mode 100644 index 0000000..dbfdcb7 Binary files /dev/null and b/src/frontend/public/assets/berset_shoot.png differ diff --git a/src/frontend/public/assets/lucas_idle.png b/src/frontend/public/assets/lucas_idle.png new file mode 100644 index 0000000..e11c389 Binary files /dev/null and b/src/frontend/public/assets/lucas_idle.png differ diff --git a/src/frontend/public/assets/lucas_shoot.png b/src/frontend/public/assets/lucas_shoot.png new file mode 100644 index 0000000..43e787c Binary files /dev/null and b/src/frontend/public/assets/lucas_shoot.png differ diff --git a/src/frontend/src/GameElements/Ball.ts b/src/frontend/src/GameElements/Ball.ts index 383bc90..f7781b8 100644 --- a/src/frontend/src/GameElements/Ball.ts +++ b/src/frontend/src/GameElements/Ball.ts @@ -10,7 +10,7 @@ import { vec, Vector, } from "excalibur"; -import { gravitationalConstant } from "../utils/physicsConstant"; +import { gravitationalConstant } from "../configs/physicsConstant"; import { Parabola as ParabolaJSON } from "../jsonTypes"; import { BallClock } from "../Timers/BallClock"; import { BaseActor } from "./BaseActor"; diff --git a/src/frontend/src/GameElements/Champion.ts b/src/frontend/src/GameElements/Champion.ts index 1337df6..8aababb 100644 --- a/src/frontend/src/GameElements/Champion.ts +++ b/src/frontend/src/GameElements/Champion.ts @@ -1,144 +1,77 @@ -import { - Actor, - ActorArgs, - Color, - Engine, - Graphic, - GraphicsGroup, - Line, - Polygon, - vec, -} from "excalibur"; -import { pixelsPerMeter } from "../utils/physicsConstant"; -import { jitterVector, randomInteger } from "../utils/randomUtils"; +import { ActorArgs, Engine, Sprite, vec } from "excalibur"; +import { pixelsPerMeter } from "../configs/physicsConstant"; +import { randomInteger } from "../utils/randomUtils"; +import { getImage } from "../imageLoader"; +import { Clock } from "../Timers/Clock"; +import { BaseActor } from "./BaseActor"; +import { ChampionName, champions } from "./champions"; -const jiggleTime = 500; +type Facing = "left" | "right"; -export class Champion extends Actor { - private _graphic: Graphic = null!; +export class Champion extends BaseActor { + facing: Facing; + championName: ChampionName; - private _jiggleTimer = randomInteger(0, 1000); - - constructor(actorArgs: ActorArgs) { + constructor(actorArgs: ActorArgs, facing: Facing, name: ChampionName) { super(actorArgs); + this.facing = facing; + this.championName = name; } // eslint-disable-next-line @typescript-eslint/no-unused-vars onInitialize(_engine: Engine): void { - const height = 1.4 * pixelsPerMeter; - const width = 0.4 * pixelsPerMeter; - const waistHeight = 0.3 * pixelsPerMeter; - const jitterMag = 0.1 * pixelsPerMeter; - const headSize = 0.5 * pixelsPerMeter; + const championConfig = champions[this.championName]; - const bodyPoints = [ - jitterVector(vec(-width / 2, waistHeight), jitterMag), - jitterVector(vec(-width / 2, height), jitterMag), - jitterVector(vec(width / 2, height), jitterMag), - jitterVector(vec(width / 2, waistHeight), jitterMag), - ]; + const height = championConfig.height * pixelsPerMeter; + const width = 0.8 * pixelsPerMeter; - const bodyGraphic = new Polygon({ - points: bodyPoints, - color: this.color, + this.anchor = vec(0.5, 0.95); + const flipHorizontal = this.facing === "right"; + + const idleImage = getImage(`${this.championName}_idle`); + const shootImage = getImage(`${this.championName}_shoot`); + + const idleGraphic = new Sprite({ + image: idleImage, + flipHorizontal, + destSize: { + width: width, + height: width + height, + }, }); - const leftLeg = new Line({ - start: bodyPoints[0], - end: vec(bodyPoints[0].x, 0), - thickness: 5, - color: Color.Black, + const shootGraphic = new Sprite({ + image: shootImage, + flipHorizontal, + destSize: { + width: width, + height: width + height, + }, }); - const rightLeg = new Line({ - start: bodyPoints[3], - end: vec(bodyPoints[3].x, 0), - thickness: 5, - color: Color.Black, - }); + this.graphics.add("idle", idleGraphic); + this.graphics.add("shoot", shootGraphic); + this.setPose("idle"); - const headPoints = [ - jitterVector(vec(-headSize / 2, 0), jitterMag), - jitterVector(vec(-headSize / 2, headSize), jitterMag), - jitterVector(vec(headSize / 2, headSize), jitterMag), - jitterVector(vec(headSize / 2, 0), jitterMag), - ]; - const headGraphic = new Polygon({ - points: headPoints, - color: this.color, - }); + this.rotation = (Math.PI / 180) * 1; - this.anchor = vec(0.5, 1); - this._graphic = new GraphicsGroup({ - members: [ - { graphic: leftLeg, offset: vec(0, -waistHeight) }, - { graphic: rightLeg, offset: vec(0, -waistHeight) }, - { graphic: bodyGraphic, offset: vec(-width / 2, -height) }, - { - graphic: headGraphic, - offset: vec(-headSize / 2, -height - headSize / 2), - }, - { - graphic: smileEyeGraphic.clone(), - offset: vec(-headSize / 4, -height), - }, - { - graphic: smileEyeGraphic.clone(), - offset: vec(headSize / 4, -height), - }, - ], - useAnchor: false, - }); - - this.graphics.add(this._graphic); - - this.rotation = (Math.PI / 180) * 5; + this._setupJiggle(); } - update(_engine: Engine, elapsed: number): void { - this._jiggle(elapsed); - } + private _setupJiggle(): void { + const jiggleClock = new Clock(); + jiggleClock.start(randomInteger(0, 1000)); - private _jiggle(elapsed: number): void { - this._jiggleTimer += elapsed; - if (this._jiggleTimer > jiggleTime) { - this._jiggleTimer -= jiggleTime; + // Repeat by starting when stopping with a new random duration. + jiggleClock.on("stop", () => { this.rotation = -this.rotation; - } + jiggleClock.start(randomInteger(500, 800)); + }); + + this.addClock(jiggleClock); + } + + setPose(pose: "idle" | "shoot"): void { + this.graphics.use(pose); } } - -// eslint-disable-next-line @typescript-eslint/no-unused-vars -const _crossEyeGraphic = new GraphicsGroup({ - members: [ - new Line({ - start: vec(-5, -5), - end: vec(5, 5), - color: Color.Black, - thickness: 3, - }), - new Line({ - start: vec(5, -5), - end: vec(-5, 5), - color: Color.Black, - thickness: 3, - }), - ], -}); - -const smileEyeGraphic = new GraphicsGroup({ - members: [ - new Line({ - start: vec(-5, 5), - end: vec(5, -5), - color: Color.Black, - thickness: 3, - }), - new Line({ - start: vec(5, -5), - end: vec(10, 5), - color: Color.Black, - thickness: 3, - }), - ], -}); diff --git a/src/frontend/src/GameElements/Cups.ts b/src/frontend/src/GameElements/Cups.ts index e35d3b6..a98be7c 100644 --- a/src/frontend/src/GameElements/Cups.ts +++ b/src/frontend/src/GameElements/Cups.ts @@ -9,7 +9,7 @@ import { Polygon, vec, } from "excalibur"; -import { pixelsPerMeter } from "../utils/physicsConstant"; +import { pixelsPerMeter } from "../configs/physicsConstant"; export const defaultCupConfiguration = { cupColor: Color.Red, diff --git a/src/frontend/src/GameElements/Ground.ts b/src/frontend/src/GameElements/Ground.ts index a9a1553..6f085c6 100644 --- a/src/frontend/src/GameElements/Ground.ts +++ b/src/frontend/src/GameElements/Ground.ts @@ -1,5 +1,5 @@ import { Actor, Color, Engine, Graphic, Rectangle } from "excalibur"; -import { groundHeight } from "../utils/physicsConstant"; +import { groundHeight } from "../configs/sceneConfiguration"; export const groundColor = Color.Gray; diff --git a/src/frontend/src/GameElements/Table.ts b/src/frontend/src/GameElements/Table.ts index 5c64675..7988bad 100644 --- a/src/frontend/src/GameElements/Table.ts +++ b/src/frontend/src/GameElements/Table.ts @@ -7,16 +7,6 @@ import { Polygon, vec, } from "excalibur"; -import { pixelsPerMeter } from "../utils/physicsConstant"; - -export const defaultTableConfiguration = { - color: Color.Brown, - width: 2.44 * pixelsPerMeter, - height: 0.7 * pixelsPerMeter, - thickness: 0.15 * pixelsPerMeter, - legOffset: 0.15 * pixelsPerMeter, - legThickness: 0.15 * pixelsPerMeter, -}; export interface TableConfiguration { readonly color: Color; diff --git a/src/frontend/src/GameElements/champions.ts b/src/frontend/src/GameElements/champions.ts new file mode 100644 index 0000000..2148383 --- /dev/null +++ b/src/frontend/src/GameElements/champions.ts @@ -0,0 +1,21 @@ +export type ChampionName = "lucas" | "berset"; + +export interface ChampionConfig { + name: ChampionName; + height: number; +} + +const lucas: ChampionConfig = { + name: "lucas", + height: 1.4, +}; + +const berset: ChampionConfig = { + name: "berset", + height: 1.5, +}; + +export const champions: Record = { + lucas, + berset, +}; diff --git a/src/frontend/src/Scenes/BaseScene.ts b/src/frontend/src/Scenes/BaseScene.ts index f7bfdd8..8bb825e 100644 --- a/src/frontend/src/Scenes/BaseScene.ts +++ b/src/frontend/src/Scenes/BaseScene.ts @@ -9,7 +9,7 @@ export class BaseScene extends Scene { this._clocks.forEach((clock) => clock.update(elapsed)); } - protected addClock(timer: Clock): void { + addClock(timer: Clock): void { this._clocks.push(timer); } diff --git a/src/frontend/src/Scenes/MatchScene.ts b/src/frontend/src/Scenes/MatchScene.ts index c36678f..e9872ef 100644 --- a/src/frontend/src/Scenes/MatchScene.ts +++ b/src/frontend/src/Scenes/MatchScene.ts @@ -1,22 +1,25 @@ -import { Connection, MatchMessageEvent } from "../Connection"; -import { Ground, groundColor } from "../GameElements/Ground"; -import { - defaultTableConfiguration, - Table as TableElement, -} from "../GameElements/Table"; -import { Cup, defaultCupConfiguration } from "../GameElements/Cups"; import { Color, vec } from "excalibur"; +import { Connection, MatchMessageEvent } from "../Connection"; 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 { Cup, defaultCupConfiguration } from "../GameElements/Cups"; +import { Ground, groundColor } from "../GameElements/Ground"; +import { Table as TableElement } from "../GameElements/Table"; import { MatchState } from "../MatchState"; -import { Action, Table } from "../jsonTypes"; -import { assertNotNull } from "../utils/assertUtils"; import { Clock } from "../Timers/Clock"; +import { + championPositions, + groundHeight, + tableConfiguration, +} from "../configs/sceneConfiguration"; +import { Action, Table } from "../jsonTypes"; +import { assertNotNull, assertNull } from "../utils/assertUtils"; +import { colorDistance } from "../utils/colorUtils"; +import { randomColor, randomInteger } from "../utils/randomUtils"; import { BaseScene } from "./BaseScene"; +const speedUpFactor = 3; + export class MatchScene extends BaseScene { private _ground: Ground = null!; private _table: TableElement = null!; @@ -27,6 +30,8 @@ export class MatchScene extends BaseScene { private _matchClock = new Clock(); + private _playingHistoryPromise?: Promise; + constructor(private _connection: Connection) { super(); @@ -34,11 +39,11 @@ export class MatchScene extends BaseScene { this._connection.on("match-message", (e: MatchMessageEvent) => { if (!this.isInitialized) { - this.once("initialize", () => this._playFroMatchState(e.matchState)); + this.once("initialize", () => this._playFromMatchState(e.matchState)); return; } - this._playFroMatchState(e.matchState); + this._playFromMatchState(e.matchState); }); } @@ -51,7 +56,7 @@ export class MatchScene extends BaseScene { this._table = new TableElement( { pos: vec(0, groundHeight) }, - defaultTableConfiguration, + tableConfiguration, ); this.add(this._table); @@ -75,15 +80,16 @@ export class MatchScene extends BaseScene { this._cups.push(cup); }); - const championPositions = [ - ...[50, 150, 250].map((v) => -v - tableHalfWidth), - ...[50, 150, 250].map((v) => v + tableHalfWidth), - ]; - championPositions.forEach((offsetX) => { - const champion = new Champion({ - color: randomNonGroundColor(), - pos: vec(offsetX, groundHeight), - }); + championPositions.forEach((offsetX, index) => { + const facing = index < 3 ? "right" : "left"; + const champion = new Champion( + { + color: randomNonGroundColor(), + pos: vec(offsetX, groundHeight), + }, + facing, + randomInteger(0, 2) === 0 ? "berset" : "lucas", + ); this.add(champion); this._champions.push(champion); }); @@ -91,19 +97,47 @@ export class MatchScene extends BaseScene { this._ball = new Ball({}, defaultBallConfiguration); } - private async _playFroMatchState(state: MatchState): Promise { + private async _playFromMatchState(state: MatchState): Promise { + const promise = this._playingHistoryPromise; + + if (promise != null) { + const previousMatchClockSpeed = this._matchClock.speedFactor; + const previousBallSpeed = this._ball.clock.speedFactor; + this._matchClock.speedFactor *= speedUpFactor; + this._ball.clock.speedFactor *= speedUpFactor; + + await promise; + + this._matchClock.speedFactor = previousMatchClockSpeed; + this._ball.clock.speedFactor = previousBallSpeed; + } + + assertNull(this._playingHistoryPromise); + + let resolver: () => void; + this._playingHistoryPromise = new Promise( + (resolve) => (resolver = resolve), + ); + 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); + const currentChampion = this._getCurrentChampion(actionOrTable.turn); + currentChampion.setPose("shoot"); this._updateFromActionState(actionOrTable); await this._ball.clock.whenEnd(); + currentChampion.setPose("idle"); + await this._matchClock.startAndWait(1000); this.updateActorVisibility(this._ball, false); } } + + this._playingHistoryPromise = undefined; + resolver!(); } private _updateFromTableState(table: Table): void { @@ -119,6 +153,10 @@ export class MatchScene extends BaseScene { const parabola = Parabola.fromJSON(action.parabola); this._ball.startParabolaAnimation(parabola); } + + private _getCurrentChampion(turn: "a" | "b"): Champion { + return turn === "a" ? this._champions[0] : this._champions[3]; + } } function randomNonGroundColor(): Color { diff --git a/src/frontend/src/Timers/BallClock.ts b/src/frontend/src/Timers/BallClock.ts index 69781da..d9cc0c0 100644 --- a/src/frontend/src/Timers/BallClock.ts +++ b/src/frontend/src/Timers/BallClock.ts @@ -1,6 +1,6 @@ import { Ball, Parabola } from "../GameElements/Ball"; import { assertNotNull } from "../utils/assertUtils"; -import { groundHeight } from "../utils/physicsConstant"; +import { groundHeight } from "../configs/sceneConfiguration"; import { Clock } from "./Clock"; export class BallClock extends Clock { @@ -24,8 +24,8 @@ export class BallClock extends Clock { assertNotNull(this._parabola); - assertNotNull(this._elapsedTime); - const newPosition = this._parabola.position(this._elapsedTime); + assertNotNull(this._elapsedTimeMS); + const newPosition = this._parabola.position(this._elapsedTimeMS); // Collide with ground const yMin = groundHeight - this._ball.configuration.radius; diff --git a/src/frontend/src/Timers/Clock.ts b/src/frontend/src/Timers/Clock.ts index 6e57201..9838b82 100644 --- a/src/frontend/src/Timers/Clock.ts +++ b/src/frontend/src/Timers/Clock.ts @@ -5,18 +5,19 @@ 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; + protected _elapsedTimeMS: number | null = null; - private _duration?: number; + private _durationMS?: number; + + speedFactor = 1; constructor(duration?: number) { super(); - this._duration = duration; + this._durationMS = duration; } get running(): boolean { @@ -26,7 +27,7 @@ export class Clock extends Evented { start(duration?: number): void { this.reset(); if (duration != null) { - this._duration = duration; + this._durationMS = duration; } this._running = true; this.emit("start", {}); @@ -34,14 +35,13 @@ export class Clock extends Evented { stop(): void { this._running = false; - this._elapsedTime = null; + this._elapsedTimeMS = null; this.emit("stop", {}); } reset(): void { this._running = false; - this._elapsedTime = null; - this.emit("reset", {}); + this._elapsedTimeMS = null; } async whenEnd(): Promise { @@ -58,17 +58,17 @@ export class Clock extends Evented { update(elapsed: number): void { if (!this.running) { - assertNull(this._elapsedTime); + assertNull(this._elapsedTimeMS); return; } - if (this._elapsedTime == null) { - this._elapsedTime = 0; + if (this._elapsedTimeMS == null) { + this._elapsedTimeMS = 0; } - this._elapsedTime += elapsed; + this._elapsedTimeMS += elapsed * this.speedFactor; - if (this._duration != null) { - if (this._elapsedTime > this._duration) { + if (this._durationMS != null) { + if (this._elapsedTimeMS > this._durationMS) { this.stop(); this.emit("end", {}); } diff --git a/src/frontend/src/utils/physicsConstant.ts b/src/frontend/src/configs/physicsConstant.ts similarity index 75% rename from src/frontend/src/utils/physicsConstant.ts rename to src/frontend/src/configs/physicsConstant.ts index fca0e41..ee0fd2e 100644 --- a/src/frontend/src/utils/physicsConstant.ts +++ b/src/frontend/src/configs/physicsConstant.ts @@ -1,3 +1,2 @@ export const pixelsPerMeter = 100; export const gravitationalConstant = 9.81 * pixelsPerMeter; -export const groundHeight = 0; diff --git a/src/frontend/src/configs/sceneConfiguration.ts b/src/frontend/src/configs/sceneConfiguration.ts new file mode 100644 index 0000000..7b073bd --- /dev/null +++ b/src/frontend/src/configs/sceneConfiguration.ts @@ -0,0 +1,27 @@ +import { Color } from "excalibur"; +import { pixelsPerMeter } from "./physicsConstant"; + +export const tableConfiguration = { + color: Color.Brown, + width: 2.44 * pixelsPerMeter, + height: 0.7 * pixelsPerMeter, + thickness: 0.15 * pixelsPerMeter, + legOffset: 0.15 * pixelsPerMeter, + legThickness: 0.15 * pixelsPerMeter, +}; + +export const groundHeight = 0; + +export const championDistanceFromTable = 0.5 * pixelsPerMeter; +export const championGap = 0.8 * pixelsPerMeter; + +const championDistances = [ + championDistanceFromTable, + championDistanceFromTable + championGap, + championDistanceFromTable + 2 * championGap, +]; + +export const championPositions = [ + ...championDistances.map((v) => -v - tableConfiguration.width / 2), + ...championDistances.map((v) => v + tableConfiguration.width / 2), +]; diff --git a/src/frontend/src/imageLoader.ts b/src/frontend/src/imageLoader.ts new file mode 100644 index 0000000..73d772c --- /dev/null +++ b/src/frontend/src/imageLoader.ts @@ -0,0 +1,26 @@ +import { ImageSource } from "excalibur"; +import { assertNotNull } from "./utils/assertUtils"; + +const imageStrings = [ + "lucas_idle.png", + "lucas_shoot.png", + "berset_idle.png", + "berset_shoot.png", +]; + +export const images = new Map( + imageStrings.map((fileName) => [ + fileName.replace(/\.[^/.]+$/, ""), + new ImageSource(`/assets/${fileName}`), + ]), +); + +export function getImage(key: string): ImageSource { + const image = images.get(key); + assertNotNull(image); + return image; +} + +export async function loadImages(): Promise { + await Promise.all([...images.values()].map((img) => img.load())); +} diff --git a/src/frontend/src/main.ts b/src/frontend/src/main.ts index e3301e2..06fd7ee 100644 --- a/src/frontend/src/main.ts +++ b/src/frontend/src/main.ts @@ -7,6 +7,7 @@ import { mockLobbyMessage, MockSocket, } from "./sockets/MockSocket"; +import { loadImages } from "./imageLoader"; const urlParams = new URLSearchParams(window.location.search); const mocked = urlParams.get("mock"); @@ -27,9 +28,11 @@ export const maxPlayers = 2; scenes: { lobby: lobbyScene, match: matchScene }, backgroundColor: ex.Color.fromHex("23213b"), }); + game.toggleDebug(); await game.start(); + await loadImages(); await game.goToScene("lobby"); connection.on("lobby-message", () => game.goToScene("lobby")); diff --git a/src/frontend/src/sockets/MockSocket.ts b/src/frontend/src/sockets/MockSocket.ts index b858a0d..e3d0c88 100644 --- a/src/frontend/src/sockets/MockSocket.ts +++ b/src/frontend/src/sockets/MockSocket.ts @@ -22,7 +22,12 @@ export class MockSocket send(message: string): void { if (message.includes("join")) { - this.sendToClient(JSON.stringify({ player: { id: 0, name: "Dubbel" } })); + this.sendToClient( + JSON.stringify({ + messageType: "joinResponse", + messageContent: { client: { id: 0, name: "Dubbel" } }, + }), + ); } } } @@ -47,8 +52,8 @@ export function mockLobbyMessage(): string { export function mockGameMessage(): string { const matchUpdate = { - state: { - stateType: "match", + messageType: "matchState", + messsageContent: { history: [ { cupsA: [true, true, true],