Robustify towards server (#8)

This commit is contained in:
lucas authored and GitHub committed 2025-10-06 19:10:47 +02:00
1 parent d5035a9a87
commit 429b0cb3cd
8 files changed
+263 -35

No files matched your search

+49 -20
View File
@@ -1,5 +1,6 @@
import { GameState } from './GameState';
import { log } from './utils/debugUtils';
import { Event, Evented } from './utils/Evented';
type Action = "join" | "toggleRole" | "toggleReady";
@@ -20,15 +21,31 @@ interface ToggleReadyRequest {
action: "toggleReady"
}
export class GameMessageEvent {
constructor(public gameState: GameState) { }
export class GameMessageEvent extends Event {
constructor(public gameState: GameState) {
super();
}
}
export class Connection {
private _socket: WebSocket | null = null;
private _observer: ((event: GameMessageEvent) => void)[] = [];
export class ConnectEvent extends Event { }
export class DisconnectEvent extends Event { }
export class ConnectOrDisconnectEvent extends Event {
constructor(public connected: boolean) {
super();
}
}
private get _connected(): boolean {
export const ConnectionEvents = {
"game-message": GameMessageEvent,
"connect": ConnectEvent,
"disconnect": DisconnectEvent,
"connect-or-disconnect": ConnectOrDisconnectEvent,
} as const;
export class Connection extends Evented<typeof ConnectionEvents> {
private _socket: WebSocket | null = null;
get connected(): boolean {
const { _socket } = this;
return _socket !== null && _socket.readyState === _socket.OPEN;
}
@@ -36,10 +53,10 @@ export class Connection {
connect(): void {
this._socket = new WebSocket("ws://127.0.0.1:8888");
this._socket.onopen = () => log("Connection", "Connected to game server.");
this._socket.onopen = () => this._onConnect();
this._socket.onmessage = (event) => this._onMessage(event);
this._socket.onerror = (event) => log("Connection", event);
this._socket.onclose = (event) => log("Connection", event);
this._socket.onerror = (event) => this._onError(event);
this._socket.onclose = () => this._onDisconnect();
}
private _onMessage(event: MessageEvent): void {
@@ -48,11 +65,32 @@ export class Connection {
const messageObject = JSON.parse(event.data);
const gameState = messageObject.gamestate;
const gameMessage = new GameMessageEvent(gameState)
this.emitOnMessage(gameMessage);
this.emit("game-message", gameMessage);
}
private _onConnect(): void {
log("Connection", "connected");
this.emit("connect", new DisconnectEvent());
this.emit("connect-or-disconnect", new ConnectOrDisconnectEvent(true));
}
private _onDisconnect(): void {
log("Connection", "disconnected");
this.emit("disconnect", new DisconnectEvent());
this.emit("connect-or-disconnect", new ConnectOrDisconnectEvent(false));
// Try again
this.connect();
}
private _onError(event: globalThis.Event): void {
log("Connection", "error", event);
}
private _send(request: Request): void {
if (!this._connected) {
if (!this.connected) {
return;
}
@@ -83,14 +121,5 @@ export class Connection {
} as ToggleReadyRequest;
this._send(toggleReadyRequest)
}
onMessage(handler: (event: GameMessageEvent) => void) {
this._observer.push(handler);
}
emitOnMessage(event: GameMessageEvent): void {
this._observer.forEach(observer => observer(event));
}
}
@@ -0,0 +1,45 @@
import { ScreenElement, vec } from "excalibur";
import { ErrorScreenElement } from "../ScreenElements/Error";
import { spacingS } from "../utils/formattingUtils";
interface ErrorListProperties {
width: number;
}
type ConstructProperties = Partial<ex.ActorArgs> & ErrorListProperties;
export class ErrorList extends ScreenElement {
private _errors: ErrorScreenElement[] = [];
private _width: number;
constructor(config: ConstructProperties){
super(config);
this._width = config.width;
}
public addError(text: string): () => void {
const index = this._errors.length;
const errorScreenElement = new ErrorScreenElement({
text,
width: this._width,
})
this.addChild(errorScreenElement);
this._errors.push(errorScreenElement);
const y = this._errors.reduce((acc, cur) => acc + cur.height, 0) + index * this._padding;
errorScreenElement.pos = vec(0, -y);
const removeHandle = () => {
this.removeChild(errorScreenElement);
this._errors.splice(index, 1);
};
return removeHandle;
}
private get _padding(): number {
return spacingS;
}
}
@@ -1,20 +1,20 @@
import * as ex from 'excalibur';
import { TextInput } from '../ScreenElements/TextInput';
import { TextInput, TextInputEvents } from '../ScreenElements/TextInput';
import { Button } from '../ScreenElements/Button';
import { paragraphFont } from '../utils/fontUtil';
import { Text } from '../ScreenElements/Text';
import { spacingM } from '../utils/formattingUtils';
import { Connection } from '../Connection';
export class PlayerNameInput extends ex.ScreenElement {
private _nameLabel: Text = null!;
private _nameInput: TextInput = null!;
private _joinButton: Button = null!;
private _joinCallback: (name: string) => void;
private _height = 0;
constructor(joinCallback: (name: string) => void) {
constructor(private _connection: Connection, private _joinCallback: (name: string) => void) {
super();
this._joinCallback = joinCallback;
}
onInitialize(_engine: ex.Engine): void {
@@ -33,7 +33,10 @@ export class PlayerNameInput extends ex.ScreenElement {
text: "Join",
anchor: ex.vec(0.5, 0),
onClick: () => this._joinCallback(this._nameInput.text),
disabled: true,
});
this._nameInput.on(TextInputEvents.Textchanged, () => this._updateJoinButtonDisabled());
this.addChild(this._joinButton);
let y = 0;
@@ -45,9 +48,31 @@ export class PlayerNameInput extends ex.ScreenElement {
this._joinButton.pos = ex.vec(0, y);
y += this._joinButton.height + spacingM;
this._height = y;
this._connection.on("connect",() => this._onConnect())
this._connection.on("disconnect",() => this._onDisconnect())
}
get playerName(): string {
return this._nameInput.text;
}
override get height(): number {
return this._height;
}
private _onConnect(): void {
this._updateJoinButtonDisabled();
}
private _onDisconnect(): void {
this._updateJoinButtonDisabled();
}
private _updateJoinButtonDisabled(): void {
const disabled = !this._connection.connected || this._nameInput.text === "";
this._joinButton.disabled = disabled;
}
}
+31 -8
View File
@@ -9,6 +9,7 @@ import { Button } from '../ScreenElements/Button';
import { PlayerNameInput } from '../GameElements/PlayerNameInput';
import { Connection, GameMessageEvent } from '../Connection';
import { Title } from '../GameElements/Title';
import { ErrorList } from '../GameElements/ErrorList';
const tableWidth = 400;
const maxPlayers = 2;
@@ -33,26 +34,30 @@ export class LobbyScene extends GameStateScene {
private _playerNameInput: PlayerNameInput = null!;
private _errorList: ErrorList = null!;
private _noConnectionErrorHandle: (() => void) | undefined;
private _screen: "join" | "lobby" = "join";
constructor(private _connection: Connection) {
super();
this._connection.onMessage((e: GameMessageEvent) => this.updateFromGameState(e.gameState))
this._connection.on("game-message", (e: GameMessageEvent) => this.updateFromGameState(e.gameState))
}
onInitialize(engine: ex.Engine): void {
const tableBorder = 10;
const paddedTableWidth = tableWidth - 2 * tableBorder - 2 * spacingM;
// Table background
this._table = new ex.ScreenElement({
anchor: ex.vec(0.5, 0)
});
this.add(this._table);
const s = 10;
const points = [
ex.vec(0, s),
ex.vec(s, 0),
ex.vec(tableWidth - s, 0),
ex.vec(tableWidth, s),
ex.vec(0, tableBorder),
ex.vec(tableBorder, 0),
ex.vec(tableWidth - tableBorder, 0),
ex.vec(tableWidth, tableBorder),
ex.vec(tableWidth, engine.screen.height),
ex.vec(0, engine.screen.height),
];
@@ -99,11 +104,28 @@ export class LobbyScene extends GameStateScene {
});
// Name input
this._playerNameInput = new PlayerNameInput((_name: string) => this._join());
this._playerNameInput = new PlayerNameInput(this._connection, (_name: string) => this._join());
this._playerNameInput.anchor = ex.vec(0.5, 0);
engine.screen.events.on("resize", () => this._updatePositions());
// Error box
const w = paddedTableWidth - 2 * spacingM;
this._errorList = new ErrorList({width: w });
this._errorList.pos = ex.vec(engine.screen.width / 2 - w / 2, engine.screen.height - spacingL);
this.add(this._errorList);
this._connection.on("connect-or-disconnect", ({connected}) => {
if (connected) {
this._noConnectionErrorHandle?.();
} else if (this._noConnectionErrorHandle == null) {
this._noConnectionErrorHandle = this._errorList.addError("No server connection");
}
});
engine.screen.events.on("resize", () => this._updatePositions());
}
onActivate(_context: ex.SceneActivationContext<unknown>): void {
this._updateVisibility();
this._updatePositions();
}
@@ -161,6 +183,7 @@ export class LobbyScene extends GameStateScene {
if (this._screen === "join") {
this._playerNameInput.pos = ex.vec(halfWidth, y);
y += this._playerNameInput.height;
} else {
this._playerList.pos = ex.vec(halfWidth, y);
y += this._playerList.childrenHeight + spacingM;
+6 -3
View File
@@ -49,14 +49,13 @@ export class Button extends ex.ScreenElement {
height,
color: ex.Color.fromHex("bad2ff")
}));
this.graphics.use('idle');
this.graphics.add('disabled', new ex.Rectangle({
width,
height,
color: ex.Color.Gray,
}));
this.graphics.use('idle');
this._updateGraphic();
this.on('pointerup', (e) => this.onPointerUp(e));
this.on('pointerenter', (e) => this.onPointerEnter(e));
@@ -73,7 +72,7 @@ export class Button extends ex.ScreenElement {
set disabled(value: boolean) {
this._disabled = value;
this.graphics.use(value ? 'disabled' : 'idle')
this._updateGraphic();
}
get height(): number {
@@ -111,4 +110,8 @@ export class Button extends ex.ScreenElement {
this.graphics.use('idle');
}
private _updateGraphic(): void {
this.graphics.use(this.disabled ? 'disabled' : 'idle')
}
}
+56
View File
@@ -0,0 +1,56 @@
import { Color, Engine, Rectangle, ScreenElement, vec } from "excalibur";
import { Text } from "./Text";
import { paragraphFont } from "../utils/fontUtil";
import { spacingS } from "../utils/formattingUtils";
interface ErrorScreenElementProperties {
text: string;
width: number;
}
type ConstructProperties = Partial<ex.ActorArgs> & ErrorScreenElementProperties;
export class ErrorScreenElement extends ScreenElement {
private _text: string;
private _width: number;
private _backgroundElement: ex.ScreenElement = null!;
private _textElement: Text = null!;
constructor(config: ConstructProperties) {
super(config);
this._text = config.text;
this._width = config.width;
}
onInitialize(_engine: Engine): void {
this._textElement = new Text({
text: this.errorText,
font: paragraphFont
});
this._textElement.pos = vec(this.padding, this.padding);
this._backgroundElement = new ScreenElement();
const background = new Rectangle({
width: this._width,
height: this.height,
color: Color.Red,
});
this._backgroundElement.graphics.add(background);
this.addChild(this._backgroundElement);
this.addChild(this._textElement);
}
get padding(): number {
return spacingS;
}
override get height(): number {
return paragraphFont.size + 2 * this.padding;
}
private get errorText(): string {
return `Error: ${this._text}`;
}
}
@@ -10,7 +10,23 @@ interface TextInputProperties {
type ConstructProperties = ex.ActorArgs & TextInputProperties;
type TextInputEvents = {
textChanged: TextChangedEvent;
}
export class TextChangedEvent extends ex.GameEvent<string> {
constructor(public text: string) {
super();
}
}
export const TextInputEvents = {
Textchanged: "textchanged"
} as const
export class TextInput extends ex.ScreenElement {
public events = new ex.EventEmitter<ex.ActorEvents & TextInputEvents>();
private _width: number;
private _text?: string;
private _textElement: Text = null!;
@@ -154,6 +170,7 @@ export class TextInput extends ex.ScreenElement {
const secondPart = this.text.slice(this._cursorPosition);
this.text = firstPart.concat(secondPart);
this.cursorPosition--;
this.emit(TextInputEvents.Textchanged, this.text);
return;
}
@@ -161,6 +178,7 @@ export class TextInput extends ex.ScreenElement {
const firstPart = this.text.slice(0, this._cursorPosition);
const secondPart = this.text.slice(this._cursorPosition + 1);
this.text = firstPart.concat(secondPart);
this.emit(TextInputEvents.Textchanged, this.text);
return;
}
@@ -186,5 +204,6 @@ export class TextInput extends ex.ScreenElement {
this.text = this.text + event.value;
this.cursorPosition++;
this.emit(TextInputEvents.Textchanged, this.text);
}
}
+28
View File
@@ -0,0 +1,28 @@
export class Event {
constructor() { }
}
type EventCtor<T extends Event = Event> = abstract new (...args: any[]) => T;
type Events = Record<string, EventCtor>;
type EventHandlers<E extends Events> = {
[K in keyof E]: ((event: InstanceType<E[K]>) => void)
}
export class Evented<E extends Events> {
private _observers: {
[K in keyof EventHandlers<E>]?: EventHandlers<E>[K][];
} = {};
on<K extends keyof EventHandlers<E>>(eventName: K, handler: EventHandlers<E>[K]): void {
const observer = (this._observers[eventName] ??= []);
observer.push(handler);
}
emit<K extends keyof EventHandlers<E>>(eventName: K, event: InstanceType<E[K]>): void {
this._observers[eventName]?.forEach(observer => observer(event));
}
}