mirror of
https://github.com/openfrontio/OpenFrontIO.git
synced 2026-07-12 11:43:58 +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>
375 lines
12 KiB
TypeScript
375 lines
12 KiB
TypeScript
import { html, LitElement } from "lit";
|
|
import { customElement, state } from "lit/decorators.js";
|
|
import { assetUrl } from "../../../core/AssetUrls";
|
|
import { EventBus } from "../../../core/EventBus";
|
|
import { GameType } from "../../../core/game/Game";
|
|
import { createNextLobby } from "../../Api";
|
|
import { ClientEnv } from "../../ClientEnv";
|
|
import "../../components/DoomsdayClockPanel";
|
|
import { Controller } from "../../Controller";
|
|
import { crazyGamesSDK } from "../../CrazyGamesSDK";
|
|
import { showInGameAlert, showInGameConfirm } from "../../InGameModal";
|
|
import { TogglePauseIntentEvent } from "../../InputHandler";
|
|
import { PauseGameIntentEvent, SendWinnerEvent } from "../../Transport";
|
|
import { translateText } from "../../Utils";
|
|
import { GameView } from "../../view";
|
|
import { ImmunityBarVisibleEvent } from "./ImmunityTimer";
|
|
import { ShowReplayPanelEvent } from "./ReplayPanel";
|
|
import { ShowSettingsModalEvent } from "./SettingsModal";
|
|
import { SpawnBarVisibleEvent } from "./SpawnTimer";
|
|
const exitIcon = assetUrl("images/ExitIconWhite.svg");
|
|
const FastForwardIconSolid = assetUrl("images/FastForwardIconSolidWhite.svg");
|
|
const pauseIcon = assetUrl("images/PauseIconWhite.svg");
|
|
const playIcon = assetUrl("images/PlayIconWhite.svg");
|
|
const newLobbyIcon = assetUrl("images/ReplayRegularIconWhite.svg");
|
|
const settingsIcon = assetUrl("images/SettingIconWhite.svg");
|
|
const fullscreenIcon = assetUrl("images/FullscreenIconWhite.svg");
|
|
const exitFullscreenIcon = assetUrl("images/ExitFullscreenIconWhite.svg");
|
|
|
|
@customElement("game-right-sidebar")
|
|
export class GameRightSidebar extends LitElement implements Controller {
|
|
public game: GameView;
|
|
public eventBus: EventBus;
|
|
|
|
@state()
|
|
private _isSinglePlayer: boolean = false;
|
|
|
|
@state()
|
|
private _isReplayVisible: boolean = false;
|
|
|
|
@state()
|
|
private _isVisible: boolean = true;
|
|
|
|
@state()
|
|
private isPaused: boolean = false;
|
|
|
|
@state()
|
|
private isFullscreen: boolean = false;
|
|
|
|
@state()
|
|
private timer: number = 0;
|
|
|
|
// CrazyGames provides its own fullscreen control in the game frame, so hide ours.
|
|
private readonly onCrazyGames = crazyGamesSDK.isOnCrazyGames();
|
|
private hasWinner = false;
|
|
private isLobbyCreator = false;
|
|
private isPrivateLobby = false;
|
|
// Guards the in-game "New lobby" button so a double click doesn't fire twice
|
|
// before we navigate to the successor lobby.
|
|
private newLobbyRequested = false;
|
|
private spawnBarVisible = false;
|
|
private immunityBarVisible = false;
|
|
|
|
createRenderRoot() {
|
|
// Stack the timer bar + doomsday-clock readout, centers aligned (the narrower
|
|
// one sits centered under the wider one).
|
|
this.style.display = "flex";
|
|
this.style.flexDirection = "column";
|
|
this.style.alignItems = "center";
|
|
this.style.gap = "6px";
|
|
return this;
|
|
}
|
|
|
|
init() {
|
|
this._isSinglePlayer =
|
|
this.game?.config()?.gameConfig()?.gameType === GameType.Singleplayer ||
|
|
this.game.config().isReplay();
|
|
this.isPrivateLobby =
|
|
this.game?.config()?.gameConfig()?.gameType === GameType.Private;
|
|
this._isVisible = true;
|
|
|
|
this.eventBus.on(SpawnBarVisibleEvent, (e) => {
|
|
this.spawnBarVisible = e.visible;
|
|
this.updateParentOffset();
|
|
});
|
|
this.eventBus.on(ImmunityBarVisibleEvent, (e) => {
|
|
this.immunityBarVisible = e.visible;
|
|
this.updateParentOffset();
|
|
});
|
|
|
|
this.eventBus.on(SendWinnerEvent, () => {
|
|
this.hasWinner = true;
|
|
this.requestUpdate();
|
|
});
|
|
|
|
this.eventBus.on(TogglePauseIntentEvent, () => {
|
|
const isReplayOrSingleplayer =
|
|
this._isSinglePlayer || this.game?.config()?.isReplay();
|
|
if (isReplayOrSingleplayer || this.isLobbyCreator) {
|
|
this.onPauseButtonClick();
|
|
}
|
|
});
|
|
|
|
this.requestUpdate();
|
|
}
|
|
|
|
private onFullscreenChange = () => {
|
|
this.isFullscreen = !!document.fullscreenElement;
|
|
};
|
|
|
|
connectedCallback() {
|
|
super.connectedCallback();
|
|
document.addEventListener("fullscreenchange", this.onFullscreenChange);
|
|
this.onFullscreenChange();
|
|
}
|
|
|
|
disconnectedCallback() {
|
|
super.disconnectedCallback();
|
|
document.removeEventListener("fullscreenchange", this.onFullscreenChange);
|
|
}
|
|
|
|
getTickIntervalMs() {
|
|
return 250;
|
|
}
|
|
|
|
tick() {
|
|
// Timer logic
|
|
// Check if the player is the lobby creator
|
|
if (!this.isLobbyCreator && this.game.myPlayer()?.isLobbyCreator()) {
|
|
this.isLobbyCreator = true;
|
|
this.requestUpdate();
|
|
}
|
|
|
|
if (this.game.inSpawnPhase()) {
|
|
// Singleplayer has no spawn timer (SpawnTimerExecution isn't added), so
|
|
// the spawn phase doesn't count down — keep the old static display.
|
|
if (this.game.config().gameConfig().gameType === GameType.Singleplayer) {
|
|
const maxTimerValue = this.game.config().gameConfig().maxTimerValue;
|
|
this.timer =
|
|
maxTimerValue !== null && maxTimerValue !== undefined
|
|
? maxTimerValue * 60
|
|
: 0;
|
|
return;
|
|
}
|
|
const spawnPhaseDurationTicks = this.game.config().numSpawnPhaseTurns();
|
|
const currentTicks = this.game.ticks();
|
|
const remainingTicks = spawnPhaseDurationTicks - currentTicks;
|
|
const remainingSeconds = Math.ceil(remainingTicks / 10);
|
|
this.timer = Math.max(0, remainingSeconds);
|
|
return;
|
|
}
|
|
|
|
const elapsedSeconds = Math.floor(this.game.elapsedGameSeconds());
|
|
|
|
if (this.hasWinner) {
|
|
return;
|
|
}
|
|
|
|
const maxTimerValue = this.game.config().gameConfig().maxTimerValue;
|
|
if (maxTimerValue !== null && maxTimerValue !== undefined) {
|
|
this.timer = Math.max(0, maxTimerValue * 60 - elapsedSeconds);
|
|
} else {
|
|
this.timer = elapsedSeconds;
|
|
}
|
|
}
|
|
|
|
private updateParentOffset(): void {
|
|
const offset =
|
|
(this.spawnBarVisible ? 7 : 0) + (this.immunityBarVisible ? 7 : 0);
|
|
const parent = this.parentElement as HTMLElement;
|
|
if (parent) {
|
|
parent.style.marginTop = `${offset}px`;
|
|
}
|
|
}
|
|
|
|
private secondsToHms = (d: number): string => {
|
|
const pad = (n: number) => (n < 10 ? `0${n}` : n);
|
|
|
|
const h = Math.floor(d / 3600);
|
|
const m = Math.floor((d % 3600) / 60);
|
|
const s = Math.floor((d % 3600) % 60);
|
|
|
|
if (h !== 0) {
|
|
return `${pad(h)}:${pad(m)}:${pad(s)}`;
|
|
} else {
|
|
return `${pad(m)}:${pad(s)}`;
|
|
}
|
|
};
|
|
|
|
private toggleReplayPanel(): void {
|
|
this._isReplayVisible = !this._isReplayVisible;
|
|
this.eventBus.emit(
|
|
new ShowReplayPanelEvent(this._isReplayVisible, this._isSinglePlayer),
|
|
);
|
|
}
|
|
|
|
private onPauseButtonClick() {
|
|
this.isPaused = !this.isPaused;
|
|
if (this.isPaused) {
|
|
crazyGamesSDK.gameplayStop();
|
|
} else {
|
|
crazyGamesSDK.gameplayStart();
|
|
}
|
|
this.eventBus.emit(new PauseGameIntentEvent(this.isPaused));
|
|
}
|
|
|
|
private async onNewLobbyButtonClick() {
|
|
if (this.newLobbyRequested) return;
|
|
// Confirm so a stray click next to pause/exit doesn't yank everyone into a
|
|
// new lobby mid-game.
|
|
const isConfirmed = await showInGameConfirm(
|
|
translateText("new_lobby_prompt.confirm"),
|
|
{ variant: "warning" },
|
|
);
|
|
if (!isConfirmed) return;
|
|
if (this.newLobbyRequested) return; // clicked again while confirming
|
|
this.newLobbyRequested = true;
|
|
this.requestUpdate();
|
|
try {
|
|
// The worker mints the successor lobby and has the current game
|
|
// broadcast its id, so everyone else gets the NewLobbyPrompt. We (the
|
|
// host) navigate straight to the new host view from the response.
|
|
const lobby = await createNextLobby(this.game.gameID());
|
|
const id = lobby.gameID;
|
|
// ?host routes the creator back into the host view on load.
|
|
window.location.href = `${window.location.origin}/${ClientEnv.workerPath(id)}/game/${id}?host`;
|
|
} catch (error) {
|
|
console.error("Failed to create successor lobby", error);
|
|
this.newLobbyRequested = false;
|
|
this.requestUpdate();
|
|
void showInGameAlert(translateText("new_lobby_prompt.failed"));
|
|
}
|
|
}
|
|
|
|
private async onExitButtonClick() {
|
|
const isAlive = this.game.myPlayer()?.isAlive();
|
|
if (isAlive) {
|
|
const isConfirmed = await showInGameConfirm(
|
|
translateText("help_modal.exit_confirmation"),
|
|
);
|
|
if (!isConfirmed) return;
|
|
}
|
|
await crazyGamesSDK.requestMidgameAd();
|
|
await crazyGamesSDK.gameplayStop();
|
|
// redirect to the home page
|
|
window.location.href = "/";
|
|
}
|
|
|
|
private onSettingsButtonClick() {
|
|
this.eventBus.emit(
|
|
new ShowSettingsModalEvent(true, this._isSinglePlayer, this.isPaused),
|
|
);
|
|
}
|
|
|
|
private onFullscreenButtonClick() {
|
|
if (!document.fullscreenElement) {
|
|
document.documentElement.requestFullscreen().catch((err) => {
|
|
console.warn("Failed to enter fullscreen:", err);
|
|
});
|
|
} else {
|
|
document.exitFullscreen().catch((err) => {
|
|
console.warn("Failed to exit fullscreen:", err);
|
|
});
|
|
}
|
|
}
|
|
|
|
render() {
|
|
if (this.game === undefined) return html``;
|
|
|
|
const timerColor =
|
|
this.game.config().gameConfig().maxTimerValue !== undefined &&
|
|
this.game.config().gameConfig().maxTimerValue !== null &&
|
|
this.timer < 60
|
|
? "text-red-400"
|
|
: "";
|
|
|
|
return html`
|
|
<aside
|
|
class=${`w-fit flex flex-row items-center gap-3 py-2 px-3 bg-gray-800/92 backdrop-blur-sm shadow-xs min-[1200px]:rounded-lg rounded-bl-lg transition-transform duration-300 ease-out transform text-white ${
|
|
this._isVisible ? "translate-x-0" : "translate-x-full"
|
|
}`}
|
|
@contextmenu=${(e: Event) => e.preventDefault()}
|
|
>
|
|
<!-- In-game time -->
|
|
<div class=${timerColor}>${this.secondsToHms(this.timer)}</div>
|
|
|
|
<!-- Buttons -->
|
|
${this.maybeRenderReplayButtons()}
|
|
|
|
<div class="cursor-pointer" @click=${this.onSettingsButtonClick}>
|
|
<img src=${settingsIcon} alt="settings" width="20" height="20" />
|
|
</div>
|
|
|
|
${document.fullscreenEnabled && !this.onCrazyGames
|
|
? html`<div
|
|
class="cursor-pointer"
|
|
@click=${this.onFullscreenButtonClick}
|
|
>
|
|
<img
|
|
src=${this.isFullscreen ? exitFullscreenIcon : fullscreenIcon}
|
|
alt=${this.isFullscreen
|
|
? translateText("fullscreen.exit")
|
|
: translateText("fullscreen.enter")}
|
|
width="20"
|
|
height="20"
|
|
/>
|
|
</div>`
|
|
: ""}
|
|
|
|
<div class="cursor-pointer" @click=${this.onExitButtonClick}>
|
|
<img src=${exitIcon} alt="exit" width="20" height="20" />
|
|
</div>
|
|
</aside>
|
|
<doomsday-clock-panel
|
|
.game=${this.game}
|
|
.hasWinner=${this.hasWinner}
|
|
.refreshKey=${this.timer}
|
|
></doomsday-clock-panel>
|
|
`;
|
|
}
|
|
|
|
maybeRenderReplayButtons() {
|
|
const isReplayOrSingleplayer =
|
|
this._isSinglePlayer || this.game?.config()?.isReplay();
|
|
const showPauseButton = isReplayOrSingleplayer || this.isLobbyCreator;
|
|
// The host of a private lobby can start a fresh lobby at any time, without
|
|
// waiting to die or for the game to end.
|
|
const showNewLobbyButton = this.isLobbyCreator && this.isPrivateLobby;
|
|
|
|
return html`
|
|
${isReplayOrSingleplayer
|
|
? html`
|
|
<div class="cursor-pointer" @click=${this.toggleReplayPanel}>
|
|
<img
|
|
src=${FastForwardIconSolid}
|
|
alt="replay"
|
|
width="20"
|
|
height="20"
|
|
/>
|
|
</div>
|
|
`
|
|
: ""}
|
|
${showPauseButton
|
|
? html`
|
|
<div class="cursor-pointer" @click=${this.onPauseButtonClick}>
|
|
<img
|
|
src=${this.isPaused ? playIcon : pauseIcon}
|
|
alt="play/pause"
|
|
width="20"
|
|
height="20"
|
|
/>
|
|
</div>
|
|
`
|
|
: ""}
|
|
${showNewLobbyButton
|
|
? html`
|
|
<div
|
|
class="cursor-pointer ${this.newLobbyRequested
|
|
? "opacity-50 pointer-events-none"
|
|
: ""}"
|
|
@click=${this.onNewLobbyButtonClick}
|
|
title=${translateText("win_modal.new_lobby")}
|
|
>
|
|
<img
|
|
src=${newLobbyIcon}
|
|
alt=${translateText("win_modal.new_lobby")}
|
|
width="20"
|
|
height="20"
|
|
/>
|
|
</div>
|
|
`
|
|
: ""}
|
|
`;
|
|
}
|
|
}
|