Pace expedition playback with sound and refine journal, equipment choices and AI

This commit is contained in:
coyotte508 2026-09-08 17:58:34 +02:00
commit de72c83e90
20 changed files with 989 additions and 56 deletions

10
docs/audio-credits.md Normal file
View file

@ -0,0 +1,10 @@
# Audio credits
`packages/viewer/src/assets/dice-roll.mp3` is adapted from `dice-29.wav` in **2 dice roll (29 throws)** by **RPG**, published 30 August 2013 on OpenGameArt.
- Source: https://opengameart.org/content/2-dice-roll-29-throws
- Original archive: https://opengameart.org/sites/default/files/Dice%20sound.7z
- License: CC0 1.0, https://creativecommons.org/publicdomain/zero/1.0/
- Adaptation: retain the first 1.42 seconds, remove low-frequency rumble, raise level by 2 dB, fade the final 60 ms, encode as mono MP3.
Movement, lava and equipment cues are synthesized by the viewer and use no external recordings. All cues follow the platform `preferences.sound` setting.

View file

@ -64,6 +64,12 @@ Automatic equipment passes use only public eligibility (cards, phase, injuries),
### Baseline AI
`moveAI(state, player)` is exported from both the engine and BGS wrapper and returns a new state through `applyMove`. The local harness and full-game simulations call the same implementation. Decisions use `stripSecret` for that player, with no access to hidden teammate dice or the random seed. The route heuristic prioritizes destinations outside the next eruption, then balances own matching total, village distance, distance from lava, pickups and eruption markers. Rerolls target nonmatching dice; unused rerolls yield Gatherer bars. It spends the minimum bars that turn a failed comparison into success. It does not optimize equipment use or Gatherer bar farming.
`moveAI(state, player)` is exported from both the engine and BGS wrapper and returns a new state through `applyMove`. The local harness and full-game simulations call the same implementation. Decisions use `stripSecret` for that player, with no access to hidden teammate dice or the random seed. The route heuristic prioritizes destinations outside the next eruption, then balances expected comparison lead after the available rerolls, village distance, distance from lava, pickups and eruption markers. Expectations use the published die faces and only publicly visible teammate faces. Rerolls include low matching faces when rolling again improves expected contribution; unused rerolls yield Gatherer bars. This is a heuristic, not a guarantee of movement or a full model of teammates’ future rerolls. It spends the minimum bars that turn a failed comparison into success. It does not optimize equipment use or Gatherer bar farming.
The wrapper's `currentPlayer` excludes players with confirmed planning intentions, so the platform bot driver does not repeatedly play an already-ready bot. Provisional confirmations remain live updates; the platform's stored clock behavior is unchanged.
## Viewer event pacing
Public movement paths and eruption cell lists in journal events allow the viewer to sequence automatic resolution without extra engine moves or saved intermediate states. The map and journal play events in order, with a skip control; the authoritative received state and platform clocks are unchanged. Initial loads and seat changes show the current state immediately. Reduced motion skips intermediate path positions. The local bot driver waits for playback and uses a 2.2-second action cadence. Confirmed-route journal records preserve the original terrain, equipment and eruption markers and reroll allowance. Equipment is public (rulebook page 8, face-up cards) and appears as pictograms with hover previews on player panels.
Sound effects combine a CC0 recording of real dice throws (see `audio-credits.md`) with synthesized Web Audio foley synchronized with presented events (steps, lava, dice, equipment), governed by the platform's reserved `preferences.sound` boolean (absent means enabled, per platform PR #503). No game-specific preference overrides the platform mute. The harness offers a local sound toggle, individual cue previews, and a random-seed restart. Copy equipment, shovel values, preparation dice and local game configuration expose their choices directly without select controls.

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"
"test:browser": "node tests/browser-smoke.mjs && node tests/bgs-bundle-smoke.mjs && node tests/presentation-smoke.mjs"
},
"devDependencies": {
"oxfmt": "0.61.0",

View file

@ -7,14 +7,29 @@ import {
neighbors,
paths,
cell,
total,
rerollAllowance,
activeDice,
face,
threatened,
} from "./game.js";
import { terrain, SKILLS, matches } from "./data.js";
import { terrain, SKILLS, matches, DICE, type Requirement } from "./data.js";
import type { State, View, Move } from "./types.js";
// Expected contribution after rolling, with the option to keep a result or
// try again. This uses the published die faces, never a teammate's hidden roll.
function rerollValue(type: number, requirement: Requirement, attempts: number): number {
let value = 0;
for (let i = 0; i < attempts; i++) {
const continuation = value;
value =
DICE[type]!.reduce((sum, color, index) => {
const contribution = matches({ color, value: index + 1 }, requirement) ? index + 1 : 0;
return sum + Math.max(contribution, continuation);
}, 0) / 6;
}
return value;
}
// Conservative playtest policy: spend the minimum that changes a failed
// comparison into a success, rather than saving every bar indefinitely.
export function choosePowerBars(state: State | View, helper: number): number {
@ -53,10 +68,33 @@ export function chooseMove(game: View, seat: number): Move {
const lavaDistance = Math.min(
...game.board.filter((tile) => tile.lava).map((tile) => Math.abs(c.x - tile.x) + Math.abs(c.y - tile.y))
);
const requirement = terrain(c.terrain).requirement;
const attempts = rerollAllowance(game, seat, path);
const expected = activeDice(p).reduce(
(sum, d) =>
sum + Math.max(matches(face(d), requirement) ? d.face : 0, rerollValue(d.type, requirement, attempts)),
p.bonus
);
const opposition = neighbors(game, seat).map((i) =>
activeDice(game.players[i]!).reduce(
(sum, d) =>
sum + (d.face ? (matches(face(d), requirement) ? d.face : 0) : rerollValue(d.type, requirement, 1)),
0
)
);
if (game.players.length === 2)
opposition.push(
game.ghost.reduce(
(sum, d) =>
sum + (d.face ? (matches(face(d), requirement) ? d.face : 0) : rerollValue(d.type, requirement, 1)),
0
)
);
const expectedLead = expected - Math.max(...opposition);
return (
(danger.has(c.id) ? -1000 : 0) -
12 / Math.max(1, lavaDistance) +
total(p, c.terrain) * 0.65 -
expectedLead * 1 -
closestVillage * 4 +
(terrain(c.terrain).kind === "village" ? 8 : 0) +
(c.equipment ? 1 : 0) -
@ -72,7 +110,7 @@ export function chooseMove(game: View, seat: number): Move {
if (game.phase === "reroll") {
const r = terrain(cell(game, p.path.at(-1)!).terrain).requirement;
const ids = activeDice(p)
.filter((d) => !matches(face(d), r))
.filter((d) => (matches(face(d), r) ? d.face : 0) < rerollValue(d.type, r, p.rerolls))
.map((d) => d.id);
return p.rerolls && ids.length ? { action: "reroll", ids } : { action: "finishRerolls" };
}

View file

@ -770,3 +770,94 @@ test("compact journey snapshots distinguish planned stays, failed comparisons an
);
}
});
test("AI rerolls weak matching dice but keeps strong matches without consulting hidden rolls", async () => {
const { chooseMove } = await import("../index.js");
const s = withPhase("reroll");
const p = s.players[1]!;
cell(s, p.path.at(-1)!).terrain = 4;
p.rerolls = 1;
p.dice.forEach((d) => (d.face = 1));
const weak = p.dice.find((d) => d.type === 1)!;
const strong = p.dice.find((d) => d.id !== weak.id)!;
strong.face = 6;
const choice = chooseMove(stripSecret(s, 1), 1);
assert.equal(choice.action, "reroll");
assert((choice.ids as string[]).includes(weak.id));
assert(!(choice.ids as string[]).includes(strong.id));
s.players[0]!.dice.forEach((d) => (d.face = 6));
assert.deepEqual(chooseMove(stripSecret(s, 1), 1), choice);
p.rerolls = 0;
assert.equal(chooseMove(stripSecret(s, 1), 1).action, "finishRerolls");
});
test("AI weighs reroll opportunities before committing to a weak three-step route", async () => {
const { chooseMove } = await import("../index.js");
const s = withPhase("planning");
s.players.forEach((p) => {
p.position = "0,0";
p.path = ["0,0"];
p.dice.forEach((d) => (d.face = 1));
});
s.board = [0, 1, 2, 3, 4].map((x) => ({
id: `${x},0`,
x,
y: 0,
terrain: x === 4 ? 30 : 4,
lava: false,
equipment: false,
eruption: 0,
}));
const choice = chooseMove(stripSecret(s, 1), 1);
const path = choice.action === "plan" ? (choice.path as string[]) : s.players[1]!.path;
assert(path.length < 4);
assert(rerollAllowance(s, 1, path) > 0);
s.players[0]!.dice.forEach((d) => (d.face = 6));
assert.deepEqual(chooseMove(stripSecret(s, 1), 1), choice);
});
test("confirmed route journal preserves terrain, pickups and untriggered eruptions", () => {
let s = withPhase("planning");
s.players[1]!.position = "0,3";
s.players[1]!.path = ["0,3"];
s.players[2]!.position = "1,2";
s.players[2]!.path = ["1,2"];
s.players[0]!.path = ["0,3", "1,3"];
cell(s, "1,3").eruption = 1;
cell(s, "1,3").equipment = true;
s.players[0]!.ready = true;
s.players[1]!.ready = true;
const expectedRerolls = rerollAllowance(s, 0);
s = applyMove(s, { action: "ready" }, 2);
const route = s.log.find((e) => e.route?.name === s.players[0]!.name)!.route!;
assert.equal(route.rerolls, expectedRerolls);
assert.deepEqual(route.cells.at(-1), { terrain: cell(s, "1,3").terrain, eruption: 1, equipment: true });
cell(s, "1,3").eruption = 0;
cell(s, "1,3").equipment = false;
assert.equal(route.cells.at(-1)!.eruption, 1);
assert.equal(route.cells.at(-1)!.equipment, true);
});
test("set-aside journal snapshots reveal only the chosen dice", () => {
for (const kind of ["buddy", "machete", "knife"] as const) {
let s = withPhase(kind === "buddy" ? "reroll" : "equipment");
const ids = s.players[0]!.dice.slice(0, kind === "buddy" ? 1 : 2).map((d) => d.id);
if (kind === "buddy") s = applyMove(s, { action: "buddy", ids }, 0);
else {
if (kind === "knife") s.players[1]!.cards = [{ id: "machete", used: 0, availableRound: 0 }];
s = equip(s, 0, kind, { ids, ...(kind === "knife" ? { copy: "machete" } : {}) });
}
const revealed = s.log.find((e) => e.setAside)!.setAside!;
assert.deepEqual(
revealed.map((d) => d.id),
ids
);
assert(revealed.every((d) => d.face > 0 && d.aside));
const frozen = structuredClone(revealed);
s.players[0]!.dice[0]!.face = 1;
assert.deepEqual(revealed, frozen);
const publicView = stripSecret(s, 1);
assert.deepEqual(publicView.log.find((e) => e.setAside)!.setAside, frozen);
assert(publicView.players[0]!.dice.filter((d) => !d.aside).every((d) => d.face === 0));
}
});

View file

@ -148,6 +148,7 @@ function phase(s: State, next: State["phase"]) {
}[next],
"phase"
);
if (next === "planning") s.log.at(-1)!.sound = "dice";
if (next === "movement") {
for (const p of s.players) diceEvent(s, `${p.name} revealed their dice`, p.dice);
if (s.ghost.length) diceEvent(s, "Neutral dice revealed", s.ghost);
@ -184,6 +185,7 @@ function erupt(s: State) {
const next = threatened(s);
for (const c of s.board) if (next.includes(c.id)) c.lava = true;
event(s, `Lava consumed ${next.length} location${next.length === 1 ? "" : "s"}.`, "eruption");
s.log.at(-1)!.animation = { kind: "eruption", cells: next };
const victim = s.players.find((p) => cell(s, p.position).lava);
if (victim) end(s, "lost", `${victim.name} was caught by the lava.`);
}
@ -390,6 +392,7 @@ function useEquipment(s: State, seat: number, m: Move) {
if (!(info.phases as readonly number[]).includes(s.phase === "planning" ? 2 : 4))
throw Error("This equipment is not usable in this phase.");
const target = () => integer(m.target, 0, s.players.length - 1);
let setAside: Die[] | undefined;
switch (id) {
case "binoculars": {
const ids = strings(m.tiles, 2);
@ -416,6 +419,8 @@ function useEquipment(s: State, seat: number, m: Move) {
const c = cell(s, ids[0]!);
if (!walkable(c) || terrain(c.terrain).kind !== "land" || distance(cell(s, p.position), c) !== 1)
throw Error("Choose an adjacent land location.");
event(s, `${p.name} moved to ${terrain(c.terrain).name} using Rope.`);
s.log.at(-1)!.animation = { kind: "move", seat, path: [p.position, c.id] };
p.position = c.id;
collect(s, p);
trigger(s, [c.id]);
@ -453,7 +458,8 @@ function useEquipment(s: State, seat: number, m: Move) {
break;
}
case "machete":
for (const d of selectedDice(p, m.ids, 1, 2)) d.aside = true;
setAside = selectedDice(p, m.ids, 1, 2);
for (const d of setAside) d.aside = true;
break;
case "lighter": {
const donor = target();
@ -480,6 +486,8 @@ function useEquipment(s: State, seat: number, m: Move) {
}
resetReady(s);
event(s, `${p.name} used ${equipment(card.id).name}${id !== card.id ? ` as ${info.name}` : ""}.`, "equipment");
if (id === "torch") s.log.at(-1)!.sound = "dice";
if (setAside) s.log.at(-1)!.setAside = structuredClone(setAside);
}
function execute(s: State, m: Move, seat: number) {
if (s.outcome) throw Error("The expedition has ended.");
@ -506,6 +514,7 @@ function execute(s: State, m: Move, seat: number) {
}
} else throw Error("Resolve the equipment effect first.");
event(s, `${p.name} resolved an equipment effect.`, "equipment");
if (pending.kind === "reroll") s.log.at(-1)!.sound = "dice";
finishPending(s);
return;
}
@ -550,7 +559,21 @@ function execute(s: State, m: Move, seat: number) {
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 player of s.players) event(s, `${player.name} chose ${player.path.join(" → ")}.`);
for (const [seat, player] of s.players.entries()) {
event(
s,
`${player.name} chose ${terrain(cell(s, player.path.at(-1)!).terrain).name} · ${player.path.length - 1} steps · ${rerollAllowance(s, seat)} rerolls.`
);
s.log.at(-1)!.route = {
name: player.name,
character: player.character,
rerolls: rerollAllowance(s, seat),
cells: player.path.map((id) => {
const c = cell(s, id);
return { terrain: c.terrain, eruption: c.eruption, equipment: c.equipment };
}),
};
}
phase(s, "reroll");
s.players.forEach((p, i) => {
p.rerolls = rerollAllowance(s, i);
@ -565,6 +588,7 @@ function execute(s: State, m: Move, seat: number) {
roll(s, dice);
p.rerolls--;
event(s, `${p.name} rerolled.`);
s.log.at(-1)!.sound = "dice";
break;
}
case "finishRerolls": {
@ -578,9 +602,11 @@ function execute(s: State, m: Move, seat: number) {
case "buddy": {
if (s.phase !== "reroll" || p.ready || !hasSkill(p, "buddy") || p.buddyUsed)
throw Error("This skill is unavailable.");
selectedDice(p, m.ids, 1, 1)[0]!.aside = true;
const die = selectedDice(p, m.ids, 1, 1)[0]!;
die.aside = true;
p.buddyUsed = true;
event(s, `${p.name} set a die aside.`);
s.log.at(-1)!.setAside = [structuredClone(die)];
break;
}
case "give": {
@ -694,6 +720,7 @@ function execute(s: State, m: Move, seat: number) {
`${p.name} reached ${terrain(cell(s, dest).terrain).name} (${result.own} vs ${Math.max(...result.peers.map((x) => x.total))}).`
);
s.log.at(-1)!.journey = journey;
if (journey.moved) s.log.at(-1)!.animation = { kind: "move", seat, path: [...route] };
win(s);
if (s.outcome) break;
collect(s, p);
@ -934,7 +961,10 @@ export function applyMove(data: State, input: unknown, seat: number): State {
advanceForcedActions(s);
s.revision++;
const live =
data.phase === "planning" && s.phase === "planning" && (move.action === "plan" || move.action === "ready");
data.phase === "planning" &&
s.phase === "planning" &&
s.round === data.round &&
(move.action === "plan" || move.action === "ready");
if (live) {
s.liveUpdate = true;
s.planningSnapshot = {

View file

@ -44,6 +44,15 @@ export interface Cell {
eruption: number;
}
export interface Event {
setAside?: Die[];
sound?: "dice";
route?: {
name: string;
character: number;
rerolls: number;
cells: { terrain: number; eruption: number; equipment: boolean }[];
};
animation?: { kind: "move"; seat: number; path: string[] } | { kind: "eruption"; cells: string[] };
detail?: boolean;
transfer?: { id: EquipmentId; from: string; to: string };
journey?: {

View file

@ -27,6 +27,7 @@
import { art } from "./lib/assets";
import Landscape from "./lib/Landscape.svelte";
import Die from "./lib/Die.svelte";
import EquipmentIcon from "./lib/EquipmentIcon.svelte";
import JournalEntry from "./lib/JournalEntry.svelte";
import PhaseIcon from "./lib/PhaseIcon.svelte";
import RequirementDisplay from "./lib/RequirementDisplay.svelte";
@ -56,7 +57,7 @@
let help = $state(false);
let journal = $state(true);
const journalEntries = $derived(
s?.log
store.journal
.filter((entry) => !entry.detail)
.slice()
.reverse() ?? []
@ -81,7 +82,18 @@
const focusTerrain = $derived(focus ? terrain(focus.terrain) : undefined);
const currentRoute = $derived(me?.path ?? []);
const destination = $derived(s && currentRoute.length ? terrain(cell(s, currentRoute.at(-1)!).terrain) : undefined);
const actionTool = $derived(tool === "knife" ? copied : tool);
const copyOptions = $derived(
EQUIPMENT.filter(
(info) =>
info.id !== "knife" &&
(info.phases as readonly number[]).includes(s?.phase === "planning" ? 2 : 4) &&
s?.players.some((p, i) => i !== seat && p.cards.some((c) => c.id === info.id && c.availableRound <= s.round))
)
);
$effect(() => {
if (tool === "knife" && !copyOptions.some((c) => c.id === copied) && copyOptions[0]) copied = copyOptions[0].id;
});
const actionTool = $derived(tool === "knife" ? (copyOptions.some((c) => c.id === copied) ? copied : null) : tool);
const pendingMe = $derived(s?.pending && seat !== undefined && s.pending.players.includes(seat));
const revealed = $derived(s?.phase === "movement" || s?.phase === "eruption" || s?.phase === "ended");
const resolvingSeat = $derived(s?.activeResolution ?? seat);
@ -271,8 +283,35 @@
onchange={(e) => store.setAutoTeammates(e.currentTarget.checked)}
/>Automatically play teammates</label
>
<button onclick={() => store.teammateStep()} disabled={!!s.outcome}>Play next teammate action</button>
<button onclick={() => store.teammateStep()} disabled={!!s.outcome || store.animating}
>Play next teammate action</button
>
<label class="auto-teammates"
><input
type="checkbox"
checked={store.sound}
onchange={(e) => {
store.setSound(e.currentTarget.checked);
localStorage.setItem("fuji-sound", String(e.currentTarget.checked));
}}
/>Sound effects</label
>
<fieldset class="visible-choices sound-tests">
<legend>Test sounds</legend>
<div class="choice-row">
<button disabled={!store.sound} onclick={() => store.testSound("step")}>Footstep</button>
<button disabled={!store.sound} onclick={() => store.testSound("dice")}>Dice</button>
<button disabled={!store.sound} onclick={() => store.testSound("lava")}>Lava</button>
<button disabled={!store.sound} onclick={() => store.testSound("gear")}>Equipment</button>
</div>
</fieldset>
<button onclick={() => (newGame = true)}>New game</button>
<button
onclick={() => {
newSeed = crypto.randomUUID().slice(0, 8);
store.restart(s.players.length, newSeed, s.difficulty);
}}>New random game</button
>
</div>
</details>{/if}
</div>
@ -326,6 +365,30 @@
: ""}</span
>
</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
class="equipment-chip"
class:packed={c.availableRound > s.round}
title={`${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>
</span>
</span>
{/each}
</span>{/if}
<span class="stamina-track" title="Injuries at 20, 15, 10 and 5 stamina remaining." aria-hidden="true">
<i style:width={`${(1 - p.stamina / EXHAUSTION) * 100}%`}></i>
{#each INJURY_AT as threshold}<span
@ -340,9 +403,14 @@
</section>
<div class="game-layout">
<div class="world-column">
{#if store.animating}<div class="presentation-status" role="status">
<span>Playing expedition events…</span><button class="text-button" onclick={() => store.skipPresentation()}
>Skip to latest</button
>
</div>{/if}
<Landscape
colorblind={store.colorblind}
state={s}
state={store.scene ?? s}
{seat}
{reserved}
selected={s.phase === "setup" ? "" : tool ? (tilePicks.at(-1) ?? "") : (currentRoute.at(-1) ?? "")}
@ -539,12 +607,14 @@
>{/each}
</div>
{#if !me.setupDone}
{#if SKILLS[me.skill].dice === 5}<label class="field"
>Choose the die to leave behind<select bind:value={drop}
>{#each me.dice as d}<option value={d.id}>Type {"ABC"[d.type]} · die {d.id.split("-")[1]}</option
>{/each}</select
></label
>{/if}
{#if SKILLS[me.skill].dice === 5}<fieldset class="visible-choices">
<legend>Choose the die to leave behind</legend>
<div class="choice-row">
{#each me.dice as d}<button aria-pressed={drop === d.id} onclick={() => (drop = d.id)}
>⚄ {"ABC"[d.type]} · {Number(d.id.split("-")[1]) + 1}</button
>{/each}
</div>
</fieldset>{/if}
<p class="packing-count">{keep.length} / {SKILLS[me.skill].keep} cards selected</p>
<button
class="primary"
@ -731,7 +801,8 @@
(info.phases as readonly number[]).includes(
s.phase === "planning" ? 2 : s.phase === "equipment" ? 4 : -1
) &&
!s.pending}
!s.pending &&
(c.id !== "knife" || copyOptions.length > 0)}
<button
class:usable={available}
class:open={tool === c.id}
@ -741,11 +812,13 @@
><strong>{info.name}</strong><span class="equipment-description">{info.description}</span><small
>{c.availableRound > s.round
? "Available next round"
: c.used
? "One use left"
: available
? "Available now"
: `Use during ${info.phases.map((p) => (p === 2 ? "planning" : "equipment")).join(" or ")}`}</small
: c.id === "knife" && !copyOptions.length
? "No equipment to copy this phase"
: c.used
? "One use left"
: available
? "Available now"
: `Use during ${info.phases.map((p) => (p === 2 ? "planning" : "equipment")).join(" or ")}`}</small
></span
><span class="equipment-plus">{tool === c.id ? "−" : "+"}</span></button
>
@ -755,14 +828,33 @@
(c) => c.id === tool
)!}{@const info = EQUIPMENT.find((e) => e.id === tool)!}
<div class="tool-form">
<p>{info.description}</p>
{#if tool === "knife"}<label class="field"
>Copy equipment<select bind:value={copied}
>{#each s.players.flatMap( (p, i) => (i === seat ? [] : p.cards.filter((c) => c.id !== "knife" && c.availableRound <= s.round)) ) as c}<option
value={c.id}>{EQUIPMENT.find((e) => e.id === c.id)?.name}</option
>{/each}</select
></label
>{/if}
{#if tool !== "knife"}<p>{info.description}</p>{/if}
{#if tool === "knife"}<fieldset class="visible-choices equipment-copy">
<legend>Copy equipment</legend>
{#each copyOptions as option}<button
class="copy-option"
aria-pressed={copied === option.id}
onclick={() => {
copied = option.id;
dice = [];
tilePicks = [];
}}
>
<EquipmentIcon id={option.id} /><span
><strong>{option.name}</strong>
<small
>{s.players
.filter(
(p, i) =>
i !== seat && p.cards.some((c) => c.id === option.id && c.availableRound <= s.round)
)
.map((p) => p.name)
.join(", ")}</small
>
<span>{option.description}</span></span
>
</button>{:else}<p>No equipment can be copied in this phase.</p>{/each}
</fieldset>{/if}
{#if ["water", "lighter", "map"].includes(actionTool ?? "")}
<PlayerChoices
players={s.players}
@ -787,11 +879,17 @@
? "one or more dice to reroll"
: "the dice"} below the map. {dice.length} selected.
</p>{/if}
{#if actionTool === "shovel"}<label class="field"
>New value<select bind:value={turnFace}
>{#each [1, 2, 3, 4, 5, 6] as n}<option value={n}>{n}</option>{/each}</select
></label
>{/if}
{#if actionTool === "shovel"}<fieldset class="visible-choices">
<legend>New value</legend>
<div class="choice-row">
{#each [1, 2, 3, 4, 5, 6] as n}<Die
die={{ ...(me.dice.find((d) => dice.includes(d.id)) ?? me.dice[0]!), face: n }}
selected={turnFace === n}
colorblind={store.colorblind}
onclick={() => (turnFace = n)}
/>{/each}
</div>
</fieldset>{/if}
{#if ["binoculars", "rope"].includes(actionTool ?? "")}<p class="muted small">
Choose {actionTool === "rope" ? "one adjacent location" : "two empty land locations"} on the map. {tilePicks.length}
selected.
@ -800,6 +898,7 @@
class="secondary"
disabled={store.waiting ||
c.availableRound > s.round ||
(tool === "knife" && !copyOptions.some((option) => option.id === copied)) ||
me.injuries.includes("arm") ||
!(info.phases as readonly number[]).includes(
s.phase === "planning" ? 2 : s.phase === "equipment" ? 4 : -1
@ -807,6 +906,7 @@
!!s.pending ||
(actionTool === "machete" && (dice.length < 1 || dice.length > 2)) ||
(actionTool === "torch" && dice.length === 0) ||
(actionTool === "shovel" && dice.length !== 1) ||
(actionTool === "map" && (dice.length !== 1 || target === seat))}
onclick={confirmTool}>Use {info.name}</button
>
@ -964,17 +1064,27 @@
>
<h2 id="new-title">Gather your expedition.</h2>
<p>This replaces the current local playtest.</p>
<label class="field"
>Adventurers<select bind:value={newPlayers}
><option value={2}>2 players · neutral dice variant</option><option value={3}>3 players</option><option
value={4}>4 players</option
></select
></label
><label class="field"
>Difficulty<select bind:value={newDifficulty}
>{#each [1, 2, 3, 4] as n}<option value={n}>Level {n}</option>{/each}</select
></label
><label class="field">Expedition seed<input bind:value={newSeed} /></label><button
<fieldset class="visible-choices">
<legend>Adventurers</legend>
<div class="choice-row">
{#each [2, 3, 4] as n}<button aria-pressed={newPlayers === n} onclick={() => (newPlayers = n)}
>{n} players</button
>{/each}
</div>
{#if newPlayers === 2}<p class="muted small">Includes neutral dice.</p>{/if}
</fieldset>
<fieldset class="visible-choices">
<legend>Difficulty</legend>
<div class="choice-row">
{#each [1, 2, 3, 4] as n}<button aria-pressed={newDifficulty === n} onclick={() => (newDifficulty = n)}
>Level {n}</button
>{/each}
</div>
</fieldset>
<label class="field">Expedition seed<input bind:value={newSeed} /></label><button
class="text-button"
onclick={() => (newSeed = crypto.randomUUID().slice(0, 8))}>Randomize seed ↻</button
><button
class="primary"
onclick={() => {
store.restart(newPlayers, newSeed, newDifficulty);

Binary file not shown.

View file

@ -5,6 +5,7 @@ import { initGame, applyMove, moveAI, stripSecret, activePlayers, type State } f
import "./lib/theme.css";
const store = new Store();
store.local = true;
store.setSound(localStorage.getItem("fuji-sound") !== "false");
store.colorblind = localStorage.getItem("fuji-colorblind") === "true";
store.savePreference = (_name, value) => localStorage.setItem("fuji-colorblind", String(value));
store.seat = 0;
@ -25,6 +26,10 @@ function scheduleTeammate() {
clearTimeout(teammateTimer);
if (!store.autoTeammates || game.outcome || !availableSeats().some((i) => i !== store.seat)) return;
teammateTimer = setTimeout(() => {
if (store.animating) {
scheduleTeammate();
return;
}
const seat = availableSeats().find((i) => i !== store.seat);
if (!store.autoTeammates || seat === undefined) return;
try {
@ -34,14 +39,18 @@ function scheduleTeammate() {
store.setAutoTeammates(false);
store.error = String(e);
}
}, 750);
}, 2200);
}
store.setAutoTeammates = (enabled) => {
store.autoTeammates = enabled;
localStorage.setItem("fuji-auto-teammates", String(enabled));
scheduleTeammate();
};
if (import.meta.hot) import.meta.hot.dispose(() => clearTimeout(teammateTimer));
if (import.meta.hot)
import.meta.hot.dispose(() => {
clearTimeout(teammateTimer);
store.destroy();
});
function publish() {
localStorage.setItem("fuji-dev-v1", JSON.stringify(game));
store.receive(stripSecret(game, store.seat));
@ -62,6 +71,7 @@ store.restart = (players, seed, difficulty) => {
publish();
};
store.teammateStep = () => {
if (store.animating) return;
try {
const available = availableSeats();
const seat = available.find((i) => i !== store.seat) ?? available[0];

View file

@ -0,0 +1,33 @@
<script lang="ts">
import type { EquipmentId } from "fuji-engine";
let { id }: { id: EquipmentId } = $props();
const paths: Record<EquipmentId, string> = {
binoculars: "M3 10V5h5v5m8 0V5h5v5M8 12h8M4 10a4 4 0 1 0 0 8 4 4 0 0 0 0-8m16 0a4 4 0 1 0 0 8 4 4 0 0 0 0-8",
flare: "M3 9h15v5H9v7H4v-7H3ZM18 9l3-3m-1 6h3M18 5V2",
rope: "M8 18c-9-5-4-16 4-15s11 12 3 14S7 8 12 8s5 9 0 13M5 19l-2 3",
shovel: "M9 2h6v4l-3 3-3-3ZM12 9v7m-5 0h10v3l-5 4-5-4Z",
torch: "M8 14h8l-2 8h-4ZM8 11c-4-5 4-6 3-10 7 5 9 10 3 11M11 10l2-4",
knife: "M5 15 16 4l5-1-2 5L8 19ZM5 15l-3 3 4 4 3-3",
water: "M9 2h6v4l3 3v12H6V9l3-3ZM6 12h12M9 6h6",
aid: "M8 6V3h8v3M3 7h18v14H3ZM12 10v8m-4-4h8",
radio: "M6 8V1m0 7h13v14H5V8ZM8 12h8M8 16h2m3 0h3m-8 3h2m3 0h3M10 3l8 3",
tape: "M12 3a9 9 0 1 0 9 9V3ZM12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8M21 12v9h-6",
machete: "M5 17 15 3h6c-1 6-6 12-13 17ZM5 17l-3 3 3 3 3-3",
lighter: "M6 11h12v11H6ZM6 11V7h7v4m1-5c-2-2 1-3 2-5 3 4 3 6 0 7",
carabiner: "M8 3c-5 0-6 7-5 12s4 8 8 6l8-6c5-4 2-12-3-12ZM15 4 8 18",
compass: "M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20M16 7l-3 7-6 3 3-7Z",
map: "M2 5l7-3 6 3 7-3v17l-7 3-6-3-7 3ZM9 2v17m6-14v17",
};
</script>
<svg
viewBox="0 0 24 24"
width="24"
height="24"
fill="none"
stroke="currentColor"
stroke-width="1.6"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"><path d={paths[id]} /></svg
>

View file

@ -1,17 +1,45 @@
<script lang="ts">
import { EQUIPMENT, terrain, type Event } from "fuji-engine";
import { art } from "./assets";
import PhaseIcon from "./PhaseIcon.svelte";
import RequirementDisplay from "./RequirementDisplay.svelte";
import Die from "./Die.svelte";
let { entry, colorblind }: { entry: Event; colorblind: boolean } = $props();
</script>
{#if entry.journey}{@const j = entry.journey}
{#if entry.route}{@const r = entry.route}
<div class="route-log">
<img class="log-portrait" src={art("character", r.character + 1)} alt="" />
<strong>{r.name}</strong><span>planned</span>
<span class="route-locations">
{#each r.cells as c, i}
{#if i > 0}<span aria-hidden="true">→</span>{/if}
<span class="route-location" title={terrain(c.terrain).name}>
<img class="log-location" src={art("land", c.terrain)} alt={terrain(c.terrain).name} />
{#if i > 0 && c.eruption}<span class="route-hazard" title={`Triggers ${c.eruption} extra eruption(s)`}
><PhaseIcon phase={4} />{#if c.eruption > 1}{c.eruption}{/if}</span
>{/if}
{#if i === r.cells.length - 1 && c.equipment}<span title="Equipment at destination"
><PhaseIcon phase={2} /></span
>{/if}
</span>
{/each}
</span>
<span class="route-requirement"
><RequirementDisplay requirement={terrain(r.cells.at(-1)!.terrain).requirement} {colorblind} /></span
>
<span title="Movement distance">{r.cells.length - 1} step{r.cells.length === 2 ? "" : "s"}</span>
<span class="route-rerolls" title={`${r.rerolls} rerolls available on this route`}
><PhaseIcon phase={1} />{r.rerolls}</span
>
</div>
{:else if entry.journey}{@const j = entry.journey}
<details class="journey-log">
<summary>
<img class="log-portrait" src={art("character", j.character + 1)} alt="" />
<strong>{j.name}</strong>
<span class:failed={j.reason === "comparison" || j.reason === "blocked"}>
{j.moved ? "→ Moved" : "• Stayed"}
{j.moved ? "→ Moved" : j.reason === "planned-stay" ? "• Stayed" : "× Could not move"}
</span>
<img class="log-location" src={art("land", j.terrain)} alt="" />
<span>{terrain(j.terrain).name}</span>
@ -37,6 +65,11 @@
<img class="log-card" src={art("equipment", EQUIPMENT.findIndex((c) => c.id === t.id) + 1)} alt="" />
<span>{EQUIPMENT.find((c) => c.id === t.id)!.name}</span><span>→</span><strong>{t.to}</strong>
</div>
{:else if entry.setAside}
<div class="journal-dice aside-log">
<span>{entry.text}</span>
{#each entry.setAside as d}<Die die={{ ...d, aside: false }} {colorblind} disabled />{/each}
</div>
{:else if entry.dice}
<details class="revealed-log">
<summary>⚄ {entry.diceLabel ?? entry.text}</summary>
@ -57,6 +90,39 @@
{/if}
<style>
.route-log,
.route-locations,
.route-location,
.route-rerolls {
display: flex;
align-items: center;
gap: 6px;
}
.route-log {
flex-wrap: wrap;
gap: 6px 9px;
}
.route-locations {
flex-wrap: wrap;
}
.route-requirement {
width: 84px;
}
.route-requirement :global(svg) {
height: 24px;
}
.route-location :global(svg),
.route-rerolls :global(svg) {
width: 16px;
height: 16px;
}
.route-hazard {
display: inline-flex;
color: #e79b65;
}
.aside-log {
align-items: center;
}
.event-icon {
margin-right: 6px;
}

View file

@ -382,12 +382,24 @@
.lava .tile-art {
opacity: 0.65;
}
@keyframes lava-arrive {
from {
stroke-width: 10;
opacity: 0;
}
to {
stroke-width: 2;
opacity: 1;
}
}
.lava-crack {
fill: none;
stroke: #f5ae4a;
stroke-width: 2;
stroke-linecap: round;
animation: pulse 4s ease-in-out infinite;
animation:
lava-arrive 0.8s ease-out,
pulse 4s ease-in-out infinite;
}
.route-shadow {
fill: none;

View file

@ -0,0 +1,144 @@
import diceRollUrl from "../assets/dice-roll.mp3?url";
export type SoundCue = "step" | "lava" | "dice" | "gear";
// Recorded dice and synthesized foley. No background loop or game RNG usage.
export class SoundDesign {
private context?: AudioContext;
private master?: GainNode;
private noise?: AudioBuffer;
private diceRoll?: AudioBuffer;
private diceLoading?: Promise<void>;
private stopVersion = 0;
private enabled = true;
private sources = new Set<AudioScheduledSourceNode>();
constructor() {
document.addEventListener("pointerdown", this.unlock);
document.addEventListener("keydown", this.unlock);
}
private unlock = () => {
if (!this.enabled) return;
try {
if (!this.context) {
this.context = new AudioContext();
this.master = this.context.createGain();
this.master.gain.value = 0.3;
this.master.connect(this.context.destination);
this.noise = this.context.createBuffer(1, this.context.sampleRate, this.context.sampleRate);
const samples = this.noise.getChannelData(0);
let seed = 314159;
for (let i = 0; i < samples.length; i++) {
seed ^= seed << 13;
seed ^= seed >>> 17;
seed ^= seed << 5;
samples[i] = (seed >>> 0) / 2147483648 - 1;
}
}
if (!this.diceLoading)
this.diceLoading = fetch(diceRollUrl)
.then((response) => response.arrayBuffer())
.then((data) => this.context!.decodeAudioData(data))
.then((buffer) => {
this.diceRoll = buffer;
})
.catch(() => {});
void this.context.resume().catch(() => {});
} catch {
/* Autoplay or unavailable audio must never interrupt play. */
}
};
setEnabled(enabled: boolean) {
this.enabled = enabled;
if (!enabled) this.stop();
}
stop() {
this.stopVersion++;
for (const source of this.sources) {
try {
source.stop();
} catch {}
}
this.sources.clear();
}
destroy() {
this.stop();
document.removeEventListener("pointerdown", this.unlock);
document.removeEventListener("keydown", this.unlock);
void this.context?.close().catch(() => {});
}
async preview(cue: SoundCue) {
if (!this.enabled) return;
this.stop();
const version = this.stopVersion;
this.unlock();
try {
await this.context?.resume();
if (cue === "dice") await this.diceLoading;
if (version === this.stopVersion) this.play(cue);
} catch {
/* Audio may be blocked by the browser. */
}
}
play(cue: SoundCue) {
const context = this.context;
if (!this.enabled || !context || context.state !== "running" || document.hidden) return;
if (cue === "dice") {
if (!this.diceRoll) return;
const source = context.createBufferSource();
source.buffer = this.diceRoll;
source.connect(this.master!);
this.sources.add(source);
source.onended = () => {
this.sources.delete(source);
source.disconnect();
};
source.start();
return;
}
const pulse = (
offset: number,
duration: number,
frequency: number,
volume: number,
noise = false,
impact = false
) => {
const at = context.currentTime + offset;
const source = noise ? context.createBufferSource() : context.createOscillator();
if (source instanceof AudioBufferSourceNode) source.buffer = this.noise!;
else {
source.type = "sine";
source.frequency.setValueAtTime(frequency, at);
source.frequency.exponentialRampToValueAtTime(frequency * (impact ? 1 : 0.6), at + duration);
}
const filter = context.createBiquadFilter();
filter.type = impact && noise ? "bandpass" : "lowpass";
filter.Q.value = impact ? 3 : 0.7;
filter.frequency.value = frequency;
const envelope = context.createGain();
envelope.gain.setValueAtTime(0, at);
envelope.gain.linearRampToValueAtTime(volume, at + Math.min(impact ? 0.001 : 0.035, duration / 4));
envelope.gain.exponentialRampToValueAtTime(0.001, at + duration);
source.connect(filter).connect(envelope).connect(this.master!);
this.sources.add(source);
source.onended = () => {
this.sources.delete(source);
source.disconnect();
filter.disconnect();
envelope.disconnect();
};
source.start(at);
source.stop(at + duration + 0.01);
};
if (cue === "step") {
pulse(0, 0.12, 110, 0.5);
pulse(0.01, 0.16, 900, 0.35, true);
} else if (cue === "lava") {
pulse(0, 0.85, 48, 0.45);
pulse(0, 0.9, 450, 0.9, true);
pulse(0.18, 0.5, 1200, 0.16, true);
} else {
pulse(0, 0.09, 680, 0.2);
pulse(0.025, 0.14, 1400, 0.18, true);
}
}
}

View file

@ -1,6 +1,53 @@
import { SoundDesign, type SoundCue } from "./sound";
import type { View, Move } from "fuji-engine";
export class Store {
state: View | null = $state(null);
private audio = new SoundDesign();
sound = $state(true);
setSound(enabled: boolean) {
this.sound = enabled;
this.audio.setEnabled(enabled);
}
testSound(cue: SoundCue) {
void this.audio.preview(cue);
}
destroy() {
this.dispose();
this.audio.destroy();
}
scene: View | null = $state(null);
journal: View["log"] = $state([]);
animating = $state(false);
private received: View | null = null;
private receivedSeat: number | undefined;
private frames: { scene: View; duration: number; cue?: SoundCue }[] = [];
private animationTimer: ReturnType<typeof setTimeout> | undefined;
private playFrame() {
const frame = this.frames.shift();
if (!frame) {
this.scene = this.state;
this.journal = this.state?.log ?? [];
this.animating = false;
this.waiting = false;
return;
}
this.animating = true;
this.waiting = true;
this.scene = frame.scene;
this.journal = frame.scene.log;
if (frame.cue) this.audio.play(frame.cue);
this.animationTimer = setTimeout(() => this.playFrame(), frame.duration);
}
dispose() {
clearTimeout(this.animationTimer);
this.audio.stop();
this.frames = [];
this.animating = false;
}
skipPresentation() {
this.dispose();
this.playFrame();
}
seat: number | undefined = $state(undefined);
error = $state("");
waiting = $state(false);
@ -18,6 +65,7 @@ export class Store {
restart: (players: number, seed: string, difficulty: number) => void = () => {};
teammateStep: () => void = () => {};
dispatch(move: Move) {
if (this.animating) return;
this.error = "";
this.waiting = true;
try {
@ -28,7 +76,53 @@ export class Store {
}
}
receive(s: View) {
const previous = this.received;
const reset =
!previous ||
this.receivedSeat !== this.seat ||
s.revision < previous.revision ||
s.log.length < previous.log.length ||
document.hidden;
this.received = s;
this.receivedSeat = this.seat;
this.state = s;
this.waiting = false;
if (reset) {
this.dispose();
this.scene = s;
this.journal = s.log;
this.waiting = false;
return;
}
if (s.revision === previous.revision) {
if (!this.animating) {
this.scene = s;
this.journal = s.log;
this.waiting = false;
}
return;
}
const scene = structuredClone(previous);
const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)").matches;
for (const event of s.log.slice(previous.log.length)) {
scene.log.push(event);
const action = event.animation;
const cue = event.sound ?? (event.type === "equipment" ? "gear" : undefined);
if (action?.kind === "move") {
for (const position of reducedMotion ? action.path.slice(-1) : action.path.slice(1)) {
scene.players[action.seat]!.position = position;
this.frames.push({ scene: structuredClone(scene), duration: 700, cue: "step" });
}
} else if (action?.kind === "eruption" && action.cells.length) {
for (const cell of scene.board) if (action.cells.includes(cell.id)) cell.lava = true;
this.frames.push({ scene: structuredClone(scene), duration: 1100, cue: "lava" });
} else if (!event.detail && (event.type !== "phase" || cue)) {
this.frames.push({
scene: structuredClone(scene),
duration: cue === "dice" ? 1500 : 1100,
cue,
});
}
}
if (!this.animating) this.playFrame();
}
}

View file

@ -1468,3 +1468,153 @@ h3 {
letter-spacing: 0.08em;
text-transform: uppercase;
}
.teammate-equipment {
display: flex;
flex-wrap: wrap;
gap: 5px;
width: 100%;
}
.equipment-chip {
position: relative;
display: inline-flex;
padding: 4px;
border-radius: 4px;
color: #e4d29b;
background: #0c292a66;
}
.equipment-chip.packed {
color: #85978b;
}
.equipment-preview {
display: none;
position: absolute;
top: 100%;
left: 0;
z-index: 30;
width: 270px;
padding: 12px;
gap: 12px;
background: #122e29;
border: 1px solid #bfa97866;
border-radius: 6px;
box-shadow: 0 8px 24px #0008;
color: #cdd7bf;
font-size: 12px;
line-height: 1.5;
pointer-events: none;
}
.equipment-chip:hover .equipment-preview {
display: flex;
}
.teammate:last-child .equipment-preview {
left: auto;
right: 0;
}
.equipment-preview img {
width: 75px;
height: 104px;
object-fit: contain;
}
.equipment-preview > span {
display: grid;
gap: 6px;
}
.equipment-preview strong {
color: #ecd99e;
}
.presentation-status {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 8px 14px;
font-size: 12px;
color: #bdcaaa;
}
.visible-choices {
border: 0;
padding: 0;
margin: 16px 0;
min-width: 0;
}
.visible-choices legend {
font-size: 12px;
color: #c4d2b8;
margin-bottom: 8px;
}
.choice-row {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.choice-row > button:not(.die) {
padding: 9px 12px;
font-size: 12px;
}
.visible-choices button[aria-pressed="true"] {
border-color: #e3cb89;
box-shadow: inset 0 0 0 1px #e3cb89;
}
.equipment-copy {
display: grid;
gap: 8px;
}
.copy-option {
display: flex;
align-items: flex-start;
gap: 12px;
padding: 12px;
text-align: left;
}
.copy-option > svg {
flex: none;
color: #e3cb89;
}
.copy-option > span {
display: grid;
gap: 4px;
font-size: 12px;
}
.copy-option small {
color: #9eaf97;
}
.equipment-phases {
display: flex;
gap: 12px;
color: #e2ca8c;
}
.equipment-phases > span {
display: flex;
gap: 4px;
align-items: center;
}
.equipment-phases svg {
width: 16px;
height: 16px;
}
.dev-toolbar {
max-height: 75vh;
overflow-y: auto;
}
.sound-tests {
margin: 0;
}
.visible-choices button:not(.die) {
background: #152e27;
color: #d0dabd;
border: 1px solid #a9bea43d;
border-radius: 4px;
}
.visible-choices button:not(.die)[aria-pressed="true"] {
background: #29473a;
border-color: #e3cb89;
}
.visible-choices button:not(.die):hover {
background: #294136;
}

View file

@ -13,6 +13,7 @@ export function launch(selector: string) {
store.savePreference = (name, value) => events.emit("update:preference", { name, value });
events.on<Record<string, unknown>>("preferences", (preferences) => {
store.colorblind = preferences?.colorblind === true;
store.setSound(preferences?.sound !== false);
});
store.send = (move) => events.emit("move", move);
events.on<View>("state", async (state) => {

View file

@ -176,6 +176,32 @@ import path from "node:path";
const given = applyMove(managerState, giveMove, 0);
if (!given.players[2].cards.some((c) => c.id === "map")) throw Error("Map card was not transferred");
const knifeState = structuredClone(s);
knifeState.players[0].cards = [{ id: "knife", used: 0, availableRound: 0 }];
knifeState.players[1].cards = [
{ id: "map", used: 0, availableRound: 0 },
{ id: "shovel", used: 0, availableRound: 0 },
];
knifeState.players[2].cards = [{ id: "torch", used: 0, availableRound: 0 }];
await page.evaluate((v) => window.bridge.emit("state", v), stripSecret(knifeState, 0));
await page.locator(".equipment-list button").filter({ hasText: "Pocketknife" }).click();
const copies = page.getByRole("group", { name: "Copy equipment" });
if ((await copies.getByRole("button").count()) !== 2)
throw Error("Copy options must only show equipment usable in this phase");
await copies.getByRole("button", { name: /Shovel/ }).click();
await page.getByRole("group", { name: "New value" }).getByRole("button").nth(5).click();
if (await page.locator("select").count()) throw Error("Gameplay should expose choices without dropdowns");
await page.screenshot({ path: "work/browser/fuji-copy-equipment.png", fullPage: true });
knifeState.players[1].cards = [];
knifeState.revision++;
await page.evaluate((v) => window.bridge.emit("state", v), stripSecret(knifeState, 0));
const unavailableKnife = page.locator(".equipment-list button").filter({ hasText: "Pocketknife" });
if ((await unavailableKnife.getAttribute("class")).includes("usable"))
throw Error("Pocketknife advertised with no eligible copy target");
await unavailableKnife.click();
if (!(await page.getByRole("button", { name: "Use Pocketknife", exact: true }).isDisabled()))
throw Error("Empty copy action must be disabled");
s.phase = "movement";
s.activeResolution = null;
s.players[1].powerBars = 2;

View file

@ -28,6 +28,7 @@ fs.mkdirSync("work/browser", { recursive: true });
await page.getByText("Playtest tools", { exact: true }).click();
const step = page.getByRole("button", { name: "Play next teammate action" });
await step.click();
await page.getByRole("button", { name: "Skip to latest", exact: true }).waitFor({ state: "hidden", timeout: 60000 });
const state = () => page.evaluate(() => JSON.parse(localStorage.getItem("fuji-dev-v1")));
let s = await state();
if (s.phase !== "planning") throw Error("Setup did not finish");
@ -65,6 +66,8 @@ fs.mkdirSync("work/browser", { recursive: true });
if (await page.getByRole("button", { name: "Resolve my journey" }).count())
throw Error("New expeditions must not ask players to choose movement order");
await step.click();
if (await page.getByRole("button", { name: "Skip to latest", exact: true }).count())
await page.getByRole("button", { name: "Skip to latest", exact: true }).click();
count++;
if (await page.locator(".error").count()) throw Error(await page.locator(".error").innerText());
}

View file

@ -0,0 +1,100 @@
import { chromium } from "playwright";
import { initGame, stripSecret } from "../packages/engine/dist/index.js";
const browser = await chromium.launch({ headless: true, executablePath: process.env.FUJI_CHROMIUM_EXECUTABLE });
try {
const page = await browser.newPage();
await page.goto("http://127.0.0.1:5187/");
await page.locator(".map").waitFor();
await page.locator(".equipment-chip").first().hover();
await page.locator(".equipment-preview").first().waitFor({ state: "visible" });
await page.screenshot({ path: "work/browser/fuji-equipment-preview.png", fullPage: true });
const result = await page.evaluate(
async (initial) => {
const { Store } = await import("/src/lib/store.svelte.ts");
const store = new Store();
const assert = (condition, message) => {
if (!condition) throw Error(message);
};
store.seat = 0;
store.receive(initial);
const next = structuredClone(initial);
next.revision++;
const start = initial.players[0].position;
const target = initial.board.find((c) => !c.lava && c.id !== start).id;
next.players[0].position = target;
next.board.find((c) => c.id === start).lava = true;
next.log.push({
round: 1,
type: "move",
text: "Token moved",
animation: { kind: "move", seat: 0, path: [start, target] },
});
next.log.push({
round: 1,
type: "eruption",
text: "Lava followed",
animation: { kind: "eruption", cells: [start] },
});
store.receive(next);
assert(
store.state.revision === next.revision && store.state.board.find((c) => c.id === start).lava,
"Authoritative state must update immediately"
);
assert(
store.animating && store.journal.at(-1).text === "Token moved",
"Movement must precede eruption in the journal"
);
assert(!store.scene.board.find((c) => c.id === start).lava, "Lava appeared before movement finished");
store.receive(structuredClone(next));
assert(
store.animating && store.journal.at(-1).text === "Token moved",
"Duplicate broadcasts interrupted playback"
);
await new Promise((resolve) => setTimeout(resolve, 760));
assert(store.journal.at(-1).text === "Lava followed", "Eruption did not advance on its own");
assert(store.scene.board.find((c) => c.id === start).lava, "Lava scene did not advance");
const later = structuredClone(next);
later.revision++;
later.log.push({ round: 1, type: "equipment", text: "Later action" });
store.receive(later);
assert(store.journal.at(-1).text === "Lava followed", "New updates jumped the queue");
store.skipPresentation();
assert(
!store.animating && !store.waiting && store.journal.at(-1).text === "Later action",
"Skip did not reach the latest state"
);
store.destroy();
return "Ordered movement, eruption and journal; queued updates, duplicate broadcasts and skip passed";
},
stripSecret(initGame(3, {}, "presentation-test"), 0)
);
await page.evaluate(() => {
window.soundStarts = 0;
for (const type of [AudioBufferSourceNode, OscillatorNode]) {
const original = type.prototype.start;
type.prototype.start = function (...args) {
window.soundStarts++;
return original.apply(this, args);
};
}
});
await page.getByText("Playtest tools", { exact: true }).click();
const soundToggle = page.getByRole("checkbox", { name: "Sound effects", exact: true });
await soundToggle.uncheck();
const previews = page.getByRole("group", { name: "Test sounds" });
if (await previews.locator("button:not([disabled])").count()) throw Error("Muted sound previews must be disabled");
await soundToggle.check();
for (const name of ["Footstep", "Dice", "Lava", "Equipment"]) {
const before = await page.evaluate(() => window.soundStarts);
await previews.getByRole("button", { name, exact: true }).click();
await page.waitForFunction((before) => window.soundStarts > before, before);
}
await soundToggle.uncheck();
const initialSeed = await page.evaluate(() => JSON.parse(localStorage.getItem("fuji-dev-v1")).seed);
await page.getByRole("button", { name: "New random game", exact: true }).click();
if (initialSeed === (await page.evaluate(() => JSON.parse(localStorage.getItem("fuji-dev-v1")).seed)))
throw Error("Random restart reused the seed");
console.log(result + "; audio previews, mute and random restart passed");
} finally {
await browser.close();
}