Allow cooperative choices to reopen with fair time credits and improve mobile controls

This commit is contained in:
coyotte508 2026-09-11 11:29:54 +02:00
commit 0907ad6b7b
13 changed files with 400 additions and 91 deletions

View file

@ -7,7 +7,7 @@
"engine": {
"package": {
"name": "fuji-engine",
"version": "0.1.4"
"version": "0.1.5"
},
"entryPoint": "dist/wrapper.js"
},

View file

@ -16,15 +16,15 @@ Upload the engine tarball and viewer JS/CSS together. The draft registration fil
## Live updates and remaining timed-beta work
The platform's [isLiveUpdate contract](https://docs.boardgamers.space/guide/engine-api#isliveupdate) is supported. BGS calls this hook on the saved state (the return value of `toSave`, or the move result when `toSave` is absent). Fuji returns true for route edits and readiness changes that leave the planning phase open. These updates preserve active seats, persist and broadcast without any turn side effects.
Fuji uses the BGS `isLiveUpdate: true`, `timeIncrements` and `canMoveOutOfTurn` hooks. Deploy platform support before publishing this engine. Route edits and readiness changes in an open planning, reroll or equipment phase synchronize active seats. Confirmed players become inactive immediately; reopening resumes their remaining clock. Unchanged active players retain their existing clocks.
Planning is one collective validation: only the final confirmation that starts rerolling is a normal turn save. Its actor receives the planning increment; other players do not receive a separate planning increment. Repeated ready → route edit → ready cycles earn nothing while the phase stays open. Definitive equipment actions, rerolls and other gameplay actions retain normal turn handling. This is an explicit alpha clock policy, not an equal per-player planning allowance; review it during multiplayer testing.
Players can reopen only their own choices while the phase is open, with no pending equipment response or injury. Revealed dice, spent equipment and resolved movement cannot be undone. Gatherer bars are awarded once when the whole team finishes rerolling, so reopening preserves unused rerolls without duplicating rewards.
The engine overwrites a single `planningSnapshot` containing only paths, readiness and revision. Provisional edits append neither replay-history entries nor public log lines. A definitive action checkpoints the latest snapshot once into replay history, then records the action. Final routes enter the public log when planning closes. The history therefore grows with definitive actions, not pointer clicks or repeated confirmations. Replaying the head also restores the pending snapshot, including after JSON serialization. The snapshot and the `liveUpdate` protocol marker are excluded from viewer projections; public paths and readiness remain visible normally.
Readiness edits overwrite the bounded `planningSnapshot` (paths, readiness, completed decisions and revision), including during reroll and equipment. They append neither history entries nor public log lines. Actual gameplay actions and phase transitions checkpoint it once for deterministic replay. The snapshot and `liveUpdate` marker are excluded from viewer projections.
No further platform protocol extension is needed for these updates. Existing development saves from before this history change are not a supported replay migration; start a new local game when testing this alpha.
Every player's first confirmation earns an increment, including the last confirmation that advances the phase. Reopening and reconfirming the same choice earns nothing. Equipment effects or gifts that reset readiness create new decisions, so confirming again earns another increment. Actual equipment uses, rerolls and other definitive actions continue to earn their normal increment. `timeIncrements` replaces the default mover increment; the last confirmer is never credited twice.
During planning and equipment phases `currentPlayer` includes all players, including those marked ready, so the BGS turn gate permits revisions and reactions before the phase closes. This also means their clocks keep running until the phase changes; the UX and clock policy need explicit integration testing.
Completion counts and confirmation flags are kept in the private `turns` field and replayed with the readiness snapshot. They grow only for completed decisions and are excluded from viewer projections. Equipment reactivations are bounded by the finite card supply and uses; only the manager can give cards away.
Fuji has a shared win/loss. The wrapper gives all players the same ranking and reports their individual contributions, but BGS's result display and Elo handling need to be checked for a cooperative title. A group loss must not appear as a competitive draw or grant inappropriate Elo.

View file

