Add four guided tutorials using protocol 0.3.0

This commit is contained in:
coyotte508 2026-09-15 21:02:51 +02:00
commit dbe5ea819d
23 changed files with 1254 additions and 62 deletions

View file

@ -25,6 +25,21 @@ pnpm fmt
The engine tests cover deterministic replay, invalid-move atomicity, private information, movement, lava, injury timing and equipment interactions. Simulation runs 150 complete expeditions across player counts and difficulty levels and verifies exact replays. Browser smoke testing covers setup, route selection, every round phase, game end, mobile overflow and the help dialog.
## Tutorial
Open `http://127.0.0.1:5187/tutorial.html?chapter=first-steps` to play a lesson. Each chapter uses the real engine, a prepared position and scripted teammates. Progress resumes separately for each chapter; the guide offers hints and restart controls.
`pnpm build` produces one viewer JS/CSS bundle for games and tutorials. Upload it as the viewer with global name `fuji`, then add these chapters under **Tutorial** in BGS admin (revision `2` for chapters 1–3, `5` for chapter 4):
| ID | Title | Covers |
| ----------------- | ---------------------------------- | ------------------------------------------------------------------------------- |
| `first-steps` | Your first journey | Destinations, matching dice, rerolls, Buddy and movement. |
| `equipment` | Equipment & helping teammates | Shovel, Map, card timing, discards and private loans. |
| `terrain-bonuses` | Location bonuses & supplies | Bonus rerolls, equipment tokens and next-round availability. |
| `lava` | When two lava waves catch the team | A deliberate defeat: an extra eruption plus the normal wave catches a teammate. |
Chapter sources: `packages/viewer/src/tutorial/first-steps.ts` and `lessons.ts`. Keep setup and teammate actions deterministic; bump the chapter revision for incompatible changes. `pnpm check` tests legal actions, lesson outcomes, hidden information and saved progress. `node tests/tutorial-browser.mjs` completes every chapter on desktop and mobile. BGS calls `fuji.launchTutorial` for local lessons and `fuji.launch` for multiplayer games.
## Packages
- `packages/engine`: pure TypeScript rules, serializable state, seeded randomness, immutable move application and `dist/wrapper.js` for BGS.

View file

