mirror of
https://github.com/openfrontio/OpenFrontIO.git
synced 2026-07-12 16:54:33 +00:00
d76691372c
**Add approved & assigned issue number here:** Resolves #4476 ## Description: Lets a private-lobby host reuse the same group for **back-to-back games without re-sharing the invite link**. **Flow:** in a private game, the host clicks a **"New lobby"** button in the top-right bar (next to pause). The game's **server** creates a fresh private lobby (same creator, default settings) and broadcasts its id to everyone still connected. Non-hosts get a one-click **"Join"** banner at the top of the screen; the host is taken straight back to the host view for the new lobby. The chain can repeat indefinitely. ### Key design decision: the server creates and broadcasts the successor lobby The successor lobby is minted by the **finished game's server**, not the host's browser. The old game's server is the only thing still connected to every player, so it has to be what announces the new lobby; because it also *creates* that lobby, the id everyone is redirected to is **authoritative**. A real lobby the server just made for the authenticated creator, not an id a client handed it to trust and fan out. The request is **creator-only** and **idempotent** per game, and every successor is wired the same way, so the group can keep playing game after game. ### How it works 1. Host clicks "New lobby" (host + private only) → confirm dialog → the client sends a `create_next_lobby` message. 2. The game server verifies the sender is the lobby creator, mints a successor private lobby on the same worker, stores it (idempotent), and broadcasts a `new_lobby` message with the new id to all connected clients. 3. Each client reacts: the host is navigated to the new lobby's host view (`/…/game/<id>?host`); everyone else sees a dismissible "Host started a new lobby — Join" banner that navigates to the join URL in one click. Two new Zod wire messages in `src/core/Schemas.ts` (`create_next_lobby`, `new_lobby`) carry the request and the broadcast. ### Screenshots <table> <tr> <td width="50%" align="center" valign="top"> <img width="220" alt="In-game New lobby button" src="https://github.com/user-attachments/assets/9a4d4425-a7f6-4b3a-9c4f-9205300b1e5b" /><br /> <sub><b>1.</b> In-game <b>New lobby</b> button (top-right, next to pause) — shown only to the host of a private lobby</sub> </td> <td width="50%" align="center" valign="top"> <img width="320" alt="Confirmation dialog" src="https://github.com/user-attachments/assets/fa023f5a-58e8-439b-8899-5150235a1e8c" /><br /> <sub><b>2.</b> Confirmation so a stray click doesn't pull everyone into a new lobby</sub> </td> </tr> <tr> <td colspan="2" align="center"> <img width="100%" alt="Join banner for non-hosts" src="https://github.com/user-attachments/assets/7e5ef490-aa7e-4449-add9-e857fe273bde" /><br /> <sub><b>3.</b> Everyone else gets a one-click <b>Join</b> banner at the top of the screen</sub> </td> </tr> <tr> <td colspan="2" align="center"> <img width="330" alt="Host view for the new lobby" src="https://github.com/user-attachments/assets/9920b070-4ed3-41f8-9345-78778b4648a7" /><br /> <sub><b>4.</b> The host lands back in the host view for the brand-new lobby</sub> </td> </tr> </table> ### Design Decisions **A. The server creates & broadcasts the successor, not the client.** The finished game's server mints the successor and broadcasts its id. Why this and not "host's browser calls `POST /api/create_game`, then asks the server to relay the id"? - The broadcast id is **authoritative/verified**: it's a real lobby the server just created for the **authenticated** lobby creator (creator identity comes from the JWT the game already holds), not an arbitrary id a client hands the server to fan out to everyone. - The **old game server is the only thing still connected to all the players**, so it must be the one to broadcast. Having it also create the lobby keeps it to one authoritative round-trip instead of "client creates, then client asks server to trust an id it didn't make." - The server can **authorise** (only the creator) and stay **idempotent**. **B. The successor starts with default settings (not a copy of the old game).** A deliberate scope choice. The host lands in the normal host view and reconfigures. Copying the exact config would mean reverse-mapping every `GameConfig` field back into the host-modal controls, which I thought would be out of scope for this PR. Same **creator** is preserved; same **settings** intentionally is not. **C. It's a brand-new lobby, not the same game resurrected.** This directly follows @evanpelle's guidance on the issue: *"A 'lobby' is really just a game that hasn't started yet. So making a persistent lobby isn't really possible. I think instead having a simple way to transfer players to a new lobby is probably the way to go."* A `GameServer` runs exactly one game (start → end → archive), so rather than reworking that lifecycle to resurrect the old game, the server spins up a fresh successor lobby and transfers the group into it, which is also why the feature is framed as "reuse the group," not "reuse the game object." **D. The host returns via a `?host` URL flag + full reload ("attach mode").** Navigating to a normal join URL (`/game/<id>`) always lands you in the **join** view, which has no Start button. So the host can't just use the join URL. The `?host` flag routes the creator to the **host view** instead (`Main.handleUrl` → `HostLobbyModal` in "attach" mode, which binds to the existing lobby id and skips creating a new one). A full reload is used because it cleanly tears down the finished game and mirrors the existing win-screen "Requeue" button's `window.location.href` pattern. **E. Each successor can spawn its own successor (recursive factory).** The first version only chained **one** generation. A spawned lobby had no factory of its own, so the *second* "New lobby" click did nothing (button just greyed out). Fixed by `wireSuccessorLobby` (a small dependency-injected helper) that wires every successor the same way. This is the whole point of the issue ("back-to-back games"), so it has its own regression test. **F. Private-only.** The successor factory is installed **only** on the private `POST /api/create_game` path in `Worker.ts`. Public games (scheduled by the master) and singleplayer never get a factory, so `handleCreateNextLobby` is a no-op for them. The client button is also gated on `isLobbyCreator && isPrivateLobby`. **G. In-game button + confirm; the win-modal button was removed.** An earlier version put the "New lobby" button on the win screen. I moved it to the in-game bar so the host can reuse the lobby **at any time** (without dying or waiting for the game to end), and added a **confirm** (matching the adjacent Exit button) so a stray click next to pause/exit doesn't yank everyone into a new lobby. The win-screen button became redundant and was removed. ### Testing - **Unit tests:** wire-message schema round-trips (`tests/NewLobbyMessages.test.ts`); the server handler — authorisation, broadcast, idempotency — against a real `GameServer` (`tests/server/CreateNextLobby.test.ts`); and successor **chaining** across multiple generations (`tests/server/SuccessorLobby.test.ts`). - **Full suite:** `npm test` passes — **1782 tests across 154 files**. - **Manual:** created a private lobby with multiple clients and played consecutive games via the button; verified non-hosts get the Join banner, the host lands back in the host view, and the chain works for 3+ games in a row. ## Please complete the following: - [X] I have added screenshots for all UI updates - [X] I process any text displayed to the user through translateText() and I've added it to the en.json file - [X] I have added relevant tests to the test directory ## Please put your Discord username so you can be contacted if a bug or regression is found: MushroomLamp --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
748 lines
20 KiB
TypeScript
748 lines
20 KiB
TypeScript
import { ClientEnv } from "src/client/ClientEnv";
|
|
import { z } from "zod";
|
|
import { EventBus, GameEvent } from "../core/EventBus";
|
|
import {
|
|
AllPlayers,
|
|
GameType,
|
|
Gold,
|
|
PlayerID,
|
|
Tick,
|
|
UnitType,
|
|
} from "../core/game/Game";
|
|
import { TileRef } from "../core/game/GameMap";
|
|
import {
|
|
AllPlayersStats,
|
|
ClientHashMessage,
|
|
ClientIntentMessage,
|
|
ClientJoinMessage,
|
|
ClientMessage,
|
|
ClientPingMessage,
|
|
ClientRejoinMessage,
|
|
ClientSendLiveStatsMessage,
|
|
ClientSendWinnerMessage,
|
|
GameConfig,
|
|
Intent,
|
|
LiveStats,
|
|
ServerMessage,
|
|
ServerMessageSchema,
|
|
Winner,
|
|
} from "../core/Schemas";
|
|
import { replacer } from "../core/Util";
|
|
import { getPlayToken } from "./Auth";
|
|
import { LobbyConfig } from "./ClientGameRunner";
|
|
import { showInGameAlert } from "./InGameModal";
|
|
import { LocalServer } from "./LocalServer";
|
|
import { translateText } from "./Utils";
|
|
import { PlayerView } from "./view";
|
|
|
|
export class PauseGameIntentEvent implements GameEvent {
|
|
constructor(public readonly paused: boolean) {}
|
|
}
|
|
|
|
export class SendAllianceRequestIntentEvent implements GameEvent {
|
|
constructor(
|
|
public readonly requestor: PlayerView,
|
|
public readonly recipient: PlayerView,
|
|
) {}
|
|
}
|
|
|
|
export class SendBreakAllianceIntentEvent implements GameEvent {
|
|
constructor(
|
|
public readonly requestor: PlayerView,
|
|
public readonly recipient: PlayerView,
|
|
) {}
|
|
}
|
|
|
|
export class SendUpgradeStructureIntentEvent implements GameEvent {
|
|
constructor(
|
|
public readonly unitId: number,
|
|
public readonly unitType: UnitType,
|
|
) {}
|
|
}
|
|
|
|
export class SendAllianceRejectIntentEvent implements GameEvent {
|
|
constructor(public readonly requestor: PlayerView) {}
|
|
}
|
|
|
|
export class SendAllianceExtensionIntentEvent implements GameEvent {
|
|
constructor(public readonly recipient: PlayerView) {}
|
|
}
|
|
|
|
export class SendSpawnIntentEvent implements GameEvent {
|
|
constructor(public readonly tile: TileRef) {}
|
|
}
|
|
|
|
export class SendAttackIntentEvent implements GameEvent {
|
|
constructor(
|
|
public readonly targetID: PlayerID | null,
|
|
public readonly troops: number,
|
|
) {}
|
|
}
|
|
|
|
export class SendBoatAttackIntentEvent implements GameEvent {
|
|
constructor(
|
|
public readonly dst: TileRef,
|
|
public readonly troops: number,
|
|
) {}
|
|
}
|
|
|
|
export class BuildUnitIntentEvent implements GameEvent {
|
|
constructor(
|
|
public readonly unit: UnitType,
|
|
public readonly tile: TileRef,
|
|
public readonly rocketDirectionUp?: boolean,
|
|
) {}
|
|
}
|
|
|
|
export class SendTargetPlayerIntentEvent implements GameEvent {
|
|
constructor(public readonly targetID: PlayerID) {}
|
|
}
|
|
|
|
export class SendEmojiIntentEvent implements GameEvent {
|
|
constructor(
|
|
public readonly recipient: PlayerView | typeof AllPlayers,
|
|
public readonly emoji: number,
|
|
) {}
|
|
}
|
|
|
|
export class SendDonateGoldIntentEvent implements GameEvent {
|
|
constructor(
|
|
public readonly recipient: PlayerView,
|
|
public readonly gold: Gold | null,
|
|
) {}
|
|
}
|
|
|
|
export class SendDonateTroopsIntentEvent implements GameEvent {
|
|
constructor(
|
|
public readonly recipient: PlayerView,
|
|
public readonly troops: number | null,
|
|
) {}
|
|
}
|
|
|
|
export class SendQuickChatEvent implements GameEvent {
|
|
constructor(
|
|
public readonly recipient: PlayerView,
|
|
public readonly quickChatKey: string,
|
|
public readonly target?: PlayerID,
|
|
) {}
|
|
}
|
|
|
|
export class SendEmbargoIntentEvent implements GameEvent {
|
|
constructor(
|
|
public readonly target: PlayerView,
|
|
public readonly action: "start" | "stop",
|
|
) {}
|
|
}
|
|
|
|
export class SendEmbargoAllIntentEvent implements GameEvent {
|
|
constructor(public readonly action: "start" | "stop") {}
|
|
}
|
|
|
|
export class SendDeleteUnitIntentEvent implements GameEvent {
|
|
constructor(public readonly unitId: number) {}
|
|
}
|
|
|
|
export class CancelAttackIntentEvent implements GameEvent {
|
|
constructor(public readonly attackID: string) {}
|
|
}
|
|
|
|
export class CancelBoatIntentEvent implements GameEvent {
|
|
constructor(public readonly unitID: number) {}
|
|
}
|
|
|
|
export class SendWinnerEvent implements GameEvent {
|
|
constructor(
|
|
public readonly winner: Winner,
|
|
public readonly allPlayersStats: AllPlayersStats,
|
|
) {}
|
|
}
|
|
export class SendLiveStatsEvent implements GameEvent {
|
|
constructor(public readonly stats: LiveStats) {}
|
|
}
|
|
export class SendHashEvent implements GameEvent {
|
|
constructor(
|
|
public readonly tick: Tick,
|
|
public readonly hash: number,
|
|
) {}
|
|
}
|
|
|
|
// Emitted when the server tells us the host started a successor lobby, carrying
|
|
// the new game id to move the group to.
|
|
export class NewLobbyEvent implements GameEvent {
|
|
constructor(public readonly gameID: string) {}
|
|
}
|
|
|
|
export class MoveWarshipIntentEvent implements GameEvent {
|
|
constructor(
|
|
public readonly unitIds: number[],
|
|
public readonly tile: number,
|
|
) {}
|
|
}
|
|
|
|
export class SendKickPlayerIntentEvent implements GameEvent {
|
|
constructor(public readonly target: string) {}
|
|
}
|
|
|
|
export class SendUpdateGameConfigIntentEvent implements GameEvent {
|
|
constructor(public readonly config: Partial<GameConfig>) {}
|
|
}
|
|
|
|
export class SendToggleGameStartTimer implements GameEvent {
|
|
constructor() {}
|
|
}
|
|
|
|
export class Transport {
|
|
private socket: WebSocket | null = null;
|
|
|
|
private localServer: LocalServer;
|
|
|
|
private buffer: string[] = [];
|
|
|
|
private onconnect: () => void;
|
|
private onmessage: (msg: ServerMessage) => void;
|
|
|
|
private pingInterval: number | null = null;
|
|
public readonly isLocal: boolean;
|
|
|
|
constructor(
|
|
private lobbyConfig: LobbyConfig,
|
|
private eventBus: EventBus,
|
|
) {
|
|
// If gameRecord is not null, we are replaying an archived game.
|
|
// For multiplayer games, GameConfig is not known until game starts.
|
|
this.isLocal =
|
|
lobbyConfig.gameRecord !== undefined ||
|
|
lobbyConfig.gameStartInfo?.config.gameType === GameType.Singleplayer;
|
|
|
|
this.eventBus.on(SendAllianceRequestIntentEvent, (e) =>
|
|
this.onSendAllianceRequest(e),
|
|
);
|
|
this.eventBus.on(SendAllianceRejectIntentEvent, (e) =>
|
|
this.onAllianceRejectUIEvent(e),
|
|
);
|
|
this.eventBus.on(SendAllianceExtensionIntentEvent, (e) =>
|
|
this.onSendAllianceExtensionIntent(e),
|
|
);
|
|
this.eventBus.on(SendBreakAllianceIntentEvent, (e) =>
|
|
this.onBreakAllianceRequestUIEvent(e),
|
|
);
|
|
this.eventBus.on(SendSpawnIntentEvent, (e) =>
|
|
this.onSendSpawnIntentEvent(e),
|
|
);
|
|
this.eventBus.on(SendAttackIntentEvent, (e) => this.onSendAttackIntent(e));
|
|
this.eventBus.on(SendUpgradeStructureIntentEvent, (e) =>
|
|
this.onSendUpgradeStructureIntent(e),
|
|
);
|
|
this.eventBus.on(SendBoatAttackIntentEvent, (e) =>
|
|
this.onSendBoatAttackIntent(e),
|
|
);
|
|
this.eventBus.on(SendTargetPlayerIntentEvent, (e) =>
|
|
this.onSendTargetPlayerIntent(e),
|
|
);
|
|
this.eventBus.on(SendEmojiIntentEvent, (e) => this.onSendEmojiIntent(e));
|
|
this.eventBus.on(SendDonateGoldIntentEvent, (e) =>
|
|
this.onSendDonateGoldIntent(e),
|
|
);
|
|
this.eventBus.on(SendDonateTroopsIntentEvent, (e) =>
|
|
this.onSendDonateTroopIntent(e),
|
|
);
|
|
this.eventBus.on(SendQuickChatEvent, (e) => this.onSendQuickChatIntent(e));
|
|
this.eventBus.on(SendEmbargoIntentEvent, (e) =>
|
|
this.onSendEmbargoIntent(e),
|
|
);
|
|
this.eventBus.on(SendEmbargoAllIntentEvent, (e) =>
|
|
this.onSendEmbargoAllIntent(e),
|
|
);
|
|
this.eventBus.on(BuildUnitIntentEvent, (e) => this.onBuildUnitIntent(e));
|
|
|
|
this.eventBus.on(PauseGameIntentEvent, (e) => this.onPauseGameIntent(e));
|
|
this.eventBus.on(SendWinnerEvent, (e) => this.onSendWinnerEvent(e));
|
|
this.eventBus.on(SendLiveStatsEvent, (e) => this.onSendLiveStatsEvent(e));
|
|
this.eventBus.on(SendHashEvent, (e) => this.onSendHashEvent(e));
|
|
this.eventBus.on(CancelAttackIntentEvent, (e) =>
|
|
this.onCancelAttackIntentEvent(e),
|
|
);
|
|
this.eventBus.on(CancelBoatIntentEvent, (e) =>
|
|
this.onCancelBoatIntentEvent(e),
|
|
);
|
|
|
|
this.eventBus.on(MoveWarshipIntentEvent, (e) => {
|
|
this.onMoveWarshipEvent(e);
|
|
});
|
|
|
|
this.eventBus.on(SendDeleteUnitIntentEvent, (e) =>
|
|
this.onSendDeleteUnitIntent(e),
|
|
);
|
|
|
|
this.eventBus.on(SendKickPlayerIntentEvent, (e) =>
|
|
this.onSendKickPlayerIntent(e),
|
|
);
|
|
|
|
this.eventBus.on(SendUpdateGameConfigIntentEvent, (e) =>
|
|
this.onSendUpdateGameConfigIntent(e),
|
|
);
|
|
|
|
this.eventBus.on(SendToggleGameStartTimer, (e) =>
|
|
this.onSendToggleGameStartTimer(e),
|
|
);
|
|
}
|
|
|
|
private startPing() {
|
|
if (this.isLocal) return;
|
|
this.pingInterval ??= window.setInterval(() => {
|
|
if (this.socket !== null && this.socket.readyState === WebSocket.OPEN) {
|
|
this.sendMsg({
|
|
type: "ping",
|
|
} satisfies ClientPingMessage);
|
|
}
|
|
}, 5 * 1000);
|
|
}
|
|
|
|
private stopPing() {
|
|
if (this.pingInterval) {
|
|
window.clearInterval(this.pingInterval);
|
|
this.pingInterval = null;
|
|
}
|
|
}
|
|
|
|
public connect(
|
|
onconnect: () => void,
|
|
onmessage: (message: ServerMessage) => void,
|
|
) {
|
|
if (this.isLocal) {
|
|
this.connectLocal(onconnect, onmessage);
|
|
} else {
|
|
this.connectRemote(onconnect, onmessage);
|
|
}
|
|
}
|
|
|
|
public updateCallback(
|
|
onconnect: () => void,
|
|
onmessage: (message: ServerMessage) => void,
|
|
) {
|
|
if (this.isLocal) {
|
|
this.localServer.updateCallback(onconnect, onmessage);
|
|
} else {
|
|
this.onconnect = onconnect;
|
|
this.onmessage = onmessage;
|
|
}
|
|
}
|
|
|
|
private connectLocal(
|
|
onconnect: () => void,
|
|
onmessage: (message: ServerMessage) => void,
|
|
) {
|
|
this.localServer = new LocalServer(
|
|
this.lobbyConfig,
|
|
this.lobbyConfig.gameRecord !== undefined,
|
|
this.eventBus,
|
|
);
|
|
this.localServer.updateCallback(onconnect, onmessage);
|
|
this.localServer.start();
|
|
}
|
|
|
|
private connectRemote(
|
|
onconnect: () => void,
|
|
onmessage: (message: ServerMessage) => void,
|
|
) {
|
|
this.startPing();
|
|
this.killExistingSocket();
|
|
const wsHost = window.location.host;
|
|
const wsProtocol = window.location.protocol === "https:" ? "wss:" : "ws:";
|
|
const workerPath = ClientEnv.workerPath(this.lobbyConfig.gameID);
|
|
this.socket = new WebSocket(`${wsProtocol}//${wsHost}/${workerPath}`);
|
|
this.onconnect = onconnect;
|
|
this.onmessage = onmessage;
|
|
this.socket.onopen = () => {
|
|
console.log("Connected to game server!");
|
|
if (this.socket === null) {
|
|
console.error("socket is null");
|
|
return;
|
|
}
|
|
while (this.buffer.length > 0) {
|
|
console.log("sending dropped message");
|
|
const msg = this.buffer.pop();
|
|
if (msg === undefined) {
|
|
console.warn("msg is undefined");
|
|
continue;
|
|
}
|
|
this.socket.send(msg);
|
|
}
|
|
onconnect();
|
|
};
|
|
this.socket.onmessage = (event: MessageEvent) => {
|
|
try {
|
|
const parsed = JSON.parse(event.data);
|
|
const result = ServerMessageSchema.safeParse(parsed);
|
|
if (!result.success) {
|
|
const error = z.prettifyError(result.error);
|
|
console.error("Error parsing server message", error);
|
|
return;
|
|
}
|
|
this.onmessage(result.data);
|
|
} catch (e) {
|
|
console.error("Error in onmessage handler:", e, event.data);
|
|
return;
|
|
}
|
|
};
|
|
this.socket.onerror = (err) => {
|
|
console.error("Socket encountered error: ", err, "Closing socket");
|
|
if (this.socket === null) return;
|
|
this.socket.close();
|
|
};
|
|
this.socket.onclose = (event: CloseEvent) => {
|
|
console.log(
|
|
`WebSocket closed. Code: ${event.code}, Reason: ${event.reason}`,
|
|
);
|
|
if (event.code === 1002) {
|
|
showInGameAlert(
|
|
translateText("error_modal.connection_refused", {
|
|
reason: event.reason,
|
|
}),
|
|
);
|
|
} else if (event.code !== 1000) {
|
|
console.log(`received error code ${event.code}, reconnecting`);
|
|
this.reconnect();
|
|
}
|
|
};
|
|
}
|
|
|
|
public reconnect() {
|
|
this.connect(this.onconnect, this.onmessage);
|
|
}
|
|
|
|
public turnComplete() {
|
|
if (this.isLocal) {
|
|
this.localServer.turnComplete();
|
|
}
|
|
}
|
|
|
|
async joinGame() {
|
|
this.sendMsg({
|
|
type: "join",
|
|
gameID: this.lobbyConfig.gameID,
|
|
// Note: clientID is not sent - server assigns it based on persistentID
|
|
username: this.lobbyConfig.playerName,
|
|
clanTag: this.lobbyConfig.playerClanTag ?? null,
|
|
cosmetics: this.lobbyConfig.cosmetics,
|
|
turnstileToken: this.lobbyConfig.turnstileToken,
|
|
token: await getPlayToken(),
|
|
} satisfies ClientJoinMessage);
|
|
}
|
|
|
|
async rejoinGame(lastTurn: number) {
|
|
this.sendMsg({
|
|
type: "rejoin",
|
|
gameID: this.lobbyConfig.gameID,
|
|
// Note: clientID is not sent - server looks it up from persistentID in token
|
|
lastTurn: lastTurn,
|
|
token: await getPlayToken(),
|
|
} satisfies ClientRejoinMessage);
|
|
}
|
|
|
|
leaveGame() {
|
|
if (this.isLocal) {
|
|
this.localServer.endGame();
|
|
return;
|
|
}
|
|
this.stopPing();
|
|
if (this.socket === null) return;
|
|
if (this.socket.readyState === WebSocket.OPEN) {
|
|
console.log("on stop: leaving game");
|
|
this.killExistingSocket();
|
|
} else {
|
|
console.log(
|
|
"WebSocket is not open. Current state:",
|
|
this.socket.readyState,
|
|
);
|
|
console.error("attempting reconnect");
|
|
this.killExistingSocket();
|
|
}
|
|
}
|
|
|
|
private onSendAllianceRequest(event: SendAllianceRequestIntentEvent) {
|
|
this.sendIntent({
|
|
type: "allianceRequest",
|
|
recipient: event.recipient.id(),
|
|
});
|
|
}
|
|
|
|
private onAllianceRejectUIEvent(event: SendAllianceRejectIntentEvent) {
|
|
this.sendIntent({
|
|
type: "allianceReject",
|
|
requestor: event.requestor.id(),
|
|
});
|
|
}
|
|
|
|
private onBreakAllianceRequestUIEvent(event: SendBreakAllianceIntentEvent) {
|
|
this.sendIntent({
|
|
type: "breakAlliance",
|
|
recipient: event.recipient.id(),
|
|
});
|
|
}
|
|
|
|
private onSendAllianceExtensionIntent(
|
|
event: SendAllianceExtensionIntentEvent,
|
|
) {
|
|
this.sendIntent({
|
|
type: "allianceExtension",
|
|
recipient: event.recipient.id(),
|
|
});
|
|
}
|
|
|
|
private onSendSpawnIntentEvent(event: SendSpawnIntentEvent) {
|
|
this.sendIntent({
|
|
type: "spawn",
|
|
tile: event.tile,
|
|
});
|
|
}
|
|
|
|
private onSendAttackIntent(event: SendAttackIntentEvent) {
|
|
this.sendIntent({
|
|
type: "attack",
|
|
targetID: event.targetID,
|
|
troops: event.troops,
|
|
});
|
|
}
|
|
|
|
private onSendBoatAttackIntent(event: SendBoatAttackIntentEvent) {
|
|
this.sendIntent({
|
|
type: "boat",
|
|
troops: event.troops,
|
|
dst: event.dst,
|
|
});
|
|
}
|
|
|
|
private onSendUpgradeStructureIntent(event: SendUpgradeStructureIntentEvent) {
|
|
this.sendIntent({
|
|
type: "upgrade_structure",
|
|
unit: event.unitType,
|
|
unitId: event.unitId,
|
|
});
|
|
}
|
|
|
|
private onSendTargetPlayerIntent(event: SendTargetPlayerIntentEvent) {
|
|
this.sendIntent({
|
|
type: "targetPlayer",
|
|
target: event.targetID,
|
|
});
|
|
}
|
|
|
|
private onSendEmojiIntent(event: SendEmojiIntentEvent) {
|
|
this.sendIntent({
|
|
type: "emoji",
|
|
recipient:
|
|
event.recipient === AllPlayers ? AllPlayers : event.recipient.id(),
|
|
emoji: event.emoji,
|
|
});
|
|
}
|
|
|
|
private onSendDonateGoldIntent(event: SendDonateGoldIntentEvent) {
|
|
this.sendIntent({
|
|
type: "donate_gold",
|
|
recipient: event.recipient.id(),
|
|
gold: event.gold ? Number(event.gold) : null,
|
|
});
|
|
}
|
|
|
|
private onSendDonateTroopIntent(event: SendDonateTroopsIntentEvent) {
|
|
this.sendIntent({
|
|
type: "donate_troops",
|
|
recipient: event.recipient.id(),
|
|
troops: event.troops,
|
|
});
|
|
}
|
|
|
|
private onSendQuickChatIntent(event: SendQuickChatEvent) {
|
|
this.sendIntent({
|
|
type: "quick_chat",
|
|
recipient: event.recipient.id(),
|
|
quickChatKey: event.quickChatKey,
|
|
target: event.target,
|
|
});
|
|
}
|
|
|
|
private onSendEmbargoIntent(event: SendEmbargoIntentEvent) {
|
|
this.sendIntent({
|
|
type: "embargo",
|
|
targetID: event.target.id(),
|
|
action: event.action,
|
|
});
|
|
}
|
|
|
|
private onSendEmbargoAllIntent(event: SendEmbargoAllIntentEvent) {
|
|
this.sendIntent({
|
|
type: "embargo_all",
|
|
action: event.action,
|
|
});
|
|
}
|
|
|
|
private onBuildUnitIntent(event: BuildUnitIntentEvent) {
|
|
this.sendIntent({
|
|
type: "build_unit",
|
|
unit: event.unit,
|
|
tile: event.tile,
|
|
rocketDirectionUp: event.rocketDirectionUp,
|
|
});
|
|
}
|
|
|
|
private onPauseGameIntent(event: PauseGameIntentEvent) {
|
|
this.sendIntent({
|
|
type: "toggle_pause",
|
|
paused: event.paused,
|
|
});
|
|
}
|
|
|
|
private onSendWinnerEvent(event: SendWinnerEvent) {
|
|
if (this.isLocal || this.socket?.readyState === WebSocket.OPEN) {
|
|
this.sendMsg({
|
|
type: "winner",
|
|
winner: event.winner,
|
|
allPlayersStats: event.allPlayersStats,
|
|
} satisfies ClientSendWinnerMessage);
|
|
} else {
|
|
console.log(
|
|
"WebSocket is not open. Current state:",
|
|
this.socket?.readyState,
|
|
);
|
|
console.log("attempting reconnect");
|
|
}
|
|
}
|
|
|
|
private onSendLiveStatsEvent(event: SendLiveStatsEvent) {
|
|
if (this.isLocal || this.socket?.readyState === WebSocket.OPEN) {
|
|
this.sendMsg({
|
|
type: "live_stats",
|
|
stats: event.stats,
|
|
} satisfies ClientSendLiveStatsMessage);
|
|
}
|
|
}
|
|
|
|
private onSendHashEvent(event: SendHashEvent) {
|
|
if (this.isLocal || this.socket?.readyState === WebSocket.OPEN) {
|
|
this.sendMsg({
|
|
type: "hash",
|
|
turnNumber: event.tick,
|
|
hash: event.hash,
|
|
} satisfies ClientHashMessage);
|
|
} else {
|
|
console.log(
|
|
"WebSocket is not open. Current state:",
|
|
this.socket?.readyState,
|
|
);
|
|
console.log("attempting reconnect");
|
|
}
|
|
}
|
|
|
|
private onCancelAttackIntentEvent(event: CancelAttackIntentEvent) {
|
|
this.sendIntent({
|
|
type: "cancel_attack",
|
|
attackID: event.attackID,
|
|
});
|
|
}
|
|
|
|
private onCancelBoatIntentEvent(event: CancelBoatIntentEvent) {
|
|
this.sendIntent({
|
|
type: "cancel_boat",
|
|
unitID: event.unitID,
|
|
});
|
|
}
|
|
|
|
private onMoveWarshipEvent(event: MoveWarshipIntentEvent) {
|
|
this.sendIntent({
|
|
type: "move_warship",
|
|
unitIds: event.unitIds,
|
|
tile: event.tile,
|
|
});
|
|
}
|
|
|
|
private onSendDeleteUnitIntent(event: SendDeleteUnitIntentEvent) {
|
|
this.sendIntent({
|
|
type: "delete_unit",
|
|
unitId: event.unitId,
|
|
});
|
|
}
|
|
|
|
private onSendKickPlayerIntent(event: SendKickPlayerIntentEvent) {
|
|
this.sendIntent({
|
|
type: "kick_player",
|
|
targetClientID: event.target,
|
|
});
|
|
}
|
|
|
|
private onSendUpdateGameConfigIntent(event: SendUpdateGameConfigIntentEvent) {
|
|
this.sendIntent({
|
|
type: "update_game_config",
|
|
config: event.config,
|
|
});
|
|
}
|
|
|
|
private onSendToggleGameStartTimer(event: SendToggleGameStartTimer) {
|
|
this.sendIntent({ type: "toggle_game_start_timer" });
|
|
}
|
|
|
|
private sendIntent(intent: Intent) {
|
|
if (this.isLocal || this.socket?.readyState === WebSocket.OPEN) {
|
|
const msg = {
|
|
type: "intent",
|
|
intent: intent,
|
|
} satisfies ClientIntentMessage;
|
|
this.sendMsg(msg);
|
|
} else {
|
|
console.log(
|
|
"WebSocket is not open. Current state:",
|
|
this.socket?.readyState,
|
|
);
|
|
console.log("attempting reconnect");
|
|
}
|
|
}
|
|
|
|
private sendMsg(msg: ClientMessage) {
|
|
if (this.isLocal) {
|
|
// Forward message to local server
|
|
this.localServer.onMessage(msg);
|
|
return;
|
|
} else if (this.socket === null) {
|
|
// Socket missing, do nothing
|
|
return;
|
|
}
|
|
const str = JSON.stringify(msg, replacer);
|
|
if (this.socket.readyState === WebSocket.CLOSED) {
|
|
// Buffer message
|
|
console.warn("socket not ready, closing and trying later");
|
|
this.socket.close();
|
|
this.socket = null;
|
|
this.connectRemote(this.onconnect, this.onmessage);
|
|
this.buffer.push(str);
|
|
} else {
|
|
// Send the message directly
|
|
this.socket.send(str);
|
|
}
|
|
}
|
|
|
|
private killExistingSocket(): void {
|
|
if (this.socket === null) {
|
|
return;
|
|
}
|
|
// Remove all event listeners
|
|
this.socket.onmessage = null;
|
|
this.socket.onopen = null;
|
|
this.socket.onclose = null;
|
|
this.socket.onerror = null;
|
|
|
|
// Close the connection if it's still open or still connecting
|
|
try {
|
|
if (
|
|
this.socket.readyState === WebSocket.OPEN ||
|
|
this.socket.readyState === WebSocket.CONNECTING
|
|
) {
|
|
this.socket.close();
|
|
}
|
|
} catch (e) {
|
|
console.warn("Error while closing WebSocket:", e);
|
|
}
|
|
|
|
this.socket = null;
|
|
}
|
|
}
|