@ -10,7 +10,7 @@
"fmt": "oxfmt",
"fmt:check": "oxfmt --check",
"simulate": "pnpm --filter fuji-engine build && node scripts/simulate.mjs",
"test:browser": "node tests/browser-smoke.mjs && node tests/bgs-bundle-smoke.mjs && node tests/presentation-smoke.mjs && node tests/chat-smoke.mjs"
"test:browser": "node tests/browser-smoke.mjs && node tests/bgs-bundle-smoke.mjs && node tests/presentation-smoke.mjs && node tests/chat-smoke.mjs && node tests/mobile-readiness-smoke.mjs"
},
"devDependencies": {
"oxfmt": "0.61.0",

View file

@ -1,6 +1,6 @@
{
"name": "fuji-engine",
"version": "0.1.4",
"version": "0.1.5",
"private": true,
"license": "AGPL-3.0-only",
"files": [

View file

@ -236,6 +236,8 @@ test("gatherer caps stored bars and applies them only to active movement total",
s.players[1]!.powerBars = 2;
s.players[1]!.rerolls = 3;
s = applyMove(s, { action: "finishRerolls" }, 1);
assert.equal(s.players[1]!.powerBars, 2);
s = applyMove(s, { action: "finishRerolls" }, 0);
assert.equal(s.players[1]!.powerBars, 3);
s.phase = "movement";
s.activeResolution = 0;
@ -1419,3 +1421,111 @@ test("AI crosses a choke point before lava disconnects the otherwise safe side",
"the extra wave would consume that destination"
);
});
test("reopening cooperative choices is bounded, preserves rerolls and replays", async () => {
const wrapper = await import("../wrapper.js");
let s = prepared();
// Distinct destinations allow the simultaneous planning phase to close.
for (let i = 0; i < 3; i++) {
const path = Object.values(paths(s, i)).find(
(path) => !s.players.some((p, j) => j !== i && p.ready && p.path.at(-1) === path.at(-1))
)!;
s = applyMove(s, { action: "plan", path }, i);
s = applyMove(s, { action: "ready" }, i);
}
assert.equal(s.phase, "reroll");
const gatherer = s.players.findIndex((p) => p.skill === "gatherer");
const initial = structuredClone(s.players[gatherer]!);
const history = s.history.length,
log = s.log.length;
for (let i = 0; i < 100; i++) {
s = applyMove(s, { action: "finishRerolls" }, gatherer);
assert.equal(wrapper.canMoveOutOfTurn(s, { action: "unready" }, gatherer), true);
assert.equal(wrapper.canMoveOutOfTurn(s, { action: "reroll", ids: [] }, gatherer), false);
s = applyMove(s, { action: "unready" }, gatherer);
}
assert.equal(s.players[gatherer]!.rerolls, initial.rerolls);
assert.equal(s.players[gatherer]!.powerBars, initial.powerBars);
assert.equal(s.history.length, history);
assert.equal(s.log.length, log);
assert.deepEqual(replay(s), s);
while (s.phase === "reroll") s = applyMove(s, { action: "finishRerolls" }, activePlayers(s)[0]!);
assert.equal(s.phase, "equipment");
const seat = activePlayers(s)[0]!;
const history2 = s.history.length,
log2 = s.log.length;
for (let i = 0; i < 100; i++) {
s = applyMove(s, { action: "ready" }, seat);
assert.equal(s.phase, "equipment");
s = applyMove(s, { action: "unready" }, seat);
}
assert.equal(s.history.length, history2);
assert.equal(s.log.length, log2);
assert.deepEqual(replay(s), s);
s.phase = "movement";
assert.equal(wrapper.canMoveOutOfTurn(s, { action: "unready" }, seat), false);
assert.throws(() => applyMove(s, { action: "unready" }, seat));
});
test("every explorer earns one planning completion, including the last, with no reconfirm credit", async () => {
const { timeIncrements, isLiveUpdate } = await import("../wrapper.js");
for (const players of [3, 4]) {
let s = prepared(players);
const baseline = timeIncrements(s);
s = applyMove(s, { action: "ready" }, 0);
s = applyMove(s, { action: "unready" }, 0);
const newDestination = Object.values(paths(s, 0)).find((route) => route.at(-1) !== s.players[0]!.position)!;
s = applyMove(s, { action: "plan", path: newDestination }, 0);
s = applyMove(s, { action: "ready" }, 0);
for (let n = 0; n < 100; n++) {
s = applyMove(s, { action: "unready" }, 0);
s = applyMove(s, { action: "ready" }, 0);
}
assert.equal(timeIncrements(s)[0], baseline[0]! + 1);
assert(isLiveUpdate(s));
assert.deepEqual(replay(JSON.parse(JSON.stringify(s))), s);
for (let i = 1; i < players; i++) {
const path = Object.values(paths(s, i)).find(
(route) => !s.players.some((p, j) => j !== i && p.ready && p.path.at(-1) === route.at(-1))
)!;
s = applyMove(s, { action: "plan", path }, i);
s = applyMove(s, { action: "ready" }, i);
}
assert.equal(s.phase, "reroll");
assert.equal(isLiveUpdate(s), false);
assert.deepEqual(
timeIncrements(s),
baseline.map((n) => n + 1)
);
assert.deepEqual(replay(s), s);
assert.equal("turns" in stripSecret(s, 0), false);
}
});
test("teammate changes renew confirmation credit while manual undo does not", async () => {
const { timeIncrements, currentPlayer } = await import("../wrapper.js");
let s = withPhase("equipment");
s.players.forEach((p) => (p.cards = [{ id: "aid", used: 0, availableRound: 0 }]));
s.players[2]!.cards = [
{ id: "machete", used: 0, availableRound: 0 },
{ id: "water", used: 0, availableRound: 0 },
];
s = applyMove(s, { action: "ready" }, 0);
const confirmed = timeIncrements(s)[0]!;
s = applyMove(s, { action: "unready" }, 0);
s = applyMove(s, { action: "ready" }, 0);
assert.equal(timeIncrements(s)[0], confirmed);
s = applyMove(s, { action: "give", id: "machete", target: 0 }, 2);
assert.equal(s.players[0]!.ready, false);
assert.equal(timeIncrements(s)[0], confirmed, "new credit waits for confirmation");
s = applyMove(s, { action: "ready" }, 0);
assert.equal(timeIncrements(s)[0], confirmed + 1);
s = applyMove(s, { action: "unready" }, 0);
s = applyMove(s, { action: "ready" }, 0);
assert.equal(timeIncrements(s)[0], confirmed + 1);
s = applyMove(s, { action: "equipment", id: "water", target: 0 }, 2);
assert.equal(currentPlayer(s), 0);
assert.equal(timeIncrements(s)[0], confirmed + 1);
s = applyMove(s, { action: "respond", ids: [s.players[0]!.dice[0]!.id] }, 0);
assert.equal(timeIncrements(s)[0], confirmed + 2);
assert.throws(() => applyMove(s, { action: "give", id: "machete", target: 0 }, 2));
});

View file

@ -143,8 +143,17 @@ function diceEvent(s: State, label: string, dice: Die[]) {
dice: structuredClone(dice),
});
}
function turnProgress(s: State) {
return (s.turns ??= s.players.map(() => ({ increments: 0, credited: false })));
}
function confirmTurn(s: State, seat: number) {
const turn = turnProgress(s)[seat]!;
if (!turn.credited) turn.increments++;
turn.credited = true;
}
function phase(s: State, next: State["phase"]) {
s.phase = next;
for (const turn of turnProgress(s)) turn.credited = false;
for (const p of s.players) {
p.ready = false;
p.radio = false;
@ -239,6 +248,7 @@ export function initGame(players = 3, options: Record<string, unknown> = {}, see
if (!Number.isInteger(scenario) || scenario < 1 || scenario > 7) throw Error("Choose scenario 1–7.");
const s: State = {
schemaVersion: 1,
turns: Array.from({ length: players }, () => ({ increments: 0, credited: false })),
seed,
counter: 0,
round: 0,
@ -384,7 +394,15 @@ function validatePath(s: State, p: Player, input: unknown, max: number) {
}
return route;
}
function equipmentDecision(s: State | View, p: Player): boolean {
return (
(hasSkill(p, "manager") && p.cards.length > 0) ||
(!p.injuries.includes("arm") &&
p.cards.some((c) => c.availableRound <= s.round && (equipment(c.id).phases as readonly number[]).includes(4)))
);
}
function resetReady(s: State) {
for (const turn of turnProgress(s)) turn.credited = false;
for (const p of s.players) p.ready = false;
}
function afterMovement(s: State) {
@ -545,6 +563,16 @@ function useEquipment(s: State, seat: number, m: Move) {
if (id === "torch") s.log.at(-1)!.sound = "dice";
if (setAside) s.log.at(-1)!.setAside = structuredClone(setAside);
}
export function canReopenChoice(s: State | View, seat: number): boolean {
const p = s.players[seat];
if (!p?.ready || s.outcome || s.pending || s.skillChoices?.length || s.players.some((p) => p.pendingInjuries))
return false;
if (s.phase === "planning") return true;
if (s.phase === "reroll")
return activeDice(p).length > 0 && (p.rerolls > 0 || (hasSkill(p, "buddy") && !p.buddyUsed));
if (s.phase === "equipment") return equipmentDecision(s, p);
return false;
}
function execute(s: State, m: Move, seat: number) {
if (s.outcome) throw Error("The expedition has ended.");
const p = s.players[seat];
@ -635,6 +663,12 @@ function execute(s: State, m: Move, seat: number) {
p.ready = false;
break;
}
case "unready": {
if (!canReopenChoice(s, seat))
throw Error("You can only reopen your own choice while the team is still choosing.");
p.ready = false;
break;
}
case "ready": {
if (s.phase !== "planning" && s.phase !== "equipment") throw Error("You cannot confirm in this phase.");
if (p.ready) throw Error("Already ready.");
@ -646,8 +680,9 @@ function execute(s: State, m: Move, seat: number) {
)
throw Error("Neighbors need different destinations.");
}
confirmTurn(s, seat);
p.ready = true;
if (s.phase !== "planning") event(s, `${p.name} is ready.`, "move", true);
if (s.players.every((p) => p.ready)) {
if (s.phase === "planning") {
for (const [seat, player] of s.players.entries()) {
@ -684,10 +719,9 @@ function execute(s: State, m: Move, seat: number) {
}
case "finishRerolls": {
if (s.phase !== "reroll" || p.ready) throw Error("Rerolls are already complete.");
if (hasSkill(p, "gatherer")) p.powerBars = Math.min(3, p.powerBars + p.rerolls);
p.rerolls = 0;
confirmTurn(s, seat);
p.ready = true;
if (s.players.every((p) => p.ready)) phase(s, "equipment");
finishTeamRerolls(s);
break;
}
case "buddy": {
@ -934,6 +968,14 @@ function finishAssistance(s: State, seat: number) {
}
if (!s.pendingHelpers?.length) execute(s, { action: "resolve" }, seat);
}
function finishTeamRerolls(s: State) {
if (!s.players.every((p) => p.ready)) return;
for (const p of s.players) {
if (hasSkill(p, "gatherer")) p.powerBars = Math.min(3, p.powerBars + p.rerolls);
p.rerolls = 0;
}
phase(s, "equipment");
}
function advanceRerolls(s: State) {
if (s.phase !== "reroll") return;
for (const p of s.players) {
@ -941,11 +983,9 @@ function advanceRerolls(s: State) {
const diceAvailable = activeDice(p).length > 0;
const canSetAside = diceAvailable && hasSkill(p, "buddy") && !p.buddyUsed;
if (canSetAside || (diceAvailable && p.rerolls > 0)) continue;
if (hasSkill(p, "gatherer")) p.powerBars = Math.min(3, p.powerBars + p.rerolls);
p.rerolls = 0;
p.ready = true;
}
if (s.players.every((p) => p.ready)) phase(s, "equipment");
finishTeamRerolls(s);
}
function advanceMovement(s: State) {
if (s.initOptions.autoMovement !== true) return;
@ -999,13 +1039,7 @@ function advanceForcedActions(s: State) {
if (s.pending || s.players.some((p) => p.pendingInjuries)) break;
if (s.phase === "equipment") {
for (const p of s.players) {
const canGive = hasSkill(p, "manager") && p.cards.length > 0;
const canUse =
!p.injuries.includes("arm") &&
p.cards.some(
(card) => card.availableRound <= s.round && (equipment(card.id).phases as readonly number[]).includes(4)
);
if (!canGive && !canUse) p.ready = true;
if (!equipmentDecision(s, p)) p.ready = true;
}
if (!s.players.every((p) => p.ready)) break;
phase(s, "movement");
@ -1038,6 +1072,7 @@ function restorePlanning(s: State, snapshot: PlanningSnapshot) {
p.ready = snapshot.players[i]!.ready;
});
s.revision = snapshot.revision;
s.turns = structuredClone(snapshot.turns);
s.planningSnapshot = structuredClone(snapshot);
s.liveUpdate = true;
}
@ -1066,16 +1101,18 @@ export function applyMove(data: State, input: unknown, seat: number): State {
if (JSON.stringify(move).length > 3000) throw Error("Move is too large.");
const s = structuredClone(data);
execute(s, move, seat);
if (!["plan", "ready", "unready", "finishRerolls"].includes(move.action)) turnProgress(s)[seat]!.increments++;
advanceForcedActions(s);
s.revision++;
const live =
data.phase === "planning" &&
s.phase === "planning" &&
["planning", "reroll", "equipment"].includes(data.phase) &&
s.phase === data.phase &&
s.round === data.round &&
(move.action === "plan" || move.action === "ready");
["plan", "ready", "unready", "finishRerolls"].includes(move.action);
if (live) {
s.liveUpdate = true;
s.planningSnapshot = {
turns: structuredClone(turnProgress(s)),
players: s.players.map((p) => ({ path: [...p.path], ready: p.ready })),
revision: s.revision,
};
@ -1094,6 +1131,7 @@ export function stripSecret(s: State, seat?: number): View {
initOptions: ____,
liveUpdate: _____,
planningSnapshot: ______,
turns: _______,
...publicState
} = structuredClone(s);
const revealed = s.phase === "movement" || s.phase === "eruption" || s.phase === "ended";

View file

@ -80,11 +80,17 @@ export interface Pending {
required: boolean;
receiver?: number;
}
export interface TurnProgress {
increments: number;
credited: boolean;
}
export interface PlanningSnapshot {
turns: TurnProgress[];
players: { path: string[]; ready: boolean }[];
revision: number;
}
export interface State {
turns?: TurnProgress[];
skillChoices?: number[];
liveUpdate?: boolean;
planningSnapshot?: PlanningSnapshot;
@ -113,7 +119,7 @@ export interface State {
}
export interface View extends Omit<
State,
"seed" | "counter" | "deck" | "history" | "initOptions" | "liveUpdate" | "planningSnapshot"
"seed" | "counter" | "deck" | "history" | "initOptions" | "liveUpdate" | "planningSnapshot" | "turns"
> {
deckCount: number;
}

View file

@ -3,6 +3,7 @@ import {
applyMove,
stripSecret,
activePlayers,
canReopenChoice,
dropGamePlayer,
setPlayerName,
replay as replayGame,
@ -11,8 +12,15 @@ import type { State } from "./src/types.js";
export { stripSecret };
export { moveAI } from "./src/ai.js";
export const hashSeed = true;
// BGS evaluates the saved state. A live update must preserve active seats.
// State sharing and time awards are independent.
export const timeIncrements = (s: State): number[] => s.players.map((_, i) => s.turns?.[i]?.increments ?? 0);
export const isLiveUpdate = (s: State): boolean => s.liveUpdate === true;
export const canMoveOutOfTurn = (s: State, move: unknown, player: number): boolean =>
canReopenChoice(s, player) &&
!!move &&
typeof move === "object" &&
"action" in move &&
(move.action === "unready" || (s.phase === "planning" && move.action === "plan"));
export async function init(players: number, expansions: string[], options: Record<string, unknown>, seed: string) {
if (expansions.length) throw Error("No expansions are implemented.");
return initGame(players, options, seed);
@ -22,7 +30,7 @@ export function move(data: State, input: unknown, player: number) {
}
export const ended = (s: State) => s.outcome !== null;
export const currentPlayer = (s: State) => {
const seats = activePlayers(s).filter((i) => s.phase !== "planning" || !s.players[i]!.ready);
const seats = activePlayers(s).filter((i) => s.pending || s.phase !== "planning" || !s.players[i]!.ready);
return seats.length === 1 ? seats[0] : seats.length ? seats : undefined;
};
export const round = (s: State) => s.round;

View file

@ -1,4 +1,5 @@
<script lang="ts">
import { equipmentPopover } from "./lib/equipmentPopover";
import ChatPanel from "./lib/ChatPanel.svelte";
import { untrack } from "svelte";
import {
@ -23,6 +24,7 @@
hasSkill,
activeDice,
activePlayers,
canReopenChoice,
type EquipmentId,
type View,
} from "fuji-engine";
@ -279,7 +281,7 @@
function mobileAction() {
if (!s || !me) return;
if (s.pending || me.pendingInjuries || s.phase === "setup") {
document.querySelector(".journey")?.scrollIntoView({ behavior: "smooth" });
document.querySelector(".journey-actions")?.scrollIntoView({ behavior: "smooth" });
return;
}
if (s.phase === "planning") {
@ -292,12 +294,12 @@
return;
}
if (s.phase === "equipment") {
document.querySelector(".journey")?.scrollIntoView({ behavior: "smooth" });
store.dispatch({ action: me.ready ? "unready" : "ready" });
return;
}
if (s.phase === "movement") {
if (s.activeResolution === null && !me.resolved) store.dispatch({ action: "beginMovement" });
else document.querySelector(".journey")?.scrollIntoView({ behavior: "smooth" });
else document.querySelector(".journey-actions")?.scrollIntoView({ behavior: "smooth" });
return;
}
if (s.phase === "eruption" && seat === 0) store.dispatch({ action: "erupt" });
@ -316,7 +318,9 @@
: s.phase === "reroll"
? "Dice actions"
: s.phase === "equipment"
? "Equipment & reveal"
? me.ready
? "Change equipment"
: "Ready to reveal"
: s.phase === "movement"
? "Resolve journey"
: "Advance lava"
@ -480,9 +484,28 @@
</div>
</details>{/if}
</div>
{#if me && !s.outcome}<div class="mobile-dock">
<div>
<span class="eyebrow">{s.phase}</span><strong
>{s.phase === "planning"
? `${destination?.name ?? ""} · ${destination ? total(me, destination.id) : 0}`
: s.phase === "reroll"
? `${me.rerolls} rerolls remaining`
: me.name}</strong
>
</div>
<button
onclick={mobileAction}
disabled={store.waiting ||
(s.phase === "planning" && !me.ready && !!reserved[currentRoute.at(-1)!]) ||
(s.phase === "reroll" && me.ready) ||
(s.phase === "equipment" && me.ready && !canReopenChoice(s, seat!)) ||
(s.phase === "eruption" && seat !== 0)}>{mobileLabel} →</button
>
</div>{/if}
<section class="team" aria-label="Your expedition">
{#each s.players as p, i}
<button
<article
class="teammate"
class:own={seat === i}
class:opposite={s.players.length === 4 && seat !== undefined && i === (seat + 2) % 4}
@ -491,16 +514,15 @@
: undefined}
class:can-act={actingSeats.includes(i)}
style:--player-color={CHARACTER_COLORS[p.character]}
onclick={() => {
if (store.local) store.selectSeat(i);
else store.clickPlayer(i);
}}
aria-label={`${p.name}${seat === i ? ", you" : ""}${actingSeats.includes(i) ? ", can act now" : ""}. ${EXHAUSTION - p.stamina} stamina remaining${p.skill === "gatherer" ? `, ${p.powerBars} power bars` : ""}${store.local ? ". Switch to this player." : ""}`}
>
<img src={art("character", p.character + 1)} alt="" class="portrait" />
<div class="teammate-info">
<span class="teammate-name"
>{p.name}{#if seat === i}<small>YOU</small>{/if}</span
<button
type="button"
class="teammate-name"
onclick={() => (store.local ? store.selectSeat(i) : store.clickPlayer(i))}
>{p.name}{#if seat === i}<small>YOU</small>{/if}</button
><span
class="role-name"
title={s.skillChoices?.includes(i)
@ -562,24 +584,26 @@
</div>
{#if p.cards.length}<span class="teammate-equipment" aria-label="Equipment">
{#each p.cards as c}{@const info = EQUIPMENT.find((e) => e.id === c.id)!}
<span
<button
type="button"
use:equipmentPopover
class="equipment-chip"
class:packed={c.availableRound > s.round}
title={`${info.name}: ${info.description}`}
aria-label={`${info.name}: ${info.description}`}
>
<EquipmentIcon id={c.id} />
<span class="equipment-preview">
<img src={art("equipment", EQUIPMENT.indexOf(info) + 1)} alt={info.name} />
<span
><strong>{info.name}</strong><span>{info.description}</span>
<span class="equipment-phases"
>{#each info.phases as phase}<span
title={phase === 2 ? "Use during planning" : "Use during equipment"}
><PhaseIcon phase={phase === 2 ? 0 : 2} />{phase === 2 ? "Plan" : "Equip"}</span
>{/each}</span
>
{#if c.availableRound > s.round}<em>Available from round {c.availableRound}</em>{/if}
</span>
<EquipmentIcon id={c.id} /></button
>
<span class="equipment-preview" popover="auto">
<img src={art("equipment", EQUIPMENT.indexOf(info) + 1)} alt={info.name} />
<span
><strong>{info.name}</strong><span>{info.description}</span>
<span class="equipment-phases"
>{#each info.phases as phase}<span
title={phase === 2 ? "Use during planning" : "Use during equipment"}
><PhaseIcon phase={phase === 2 ? 0 : 2} />{phase === 2 ? "Plan" : "Equip"}</span
>{/each}</span
>
{#if c.availableRound > s.round}<em>Available from round {c.availableRound}</em>{/if}
</span>
</span>
{/each}
@ -593,7 +617,7 @@
title={`Injury at ${EXHAUSTION - threshold} stamina remaining`}><span>◆</span></span
>{/each}
</span>
</button>
</article>
{/each}
</section>
<div class="game-layout">
@ -652,6 +676,11 @@
</p>{/if}
{#if s.phase === "reroll"}<section class="reroll-actions" aria-label="Dice actions">
{#if me.ready}<p class="confirmed">✓ Your dice are kept. Waiting for the team.</p>
<button
class="text-button"
onclick={() => store.dispatch({ action: "unready" })}
disabled={store.waiting || !canReopenChoice(s, seat!)}>Change my dice choices</button
>
{:else}
<div class="reroll-choice">
<strong>{me.rerolls} reroll{me.rerolls === 1 ? "" : "s"} remaining</strong>
@ -933,7 +962,12 @@
class="primary"
onclick={() => store.dispatch({ action: "ready" })}
disabled={store.waiting}>Ready to reveal <span>→</span></button
>{:else}<p class="confirmed">✓ Ready. Waiting for the team.</p>{/if}
>{:else}<p class="confirmed">✓ Ready. Waiting for the team.</p>
<button
class="text-button"
onclick={() => store.dispatch({ action: "unready" })}
disabled={store.waiting || !canReopenChoice(s, seat!)}>Change my choice</button
>{/if}
{:else if s.phase === "movement"}
{#if s.activeResolution === null}<p class="instruction">
Choose who moves next. A route that triggers extra lava is often best resolved last.
@ -1224,24 +1258,6 @@
{#each s.ghost as d}<Die colorblind={store.colorblind} die={d} disabled />{/each}
</div>
</details>{/if}
{#if me && !s.outcome}<div class="mobile-dock">
<div>
<span class="eyebrow">{s.phase}</span><strong
>{s.phase === "planning"
? `${destination?.name ?? ""} · ${destination ? total(me, destination.id) : 0}`
: s.phase === "reroll"
? `${me.rerolls} rerolls remaining`
: me.name}</strong
>
</div>
<button
onclick={mobileAction}
disabled={store.waiting ||
(s.phase === "planning" && !me.ready && !!reserved[currentRoute.at(-1)!]) ||
(s.phase === "reroll" && me.ready) ||
(s.phase === "eruption" && seat !== 0)}>{mobileLabel} →</button
>
</div>{/if}
</main>
{:else}<div class="waiting">
<h1>FUJI</h1>

View file

@ -0,0 +1,53 @@
// Top-layer previews avoid clipping inside the scrolling player strip.
export function equipmentPopover(node: HTMLButtonElement) {
const preview = node.nextElementSibling as HTMLElement;
let pinned = false;
const toggled = () => {
if (!preview.matches(":popover-open")) pinned = false;
};
const close = () => {
pinned = false;
preview.hidePopover();
};
const open = () => {
preview.showPopover();
const anchor = node.getBoundingClientRect();
const box = preview.getBoundingClientRect();
const width = document.documentElement.clientWidth;
preview.style.left = `${Math.max(8, Math.min(anchor.left, width - box.width - 8))}px`;
preview.style.top = `${Math.max(8, Math.min(anchor.bottom + 6, window.innerHeight - box.height - 8))}px`;
};
const enter = (e: PointerEvent) => {
if (e.pointerType === "mouse") open();
};
const leave = () => {
if (!pinned) close();
};
const click = () => {
if (pinned) close();
else {
open();
pinned = true;
}
};
preview.addEventListener("toggle", toggled);
node.addEventListener("pointerenter", enter);
node.addEventListener("pointerleave", leave);
node.addEventListener("focus", open);
node.addEventListener("blur", leave);
node.addEventListener("click", click);
window.addEventListener("resize", close);
window.addEventListener("scroll", close, true);
return {
destroy() {
preview.removeEventListener("toggle", toggled);
node.removeEventListener("pointerenter", enter);
node.removeEventListener("pointerleave", leave);
node.removeEventListener("focus", open);
node.removeEventListener("blur", leave);
node.removeEventListener("click", click);
window.removeEventListener("resize", close);
window.removeEventListener("scroll", close, true);
},
};
}

View file

@ -1073,19 +1073,15 @@ h3 {
display: none;
}
@media (max-width: 850px) {
.expedition {
padding-bottom: 90px;
}
.mobile-dock {
position: fixed;
bottom: 0;
left: 0;
right: 0;
position: sticky;
top: 0;
margin: 0 -12px 12px;
z-index: 20;
background: #152e26f5;
backdrop-filter: blur(10px);
border-top: 1px solid #dcc48766;
padding: 12px 16px max(12px, env(safe-area-inset-bottom));
padding: 8px 14px;
display: flex;
align-items: center;
gap: 12px;
@ -1189,7 +1185,7 @@ h3 {
}
@media (max-width: 850px) {
.expedition {
padding: 6px 12px 90px;
padding: 6px 12px 16px;
}
.game-tools {
gap: 12px;
@ -1518,13 +1514,10 @@ h3 {
line-height: 1.5;
pointer-events: none;
}
.equipment-chip:hover .equipment-preview {
.equipment-preview:popover-open {
display: flex;
}
.teammate:last-child .equipment-preview {
left: auto;
right: 0;
}
.equipment-preview img {
width: 75px;
height: 104px;
@ -1646,10 +1639,10 @@ h3 {
}
.teammate {
cursor: pointer;
cursor: default;
}
.teammate:hover .teammate-name,
.teammate:focus-visible .teammate-name {
.teammate-name:hover,
.teammate-name:focus-visible {
color: var(--gold);
text-decoration: underline;
text-underline-offset: 3px;
@ -1684,3 +1677,32 @@ h3 {
.role-name[title] {
cursor: help;
}
button.teammate-name {
background: none;
border: 0;
padding: 0;
text-align: left;
color: inherit;
}
button.teammate-name:hover {
text-decoration: underline;
color: var(--gold);
}
button.equipment-chip {
border: 0;
}
.equipment-preview {
position: fixed;
margin: 0;
inset: auto;
width: min(300px, calc(100vw - 16px));
max-height: calc(100dvh - 16px);
overflow-y: auto;
pointer-events: auto;
}
@media (max-width: 850px) {
.mobile-dock button {
min-height: 40px;
}
}

View file

@ -92,6 +92,10 @@ fs.mkdirSync("work/browser", { recursive: true });
if (errors.length || !s.outcome) throw Error("Playtest incomplete");
await page.screenshot({ path: "work/browser/fuji-result.png", fullPage: true });
const autoPage = await browser.newPage();
await autoPage.addInitScript(
(game) => localStorage.setItem("fuji-dev-v1", JSON.stringify(game)),
initGame(3, { skillAssignment: "fixed" }, "first-light")
);
await autoPage.goto("http://127.0.0.1:5187");
await autoPage.getByText("Playtest tools", { exact: true }).click();
const auto = autoPage.getByRole("checkbox", { name: "Automatically play teammates" });

View file

@ -0,0 +1,52 @@
import { chromium } from "playwright";
import assert from "node:assert/strict";
const root = process.cwd() + "/";
const { initGame, applyMove, stripSecret } = await import(root + "packages/engine/dist/index.js");
let state = initGame(3, { skillAssignment: "fixed" }, "mobile-readiness");
for (let i = 0; i < 3; i++)
if (!state.players[i].setupDone)
state = applyMove(
state,
{ action: "setup", keep: state.players[i].cards.slice(0, i === 2 ? 2 : 1).map((c) => c.id) },
i
);
const browser = await chromium.launch({ executablePath: process.env.FUJI_CHROMIUM_EXECUTABLE, headless: true });
const page = await browser.newPage({ viewport: { width: 390, height: 740 }, isMobile: true, hasTouch: true });
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.setContent('<meta name="viewport" content="width=device-width, initial-scale=1"><div id="app"></div>');
await page.addStyleTag({ path: root + "packages/viewer/dist/fuji-viewer.css" });
await page.addScriptTag({ path: root + "packages/viewer/dist/fuji-viewer.iife.js" });
await page.evaluate(
(s) => {
window.events = [];
window.bridge = fuji.launch("#app");
bridge.on("player:clicked", (p) => events.push(["player", p]));
bridge.on("move", (p) => events.push(["move", p]));
bridge.emit("player", { index: 0 });
bridge.emit("state", s);
},
stripSecret(state, 0)
);
await page.locator(".teammate-status").first().click();
assert.deepEqual(await page.evaluate(() => events), []);
await page.locator(".teammate-name").first().click();
assert.equal((await page.evaluate(() => events))[0][0], "player");
for (const index of [0, 2]) {
await page.locator(".teammate").nth(index).locator(".equipment-chip").first().click();
const rect = await page.locator(".equipment-preview:popover-open").boundingBox();
assert(rect && rect.x >= 0 && rect.x + rect.width <= 390 && rect.y >= 0 && rect.y + rect.height <= 740);
await page.keyboard.press("Escape");
}
await page.evaluate(() => scrollTo(0, 600));
const rect = await page.locator(".mobile-dock").boundingBox();
assert(rect && rect.y >= -1 && rect.y < 5);
await page.locator(".mobile-dock button").click();
assert.equal((await page.evaluate(() => events)).at(-1)[1].action, "ready");
assert.deepEqual(errors, []);
console.log(
"Mobile ready button remains visible; only username emits player click; equipment previews fit first/last cards."
);
await browser.close();