@ -6,11 +6,11 @@
"dev": "pnpm --filter fuji-engine build && pnpm --filter fuji-viewer dev",
"build": "pnpm --filter fuji-engine build && pnpm --filter fuji-viewer build",
"test": "pnpm --filter fuji-engine test",
"check": "pnpm fmt:check && pnpm build && pnpm --filter fuji-viewer check && pnpm test",
"check": "pnpm fmt:check && pnpm build && pnpm --filter fuji-viewer check && pnpm test && pnpm --filter fuji-viewer test:tutorial",
"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 && node tests/mobile-readiness-smoke.mjs && node tests/chat-tabs-smoke.mjs && node tests/chat-mentions-smoke.mjs && node tests/protocol-lifecycle-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 && node tests/chat-tabs-smoke.mjs && node tests/chat-mentions-smoke.mjs && node tests/protocol-lifecycle-smoke.mjs && node tests/tutorial-browser.mjs"
},
"devDependencies": {
"oxfmt": "0.61.0",

View file

@ -7,10 +7,11 @@
"scripts": {
"dev": "vite --host 127.0.0.1 --port 5187 --strictPort",
"build": "vite build",
"check": "svelte-check --tsconfig ./tsconfig.json"
"check": "svelte-check --tsconfig ./tsconfig.json",
"test:tutorial": "node --test src/tutorial/*.spec.ts"
},
"dependencies": {
"@boardgamers/protocol": "0.2.2",
"@boardgamers/protocol": "0.3.0",
"fuji-engine": "workspace:*"
},
"devDependencies": {

View file

@ -148,6 +148,7 @@
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 shovelDie = $derived(dice.length === 1 ? me?.dice.find((d) => d.id === dice[0]) : undefined);
const binocularReasons = $derived.by(() => {
if (actionTool !== "binoculars" || !s) return undefined;
return Object.fromEntries(
@ -252,7 +253,7 @@
});
function pickDie(id: string) {
dice = dice.includes(id) ? dice.filter((x) => x !== id) : [...dice, id];
dice = dice.includes(id) ? dice.filter((x) => x !== id) : actionTool === "shovel" ? [id] : [...dice, id];
}
function chooseLocation(id: string) {
if (s?.phase === "setup") return;
@ -393,7 +394,7 @@
</script>
{#snippet journalPanel(location: string)}
<section class="journal inline-journal" aria-label="Expedition journal">
<section data-tutorial="journal" class="journal inline-journal" aria-label="Expedition journal">
<header class="journal-header">
<h2>Expedition journal</h2>
<button
@ -552,6 +553,7 @@
>
</div>
<button
data-tutorial={s.phase === "movement" ? "resolve" : "confirm"}
onclick={mobileAction}
disabled={store.waiting ||
(s.phase === "planning" && !me.ready && !!reserved[currentRoute.at(-1)!]) ||
@ -707,7 +709,7 @@
if (s.phase !== "setup") inspected = id;
}}
/>
<section class="personal" aria-label="Your dice">
<section class="personal" aria-label="Your dice" data-tutorial="dice">
<div class="personal-title">
<div>
<span class="eyebrow"
@ -722,6 +724,7 @@
{#if me}
<div class="dice-row">
{#each me.dice as d (d.id)}<Die
tutorialTarget={`die:${d.id}`}
colorblind={store.colorblind}
die={d}
selected={dice.includes(d.id)}
@ -783,6 +786,7 @@
<button
class="primary finish-dice"
disabled={store.waiting}
data-tutorial="finish-rerolls"
onclick={() => store.dispatch({ action: "finishRerolls" })}
>Done with my dice{hasSkill(me, "gatherer") && me.rerolls
? ` · gain ${Math.min(me.rerolls, 3 - me.powerBars)} bars`
@ -1028,6 +1032,7 @@
{#if !me.ready}<button
class="primary"
disabled={store.waiting || !!reserved[currentRoute.at(-1)!]}
data-tutorial="confirm"
onclick={confirmTravel}>Ready to travel <span>→</span></button
>{:else}<p class="confirmed">✓ Your route is set. Waiting for the team.</p>
<button class="revise-choice" onclick={() => store.dispatch({ action: "plan", path: me.path })}
@ -1041,6 +1046,7 @@
</p>
{#if !me.ready}<button
class="primary"
data-tutorial="confirm"
onclick={() => store.dispatch({ action: "ready" })}
disabled={store.waiting}>Ready to reveal <span>→</span></button
>{:else}<p class="confirmed">✓ Ready. Waiting for the team.</p>
@ -1059,8 +1065,10 @@
{:else if s.activeResolution === null}<p class="instruction">
Choose who moves next. A route that triggers extra lava is often best resolved last.
</p>
{#if !me.resolved}<button class="primary" onclick={() => store.dispatch({ action: "beginMovement" })}
>Resolve my journey <span>→</span></button
{#if !me.resolved}<button
data-tutorial="resolve"
class="primary"
onclick={() => store.dispatch({ action: "beginMovement" })}>Resolve my journey <span>→</span></button
>{:else}<p class="confirmed">✓ Your journey is resolved.</p>{/if}
{:else if resolvingPlayer && result}{@const criterion = terrain(
cell(s, resolvingPlayer.path.at(-1)!).terrain
@ -1131,12 +1139,16 @@
location.
</p>
<div class="eruption-count"><strong>{danger.length}</strong><span>locations threatened</span></div>
<button class="primary ember" disabled={seat !== 0} onclick={() => store.dispatch({ action: "erupt" })}
<button
data-tutorial="erupt"
class="primary ember"
disabled={seat !== 0}
onclick={() => store.dispatch({ action: "erupt" })}
>{seat === 0 ? "Let the lava advance" : "Waiting for the expedition leader"} <span>→</span></button
>
{/if}
{#if me && s.phase !== "setup" && !s.outcome}
<section class="equipment-section">
<section class="equipment-section" data-tutorial="equipment">
<div class="section-title">
<h3>Your equipment</h3>
<span>{me.cards.length}</span>
@ -1152,6 +1164,7 @@
!s.pending &&
(c.id !== "knife" || copyOptions.length > 0)}
<button
data-tutorial={`equipment:${c.id}`}
class:usable={available}
class:open={tool === c.id}
onclick={() => chooseTool(c.id)}
@ -1221,17 +1234,19 @@
{#if ["shovel", "torch", "tape", "machete", "compass", "map"].includes(actionTool ?? "")}<p
class="muted small"
>
Select {actionTool === "machete"
? "one or two dice"
: actionTool === "torch"
? "one or more dice to reroll"
: "the dice"} below the map. {dice.length} selected.
Select {actionTool === "shovel"
? "one die"
: actionTool === "machete"
? "one or two dice"
: actionTool === "torch"
? "one or more dice to reroll"
: "the dice"} below the map. {dice.length} selected.
</p>{/if}
{#if actionTool === "shovel"}<fieldset class="visible-choices">
{#if actionTool === "shovel" && shovelDie}<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 }}
die={{ ...shovelDie, face: n }}
selected={turnFace === n}
colorblind={store.colorblind}
onclick={() => (turnFace = n)}

View file

@ -7,6 +7,7 @@
relevant = false,
conflicts = [],
disabled = false,
tutorialTarget,
onclick = () => {},
}: {
die: Die;
@ -15,6 +16,7 @@
relevant?: boolean;
conflicts?: { seat: number; name: string; color: string; location: string; provisional?: boolean }[];
disabled?: boolean;
tutorialTarget?: string;
onclick?: () => void;
} = $props();
const f = $derived(face(die));
@ -38,6 +40,7 @@
<button
class="die"
data-tutorial={tutorialTarget}
class:chosen={selected}
class:relevant
class:aside={die.aside}

View file

@ -78,12 +78,12 @@
{#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>
<div class="revealed-log">
<div>⚄ {entry.diceLabel ?? entry.text}</div>
<div class="journal-dice">
{#each entry.dice as d}<Die die={d} {colorblind} disabled />{:else}<span>No matching dice</span>{/each}
</div>
</details>
</div>
{:else}
<span
><span class="event-icon" aria-hidden="true"

View file

@ -115,7 +115,12 @@
};
</script>
<div class="landscape" style:--route-color={ownColor} style:--landscape-art={`url(${art("land", 21)})`}>
<div
data-tutorial="board"
class="landscape"
style:--route-color={ownColor}
style:--landscape-art={`url(${art("land", 21)})`}
>
<div class="map-scroll">
<svg
viewBox={`0 0 ${mapWidth} ${mapHeight}`}
@ -151,6 +156,7 @@
{@const data = terrain(c.terrain)}
<g
class="location"
data-tutorial={`tile:${c.id}`}
class:inactive={state.phase === "setup"}
class:reserved={!!reserved[c.id]}
class:reachable={reachable.includes(c.id)}

View file

@ -33,6 +33,15 @@ export class Store {
private receivedSeat: number | undefined;
private frames: { scene: View; duration: number; cue?: SoundCue }[] = [];
private animationTimer: ReturnType<typeof setTimeout> | undefined;
private presentationDone = new Set<() => void>();
private finishPresentation() {
for (const done of this.presentationDone) done();
this.presentationDone.clear();
}
async present(view: View) {
this.receive(view);
if (this.animating) await new Promise<void>((resolve) => this.presentationDone.add(resolve));
}
private playFrame() {
const frame = this.frames.shift();
if (!frame) {
@ -40,6 +49,7 @@ export class Store {
this.journal = this.state?.log ?? [];
this.animating = false;
this.waiting = false;
this.finishPresentation();
return;
}
this.animating = true;
@ -54,6 +64,7 @@ export class Store {
this.audio.stop();
this.frames = [];
this.animating = false;
this.finishPresentation();
}
skipPresentation() {
this.dispose();

View file

@ -0,0 +1,67 @@
import { mount, tick, unmount } from "svelte";
import { createTutorial, type TutorialMount } from "@boardgamers/protocol/tutorial";
import { mountTutorialGuide } from "@boardgamers/protocol/tutorial/dom";
import { stripSecret } from "fuji-engine";
import App from "./App.svelte";
import { Store } from "./lib/store.svelte";
import { lessons } from "./tutorial/lessons";
import "./lib/theme.css";
import "./tutorial/tutorial.css";
export const mountTutorial: TutorialMount = async (target, { chapter, onProgress }) => {
const lesson = lessons.find((entry) => entry.id === chapter);
if (!lesson) throw Error("Unknown chapter");
target.className = "tutorial-session";
const guide = document.createElement("div");
guide.className = "tutorial-guide-host";
const game = document.createElement("div");
target.append(guide, game);
let storage: Storage | undefined;
try {
storage = localStorage;
} catch {
/* Private browsing may block persistence. */
}
const store = new Store();
store.seat = 0;
store.chat.setDisabled(true);
let animateNextMove = false;
const controller = await createTutorial({
...lesson,
storage,
onProgress,
move: async (state, move) => {
const animate = animateNextMove;
animateNextMove = false;
const next = await lesson.move(state, move);
if (animate) await store.present(stripSecret(next, 0));
return next;
},
});
store.send = (move) => {
animateNextMove = true;
void controller.play(move).finally(() => {
animateNextMove = false;
});
};
const unsubscribe = controller.subscribe(({ state, error, busy, canContinue, completed }) => {
store.receive(stripSecret(state, 0));
store.error = error;
store.waiting = busy || canContinue || completed;
});
const app = mount(App, { target: game, props: { store } });
await tick();
const cleanupGuide = mountTutorialGuide(guide, controller);
const resize = new ResizeObserver(() => {
target.style.setProperty("--tutorial-height", `${guide.getBoundingClientRect().height}px`);
});
resize.observe(guide);
return () => {
resize.disconnect();
cleanupGuide();
unsubscribe();
controller.destroy();
store.destroy();
void unmount(app);
};
};

View file

@ -0,0 +1,83 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { createTutorial } from "@boardgamers/protocol/tutorial";
import { stripSecret, total, cell } from "fuji-engine";
import { firstSteps, DESTINATION, buddyChoices } from "./first-steps.ts";
test("every allowed reroll choice completes the first chapter with legal engine moves", async () => {
for (let subset = 1; subset < 8; subset++) {
const c = await createTutorial(firstSteps);
assert.ok(stripSecret(c.snapshot.state, 0).players[1]!.dice.every((d) => d.face === 0));
await c.continue();
assert.equal(await c.play({ action: "ready" }), false);
assert.equal(await c.play({ action: "plan", path: ["0,3", DESTINATION] }), true);
await c.continue();
await c.play({ action: "ready" });
assert.equal(c.snapshot.state.phase, "reroll");
assert.equal(await c.play({ action: "reroll", ids: ["0-0"] }), false);
await c.play({ action: "reroll", ids: ["0-3", "0-4", "0-5"].filter((_, i) => subset & (1 << i)) });
const before = c.snapshot.state;
const ownTotal = total(before.players[0]!, 8);
const renTile = cell(before, before.players[2]!.path.at(-1)!).terrain;
const renConflict = total(before.players[0]!, renTile);
const die = buddyChoices(before)[0]!;
assert.equal(die.face, 5);
assert.equal(await c.play({ action: "finishRerolls" }), false);
assert.equal(await c.play({ action: "buddy", ids: ["0-0"] }), false);
assert.equal(await c.play({ action: "buddy", ids: [die.id] }), true, c.snapshot.error);
assert.equal(c.snapshot.state.phase, "equipment");
assert.equal(total(c.snapshot.state.players[0]!, 8), ownTotal);
assert.equal(total(c.snapshot.state.players[0]!, renTile), renConflict - 5);
assert.ok(stripSecret(c.snapshot.state, 1).players[0]!.dice.find((d) => d.id === die.id)?.face === 5);
await c.play({ action: "ready" });
assert.equal(c.snapshot.state.phase, "movement");
assert.ok(stripSecret(c.snapshot.state, 0).players[1]!.dice.every((d) => d.face > 0));
await c.play({ action: "beginMovement" });
assert.equal(c.snapshot.state.players[0]!.position, DESTINATION);
assert.equal(c.snapshot.state.players[0]!.stamina, 2);
assert.ok(c.snapshot.state.log.some((e) => e.text === "Ren rerolled."));
const journeys = c.snapshot.state.log.flatMap((e) => (e.journey ? [e.journey] : []));
assert.deepEqual(
journeys.map((j) => j.name),
["You", "Mika", "Ren"]
);
assert.ok(journeys.every((j) => j.moved));
assert.ok(journeys[1]!.own >= 10);
assert.ok(journeys[2]!.own >= 15);
assert.equal(c.snapshot.state.round, 2);
assert.ok(c.snapshot.state.log.some((e) => e.animation?.kind === "eruption"));
assert.equal(c.snapshot.canContinue, false);
assert.equal(c.snapshot.completed, true, c.snapshot.error);
}
});
test("reloading and retrying a reroll reproduces the same roll without changing live-game state", async () => {
const records = new Map<string, string>();
const options = {
...firstSteps,
storage: {
getItem: (k: string) => records.get(k) ?? null,
setItem: (k: string, v: string) => {
records.set(k, v);
},
},
};
const c = await createTutorial(options);
await c.continue();
await c.play({ action: "plan", path: ["0,3", DESTINATION] });
await c.continue();
await c.play({ action: "ready" });
const restored = await createTutorial(options);
assert.deepEqual(restored.snapshot.state, c.snapshot.state);
await c.play({ action: "reroll", ids: ["0-3", "0-4", "0-5"] });
await restored.play({ action: "reroll", ids: ["0-3", "0-4", "0-5"] });
assert.deepEqual(restored.snapshot.state, c.snapshot.state);
const beforeBuddy = await createTutorial(options);
assert.match(beforeBuddy.snapshot.text, /pink 5/);
await beforeBuddy.play({ action: "buddy", ids: [buddyChoices(beforeBuddy.snapshot.state)[0]!.id] });
const afterBuddy = await createTutorial(options);
assert.deepEqual(afterBuddy.snapshot.state, beforeBuddy.snapshot.state);
assert.equal(afterBuddy.snapshot.state.players[0]!.buddyUsed, true);
assert.equal(records.size, 1);
assert.ok(records.has("bgs:tutorial:fuji:first-steps"));
});

View file

@ -0,0 +1,228 @@
import {
applyMove,
initGame,
SKILLS,
cell,
paths,
total,
face,
matches,
terrain,
type State,
type Move,
} from "fuji-engine";
import type { TutorialOptions } from "@boardgamers/protocol/tutorial";
export const DESTINATION = "1,3";
export function firstStepsState(): State {
let state = initGame(
3,
{
skillAssignment: "fixed",
skills: ["buddy", "scout", "manager"],
difficulty: 1,
scenario: 1,
autoMovement: false,
autoProgress: false,
},
"tutorial-first-steps"
);
for (let seat = 0; seat < 3; seat++) {
const player = state.players[seat]!;
if (!player.setupDone) {
state = applyMove(
state,
{
action: "setup",
keep: player.cards.slice(0, SKILLS[player.skill].keep).map((c) => c.id),
drop: SKILLS[player.skill].dice === 5 ? player.dice.at(-1)!.id : undefined,
},
seat
);
}
}
const target = cell(state, DESTINATION);
const lookout = state.board.find((c) => c.terrain === 8)!;
[lookout.terrain, target.terrain] = [target.terrain, lookout.terrain];
// A prepared lesson, before the first learner action. All subsequent changes use applyMove.
const rolls = [
[6, 4, 2, 1, 3, 5],
[4, 4, 2, 1, 1],
[5, 1, 5, 1, 5, 3],
];
state.players.forEach((player, seat) => {
player.name = ["You", "Mika", "Ren"][seat]!;
player.dice.forEach((die, index) => {
die.face = rolls[seat]![index]!;
});
state.deck.push(...player.cards.map((c) => c.id));
player.cards = [];
});
state.log = [];
state.history = [];
return state;
}
export function lessonMove(state: State, move: Move): State {
const phase = state.phase;
let next = applyMove(state, move, 0);
if (phase === "planning" && move.action === "ready") {
for (const seat of [1, 2]) {
const reserved = next.players.filter((p, i) => i !== seat && p.ready).map((p) => p.path.at(-1));
const route = Object.values(paths(next, seat)).find(
(p) => p.length >= 2 && p.length <= 3 && !reserved.includes(p.at(-1))
);
if (!route) throw Error("No scripted route is available.");
next = applyMove(next, { action: "plan", path: route }, seat);
next = applyMove(next, { action: "ready" }, seat);
}
}
if (phase === "reroll" && next.players[0]!.ready) {
const ren = next.players[2]!;
const rule = terrain(cell(next, ren.path.at(-1)!).terrain).requirement;
const weakDie = ren.dice.filter((d) => !matches(face(d), rule)).sort((a, b) => b.face - a.face)[0];
if (!ren.ready && ren.rerolls > 0 && weakDie) {
next = applyMove(next, { action: "reroll", ids: [weakDie.id] }, 2);
}
for (const seat of [1, 2]) {
if (!next.players[seat]!.ready && next.phase === "reroll")
next = applyMove(next, { action: "finishRerolls" }, seat);
}
}
if (phase === "equipment" && move.action === "ready") {
for (const seat of [1, 2]) next = applyMove(next, { action: "ready" }, seat);
}
if (phase === "movement" && next.players[0]!.resolved) {
for (const seat of [1, 2]) next = applyMove(next, { action: "beginMovement" }, seat);
if (next.phase === "eruption") next = applyMove(next, { action: "erupt" }, 0);
}
return next;
}
export function buddyChoices(state: State) {
const player = state.players[0]!;
const own = terrain(cell(state, DESTINATION).terrain).requirement;
const teammate = terrain(cell(state, state.players[2]!.path.at(-1)!).terrain).requirement;
const useful = player.dice.filter(
(d) => !d.aside && !d.remove && !matches(face(d), own) && matches(face(d), teammate)
);
const best = Math.max(...useful.map((d) => d.face));
return useful.filter((d) => d.face === best);
}
const only =
(...actions: string[]) =>
(_s: State, move: Move) =>
actions.includes(move.action)
? undefined
: "Follow the highlighted action for this step. You can retry the step at any time.";
export const firstSteps: TutorialOptions<State, Move> = {
game: "fuji",
id: "first-steps",
version: 2,
initialState: firstStepsState,
move: lessonMove,
steps: [
{
id: "welcome",
title: "Escape together",
text: "Help everyone reach the village before the lava catches anyone. You control the gold explorer; Mika and Ren are scripted teammates. Preparation is done — let’s plan your first move.",
target: "board",
},
{
id: "destination",
title: "Choose Hilltop lookout",
text: "Select the highlighted tile, one space to the right of your explorers. Its 2 · 4 · 6 symbols mean that only even-valued dice count here.",
hint: "Click or tap Hilltop lookout on the map. Choosing a destination does not move your explorer yet.",
target: `tile:${DESTINATION}`,
complete: (s) => s.players[0]!.path.at(-1) === DESTINATION,
validateMove: (s, m) =>
only("plan")(s, m) ??
(Array.isArray(m.path) && m.path.length === 2 && m.path.at(-1) === DESTINATION
? undefined
: "For this first journey, choose the highlighted Hilltop lookout."),
},
{
id: "dice",
title: "Count the matching dice",
text: (s) =>
`Your 6 + 4 + 2 give a total of ${total(s.players[0]!, 8)} here. The 1, 3 and 5 do not count. You will need a higher total than each neighbor on this same tile, even if they chose different destinations. Their dice stay hidden until movement.`,
target: "dice",
hint: "The viewer highlights matching dice and shows your total below them. Never share exact dice values or totals with teammates in a real game.",
},
{
id: "confirm",
title: "Confirm your destination",
text: "Choose Ready to travel. A one- or two-space journey normally gives one reroll; three spaces give none. Mika and Ren will choose short routes to locations that fit their dice.",
target: "confirm",
complete: (s) => s.phase === "reroll",
validateMove: only("ready"),
},
{
id: "reroll",
title: "Improve your dice",
text: "Rerolling is a quiet phase: no discussion. Keep the even dice. Select one or more odd dice, then choose Reroll selected. Rolling several selected dice together spends just one reroll.",
target: "dice",
hint: "Select the 1, 3 and/or 5 below the map, then press Reroll selected.",
complete: (s) => s.players[0]!.rerolls === 0,
validateMove: (s, m) =>
only("reroll")(s, m) ??
(Array.isArray(m.ids) &&
m.ids.length &&
m.ids.every((id) => s.players[0]!.dice.some((d) => d.id === id && d.face % 2 === 1))
? undefined
: "Keep your matching even dice. Select at least one odd die to reroll."),
},
{
id: "buddy",
title: "Help Ren with Buddy",
text: (s) => {
const die = buddyChoices(s)[0]!;
return `Your ${face(die).color} ${die.face} does not help at Hilltop lookout, but adds ${die.face} to the total Ren must beat. Select it, then choose Set selected die aside. Buddy makes it public and excludes it from all comparisons until next round, without spending a reroll.`;
},
hint: "The blue 3 below this die marks Ren's destination. Keep your even dice. Setting this die aside leaves your own total unchanged; with no rerolls remaining, your dice choices are then finished.",
target: (s) => `die:${buddyChoices(s)[0]!.id}`,
complete: (s) => s.players[0]!.buddyUsed && s.phase === "equipment",
validateMove: (s, m) => {
const ids = m.ids;
return (
only("buddy")(s, m) ??
(Array.isArray(ids) && ids.length === 1 && buddyChoices(s).some((d) => d.id === ids[0])
? undefined
: "Set aside the highlighted 5 to help Ren without reducing your own total.")
);
},
},
{
id: "equipment",
title: "Ready for the reveal",
text: "Ren used a reroll to improve a non-matching die; Mika kept strong dice for Flooded forest. You may talk again and use equipment. This chapter starts with empty packs, so choose Ready to reveal. The remaining dice are revealed when everyone is ready.",
target: "confirm",
complete: (s) => s.phase === "movement",
validateMove: only("ready"),
},
{
id: "move",
title: "Compare and move",
text: (s) =>
`For Hilltop lookout, your total is ${total(s.players[0]!, 8)}, Mika's is ${total(s.players[1]!, 8)} and Ren's is ${total(s.players[2]!, 8)}. Yours is higher than both. Resolve your journey using the highlighted button, then watch Mika and Ren move and the lava spread.`,
target: "resolve",
complete: (s) => s.round > 1,
validateMove: only("beginMovement"),
},
],
completion: {
title: "Your first journey",
text: (s) => {
const result = s.log
.slice()
.reverse()
.find((e) => e.journey?.name === "You")?.journey;
return `You reached Hilltop lookout! Your lead was ${(result?.own ?? 0) - (result?.highest ?? 0)} and you lost ${result?.loss ?? 0} stamina. A small lead costs more stamina; a tie or lower means you stay put. The journal records the comparison. Mika and Ren have also resolved their journeys, and the lava has spread. A new round is ready.`;
},
target: "journal",
hint: "The whole team must escape. Keep an eye on teammates' destinations as well as your own. Every round ends with lava spreading after everyone has resolved their journey.",
},
};

View file

@ -0,0 +1,107 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { createTutorial } from "@boardgamers/protocol/tutorial";
import { applyMove, cell, paths, stripSecret, terrain, threatened } from "fuji-engine";
import { equipmentLesson, terrainLesson, lavaLesson, BONUS_TILE, ERUPTION_TILE } from "./lessons.ts";
test("equipment teaches a legal turn and private loan, with cards discarded once", async () => {
const c = await createTutorial(equipmentLesson);
await c.continue();
assert.equal(await c.play({ action: "ready" }), false);
assert.equal(await c.play({ action: "equipment", id: "shovel", ids: ["0-3"], face: 6 }), true, c.snapshot.error);
assert.equal(await c.play({ action: "equipment", id: "map", ids: ["0-5"], target: 1 }), false);
assert.equal(await c.play({ action: "equipment", id: "map", ids: ["0-5"], target: 2 }), true, c.snapshot.error);
assert.equal(stripSecret(c.snapshot.state, 1).players[2]!.dice.find((d) => d.id === "0-5")?.face, 0);
assert.equal(stripSecret(c.snapshot.state, 2).players[2]!.dice.find((d) => d.id === "0-5")?.face, 5);
assert.deepEqual(c.snapshot.state.discard.slice(-2), ["shovel", "map"]);
await c.play({ action: "ready" });
await c.play({ action: "beginMovement" });
assert.equal(c.snapshot.state.players[0]!.position, "1,3");
assert.equal(c.snapshot.state.players[0]!.stamina, 0);
assert.equal(c.snapshot.state.round, 2);
assert.equal(c.snapshot.state.log.filter((entry) => entry.journey?.moved).length, 3);
assert.ok(
c.snapshot.state.players[0]!.dice.some((d) => d.id === "0-5"),
"The Map loan returns after lava"
);
assert.equal(c.snapshot.canContinue, false);
assert.equal(c.snapshot.completed, true, c.snapshot.error);
});
test("the location bonus is granted before moving; the token grants next-round equipment on arrival", async () => {
const c = await createTutorial(terrainLesson);
await c.play({ action: "plan", path: ["0,3", BONUS_TILE] });
await c.play({ action: "ready" });
assert.equal(c.snapshot.state.players[0]!.rerolls, 2);
assert.equal(c.snapshot.state.players[0]!.position, "0,3");
assert.ok(cell(c.snapshot.state, BONUS_TILE).equipment);
assert.equal(await c.play({ action: "reroll", ids: ["0-5"] }), false);
await c.play({ action: "reroll", ids: ["0-4", "0-5"] });
assert.equal(c.snapshot.state.players[0]!.rerolls, 1);
assert.deepEqual(
c.snapshot.state.players[0]!.dice.slice(-2).map((d) => d.face),
[5, 1]
);
assert.equal(await c.play({ action: "reroll", ids: ["0-5"] }), false);
await c.play({ action: "reroll", ids: ["0-4"] });
assert.equal(c.snapshot.state.phase, "equipment");
assert.equal(c.snapshot.state.players[0]!.cards.length, 0);
await c.play({ action: "ready" });
await c.play({ action: "beginMovement" });
assert.equal(c.snapshot.state.players[0]!.position, BONUS_TILE);
assert.ok(!cell(c.snapshot.state, BONUS_TILE).equipment);
const card = c.snapshot.state.players[0]!.cards[0]!;
assert.equal(card.id, "rope");
assert.equal(card.availableRound, c.snapshot.state.round);
assert.equal(c.snapshot.state.round, 2);
assert.ok(c.snapshot.state.log.some((entry) => entry.animation?.kind === "eruption"));
assert.equal(c.snapshot.state.log.filter((entry) => entry.journey?.moved).length, 3);
assert.equal(c.snapshot.canContinue, false);
assert.equal(c.snapshot.completed, true, c.snapshot.error);
});
test("automatic movement cannot save a plan caught by the extra plus normal eruption", async () => {
const c = await createTutorial(lavaLesson);
const before = c.snapshot.state;
assert.equal(before.phase, "equipment");
assert.equal(before.initOptions.autoMovement, true);
assert.equal(before.initOptions.autoProgress, true);
assert.equal(terrain(cell(before, "4,2").terrain).kind, "village", "Keep the village entrance in its normal place");
assert.ok(before.players.every((p) => !cell(before, p.position).lava));
assert.ok(!threatened(before).includes(before.players[1]!.position));
const withoutMarker = structuredClone(before);
cell(withoutMarker, ERUPTION_TILE).eruption = 0;
const singleWave = applyMove(withoutMarker, { action: "ready" }, 0);
assert.equal(singleWave.outcome, null, "The normal wave alone does not catch Mika this round");
assert.equal(singleWave.log.filter((e) => e.animation?.kind === "eruption").length, 1);
await c.continue();
assert.equal(await c.play({ action: "beginMovement" }), false, "The learner cannot choose movement order");
assert.equal(await c.play({ action: "ready" }), true, c.snapshot.error);
const after = c.snapshot.state;
assert.equal(after.phase, "ended");
assert.equal(after.outcome, "lost");
assert.equal(cell(after, ERUPTION_TILE).eruption, 0);
assert.ok(after.players.every((p) => p.resolved));
assert.deepEqual(
after.players.map((p) => p.position),
[ERUPTION_TILE, "3,2", "4,2"]
);
const waves = after.log.flatMap((entry) => (entry.animation?.kind === "eruption" ? [entry.animation.cells] : []));
assert.equal(waves.length, 2);
assert.ok(!waves[0]!.includes("3,2"), "Mika survives the extra wave");
assert.ok(waves[1]!.includes("3,2"), "The normal wave then catches Mika");
const villageRoutes = (seat: number) =>
Object.values(paths(after, seat)).filter(
(route) =>
terrain(cell(after, route.at(-1)!).terrain).kind === "village" && !threatened(after).includes(route.at(-1)!)
);
assert.ok(
villageRoutes(0).some((you) => villageRoutes(2).some((ren) => you.at(-1) !== ren.at(-1))),
"Both survivors can reach different village tiles before the next eruption; the road is not cut off"
);
assert.match(after.log.at(-1)!.text, /Mika was caught by the lava/);
assert.equal(c.snapshot.canContinue, false);
assert.equal(c.snapshot.completed, true, c.snapshot.error);
});

View file

@ -0,0 +1,281 @@
import { applyMove, cell, terrain, threatened, total, type State, type Move, type EquipmentId } from "fuji-engine";
import type { TutorialOptions } from "@boardgamers/protocol/tutorial";
import { firstSteps, firstStepsState, lessonMove, DESTINATION } from "./first-steps.ts";
const only =
(...actions: string[]) =>
(_state: State, move: Move) =>
actions.includes(move.action)
? undefined
: "Follow this step's highlighted action. Choose Retry step to try again.";
function setTerrain(state: State, id: string, type: number) {
const target = cell(state, id);
const source = state.board.find((c) => c.terrain === type)!;
if (terrain(source.terrain).kind !== terrain(target.terrain).kind)
throw Error("Tutorial swaps must preserve location kinds.");
[source.terrain, target.terrain] = [target.terrain, source.terrain];
}
function giveCards(state: State, cards: EquipmentId[]) {
state.deck = state.deck.filter((id) => !cards.includes(id));
state.players[0]!.cards = cards.map((id) => ({ id, used: 0, availableRound: state.round }));
}
function equipmentPosition(state: State, routes: string[][]) {
for (let seat = 0; seat < routes.length; seat++) {
state = applyMove(state, { action: "plan", path: routes[seat] }, seat);
state = applyMove(state, { action: "ready" }, seat);
}
for (let seat = 0; seat < routes.length; seat++) {
if (state.phase === "reroll" && !state.players[seat]!.ready)
state = applyMove(state, { action: "finishRerolls" }, seat);
}
return state;
}
function equipmentState() {
const state = firstStepsState();
giveCards(state, ["shovel", "map"]);
return equipmentPosition(state, [
["0,3", DESTINATION],
["0,3", "1,3", "1,2"],
["0,3", "1,3", "1,4"],
]);
}
export const equipmentLesson: TutorialOptions<State, Move> = {
game: "fuji",
id: "equipment",
version: 2,
initialState: equipmentState,
move: lessonMove,
steps: [
{
id: "packs",
title: "Make your equipment count",
text: "Routes and rerolls are finished. Your pack holds a Shovel and a Map, both usable during the equipment phase. Open cards to inspect their effect and timing. Most equipment is discarded after one use; the Tinkerer skill is an exception.",
target: "equipment",
},
{
id: "shovel",
title: "Turn a die with the Shovel",
text: "Open Shovel, select your yellow 1 below the map, choose 6 under New value, then Use Shovel. Your destination counts even values: this turns a useless die into six more points.",
hint: "Choose the fourth die from the left (yellow 1). The face picker shows all six possible faces, including their colors.",
target: "equipment:shovel",
complete: (s) => s.players[0]!.dice.find((d) => d.id === "0-3")?.face === 6 && s.discard.includes("shovel"),
validateMove: (_s, m) =>
m.action === "equipment" &&
m.id === "shovel" &&
m.face === 6 &&
Array.isArray(m.ids) &&
m.ids.length === 1 &&
m.ids[0] === "0-3"
? undefined
: "Use the Shovel to turn the yellow 1 into a 6.",
},
{
id: "map",
title: "Lend a die with the Map",
text: "Your blue 5 does not count at your even-valued destination, but it counts at Ren's. Open Map, select that 5, choose Ren and Use Map. Lending it both helps Ren and removes it from the total Ren must beat.",
hint: "The blue 5 is the last die. A Map loan lasts until the end of the round. Only the sender and recipient see the lent face before the reveal; other players see that a die was lent.",
target: "equipment:map",
complete: (s) => s.players[2]!.dice.some((d) => d.id === "0-5") && s.discard.includes("map"),
validateMove: (_s, m) =>
m.action === "equipment" &&
m.id === "map" &&
m.target === 2 &&
Array.isArray(m.ids) &&
m.ids.length === 1 &&
m.ids[0] === "0-5"
? undefined
: "Lend your blue 5 to Ren using the Map.",
},
{
id: "reveal",
title: "Reveal when everyone is ready",
text: "The Shovel and Map are now discarded. Your matching total is 18, and Ren has the borrowed die. Choose Ready to reveal. Using equipment can change the team's choices, so everyone confirms again afterward.",
target: "confirm",
complete: (s) => s.phase === "movement",
validateMove: only("ready"),
},
{
id: "move",
title: "Put the improved dice to work",
text: "Your improved even dice beat both neighbors at Hilltop lookout. Resolve your journey, then watch your teammates move and the lava spread.",
target: "resolve",
complete: (s) => s.round > 1,
validateMove: only("beginMovement"),
},
],
completion: {
title: "Equipment helps the whole team",
text: "You moved without losing stamina, and Ren used your loan to reach his destination. Everyone has moved, the lava has spread and your die has returned for the new round. A card can improve your own dice, help a teammate, or both. Check its timing before using it: for example, Torch works during planning, whereas Shovel and Map work during equipment. An arm injury prevents equipment use.",
target: "journal",
},
};
export const BONUS_TILE = "1,3";
function bonusState() {
const state = firstStepsState();
setTerrain(state, BONUS_TILE, 10);
const marker = state.board.find((c) => c.equipment)!;
marker.equipment = false;
cell(state, BONUS_TILE).equipment = true;
state.players[0]!.skill = "manager";
const rolls = [
[1, 2, 2, 1, 6, 6],
[4, 4, 4, 6, 6],
[5, 5, 5, 5, 5, 5],
];
state.players.forEach((player, seat) =>
player.dice.forEach((die, index) => {
die.face = rolls[seat]![index]!;
})
);
state.deck = ["rope", ...state.deck.filter((id) => id !== "rope")];
return state;
}
export const terrainLesson: TutorialOptions<State, Move> = {
game: "fuji",
id: "terrain-bonuses",
version: 2,
initialState: bonusState,
move: lessonMove,
steps: [
{
id: "destination",
title: "Read the location's symbols",
text: "Choose Hidden passage, one space to the right. Only 1s and 2s count here. Its circular arrow grants one extra reroll when you choose it as your destination. The equipment token is a separate reward for finishing your movement here.",
hint: "Look for the arrow symbol, not just the numbers: not every location with low values gives an extra reroll. Passing through a location does not grant its destination bonus.",
target: `tile:${BONUS_TILE}`,
complete: (s) => s.players[0]!.path.at(-1) === BONUS_TILE,
validateMove: (_s, m) =>
m.action === "plan" && Array.isArray(m.path) && m.path.length === 2 && m.path.at(-1) === BONUS_TILE
? undefined
: "Choose the highlighted Hidden passage, one space away.",
},
{
id: "confirm",
title: "One normal reroll, plus one bonus",
text: "Confirm Ready to travel. This one-space route gives one normal reroll, plus one for the destination's arrow: two in total. The bonus is available before you move, not after landing.",
target: "confirm",
complete: (s) => s.phase === "reroll" && s.players[0]!.rerolls === 2,
validateMove: only("ready"),
},
{
id: "first-roll",
title: "Spend the first reroll",
text: "Keep the four matching dice (1, 2, 2, 1). Select both 6s — the fifth and sixth dice — and reroll them together. This spends one reroll, leaving one more.",
target: "dice",
complete: (s) => s.players[0]!.rerolls === 1,
validateMove: (_s, m) =>
m.action === "reroll" &&
Array.isArray(m.ids) &&
m.ids.length === 2 &&
m.ids.includes("0-4") &&
m.ids.includes("0-5")
? undefined
: "Select both 6s (dice 5 and 6), keeping the four matching dice.",
},
{
id: "bonus-roll",
title: "Use the extra chance",
text: (s) =>
`The last die is now a matching 1: keep it. The fifth die shows ${s.players[0]!.dice[4]!.face}, which does not count here. Reroll just that fifth die using your bonus chance.`,
target: "die:0-4",
complete: (s) => s.phase === "equipment",
validateMove: (_s, m) =>
m.action === "reroll" && Array.isArray(m.ids) && m.ids.length === 1 && m.ids[0] === "0-4"
? undefined
: "Keep the new 1. Use your second reroll on the fifth die.",
},
{
id: "reveal",
title: "The token is still on the board",
text: "You have used the bonus, but have not moved or collected equipment yet. Your pack is empty. Choose Ready to reveal, then compare dice as usual.",
target: "confirm",
complete: (s) => s.phase === "movement",
validateMove: only("ready"),
},
{
id: "arrive",
title: "Finish here to collect equipment",
text: (s) =>
`Your matching total is ${total(s.players[0]!, 10)}, higher than both neighbors. Resolve your journey to land on the equipment token. Passing over it would not collect it.`,
target: "resolve",
complete: (s) => s.players[0]!.position === BONUS_TILE && !cell(s, BONUS_TILE).equipment,
validateMove: only("beginMovement"),
},
],
completion: {
title: "Your Rope is ready",
text: "You collected a Rope on arrival. New equipment must wait until the next round: your teammates have now moved and the lava has spread, so that round has begun and your Rope is available. The equipment token is gone, but the printed reroll arrow can help again on a later visit.",
target: "equipment:rope",
},
};
export const ERUPTION_TILE = "5,2";
export function lavaState() {
let state = firstStepsState();
state.players.forEach((p) => {
p.position = "3,2";
p.path = [p.position];
});
// A later-round checkpoint: advance the prepared lava front by three normal waves.
for (let wave = 0; wave < 3; wave++) {
const next = threatened(state);
for (const c of state.board) if (next.includes(c.id)) c.lava = true;
}
setTerrain(state, ERUPTION_TILE, 8);
setTerrain(state, "3,2", 19);
const rolls = [
[6, 6, 6, 1, 1, 1],
[5, 5, 5, 5, 5],
[5, 5, 5, 5, 5, 5],
];
state.players.forEach((player, seat) =>
player.dice.forEach((die, index) => {
die.face = rolls[seat]![index]!;
})
);
state = equipmentPosition(state, [["3,2", "4,2", ERUPTION_TILE], ["3,2"], ["3,2", "4,2"]]);
for (const seat of [1, 2]) state = applyMove(state, { action: "ready" }, seat);
state.initOptions.autoMovement = true;
state.initOptions.autoProgress = true;
state.round = 4;
return state;
}
export const lavaLesson: TutorialOptions<State, Move> = {
game: "fuji",
id: "lava",
version: 5,
initialState: lavaState,
move: (state, move) => applyMove(state, move, 0),
steps: [
{
id: "warning",
title: "A deliberately unsafe plan",
text: "This plan ends in defeat. Mika stays put while your route crosses an eruption marker. Its extra wave, followed by the normal eruption, will catch Mika.",
hint: "Markers trigger once when entered or crossed. Check every teammate's position against both waves.",
target: `tile:${ERUPTION_TILE}`,
},
{
id: "reveal",
title: "Watch the two waves",
text: "Choose Ready to reveal and watch both eruptions. The game chooses movement order automatically.",
target: "confirm",
complete: (s) => s.outcome === "lost",
validateMove: only("ready"),
},
],
completion: {
title: "One explorer caught, the whole team loses",
text: "Mika survived the extra wave, but the normal eruption caught her. Remember to plan for both waves.",
target: "board",
},
};
export const lessons = [firstSteps, equipmentLesson, terrainLesson, lavaLesson];

View file

@ -0,0 +1,115 @@
.tutorial-session {
--tutorial-height: 160px;
}
.tutorial-guide-host {
position: sticky;
top: 0;
z-index: 40;
padding: 8px 16px;
background: #0b211b;
}
.bgs-tutorial-guide {
border: 1px solid #d8be7890;
border-radius: 5px;
background: #19392e;
color: #eee5ce;
padding: 12px 16px;
box-shadow: 0 4px 16px #0003;
}
.bgs-tutorial-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
color: #f2d58d;
}
.bgs-tutorial-body p {
margin: 8px 0 12px;
line-height: 1.5;
max-width: 1050px;
}
.bgs-tutorial-controls {
display: flex;
gap: 8px;
flex-wrap: wrap;
align-items: start;
}
.bgs-tutorial-resets {
display: flex;
gap: 8px;
margin-left: auto;
}
.bgs-tutorial-guide button {
min-height: 32px;
padding: 5px 12px;
border: 1px solid #d8be7855;
border-radius: 4px;
background: #24483a;
color: #f5e8c0;
font: inherit;
cursor: pointer;
}
.bgs-tutorial-guide button:hover {
background: #375e49;
}
.bgs-tutorial-guide button:disabled {
opacity: 0.5;
cursor: default;
}
.bgs-tutorial-guide button:focus-visible {
outline: 2px solid #f2d58d;
outline-offset: 2px;
}
.bgs-tutorial-guide [hidden] {
display: none;
}
.bgs-tutorial-guide small {
display: block;
color: #a9bfae;
margin-top: 8px;
font-size: 11px;
}
.bgs-tutorial-guide [role="alert"] {
color: #ffd6b7;
}
.bgs-tutorial-highlight {
outline: 2px dashed #ffe39b;
outline-offset: 4px;
}
.location.bgs-tutorial-highlight {
outline: none;
}
.location.bgs-tutorial-highlight .location-ring {
stroke: #ffe39b;
stroke-width: 4px;
stroke-dasharray: 6 3;
}
.tutorial-session [data-tutorial] {
scroll-margin-top: calc(var(--tutorial-height) + 75px);
scroll-margin-bottom: 20px;
}
.tutorial-session .mobile-dock {
top: var(--tutorial-height);
}
@media (max-width: 850px) {
.tutorial-guide-host {
padding: 6px 8px;
}
.bgs-tutorial-guide {
padding: 8px 10px;
font-size: 13px;
}
.bgs-tutorial-body p {
margin: 6px 0 8px;
}
.bgs-tutorial-guide button {
min-height: 36px;
padding: 5px 9px;
}
.bgs-tutorial-controls {
gap: 6px;
}
.bgs-tutorial-guide small {
display: none;
}
}

View file

@ -4,37 +4,42 @@ import App from "./App.svelte";
import { Store } from "./lib/store.svelte";
import type { View, Move } from "fuji-engine";
import "./lib/theme.css";
import { mountTutorial } from "./tutorial";
registerViewer<View, Move>("fuji", ({ target, move, openPlayer, updatePreference, replaceLog }) => {
const store = new Store();
store.send = move;
store.clickPlayer = openPlayer;
store.savePreference = updatePreference;
const app = mount(App, { target, props: { store } });
return {
chat: store.chat,
async onState(state) {
store.receive(state);
replaceLog(state.log.map((entry) => entry.text));
await tick();
},
onPlayer({ index }) {
store.seat = index;
},
onPreferences(preferences) {
store.colorblind = preferences.colorblind === true;
store.setSound(preferences.sound !== false);
},
onAvatars(avatars) {
store.avatars = avatars;
},
onError(error) {
store.error = error instanceof Error ? error.message : String(error);
store.waiting = false;
},
destroy() {
store.destroy();
void unmount(app);
},
};
});
registerViewer<View, Move>(
"fuji",
({ target, move, openPlayer, updatePreference, replaceLog }) => {
const store = new Store();
store.send = move;
store.clickPlayer = openPlayer;
store.savePreference = updatePreference;
const app = mount(App, { target, props: { store } });
return {
chat: store.chat,
async onState(state) {
store.receive(state);
replaceLog(state.log.map((entry) => entry.text));
await tick();
},
onPlayer({ index }) {
store.seat = index;
},
onPreferences(preferences) {
store.colorblind = preferences.colorblind === true;
store.setSound(preferences.sound !== false);
},
onAvatars(avatars) {
store.avatars = avatars;
},
onError(error) {
store.error = error instanceof Error ? error.message : String(error);
store.waiting = false;
},
destroy() {
store.destroy();
void unmount(app);
},
};
},
{ tutorial: mountTutorial }
);

View file

@ -11,6 +11,7 @@
"forceConsistentCasingInFileNames": true,
"types": ["vite/client"],
"noEmit": true,
"allowImportingTsExtensions": true,
"allowJs": true,
"checkJs": false,
"isolatedModules": true,

View file

@ -0,0 +1,17 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Fuji · Learn to play</title>
</head>
<body>
<div id="app"></div>
<script type="module">
import "./src/viewer.ts";
await window.fuji.launchTutorial("#app", {
chapter: new URLSearchParams(location.search).get("chapter") || "first-steps",
});
</script>
</body>
</html>

View file

@ -9,7 +9,12 @@ export default defineConfig({
build: {
cssCodeSplit: false,
// Vite requires a bundle name; registerViewer owns the fuji global.
lib: { name: "fujiBundle", entry: "src/viewer.ts", formats: ["iife"], fileName: () => "fuji-viewer.iife.js" },
lib: {
name: "fujiBundle",
entry: "src/viewer.ts",
formats: ["iife"],
fileName: () => "fuji-viewer.iife.js",
},
rolldownOptions: { output: { assetFileNames: "fuji-viewer.[ext]" } },
},
});

10
pnpm-lock.yaml generated
View file

@ -34,8 +34,8 @@ importers:
packages/viewer:
dependencies:
'@boardgamers/protocol':
specifier: 0.2.2
version: 0.2.2
specifier: 0.3.0
version: 0.3.0
fuji-engine:
specifier: workspace:*
version: link:../engine
@ -61,8 +61,8 @@ importers:
packages:
'@boardgamers/protocol@0.2.2':
resolution: {integrity: sha512-5o5nPZW6CN6PysF0i90OR+B30djiFhAGutCZe5RKJV6h3RgqE36HA7l0pOpvhdHz8uYtqE0nmaPlc+2ZtYiM/A==}
'@boardgamers/protocol@0.3.0':
resolution: {integrity: sha512-9XI2+XK5RPdDM709Vh+uqHchr1cxe0DrtxLSvIMhhyDFaM0EutCQAuJkySQvKmdXTHizHxag+mNu4eaKx5Affw==}
'@jridgewell/gen-mapping@0.3.13':
resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}
@ -631,7 +631,7 @@ packages:
snapshots:
'@boardgamers/protocol@0.2.2':
'@boardgamers/protocol@0.3.0':
dependencies:
zod: 4.6.2

View file

@ -1,4 +1,4 @@
packages:
- packages/*
minimumReleaseAgeExclude:
- "@boardgamers/protocol@0.2.2"
- "@boardgamers/protocol@0.2.2 || 0.3.0"

View file

@ -289,6 +289,7 @@ import path from "node:path";
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.locator(".personal .die:not([disabled])").first().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 });

View file

@ -40,6 +40,19 @@ try {
current.emit("chat:result", { requestId: request.requestId, ok: true });
});
assert.equal(await input.inputValue(), "Edited while sending");
await page.evaluate(() => fuji.launchTutorial("#app", { chapter: "lava" }));
await page.locator(".bgs-tutorial-guide").waitFor();
assert.equal(await page.getByRole("textbox", { name: "Chat message" }).count(), 0);
assert.equal(await page.evaluate(() => current.emit("state:updated")), false);
await page.evaluate((state) => {
window.current = fuji.launch("#app");
current.emit("player", { index: 0 });
current.emit("state", state);
current.emit("chat:state", { canSend: true });
}, state);
await page.getByRole("textbox", { name: "Chat message" }).waitFor();
assert.equal(await page.locator(".bgs-tutorial-guide").count(), 0);
assert.equal(await page.locator(".tutorial-session").count(), 0);
await page.evaluate(() => fuji.destroy());
assert.equal(await page.locator("#app").innerHTML(), "");
assert.equal(await page.evaluate(() => current.emit("state:updated")), false);

218
tests/tutorial-browser.mjs Normal file
View file

@ -0,0 +1,218 @@
import assert from "node:assert/strict";
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
import { chromium } from "playwright";
async function recordPresentation(page) {
await page.evaluate(() => {
const frames = [];
const record = () => {
const frame = {
positions: Array.from(document.querySelectorAll(".traveler"), (el) => el.style.transform),
lava: document.querySelectorAll(".location.lava").length,
complete: document.querySelector(".bgs-tutorial-heading strong")?.textContent === "Chapter complete",
};
if (JSON.stringify(frame) !== JSON.stringify(frames.at(-1))) frames.push(frame);
};
record();
const observer = new MutationObserver(record);
observer.observe(document.body, { subtree: true, childList: true, attributes: true, characterData: true });
window.readTutorialFrames = () => {
record();
observer.disconnect();
return frames;
};
});
}
async function finishRound(page) {
await recordPresentation(page);
await page.locator('[data-tutorial="resolve"]:visible').first().click();
await page.getByText("Chapter complete", { exact: true }).waitFor();
const frames = await page.evaluate(() => window.readTutorialFrames());
const first = frames[0];
const last = frames.at(-1);
assert.ok(last.lava > first.lava, "The round ends with lava spreading");
for (const seat of [0, 1, 2]) {
assert.notEqual(last.positions[seat], first.positions[seat], `Explorer ${seat} moves`);
assert.ok(
frames.some((f) => !f.complete && f.positions[seat] === last.positions[seat] && f.lava === first.lava),
`Explorer ${seat}'s move is presented before the lava and completion`
);
}
assert.ok(
frames.some((f) => !f.complete && f.lava === last.lava),
"The guide waits for the lava animation"
);
}
const server = createServer(async (req, res) => {
if (req.url === "/fuji-viewer.iife.js" || req.url === "/fuji-viewer.css") {
res.setHeader("content-type", req.url.endsWith("css") ? "text/css" : "text/javascript");
res.end(await readFile(new URL(`../packages/viewer/dist${req.url}`, import.meta.url)));
} else {
res.setHeader("content-type", "text/html");
res.end(
`<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="/fuji-viewer.css"><div id="app"></div><script src="/fuji-viewer.iife.js"></script><script>fuji.launchTutorial('#app', {chapter:new URLSearchParams(location.search).get('chapter') || 'first-steps'});</script>`
);
}
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const url = `http://127.0.0.1:${server.address().port}`;
const browser = await chromium.launch({ headless: true, executablePath: process.env.FUJI_CHROMIUM_EXECUTABLE });
try {
for (const viewport of [
{ width: 1440, height: 1000 },
{ width: 390, height: 844 },
]) {
const context = await browser.newContext({ viewport, reducedMotion: "reduce" });
const page = await context.newPage();
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.goto(url);
const guide = page.locator(".bgs-tutorial-guide");
const step = (number) =>
page.waitForFunction(
(n) => document.querySelector(".bgs-tutorial-heading strong")?.textContent.startsWith(`${n}/8`),
number
);
await step(1);
assert.equal(await page.locator(".dev-toolbar, .expedition-chat").count(), 0);
await guide.getByRole("button", { name: "Continue", exact: true }).click();
await step(2);
await guide.getByRole("button", { name: "Show me", exact: true }).click();
await page.locator('[data-tutorial="tile:1,3"]').click();
await step(3);
await guide.getByRole("button", { name: "Continue", exact: true }).click();
await step(4);
await page.locator('[data-tutorial="confirm"]:visible').first().click();
await step(5);
await page.reload();
await step(5);
await guide.getByRole("button", { name: "Show me", exact: true }).click();
for (const index of [3, 4, 5]) await page.locator(".personal .dice-row .die").nth(index).click();
await page.getByRole("button", { name: /Reroll 3 dice/ }).click();
await step(6);
await page.reload();
await step(6);
assert.match(await guide.innerText(), /pink 5/);
await guide.getByRole("button", { name: "Show me", exact: true }).click();
await page.locator(".personal .die.bgs-tutorial-highlight").click();
await page.getByRole("button", { name: "Set selected die aside", exact: true }).click();
await step(7);
await page.locator('[data-tutorial="confirm"]:visible').first().click();
await step(8);
assert.equal(await page.locator("details.revealed-log").count(), 0);
assert.ok((await page.locator(".revealed-log .die").count()) > 0);
await finishRound(page);
await page.waitForFunction(
() => document.querySelector(".bgs-tutorial-heading strong")?.textContent === "Chapter complete"
);
assert.match(await guide.innerText(), /You reached Hilltop lookout/);
assert.equal(await guide.getByRole("button", { name: "Continue", exact: true }).isVisible(), false);
await page.reload();
await page.waitForFunction(
() => document.querySelector(".bgs-tutorial-heading strong")?.textContent === "Chapter complete"
);
await guide.getByRole("button", { name: "Restart chapter", exact: true }).click();
await step(1);
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1));
assert.deepEqual(errors, []);
await context.close();
}
for (const width of [1440, 390]) {
for (const chapter of ["equipment", "terrain-bonuses", "lava"]) {
const page = await browser.newPage({ viewport: { width, height: 900 }, reducedMotion: "reduce" });
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.goto(`${url}/?chapter=${chapter}`);
const guide = page.locator(".bgs-tutorial-guide");
const step = (n) =>
guide
.locator(".bgs-tutorial-heading strong")
.filter({ hasText: new RegExp(`^${n}/`) })
.waitFor();
const next = () => guide.getByRole("button", { name: "Continue", exact: true }).click();
const confirm = () => page.locator('[data-tutorial="confirm"]:visible').first().click();
await step(1);
if (chapter === "equipment") {
await next();
await step(2);
await page.locator('[data-tutorial="equipment:shovel"]').click();
const faces = page.getByRole("group", { name: "New value" });
assert.equal(await faces.count(), 0, "Choose a die before showing its possible faces");
await page.locator('[data-tutorial="die:0-0"]').click();
assert.match(await faces.locator(".die").first().getAttribute("aria-label"), /^blue 1/);
await page.locator('[data-tutorial="die:0-3"]').click();
assert.equal(await page.locator(".personal .die.chosen").count(), 1);
assert.deepEqual(
await faces.locator(".die").evaluateAll((els) => els.map((el) => el.getAttribute("aria-label"))),
["yellow 1", "pink 2", "blue 3", "blue 4", "pink 5", "yellow 6"]
);
await faces.locator(".die").nth(5).click();
await page.getByRole("button", { name: "Use Shovel", exact: true }).click();
await step(3);
await page.reload();
await step(3);
await page.locator('[data-tutorial="equipment:map"]').click();
await page.locator('[data-tutorial="die:0-5"]').click();
await page.getByRole("group", { name: "Lend a die to" }).getByRole("button", { name: /Ren/ }).click();
await page.getByRole("button", { name: "Use Map", exact: true }).click();
await step(4);
await confirm();
await step(5);
await finishRound(page);
} else if (chapter === "terrain-bonuses") {
await page.locator('[data-tutorial="tile:1,3"]').click();
await step(2);
await confirm();
await step(3);
await page.locator('[data-tutorial="die:0-4"]').click();
await page.locator('[data-tutorial="die:0-5"]').click();
await page.getByRole("button", { name: /Reroll 2 dice/ }).click();
await step(4);
assert.match(await guide.innerText(), /last die is now a matching 1/);
await page.locator('[data-tutorial="die:0-4"]').click();
await page.getByRole("button", { name: /Reroll 1 die/ }).click();
await step(5);
await confirm();
await step(6);
await finishRound(page);
} else {
await next();
await step(2);
await page.reload();
await step(2);
await recordPresentation(page);
await confirm();
await guide.getByText("Chapter complete", { exact: true }).waitFor();
const frames = await page.evaluate(() => window.readTutorialFrames());
const counts = [...new Set(frames.map((f) => f.lava))];
assert.equal(counts.length, 3, "Two separate lava waves are animated");
for (const count of counts.slice(1)) {
assert.ok(
frames.some((f) => !f.complete && f.lava === count),
"Each wave appears before completion"
);
}
assert.match(await page.locator('[data-tutorial="journal"]').innerText(), /Mika was caught by the lava/);
}
await guide.getByText("Chapter complete", { exact: true }).waitFor();
assert.equal(await guide.getByRole("button", { name: "Continue", exact: true }).isVisible(), false);
if (chapter === "terrain-bonuses") {
assert.match(await page.locator('[data-tutorial="equipment:rope"]').innerText(), /Available now/);
}
await page.reload();
await guide.getByText("Chapter complete", { exact: true }).waitFor();
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1));
assert.deepEqual(errors, []);
await page.close();
}
}
console.log(
"Fuji tutorials: all four chapters complete on desktop/mobile, with reload, equipment, lava and visible dice logs."
);
} finally {
await browser.close();
await new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));
}