Frontend - Lint shit and add github action (#21)

This commit is contained in:
lucas authored and GitHub committed 2025-10-27 21:43:43 +01:00
1 parent f938c4ebdf
commit f2ae34e490
22 files changed
+319 -178

No files matched your search

+18
View File
@@ -0,0 +1,18 @@
name: CI
on: push
jobs:
lint_frontend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- name: Install
run: |
cd src/frontend
npm ci
- name: Run ESLint
run: |
cd src/frontend
npm run lint
+22 -21
View File
@@ -1,30 +1,30 @@
import { GameState } from './GameState'; import { GameState } from "./GameState";
import { Client, GameStateRaw, Id } from './GameStateRaw'; import { Client, GameStateRaw, Id } from "./GameStateRaw";
import { log } from './utils/debugUtils'; import { log } from "./utils/debugUtils";
import { Event, Evented } from './utils/Evented'; import { Event, Evented } from "./utils/Evented";
type Action = "join" | "rejoin" | "toggleRole" | "toggleReady"; type Action = "join" | "rejoin" | "toggleRole" | "toggleReady";
interface Request { interface Request {
action: Action, action: Action;
} }
interface JoinRequest { interface JoinRequest {
action: "join", action: "join";
name: string, name: string;
} }
interface RejoinRequest { interface RejoinRequest {
action: "rejoin", action: "rejoin";
id: Id, id: Id;
} }
interface ToggleRoleRequest { interface ToggleRoleRequest {
action: "toggleRole" action: "toggleRole";
} }
interface ToggleReadyRequest { interface ToggleReadyRequest {
action: "toggleReady" action: "toggleReady";
} }
export class GameMessageEvent extends Event { export class GameMessageEvent extends Event {
@@ -44,9 +44,9 @@ export class ConnectOrDisconnectEvent extends Event {
export const ConnectionEvents = { export const ConnectionEvents = {
"game-message": GameMessageEvent, "game-message": GameMessageEvent,
"joined": JoinedEvent, joined: JoinedEvent,
"connect": ConnectEvent, connect: ConnectEvent,
"disconnect": DisconnectEvent, disconnect: DisconnectEvent,
"connect-or-disconnect": ConnectOrDisconnectEvent, "connect-or-disconnect": ConnectOrDisconnectEvent,
} as const; } as const;
@@ -72,7 +72,7 @@ export class Connection extends Evented<typeof ConnectionEvents> {
} }
private _onMessage(event: MessageEvent): void { private _onMessage(event: MessageEvent): void {
log("Connection", "received", event) log("Connection", "received", event);
const messageObject = JSON.parse(event.data); const messageObject = JSON.parse(event.data);
@@ -84,11 +84,12 @@ export class Connection extends Evented<typeof ConnectionEvents> {
return; return;
} }
// We only emit game message events when we have joined. // We only emit game message events when we have joined.
if (this._client) { if (this._client) {
const gameState: GameStateRaw = messageObject.gamestate; const gameState: GameStateRaw = messageObject.gamestate;
const gameMessage = new GameMessageEvent(new GameState(gameState, this._client)); const gameMessage = new GameMessageEvent(
new GameState(gameState, this._client),
);
this.emit("game-message", gameMessage); this.emit("game-message", gameMessage);
} }
} }
@@ -152,18 +153,18 @@ export class Connection extends Evented<typeof ConnectionEvents> {
toggleRole(): void { toggleRole(): void {
const toggleRoleRequest = { const toggleRoleRequest = {
action: "toggleRole" action: "toggleRole",
} as ToggleRoleRequest; } as ToggleRoleRequest;
this._send(toggleRoleRequest) this._send(toggleRoleRequest);
} }
toggleReady(): void { toggleReady(): void {
const toggleReadyRequest = { const toggleReadyRequest = {
action: "toggleReady" action: "toggleReady",
} as ToggleReadyRequest; } as ToggleReadyRequest;
this._send(toggleReadyRequest) this._send(toggleReadyRequest);
} }
} }
+13 -3
View File
@@ -1,15 +1,25 @@
import * as ex from 'excalibur'; import * as ex from "excalibur";
const radius = 20; const radius = 20;
const margin = 2; const margin = 2;
export class Cups extends ex.Graphic { export class Cups extends ex.Graphic {
protected _drawImage(context: ex.ExcaliburGraphicsContext, x: number, y: number): void { protected _drawImage(
context: ex.ExcaliburGraphicsContext,
x: number,
y: number,
): void {
y += radius; y += radius;
for (let r = 4; r > 0; r--) { for (let r = 4; r > 0; r--) {
x = -r * radius + radius; x = -r * radius + radius;
for (let c = 0; c < r; c++) { for (let c = 0; c < r; c++) {
context.drawCircle(ex.vec(x, y), radius, ex.Color.Red, ex.Color.White, 2) context.drawCircle(
ex.vec(x, y),
radius,
ex.Color.Red,
ex.Color.White,
2,
);
x += radius * 2 + margin; x += radius * 2 + margin;
} }
+4 -3
View File
@@ -2,7 +2,6 @@ import { ScreenElement, vec } from "excalibur";
import { ErrorScreenElement } from "../ScreenElements/Error"; import { ErrorScreenElement } from "../ScreenElements/Error";
import { spacingS } from "../utils/formattingUtils"; import { spacingS } from "../utils/formattingUtils";
interface ErrorListProperties { interface ErrorListProperties {
width: number; width: number;
} }
@@ -24,11 +23,13 @@ export class ErrorList extends ScreenElement {
const errorScreenElement = new ErrorScreenElement({ const errorScreenElement = new ErrorScreenElement({
text, text,
width: this._width, width: this._width,
}) });
this.addChild(errorScreenElement); this.addChild(errorScreenElement);
this._errors.push(errorScreenElement); this._errors.push(errorScreenElement);
const y = this._errors.reduce((acc, cur) => acc + cur.height, 0) + index * this._padding; const y =
this._errors.reduce((acc, cur) => acc + cur.height, 0) +
index * this._padding;
errorScreenElement.pos = vec(0, -y); errorScreenElement.pos = vec(0, -y);
const removeHandle = () => { const removeHandle = () => {
@@ -1,11 +1,11 @@
import * as ex from 'excalibur'; import * as ex from "excalibur";
import { TextInput, TextInputEvents } from '../ScreenElements/TextInput'; import { TextInput, TextInputEvents } from "../ScreenElements/TextInput";
import { Button } from '../ScreenElements/Button'; import { Button } from "../ScreenElements/Button";
import { paragraphFont } from '../utils/fontUtil'; import { paragraphFont } from "../utils/fontUtil";
import { Text } from '../ScreenElements/Text'; import { Text } from "../ScreenElements/Text";
import { spacingM } from '../utils/formattingUtils'; import { spacingM } from "../utils/formattingUtils";
import { Connection, storedClient } from '../Connection'; import { Connection, storedClient } from "../Connection";
import { Id } from '../GameStateRaw'; import { Id } from "../GameStateRaw";
export class PlayerNameInput extends ex.ScreenElement { export class PlayerNameInput extends ex.ScreenElement {
private _nameLabel: Text = null!; private _nameLabel: Text = null!;
@@ -15,15 +15,20 @@ export class PlayerNameInput extends ex.ScreenElement {
private _height = 0; private _height = 0;
constructor(private _connection: Connection, private _joinCallback: (name: string) => void, private _rejoinCallback: (id: Id) => void) { constructor(
private _connection: Connection,
private _joinCallback: (name: string) => void,
private _rejoinCallback: (id: Id) => void,
) {
super(); super();
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
onInitialize(_engine: ex.Engine): void { onInitialize(_engine: ex.Engine): void {
this._nameLabel = new Text({ this._nameLabel = new Text({
text: "What are you called?", text: "What are you called?",
font: paragraphFont, font: paragraphFont,
}) });
this._nameLabel.anchor = ex.vec(0.5, 0); this._nameLabel.anchor = ex.vec(0.5, 0);
this.addChild(this._nameLabel); this.addChild(this._nameLabel);
@@ -50,7 +55,9 @@ export class PlayerNameInput extends ex.ScreenElement {
this.addChild(this._rejoinButton); this.addChild(this._rejoinButton);
} }
this._nameInput.on(TextInputEvents.Textchanged, () => this._updateJoinButtonDisabled()); this._nameInput.on(TextInputEvents.Textchanged, () =>
this._updateJoinButtonDisabled(),
);
let y = 0; let y = 0;
this._nameLabel.pos = ex.vec(0, y); this._nameLabel.pos = ex.vec(0, y);
@@ -69,8 +76,8 @@ export class PlayerNameInput extends ex.ScreenElement {
this._height = y; this._height = y;
this._connection.on("connect",() => this._onConnect()) this._connection.on("connect", () => this._onConnect());
this._connection.on("disconnect",() => this._onDisconnect()) this._connection.on("disconnect", () => this._onDisconnect());
} }
get playerName(): string { get playerName(): string {
+1 -1
View File
@@ -7,6 +7,7 @@ export class Title extends ScreenElement {
private _title: Text = null!; private _title: Text = null!;
private _subTitle: Text = null!; private _subTitle: Text = null!;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
onInitialize(_engine: Engine): void { onInitialize(_engine: Engine): void {
// Title // Title
this._title = new Text({ this._title = new Text({
@@ -16,7 +17,6 @@ export class Title extends ScreenElement {
this._title.anchor = vec(0.5, 0); this._title.anchor = vec(0.5, 0);
this.addChild(this._title); this.addChild(this._title);
// Sub title // Sub title
this._subTitle = new Text({ this._subTitle = new Text({
text: "An auto battler with stupid people.", text: "An auto battler with stupid people.",
+17 -8
View File
@@ -1,21 +1,30 @@
import { Client, GameStateRawReadonly, Id, Player, Spectator } from "./GameStateRaw"; import {
Client,
GameStateRawReadonly,
Id,
Player,
Spectator,
} from "./GameStateRaw";
import { maxPlayers } from "./main"; import { maxPlayers } from "./main";
import { log } from "./utils/debugUtils"; import { log } from "./utils/debugUtils";
export class GameState { export class GameState {
_errors: string[] = []; _errors: string[] = [];
constructor(public readonly gameStateRaw: GameStateRawReadonly, readonly client: Client) { constructor(
public readonly gameStateRaw: GameStateRawReadonly,
readonly client: Client,
) {
this._validate(); this._validate();
} }
private _validate(): void { private _validate(): void {
if (!this.isPlayer && !this.isSpectator) { if (!this.isPlayer && !this.isSpectator) {
this._errors.push("You must be either a player or spectator.") this._errors.push("You must be either a player or spectator.");
} }
if (this.isPlayer && this.isSpectator) { if (this.isPlayer && this.isSpectator) {
this._errors.push("You cannot be both player and spectator.") this._errors.push("You cannot be both player and spectator.");
} }
if (this._errors.length > 0) { if (this._errors.length > 0) {
@@ -36,7 +45,7 @@ export class GameState {
} }
get isPlayer(): boolean { get isPlayer(): boolean {
return this.players.map(p => p.player.id).includes(this.client.id); return this.players.map((p) => p.player.id).includes(this.client.id);
} }
get isReady(): boolean { get isReady(): boolean {
@@ -44,14 +53,14 @@ export class GameState {
} }
get isSpectator(): boolean { get isSpectator(): boolean {
return this.spectators.map(p => p.player.id).includes(this.client.id); return this.spectators.map((p) => p.player.id).includes(this.client.id);
} }
getPlayerById(id: Id): Player | undefined { getPlayerById(id: Id): Player | undefined {
return this.players.find(p => p.player.id === id); return this.players.find((p) => p.player.id === id);
} }
getSpectatorById(id: Id): Spectator | undefined { getSpectatorById(id: Id): Spectator | undefined {
return this.spectators.find(p => p.player.id === id); return this.spectators.find((p) => p.player.id === id);
} }
} }
+1 -1
View File
@@ -5,7 +5,7 @@ export interface GameStateRaw {
spectators: Spectator[]; spectators: Spectator[];
} }
export type GameStateRawReadonly = Readonly<GameStateRaw> export type GameStateRawReadonly = Readonly<GameStateRaw>;
export interface Player { export interface Player {
player: Client; player: Client;
+3 -2
View File
@@ -1,6 +1,7 @@
import * as ex from 'excalibur'; import * as ex from "excalibur";
import { GameState } from '../GameState'; import { GameState } from "../GameState";
export class GameStateScene extends ex.Scene { export class GameStateScene extends ex.Scene {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public updateFromGameState(_gameState: GameState): void {} public updateFromGameState(_gameState: GameState): void {}
} }
+49 -29
View File
@@ -1,17 +1,17 @@
import * as ex from 'excalibur'; import * as ex from "excalibur";
import { spacingL, spacingM } from '../utils/formattingUtils'; import { spacingL, spacingM } from "../utils/formattingUtils";
import { Cups } from '../Cups'; import { Cups } from "../Cups";
import { GameStateScene } from './GameStateScene'; import { GameStateScene } from "./GameStateScene";
import { PlayerListScreenElement } from '../ScreenElements/PlayerListScreenElement'; import { PlayerListScreenElement } from "../ScreenElements/PlayerListScreenElement";
import { ClientListScreenElement } from '../ScreenElements/ClientListScreenElement'; import { ClientListScreenElement } from "../ScreenElements/ClientListScreenElement";
import { Button } from '../ScreenElements/Button'; import { Button } from "../ScreenElements/Button";
import { PlayerNameInput } from '../GameElements/PlayerNameInput'; import { PlayerNameInput } from "../GameElements/PlayerNameInput";
import { Connection, GameMessageEvent } from '../Connection'; import { Connection, GameMessageEvent } from "../Connection";
import { Title } from '../GameElements/Title'; import { Title } from "../GameElements/Title";
import { ErrorList } from '../GameElements/ErrorList'; import { ErrorList } from "../GameElements/ErrorList";
import { GameState } from '../GameState'; import { GameState } from "../GameState";
import { maxPlayers } from '../main'; import { maxPlayers } from "../main";
import { Id } from '../GameStateRaw'; import { Id } from "../GameStateRaw";
const tableWidth = 400; const tableWidth = 400;
@@ -51,7 +51,9 @@ export class LobbyScene extends GameStateScene {
this._playerNameInput.clear(); this._playerNameInput.clear();
this.setScreen("join"); this.setScreen("join");
}); });
this._connection.on("game-message", (e: GameMessageEvent) => this.updateFromGameState(e.gameState)); this._connection.on("game-message", (e: GameMessageEvent) =>
this.updateFromGameState(e.gameState),
);
} }
onInitialize(engine: ex.Engine): void { onInitialize(engine: ex.Engine): void {
@@ -59,7 +61,7 @@ export class LobbyScene extends GameStateScene {
const paddedTableWidth = tableWidth - 2 * tableBorder - 2 * spacingM; const paddedTableWidth = tableWidth - 2 * tableBorder - 2 * spacingM;
// Table background // Table background
this._table = new ex.ScreenElement({ this._table = new ex.ScreenElement({
anchor: ex.vec(0.5, 0) anchor: ex.vec(0.5, 0),
}); });
this.add(this._table); this.add(this._table);
@@ -84,7 +86,7 @@ export class LobbyScene extends GameStateScene {
this._bar3 = this._createBar(); this._bar3 = this._createBar();
// Cups // Cups
this._cups = new ex.ScreenElement({}) this._cups = new ex.ScreenElement({});
this._cups.anchor.setTo(0.5, 0); this._cups.anchor.setTo(0.5, 0);
this._cups.graphics.add(new Cups()); this._cups.graphics.add(new Cups());
this.add(this._cups); this.add(this._cups);
@@ -125,13 +127,20 @@ export class LobbyScene extends GameStateScene {
}); });
// Name input // Name input
this._playerNameInput = new PlayerNameInput(this._connection, (name: string) => this._join(name), (id: Id) => this._rejoin(id)); this._playerNameInput = new PlayerNameInput(
this._connection,
(name: string) => this._join(name),
(id: Id) => this._rejoin(id),
);
this._playerNameInput.anchor = ex.vec(0.5, 0); this._playerNameInput.anchor = ex.vec(0.5, 0);
// Error box // Error box
const w = paddedTableWidth - 2 * spacingM; const w = paddedTableWidth - 2 * spacingM;
this._errorList = new ErrorList({ width: w }); this._errorList = new ErrorList({ width: w });
this._errorList.pos = ex.vec(engine.screen.width / 2 - w / 2, engine.screen.height - spacingL); this._errorList.pos = ex.vec(
engine.screen.width / 2 - w / 2,
engine.screen.height - spacingL,
);
this.add(this._errorList); this.add(this._errorList);
@@ -139,13 +148,16 @@ export class LobbyScene extends GameStateScene {
if (connected) { if (connected) {
this._noConnectionErrorHandle?.(); this._noConnectionErrorHandle?.();
} else if (this._noConnectionErrorHandle == null) { } else if (this._noConnectionErrorHandle == null) {
this._noConnectionErrorHandle = this._errorList.addError("No server connection"); this._noConnectionErrorHandle = this._errorList.addError(
"No server connection",
);
} }
}); });
engine.screen.events.on("resize", () => this._updatePositions()); engine.screen.events.on("resize", () => this._updatePositions());
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
onActivate(_context: ex.SceneActivationContext<unknown>): void { onActivate(_context: ex.SceneActivationContext<unknown>): void {
this._updateVisibility(); this._updateVisibility();
this._updatePositions(); this._updatePositions();
@@ -154,12 +166,14 @@ export class LobbyScene extends GameStateScene {
private _createBar(): ex.ScreenElement { private _createBar(): ex.ScreenElement {
const bar = new ex.ScreenElement({ const bar = new ex.ScreenElement({
anchor: ex.vec(0.5, 0), anchor: ex.vec(0.5, 0),
}) });
bar.graphics.add(new ex.Rectangle({ bar.graphics.add(
new ex.Rectangle({
width: tableWidth - 2 * spacingM, width: tableWidth - 2 * spacingM,
height: 5, height: 5,
color: ex.Color.White, color: ex.Color.White,
})); }),
);
this.add(bar); this.add(bar);
return bar; return bar;
} }
@@ -172,24 +186,27 @@ export class LobbyScene extends GameStateScene {
} else { } else {
this.remove(g); this.remove(g);
} }
} };
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 isReadyVisible = isPlayer && (gameState?.isReady ?? false);
const isNotReadyVisible = isPlayer && ((gameState != null && !gameState.isReady) ?? false); const isNotReadyVisible =
isPlayer && ((gameState != null && !gameState.isReady) ?? false);
const isLobbyFull = gameState?.isFull ?? false; const isLobbyFull = gameState?.isFull ?? false;
setVisible(this._playerNameInput, isJoinScreen); setVisible(this._playerNameInput, isJoinScreen);
setVisible(this._playerList, !isJoinScreen); setVisible(this._playerList, !isJoinScreen);
setVisible(this._joinPlayerButton, !isJoinScreen && isSpectator && !isLobbyFull); setVisible(
this._joinPlayerButton,
!isJoinScreen && isSpectator && !isLobbyFull,
);
setVisible(this._spectatorsList, !isJoinScreen); setVisible(this._spectatorsList, !isJoinScreen);
setVisible(this._bar3, !isJoinScreen); setVisible(this._bar3, !isJoinScreen);
setVisible(this._joinSpectatorButton, !isJoinScreen && isPlayer); setVisible(this._joinSpectatorButton, !isJoinScreen && isPlayer);
setVisible(this._readyButton, !isJoinScreen && isNotReadyVisible); setVisible(this._readyButton, !isJoinScreen && isNotReadyVisible);
setVisible(this._unreadyButton, !isJoinScreen && isReadyVisible); setVisible(this._unreadyButton, !isJoinScreen && isReadyVisible);
} }
private _updatePositions(): void { private _updatePositions(): void {
@@ -200,7 +217,7 @@ export class LobbyScene extends GameStateScene {
y += spacingM; y += spacingM;
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.computeHeight! + spacingM;
this._bar1.pos = ex.vec(halfWidth, y); this._bar1.pos = ex.vec(halfWidth, y);
@@ -237,7 +254,10 @@ export class LobbyScene extends GameStateScene {
public updateFromGameState(gameState: GameState): void { public updateFromGameState(gameState: GameState): void {
this._playerList.updateFromGameState(gameState.players, gameState.client); this._playerList.updateFromGameState(gameState.players, gameState.client);
this._spectatorsList.updateFromGameState(gameState.spectators, gameState.client); this._spectatorsList.updateFromGameState(
gameState.spectators,
gameState.client,
);
this._updatePositions(); this._updatePositions();
this._updateVisibility(gameState); this._updateVisibility(gameState);
} }
+42 -21
View File
@@ -1,13 +1,16 @@
import * as ex from 'excalibur'; import * as ex 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";
import { lowerBarHeightDown, makeStyledRectangle } from '../utils/styledRectangles'; import {
lowerBarHeightDown,
makeStyledRectangle,
} from "../utils/styledRectangles";
interface ButtonProperties { interface ButtonProperties {
text?: string; text?: string;
disabled?: boolean; disabled?: boolean;
color?: ex.Color, color?: ex.Color;
onClick?: (event: ex.PointerEvent) => void; onClick?: (event: ex.PointerEvent) => void;
} }
@@ -32,13 +35,14 @@ export class Button extends ex.ScreenElement {
this._onClick = config?.onClick; this._onClick = config?.onClick;
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
onInitialize(_engine: ex.Engine): void { onInitialize(_engine: ex.Engine): void {
const { height, width } = this; const { height, width } = this;
this._textElement = new Text({ this._textElement = new Text({
text: this._text, text: this._text,
font: paragraphFont, font: paragraphFont,
}) });
this._textElement.anchor = ex.vec(0.5, 0.5); this._textElement.anchor = ex.vec(0.5, 0.5);
this._textElement.pos = ex.vec(0, height / 2); this._textElement.pos = ex.vec(0, height / 2);
this.addChild(this._textElement); this.addChild(this._textElement);
@@ -46,17 +50,26 @@ export class Button extends ex.ScreenElement {
const color = this._color ?? ex.Color.fromHex("4788ff"); const color = this._color ?? ex.Color.fromHex("4788ff");
const hoverColor = color.lighten(0.5); const hoverColor = color.lighten(0.5);
this.graphics.add('idle', makeStyledRectangle(width, height, color, false)); this.graphics.add("idle", makeStyledRectangle(width, height, color, false));
this.graphics.add('hover', makeStyledRectangle(width, height, hoverColor, false)); this.graphics.add(
this.graphics.add('disabled', makeStyledRectangle(width, height, ex.Color.Gray, false)); // this._createButtonGraphic(ex.Color.Gray)); "hover",
this.graphics.add("clicked", makeStyledRectangle(width, height, hoverColor, true)); makeStyledRectangle(width, height, hoverColor, false),
);
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),
);
this._updateGraphic("idle"); this._updateGraphic("idle");
this.on('pointerup', (e) => this.onPointerUp(e)); this.on("pointerup", (e) => this.onPointerUp(e));
this.on('pointerdown', (e) => this.onPointerDown(e)); this.on("pointerdown", (e) => this.onPointerDown(e));
this.on('pointerenter', (e) => this.onPointerEnter(e)); this.on("pointerenter", (e) => this.onPointerEnter(e));
this.on('pointerleave', (e) => this.onPointerLeave(e)); this.on("pointerleave", (e) => this.onPointerLeave(e));
} }
get text(): string { get text(): string {
@@ -73,7 +86,9 @@ export class Button extends ex.ScreenElement {
} }
get width(): number { get width(): number {
return paragraphFont.measureTextWithoutCache(this.text).width + this.padding; return (
paragraphFont.measureTextWithoutCache(this.text).width + this.padding
);
} }
get height(): number { get height(): number {
@@ -84,13 +99,14 @@ export class Button extends ex.ScreenElement {
return 2 * spacingS; return 2 * spacingS;
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
onPointerDown(_event: ex.PointerEvent): void { onPointerDown(_event: ex.PointerEvent): void {
if (this._disabled) { if (this._disabled) {
return; return;
} }
this._down = true; this._down = true;
this._updateGraphic("clicked") this._updateGraphic("clicked");
} }
onPointerUp(event: ex.PointerEvent): void { onPointerUp(event: ex.PointerEvent): void {
@@ -105,23 +121,25 @@ export class Button extends ex.ScreenElement {
_onClick(event); _onClick(event);
} }
this._updateGraphic("hover") this._updateGraphic("hover");
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
onPointerEnter(_event: ex.PointerEvent): void { onPointerEnter(_event: ex.PointerEvent): void {
if (this._disabled || this._down) { if (this._disabled || this._down) {
return; return;
} }
this._updateGraphic("hover") this._updateGraphic("hover");
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
onPointerLeave(_event: ex.PointerEvent): void { onPointerLeave(_event: ex.PointerEvent): void {
if (this._disabled) { if (this._disabled) {
return; return;
} }
this._updateGraphic("idle") this._updateGraphic("idle");
} }
private _updateGraphic(state: string = "idle"): void { private _updateGraphic(state: string = "idle"): void {
@@ -131,6 +149,9 @@ export class Button extends ex.ScreenElement {
} }
this.graphics.use(state); this.graphics.use(state);
this._textElement.pos = state === "clicked" ? ex.vec(0, this.height / 2 + lowerBarHeightDown) : ex.vec(0, this.height / 2) ; this._textElement.pos =
state === "clicked"
? ex.vec(0, this.height / 2 + lowerBarHeightDown)
: ex.vec(0, this.height / 2);
} }
} }
+11 -9
View File
@@ -1,10 +1,10 @@
import * as ex from 'excalibur'; import * as ex from "excalibur";
import { paragraphFont } from '../utils/fontUtil'; import { paragraphFont } from "../utils/fontUtil";
import { spacingS } from '../utils/formattingUtils'; import { spacingS } from "../utils/formattingUtils";
interface CheckboxProperties { interface CheckboxProperties {
checked: boolean; checked: boolean;
}; }
type ConstructProperties = ex.ActorArgs & CheckboxProperties; type ConstructProperties = ex.ActorArgs & CheckboxProperties;
@@ -22,15 +22,17 @@ export class Checkbox extends ex.ScreenElement {
const checkedGraphics = new ex.GraphicsGroup({ const checkedGraphics = new ex.GraphicsGroup({
members: [ members: [
{ graphic: new ex.Circle({ radius: size / 2, color }), offset: ex.vec(0, 0) }, {
graphic: new ex.Circle({ radius: size / 2, color }),
offset: ex.vec(0, 0),
},
], ],
}); });
const uncheckedGraphics = new ex.GraphicsGroup({ members: [ ], }) const uncheckedGraphics = new ex.GraphicsGroup({ members: [] });
this.graphics.add('checked', checkedGraphics); this.graphics.add("checked", checkedGraphics);
this.graphics.add('unchecked', uncheckedGraphics); this.graphics.add("unchecked", uncheckedGraphics);
this._updateGraphic(); this._updateGraphic();
} }
@@ -1,11 +1,11 @@
import * as ex from 'excalibur'; import * as ex from "excalibur";
import { spacingS } from '../utils/formattingUtils'; import { spacingS } from "../utils/formattingUtils";
import { headingFont, paragraphFont } from '../utils/fontUtil'; import { headingFont, paragraphFont } from "../utils/fontUtil";
import { Text } from './Text'; import { Text } from "./Text";
import { Client, Player, Spectator } from '../GameStateRaw'; import { Client, Player, Spectator } from "../GameStateRaw";
const clientColor = ex.Color.fromHex("40E0D0") const clientColor = ex.Color.fromHex("40E0D0");
export class ClientListScreenElement extends ex.ScreenElement { export class ClientListScreenElement extends ex.ScreenElement {
protected _clients: Player[] | Spectator[] = []; protected _clients: Player[] | Spectator[] = [];
@@ -18,10 +18,11 @@ export class ClientListScreenElement extends ex.ScreenElement {
super(); super();
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
override onInitialize(_engine: ex.Engine): void { override onInitialize(_engine: ex.Engine): void {
this.heading = new Text({ this.heading = new Text({
text: this._headingText, text: this._headingText,
font: headingFont font: headingFont,
}); });
this.heading.anchor.setTo(0.5, 0); this.heading.anchor.setTo(0.5, 0);
this.addChild(this.heading); this.addChild(this.heading);
@@ -33,8 +34,11 @@ export class ClientListScreenElement extends ex.ScreenElement {
return this.computeChildrenHeight(this._clients.length); return this.computeChildrenHeight(this._clients.length);
} }
public updateFromGameState(clients: Player[] | Spectator[], client: Client): void { public updateFromGameState(
this._clients = clients clients: Player[] | Spectator[],
client: Client,
): void {
this._clients = clients;
this._client = client; this._client = client;
if (this.isInitialized) { if (this.isInitialized) {
this.updateList(); this.updateList();
@@ -65,17 +69,20 @@ export class ClientListScreenElement extends ex.ScreenElement {
this.addChild(label); this.addChild(label);
this.entities.push(label); this.entities.push(label);
} }
} }
protected createLabel(client: Player | Spectator, y: number, isClient: boolean): Text { protected createLabel(
client: Player | Spectator,
y: number,
isClient: boolean,
): Text {
const color = isClient ? clientColor : undefined; const color = isClient ? clientColor : undefined;
const { name } = client.player; const { name } = client.player;
const label = new Text({ const label = new Text({
text: name, text: name,
font: paragraphFont, font: paragraphFont,
color, color,
}) });
label.pos.setTo(0, y); label.pos.setTo(0, y);
label.anchor.setTo(0.5, 0); label.anchor.setTo(0.5, 0);
@@ -83,7 +90,11 @@ export class ClientListScreenElement extends ex.ScreenElement {
} }
protected computeChildrenHeight(numLabels: number): number { protected computeChildrenHeight(numLabels: number): number {
return headingFont.size + spacingS + Math.max(1, numLabels) * (spacingS + paragraphFont.size); return (
headingFont.size +
spacingS +
Math.max(1, numLabels) * (spacingS + paragraphFont.size)
);
} }
protected clearLabelEntities(): void { protected clearLabelEntities(): void {
@@ -92,6 +103,4 @@ export class ClientListScreenElement extends ex.ScreenElement {
} }
this.entities = []; this.entities = [];
} }
} }
+2 -2
View File
@@ -22,10 +22,11 @@ export class ErrorScreenElement extends ScreenElement {
this._width = config.width; this._width = config.width;
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
onInitialize(_engine: Engine): void { onInitialize(_engine: Engine): void {
this._textElement = new Text({ this._textElement = new Text({
text: this.errorText, text: this.errorText,
font: paragraphFont font: paragraphFont,
}); });
this._textElement.pos = vec(this.padding, this.padding); this._textElement.pos = vec(this.padding, this.padding);
@@ -37,7 +38,6 @@ export class ErrorScreenElement extends ScreenElement {
}); });
this._backgroundElement.graphics.add(background); this._backgroundElement.graphics.add(background);
this.addChild(this._backgroundElement); this.addChild(this._backgroundElement);
this.addChild(this._textElement); this.addChild(this._textElement);
} }
@@ -1,15 +1,17 @@
import * as ex from 'excalibur'; import * as ex from "excalibur";
import { spacingS } from '../utils/formattingUtils'; import { spacingS } from "../utils/formattingUtils";
import { disabledFont } from '../utils/fontUtil'; import { disabledFont } from "../utils/fontUtil";
import { Text } from './Text'; import { Text } from "./Text";
import { Checkbox } from './Checkbox'; import { Checkbox } from "./Checkbox";
import { Player } from '../GameStateRaw'; import { Player } from "../GameStateRaw";
import { ClientListScreenElement } from './ClientListScreenElement'; import { ClientListScreenElement } from "./ClientListScreenElement";
export class PlayerListScreenElement extends ClientListScreenElement { export class PlayerListScreenElement extends ClientListScreenElement {
protected override _clients: Player[] = []; protected override _clients: Player[] = [];
constructor(headingText: string, private _maxPlayers: number) { constructor(
headingText: string,
private _maxPlayers: number,
) {
super(headingText); super(headingText);
} }
@@ -28,9 +30,8 @@ export class PlayerListScreenElement extends ClientListScreenElement {
this.addChild(label); this.addChild(label);
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);
@@ -43,13 +44,12 @@ export class PlayerListScreenElement extends ClientListScreenElement {
const label = new Text({ const label = new Text({
text: "Empty", text: "Empty",
font: disabledFont, font: disabledFont,
}) });
label.pos.setTo(0, y); label.pos.setTo(0, y);
label.anchor.setTo(0.5, 0); label.anchor.setTo(0.5, 0);
y += label.font.size + spacingS; y += label.font.size + spacingS;
this.addChild(label); this.addChild(label);
this.entities.push(label); this.entities.push(label);
} }
} }
+1 -1
View File
@@ -1,4 +1,4 @@
import * as ex from 'excalibur'; import * as ex from "excalibur";
type ConstructProperties = ex.LabelOptions & ex.ActorArgs; type ConstructProperties = ex.LabelOptions & ex.ActorArgs;
+35 -18
View File
@@ -1,18 +1,18 @@
import * as ex from 'excalibur'; import * as ex from "excalibur";
import { paragraphFont } from '../utils/fontUtil'; import { paragraphFont } from "../utils/fontUtil";
import { Text } from './Text'; import { Text } from "./Text";
import { spacingS } from '../utils/formattingUtils'; import { spacingS } from "../utils/formattingUtils";
interface TextInputProperties { interface TextInputProperties {
text?: string; text?: string;
width: number; width: number;
}; }
type ConstructProperties = ex.ActorArgs & TextInputProperties; type ConstructProperties = ex.ActorArgs & TextInputProperties;
type TextInputEvents = { type TextInputEvents = {
textChanged: TextChangedEvent; textChanged: TextChangedEvent;
} };
export class TextChangedEvent extends ex.GameEvent<string> { export class TextChangedEvent extends ex.GameEvent<string> {
constructor(public text: string) { constructor(public text: string) {
@@ -21,8 +21,8 @@ export class TextChangedEvent extends ex.GameEvent<string> {
} }
export const TextInputEvents = { export const TextInputEvents = {
Textchanged: "textchanged" Textchanged: "textchanged",
} as const } as const;
export class TextInput extends ex.ScreenElement { export class TextInput extends ex.ScreenElement {
public events = new ex.EventEmitter<ex.ActorEvents & TextInputEvents>(); public events = new ex.EventEmitter<ex.ActorEvents & TextInputEvents>();
@@ -35,7 +35,7 @@ export class TextInput extends ex.ScreenElement {
private _cursor: ex.ScreenElement = null!; private _cursor: ex.ScreenElement = null!;
private _cursorPosition = 0; private _cursorPosition = 0;
private _cursorTimer: ex.Timer = null! private _cursorTimer: ex.Timer = null!;
constructor(config: ConstructProperties) { constructor(config: ConstructProperties) {
super(config); super(config);
@@ -55,21 +55,25 @@ export class TextInput extends ex.ScreenElement {
this._textElement.pos = ex.vec(-width / 2 + this.padding, height / 2); this._textElement.pos = ex.vec(-width / 2 + this.padding, height / 2);
this.addChild(this._textElement); this.addChild(this._textElement);
this.graphics.add(new ex.Rectangle({ this.graphics.add(
new ex.Rectangle({
width, width,
height, height,
color: ex.Color.fromHex("D3D3D3"), color: ex.Color.fromHex("D3D3D3"),
})); }),
);
this._cursor = new ex.ScreenElement(); this._cursor = new ex.ScreenElement();
this._cursor.graphics.add(new ex.Line({ this._cursor.graphics.add(
new ex.Line({
start: ex.vec(0, 0), start: ex.vec(0, 0),
end: ex.vec(0, this.textHeight), end: ex.vec(0, this.textHeight),
thickness: 2, thickness: 2,
color: ex.Color.Black, color: ex.Color.Black,
})); }),
);
this._cursor.graphics.isVisible = false; this._cursor.graphics.isVisible = false;
this._cursor.pos = ex.vec(-width / 2 + this.padding, this.padding) this._cursor.pos = ex.vec(-width / 2 + this.padding, this.padding);
this._cursorTimer = new ex.Timer({ this._cursorTimer = new ex.Timer({
fcn: () => { fcn: () => {
@@ -131,7 +135,8 @@ export class TextInput extends ex.ScreenElement {
private _updateCursor(): void { private _updateCursor(): void {
const textBeforeCursor = this.text.slice(0, this._cursorPosition); const textBeforeCursor = this.text.slice(0, this._cursorPosition);
const textWidth = this._textElement.font.measureTextWithoutCache(textBeforeCursor).width; const textWidth =
this._textElement.font.measureTextWithoutCache(textBeforeCursor).width;
const x = -this._width / 2 + this.padding + textWidth - 2; const x = -this._width / 2 + this.padding + textWidth - 2;
this._cursor.pos = ex.vec(x, this.padding); this._cursor.pos = ex.vec(x, this.padding);
this._cursor.graphics.isVisible = true; this._cursor.graphics.isVisible = true;
@@ -158,9 +163,21 @@ export class TextInput extends ex.ScreenElement {
return; return;
} }
const invalidKeys = [
const invalidKeys = [ex.Keys.Alt, ex.Keys.ShiftLeft, ex.Keys.ShiftRight, ex.Keys.AltLeft, ex.Keys.AltRight, ex.Keys.ControlLeft, ex.Keys.ControlRight, ex.Keys.Alt,
ex.Keys.Home, ex.Keys.End, ex.Keys.PageDown, ex.Keys.PageUp, ex.Keys.Insert, ex.Keys.PrintScreen]; ex.Keys.ShiftLeft,
ex.Keys.ShiftRight,
ex.Keys.AltLeft,
ex.Keys.AltRight,
ex.Keys.ControlLeft,
ex.Keys.ControlRight,
ex.Keys.Home,
ex.Keys.End,
ex.Keys.PageDown,
ex.Keys.PageUp,
ex.Keys.Insert,
ex.Keys.PrintScreen,
];
if (invalidKeys.includes(key)) { if (invalidKeys.includes(key)) {
return; return;
} }
+9 -3
View File
@@ -35,9 +35,15 @@ function dummyGameState(): GameState {
const you = { name: "Dubbel", id: 0 }; const you = { name: "Dubbel", id: 0 };
const dummyState: GameStateRaw = { const dummyState: GameStateRaw = {
players: [{player: { name: "Dubbel", id: 0}, ready: true }, { player: { name: "Yeah", id: 1 }, ready: false }], players: [
spectators: [ { player: { name: "Dubbel", id: 2} }, { player: { name: "Cocksucker", id: 3 } }], { player: { name: "Dubbel", id: 0 }, ready: true },
} { player: { name: "Yeah", id: 1 }, ready: false },
],
spectators: [
{ player: { name: "Dubbel", id: 2 } },
{ player: { name: "Cocksucker", id: 3 } },
],
};
return new GameState(dummyState, you); return new GameState(dummyState, you);
} }
+12 -8
View File
@@ -2,27 +2,31 @@ export class Event {
constructor() {} constructor() {}
} }
// 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;
type Events = Record<string, EventCtor>; type Events = Record<string, EventCtor>;
type EventHandlers<E extends Events> = { type EventHandlers<E extends Events> = {
[K in keyof E]: ((event: InstanceType<E[K]>) => void) [K in keyof E]: (event: InstanceType<E[K]>) => void;
} };
export class Evented<E extends Events> { export class Evented<E extends Events> {
private _observers: { private _observers: {
[K in keyof EventHandlers<E>]?: EventHandlers<E>[K][]; [K in keyof EventHandlers<E>]?: EventHandlers<E>[K][];
} = {}; } = {};
on<K extends keyof EventHandlers<E>>(
eventName: K,
on<K extends keyof EventHandlers<E>>(eventName: K, handler: EventHandlers<E>[K]): void { handler: EventHandlers<E>[K],
): void {
const observer = (this._observers[eventName] ??= []); const observer = (this._observers[eventName] ??= []);
observer.push(handler); observer.push(handler);
} }
emit<K extends keyof EventHandlers<E>>(eventName: K, event: InstanceType<E[K]>): void { emit<K extends keyof EventHandlers<E>>(
this._observers[eventName]?.forEach(observer => observer(event)); eventName: K,
event: InstanceType<E[K]>,
): void {
this._observers[eventName]?.forEach((observer) => observer(event));
} }
} }
+1
View File
@@ -1,5 +1,6 @@
export type LogSource = "Connection" | "GameState"; export type LogSource = "Connection" | "GameState";
// 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 {
console.log(`${source}: `, ...data); console.log(`${source}: `, ...data);
} }
+3 -4
View File
@@ -1,10 +1,10 @@
import * as ex from 'excalibur'; import * as ex from "excalibur";
const fontFamily = "impact"; const fontFamily = "impact";
const shadow = { const shadow = {
color: ex.Color.Black, color: ex.Color.Black,
offset: ex.vec(4, 4), offset: ex.vec(4, 4),
} };
export const paragraphFont = new ex.Font({ export const paragraphFont = new ex.Font({
family: fontFamily, family: fontFamily,
@@ -39,5 +39,4 @@ export const disabledFont = new ex.Font({
color: ex.Color.Gray, color: ex.Color.Gray,
size: 20, size: 20,
shadow, shadow,
});
})
+18 -3
View File
@@ -5,7 +5,12 @@ const lowerBarHeight = spacingS;
export const lowerBarHeightDown = spacingS / 2; export const lowerBarHeightDown = spacingS / 2;
/** Return a GraphicsGroup of a clicky button. */ /** Return a GraphicsGroup of a clicky button. */
export function makeStyledRectangle(width: number, height: number, color: Color, down: boolean): GraphicsGroup { export function makeStyledRectangle(
width: number,
height: number,
color: Color,
down: boolean,
): GraphicsGroup {
const offsetYTop = !down ? 0 : lowerBarHeightDown; const offsetYTop = !down ? 0 : lowerBarHeightDown;
// The lower bar is the side of the rectangle on the bottom part that makes it look 3d. // The lower bar is the side of the rectangle on the bottom part that makes it look 3d.
@@ -14,8 +19,18 @@ export function makeStyledRectangle(width: number, height: number, color: Color,
return new GraphicsGroup({ return new GraphicsGroup({
members: [ members: [
{ graphic: new Rectangle({ width, height, color, }), offset: vec(0, offsetYTop) }, {
{ graphic: new Rectangle({ width, height: heightLowerBar, color: color.darken(0.5), }), offset: vec(0, offsetYLowerBar) }, graphic: new Rectangle({ width, height, color }),
offset: vec(0, offsetYTop),
},
{
graphic: new Rectangle({
width,
height: heightLowerBar,
color: color.darken(0.5),
}),
offset: vec(0, offsetYLowerBar),
},
], ],
}); });
} }