Add guided Outpost tutorials and fix open auction feedback

This commit is contained in:
coyotte508 2026-09-16 00:02:55 +02:00
commit 82aa8b3324
22 changed files with 1445 additions and 71 deletions

View file

@ -96,6 +96,36 @@ Dev harness URL params: `?players=4&seed=xyz&delay=700&auto=1&fastBid=1&kicker=1
Node >= 24, pnpm 11 (see `packageManager`). All dependencies pinned.
## Tutorials
The ordinary viewer bundle also exposes `window.outpost.launchTutorial(selector, { chapter })`.
No second bundle is needed. Chapter metadata is exported as `tutorialChapters` from
`packages/viewer/src/tutorial/lessons.ts` for the BGS version's `tutorial.chapters` field.
| Chapter ID | Lesson |
| ----------------- | --------------------------------------------------------- |
| `colony` | Production cards, Water factories and operator transfers |
| `auctions` | Open bidding, passing and paying for an upgrade |
| `sealed-bids` | Maximum bids, second-price payment and personal discounts |
| `staffing` | Robot limits and choosing which factories to operate |
| `storage` | Hand capacity and exempt Research/Microbiotics cards |
| `new-chemicals` | Spending a Research card to build a New Chemicals factory |
| `mega-production` | Blind production choices and Mega-card storage |
| `victory` | Reaching 75 VP and finishing the round |
Each chapter uses a prepared position and the real engine. Opponents' turns are scripted;
the viewer still hides their private cards and unresolved sealed bids. The shared guide
provides saved progress, previous-step navigation and replay.
```bash
pnpm build
pnpm preview:tutorial # http://127.0.0.1:5198/?chapter=colony
pnpm test:tutorial
pnpm test:tutorial:browser # requires Playwright Chromium
```
Set `OUTPOST_CHROMIUM_EXECUTABLE` when using an existing Chromium installation.
## Deploying to BGS
- Engine: `npm pack` the built `outpost-engine` (or publish) and register it as the game

View file

@ -8,13 +8,16 @@
"scripts": {
"dev": "pnpm --filter outpost-viewer dev",
"build": "pnpm --filter outpost-engine build && pnpm --filter outpost-viewer build",
"test": "pnpm --filter outpost-engine test",
"test": "pnpm --filter outpost-engine test && pnpm test:tutorial",
"tsc": "pnpm --filter outpost-engine tsc && pnpm --filter outpost-viewer tsc",
"fmt": "oxfmt",
"fmt:check": "oxfmt --check",
"lint": "oxlint",
"check": "pnpm fmt:check && pnpm lint && pnpm tsc && pnpm test && pnpm build",
"test:browser": "node tests/protocol-smoke.mjs"
"test:browser": "node tests/protocol-smoke.mjs",
"test:tutorial": "pnpm --filter outpost-engine build && node --test tests/tutorial.spec.mjs",
"test:tutorial:browser": "node tests/tutorial-browser.mjs",
"preview:tutorial": "node tests/tutorial-preview.mjs"
},
"devDependencies": {
"oxfmt": "0.61.0",

View file

@ -1,6 +1,6 @@
{
"name": "outpost-engine",
"version": "0.10.13",
"version": "0.10.14",
"description": "Unofficial Outpost rules engine for boardgamers.space",
"license": "AGPL-3.0",
"files": [

View file

@ -1,6 +1,8 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { moveAI } from "./ai.js";
import { describeLogEntry } from "./describe.js";
import { UPGRADE_SPECS } from "./data.js";
import { applyMove, initGame } from "./moves.js";
import { replay } from "./replay.js";
import { handValueRange } from "./state.js";
@ -67,6 +69,37 @@ test("stripped state stays JSON-round-trippable", () => {
assert.deepEqual(JSON.parse(JSON.stringify(stripped)), stripped);
});
test("open auction bids stay public in state and log slices during and after bidding", () => {
const state = initGame(3, { fastBid: false }, "open-bid-log");
for (const player of state.players) {
player.hand = Array.from({ length: 6 }, () => ({ t: "water", v: 10 }));
}
const marketIndex = state.market.findIndex((upgrade) => UPGRADE_SPECS[upgrade].price === 25);
applyMove(state, { action: "auction", marketIndex, bid: 25 }, state.activeSeat);
const bidder = state.auction!.activeBidder;
state.players[bidder]!.name = "Ada";
applyMove(state, { action: "bid", amount: 30 }, bidder);
const index = state.log.length - 1;
const source = structuredClone(state.log[index]);
const check = () => {
for (const viewer of [0, 1, 2, undefined]) {
const stripped = wrapper.stripSecret(state, viewer);
assert.deepEqual(stripped.log[index], source);
assert.equal(describeLogEntry(stripped, stripped.log[index]!), "Ada bids 30");
const slice = wrapper.logSlice(state, { player: viewer, start: index, end: index + 1 });
assert.deepEqual(slice.log, [{ ...source, simple: "Ada bids 30" }]);
}
};
assert.equal(state.phase, "auction");
check();
for (let i = 0; state.phase === "auction" && i < 3; i++) {
applyMove(state, { action: "bidPass" }, state.auction!.activeBidder);
}
assert.equal(state.phase, "auctionPayment");
check();
assert.deepEqual(state.log[index], source);
});
test("replay rebuilds the same public state from the log", () => {
const state = play(initGame(3, {}, "replay-spec"), 200);
const replayed = replay(state);

View file

@ -114,11 +114,10 @@ function hideProduced(
// The seed derives every deck order; it must never reach a client.
return { ...entry, seed: "" };
}
if (entry.type === "move" && entry.move.action === "bid" && entry.player !== viewer && !sealedBidVisible) {
if (fastBid && entry.type === "move" && entry.move.action === "bid" && entry.player !== viewer && !sealedBidVisible) {
// fastBid: another player's sealed bid stays hidden while its auction
// runs; once the auction resolves every bid is revealed (even losing
// ones), like Powergrid. Masking a sequential bid too is harmless — the
// amount is already public via auction.highBid for the seats it concerns.
// runs; once the auction resolves every bid is revealed, including
// losing ones. Sequential auctions keep every bid public throughout.
return { ...entry, move: { action: "bid", amount: -1 } };
}
if (

View file

@ -16,7 +16,7 @@
"preview": "vite preview"
},
"dependencies": {
"@boardgamers/protocol": "0.2.2",
"@boardgamers/protocol": "0.3.1",
"outpost-engine": "workspace:*"
},
"devDependencies": {

View file

@ -98,13 +98,13 @@
});
</script>
{#if state && !state.ended && !store.replay.active}
<div class="actionbar">
{#if state && !state.ended && !store.replay.active && !store.myBidTurn}
<div class="actionbar" data-tutorial="actions">
{#if store.myMega && me}
<div class="flow mega-flow">
<span class="hint gold-hint">
Production: choose Mega cards <strong>before</strong> seeing your draws (rule 12.1). Each costs a group of 4 operated
factories; the rest of your draws are kept as singles.
Production: choose Mega cards <strong>before</strong> seeing your draws. Each costs a group of 4 operated factories;
the rest of your draws are kept as singles.
</span>
{#each Object.entries(store.megaEligible) as [resource, groups] (resource)}
{@const mega = MEGA_CARDS[resource as keyof typeof MEGA_CARDS]}
@ -277,7 +277,7 @@
</span>
</div>
{/if}
{:else if !store.myBidTurn}
{:else}
<div class="flow">
<span class="hint dim">{waitingOn}</span>
</div>

View file

@ -37,7 +37,7 @@
</script>
{#if auction && spec}
<div class="banner">
<div class="banner" data-tutorial="auction">
<div class="block">
<span class="label">On the block</span>
<span class="uname">{spec.name}</span>

View file

@ -15,7 +15,7 @@
</script>
{#if state?.ended}
<div class="banner">
<div class="banner" data-tutorial="result">
<h2>Game over</h2>
<p class="result">
{#if winners.length > 1}

View file

@ -55,7 +55,9 @@
{/if}
{/if}
<span class="item phase">{phaseLabel}</span>
<span class="item dim">First to {VICTORY_VP} VP wins</span>
<span class="item dim" title="Finish the round when someone reaches 75 VP. The player with the most VP wins.">
{VICTORY_VP} VP · finish the round
</span>
</div>
<style>

View file

@ -55,7 +55,7 @@
}
</script>
<div class="market">
<div class="market" data-tutorial="market">
<div class="caption">Colony upgrades for auction</div>
{#if state.market.length === 0}
<div class="empty">The market is empty. New upgrades arrive with the next colony ship.</div>

View file

@ -96,6 +96,7 @@
<div
class="panel"
data-tutorial={isMe ? "colony" : undefined}
class:active={isActive}
class:dropped={player.dropped}
class:me={isMe}
@ -285,7 +286,7 @@
{/each}
</div>
{/if}
<div class="row hand">
<div class="row hand" data-tutorial={isMe ? "hand" : undefined}>
{#if isMe}
{#each player.hand as card, i (i)}
{#if store.myExchange}

View file

@ -237,7 +237,10 @@ export class ViewerStore {
turnBuys = $state<TurnBuy[]>([]);
private draft = $state<GameState | null>(null);
constructor(private commands: ViewerCommands<Move>) {}
constructor(
private commands: ViewerCommands<Move>,
private optimistic = true
) {}
destroy(): void {
this.unsubscribeChat();
@ -997,7 +1000,9 @@ export class ViewerStore {
private send(move: Move): void {
this.commands.move($state.snapshot(move));
this.cancel();
this.applyOptimistic(move);
if (this.optimistic) {
this.applyOptimistic(move);
}
}
// Apply my own move to the local (stripped) state right away so the UI feels

View file

@ -0,0 +1,670 @@
import type { TutorialOptions, TutorialStep } from "@boardgamers/protocol/tutorial";
import {
applyMove,
beginRound,
countingHandSize,
enterDiscardPhase,
handValue,
setup,
victoryPoints,
type GameState,
type Move,
type ProductionCard,
type Resource,
type Upgrade,
} from "outpost-engine";
export type LessonAction = { kind: "move"; move: Move } | { kind: "watch" } | { kind: "answer"; answer: string };
export interface LessonState {
game: GameState;
answer?: string;
}
export interface Lesson extends Omit<TutorialOptions<LessonState, LessonAction>, "move"> {
title: string;
description: string;
move(state: LessonState, action: LessonAction, frame?: (game: GameState) => void): LessonState;
choices?: Record<string, { label: string; answer: string }[]>;
watch?: Record<string, string>;
}
const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T;
function take(game: GameState, resource: Resource, value: number): ProductionCard {
const index = game.decks[resource].indexOf(value);
if (index < 0) {
throw Error(`No ${resource} ${value} available in this lesson.`);
}
game.decks[resource].splice(index, 1);
return { t: resource, v: value };
}
function hand(game: GameState, seat: number, cards: [Resource, number][]) {
const player = game.players[seat]!;
for (const card of player.hand) {
game.decks[card.t].push(card.v);
}
player.hand = cards.map(([resource, value]) => take(game, resource, value));
}
function giveUpgrade(game: GameState, seat: number, upgrade: Upgrade, count = 1) {
game.players[seat]!.upgrades[upgrade] += count;
game.supply[upgrade] -= count;
}
function market(game: GameState, cards: Upgrade[]) {
for (const upgrade of game.market) {
game.supply[upgrade]++;
}
game.market = cards;
for (const upgrade of cards) {
game.supply[upgrade]--;
}
}
function base(fastBid = false): GameState {
const game = setup(3, { fastBid }, "outpost-lessons-1");
game.players.forEach((player, seat) => {
player.name = ["You", "Ada", "Leo"][seat]!;
});
game.round = 3;
game.era = 1;
game.purchaseOrder = [0, 1, 2];
game.activeSeat = 0;
game.log = [];
market(game, ["heavyEquipment", "warehouse", "nodule"]);
return game;
}
function growthState(): LessonState {
const game = base();
hand(game, 0, [
["water", 10],
["ore", 5],
["ore", 4],
["ore", 2],
]);
hand(game, 1, [
["water", 10],
["water", 10],
]);
hand(game, 2, [
["water", 8],
["ore", 2],
["ore", 5],
]);
return { game };
}
function auctionState(): LessonState {
const game = base();
hand(game, 0, [
["water", 10],
["water", 10],
["water", 7],
["ore", 5],
]);
hand(game, 1, [
["water", 9],
["water", 9],
["water", 8],
["water", 8],
]);
hand(game, 2, [
["water", 9],
["water", 8],
["water", 7],
["water", 7],
]);
return { game };
}
function sealedState(): LessonState {
const game = base(true);
game.round = 8;
game.era = 2;
giveUpgrade(game, 0, "dataLibrary", 2);
giveUpgrade(game, 1, "scientists");
giveUpgrade(game, 2, "orbitalLab");
market(game, ["scientists", "orbitalLab", "ecoplants"]);
hand(game, 0, [
["water", 10],
["water", 10],
["water", 7],
["ore", 5],
["ore", 4],
["ore", 4],
]);
hand(game, 1, [
["research", 17],
["research", 16],
["research", 15],
]);
hand(game, 2, [
["microbiotics", 20],
["microbiotics", 19],
["microbiotics", 18],
]);
game.purchaseOrder = [1, 2, 0];
game.activeSeat = 1;
applyMove(game, { action: "auction", marketIndex: 0, bid: 40 }, 1);
return { game };
}
function staffingState(): LessonState {
const game = base();
game.round = 8;
game.era = 2;
giveUpgrade(game, 0, "robots");
giveUpgrade(game, 0, "heavyEquipment");
game.players[0]!.factories.push(...Array.from({ length: 3 }, () => ({ type: "titanium" as const, manned: false })));
hand(game, 0, [["water", 10]]);
return { game };
}
function storageState(): LessonState {
const game = base();
game.round = 8;
game.era = 2;
giveUpgrade(game, 0, "scientists");
hand(game, 0, [
...[1, 2, 3, 3, 4, 4, 4, 5, 5, 5].map((value): [Resource, number] => ["ore", value]),
["water", 8],
["water", 10],
["research", 12],
["research", 13],
]);
enterDiscardPhase(game);
return { game };
}
function megaState(): LessonState {
const game = base();
game.players[0]!.population = 4;
game.players[0]!.factories = Array.from({ length: 4 }, () => ({ type: "water", manned: true }));
beginRound(game);
return { game };
}
function chemicalsState(): LessonState {
const game = base();
game.round = 10;
game.era = 2;
giveUpgrade(game, 0, "laboratory");
game.players[0]!.population = 4;
game.players[0]!.factories.push({ type: "research", manned: true });
hand(game, 0, [
["research", 12],
["water", 10],
["water", 10],
["water", 10],
["water", 9],
["water", 9],
]);
return { game };
}
function victoryState(): LessonState {
const game = base();
game.round = 18;
game.era = 3;
for (const [seat, upgrades] of [
[0, ["moonBase", "moonBase", "planetaryCruiser", "spaceStation"]],
[1, ["planetaryCruiser", "spaceStation", "ecoplants"]],
[2, ["outpost", "laboratory", "orbitalLab"]],
] as [number, Upgrade[]][]) {
for (const upgrade of upgrades) {
giveUpgrade(game, seat, upgrade);
}
}
game.players[0]!.population = 5;
game.players[0]!.factories = Array.from({ length: 5 }, () => ({ type: "water", manned: true }));
game.players[2]!.factories.push({ type: "titanium", manned: false }, { type: "research", manned: false });
game.players[2]!.factories.forEach((factory, index) => {
factory.manned = index >= 2;
});
hand(game, 0, [
["orbitalMedicine", 30],
["moonOre", 60],
]);
hand(game, 1, [["ore", 5]]);
hand(game, 2, [["ore", 4]]);
market(game, ["ecoplants"]);
return { game };
}
function finish(game: GameState, seat: number, grow = false): Move {
const player = game.players[seat]!;
if (grow && handValue(player) >= 20) {
return {
action: "endTurn",
buys: [{ buy: "factory", factory: "water", cards: [0, 1] }],
manned: [1, 2, 3],
};
}
return { action: "endTurn", buys: [], manned: player.factories.flatMap((factory, i) => (factory.manned ? [i] : [])) };
}
function run(id: string): Lesson["move"] {
return (state, action, frame) => {
const next = clone(state);
const game = next.game;
const apply = (move: Move, seat: number) => {
applyMove(game, move, seat);
frame?.(clone(game));
};
if (action.kind === "answer") {
next.answer = action.answer;
} else if (action.kind === "watch") {
apply(finish(game, 1, id === "colony"), 1);
apply(finish(game, 2), 2);
} else {
apply(action.move, 0);
if (id === "auctions" && action.move.action === "auction") {
apply({ action: "bid", amount: 30 }, 1);
apply({ action: "bidPass" }, 2);
} else if (id === "auctions" && action.move.action === "bid") {
apply({ action: "bidPass" }, 1);
} else if (id === "sealed-bids" && action.move.action === "bid") {
apply({ action: "bid", amount: 50 }, 2);
} else if (id === "victory" && action.move.action === "endTurn") {
apply(finish(game, 1), 1);
apply(finish(game, 2), 2);
}
}
return next;
};
}
function actionStep(
id: string,
title: string,
text: string,
allowed: (action: LessonAction, state: LessonState) => boolean,
complete: (state: LessonState) => boolean,
target = "actions"
): TutorialStep<LessonState, LessonAction> {
return {
id,
title,
text,
target,
complete,
validateMove: (state, action) =>
allowed(action, state) ? undefined : "Follow this step’s instructions. Use Replay step to start it again.",
};
}
function question(id: string, title: string, text: string, answer: string): TutorialStep<LessonState, LessonAction> {
return {
...actionStep(
id,
title,
text,
(action) => action.kind === "answer" && action.answer === answer,
(state) => state.answer === answer,
"lesson-choices"
),
validateMove: (_state, action) =>
action.kind === "answer" && action.answer === answer ? undefined : "Not quite. Try another answer.",
};
}
const isMove = (action: Move["action"]) => (value: LessonAction) =>
value.kind === "move" && value.move.action === action;
const isWatch = (value: LessonAction) => value.kind === "watch";
const shell = (id: string) => ({ game: "outpost", id, version: 1, move: run(id) });
const answers = (...values: string[]) => values.map((value) => ({ label: value, answer: value }));
export const lessons: Lesson[] = [
{
...shell("colony"),
version: 2,
title: "Grow your colony",
description: "Buy a Water factory and move an Ore operator to it for stronger income.",
initialState: growthState,
steps: [
{
id: "intro",
title: "Factories earn your income",
text: "Your colony starts with two Ore factories, one Water factory and three colonists. Each staffed factory produces one card per round and earns VP. Expand your colony to reach 75 VP.",
target: "colony",
},
question(
"credits",
"Cards are your money",
"You have 21 credits in four cards. Purchases consume whole cards and give no change. If you spend all 21 on a Water factory costing 20, how many credits come back?",
"0"
),
actionStep(
"build",
"Move an operator to Water",
"Buy one Water factory for 20 and confirm the payment. Choose Assign operators…. Click either Ore factory to free its operator, then click the new Water factory to staff it. Keep the other Water factory working and End turn. Water averages 7 credits per card; Ore averages 3.",
(action) =>
action.kind === "move" &&
action.move.action === "endTurn" &&
action.move.buys.length === 1 &&
action.move.buys[0]?.buy === "factory" &&
action.move.buys[0].factory === "water" &&
(action.move.buys[0].count ?? 1) === 1 &&
action.move.manned.length === 3 &&
action.move.manned.includes(2) &&
action.move.manned.includes(3),
(state) => state.game.players[0]!.done
),
actionStep(
"production",
"Watch the next production",
"Ada also buys Water and transfers an Ore operator. Leo saves his remaining cards. Once both finish, you will collect two Water cards and one Ore card. The idle Ore factory produces nothing. Unspent cards carry over between rounds.",
isWatch,
(state) => state.game.round === 4,
"lesson-choices"
),
],
choices: { credits: answers("0", "1", "21") },
watch: { production: "Watch their turns and production" },
completion: {
title: "Stronger income with the same colonists",
text: "Your three colonists now run two Water factories and one Ore factory. Average income rises from 13 to 17 credits per round. You still have 3 VP: only staffed factories score. The spare Ore factory can work again when you recruit another operator.",
},
},
{
...shell("auctions"),
title: "Bid for an upgrade",
description: "Open an auction, raise a bid and pay for Heavy Equipment.",
initialState: auctionState,
steps: [
{
id: "intro",
title: "Upgrades are auctioned",
text: "On your turn, auction upgrades before buying factories or colonists. Heavy Equipment costs at least 25. It unlocks Titanium factories and gives discounts on other upgrades. This chapter uses open bidding.",
target: "market",
},
actionStep(
"open",
"Open at 25",
"Select Heavy Equipment in the market, then confirm Auction at 25. Other players can raise your bid even when it is not their action turn.",
(action) =>
action.kind === "move" &&
action.move.action === "auction" &&
action.move.marketIndex === 0 &&
action.move.bid === 25,
(state) => state.game.auction?.highBid === 30,
"market"
),
actionStep(
"raise",
"Beat Ada’s 30",
"Ada offers 30 and Leo passes. Bid 31 to stay in the auction. Passing would remove you from this auction; Leo cannot rejoin after passing.",
(action) => action.kind === "move" && action.move.action === "bid" && action.move.amount === 31,
(state) => state.game.phase === "auctionPayment",
"auction"
),
actionStep(
"pay",
"Pay with your cards",
"Ada passes, so you win for 31. The smallest payment your cards can make is 32. Confirm the selected cards: you lose the extra credit. Only the winner pays, and your action turn resumes afterward.",
isMove("pay"),
(state) => state.game.players[0]!.upgrades.heavyEquipment === 1
),
],
completion: {
title: "Heavy Equipment is yours",
text: "Your upgrade adds 1 VP and unlocks Titanium factories. Those factories cost 30, produce stronger cards and score 2 VP when staffed. In a normal turn you could auction another upgrade, then make purchases and finish your turn.",
},
},
{
...shell("sealed-bids"),
title: "Sealed bids and discounts",
description: "Set a maximum bid and see what you actually pay with a discount.",
initialState: sealedState,
steps: [
{
id: "intro",
title: "One secret bid each",
text: "With the sealed-auction option, everyone submits one maximum bid or passes. Ada has opened a Scientists auction. You own two Data Libraries, giving you a 20-credit discount on Scientists. Bid amounts are compared before discounts.",
target: "auction",
},
actionStep(
"bid",
"Set your maximum to 60",
"You hold 40 credits and have a 20-credit discount, so you can bid up to 60. Enter 60 and submit it. Other bidders must bid at least 41, one above the Scientists’ base price. Their amounts stay hidden until everyone responds.",
(action) => action.kind === "move" && action.move.action === "bid" && action.move.amount === 60,
(state) => state.game.phase === "auctionPayment",
"auction"
),
question(
"price",
"How much do you owe?",
"You bid 60, Leo bid 50 and Ada bid 40. The price is the second-highest bid plus 1, here 51. Subtract your two Data Libraries’ 20-credit discount. How much do you pay?",
"31"
),
actionStep(
"pay",
"Pay 31, keep the rest",
"Confirm the suggested 31-credit payment. Your maximum bid was 60, but you only owe 31 after the auction and discount. Scientists will produce one Research card each round without an operator.",
isMove("pay"),
(state) => state.game.players[0]!.upgrades.scientists === 1
),
],
choices: { price: answers("31", "40", "51") },
completion: {
title: "Maximum bid and actual payment",
text: "You keep 9 credits. The auction price never exceeds your bid or falls below the base price, then your discount applies. Equal highest bids are broken in purchase order starting with the auction opener. If everyone else passes, the opener pays the base price before discounts.",
},
},
{
...shell("staffing"),
title: "People, robots and factories",
description: "Buy a robot and assign operators to your most useful factories.",
initialState: staffingState,
steps: [
{
id: "intro",
title: "Unstaffed factories do nothing",
text: "You have six factories but only three colonists. The three Titanium factories are idle: they produce nothing and score no VP. You already own the Robots upgrade, so you may buy robot tokens for 10 each.",
target: "colony",
},
question(
"limit",
"How many robots can operate?",
"Each Robots upgrade lets you operate as many robots as you have colonists. With three colonists and one Robots upgrade, how many robots could work? Robots do not use your colonist capacity.",
"3"
),
actionStep(
"assign",
"Put a robot to work",
"Buy one robot for 10 and confirm its payment. Choose Assign operators…. Leave the Water factory staffed, unstaff both Ore factories, and staff all three Titanium factories. Then End turn with four factories working.",
(action) =>
action.kind === "move" &&
action.move.action === "endTurn" &&
action.move.buys.length === 1 &&
action.move.buys[0]?.buy === "robots" &&
action.move.buys[0].count === 1 &&
action.move.manned.length === 4 &&
[2, 3, 4, 5].every((i) => action.move.action === "endTurn" && action.move.manned.includes(i)),
(state) => state.game.players[0]!.done
),
actionStep(
"production",
"See the result",
"Your operators now run one Water and three Titanium factories. Watch the other players finish and collect your next production.",
isWatch,
(state) => state.game.round === 9,
"lesson-choices"
),
],
choices: { limit: answers("1", "3", "5") },
watch: { production: "Collect next round’s production" },
completion: {
title: "Better use of your operators",
text: "You collect one Water card and three Titanium cards. Those factories score 7 VP, plus 4 from your upgrades. Colonists start with a capacity of five; Nodules and Outposts increase it. Excess robots can be owned but stay idle until your operating limit grows.",
},
},
{
...shell("storage"),
title: "Make room for production",
description: "Understand hand capacity and choose which cards to discard.",
initialState: storageState,
steps: [
{
id: "intro",
title: "Storage is limited",
text: "After production, discard excess cards before anyone takes an action turn. Your basic hand capacity is ten. You cannot buy something first to avoid discarding. A Warehouse upgrade adds three spaces per copy.",
target: "hand",
},
question(
"count",
"Which cards use space?",
"You hold fourteen cards: ten Ore, two Water and two Research. Research and Microbiotics use no hand capacity. How many of your cards count toward the limit?",
"12"
),
actionStep(
"discard",
"Keep the valuable cards",
"Discard the Ore cards worth 1 and 2. They are already suggested. Confirm Discard to keep all the more valuable cards, including both Research cards.",
(action, state) =>
action.kind === "move" &&
action.move.action === "discard" &&
action.move.cards.length === 2 &&
action.move.cards.every(
(i) => state.game.players[0]!.hand[i]?.t === "ore" && state.game.players[0]!.hand[i]!.v <= 2
),
(state) => countingHandSize(state.game.players[0]!) === 10
),
],
choices: { count: answers("10", "12", "14") },
completion: {
title: "Twelve cards, ten spaces",
text: "Your ten counting cards fill the available storage. Both Research cards stay outside that limit. Production upgrades such as Scientists and Orbital Lab earn useful cards that do not crowd out your other income.",
},
},
{
...shell("new-chemicals"),
title: "Research opens new industry",
description: "Include a Research card when paying for a New Chemicals factory.",
initialState: chemicalsState,
steps: [
{
id: "intro",
title: "Research has two uses",
text: "Your Laboratory came with a Research factory and allows you to buy more. Staffed Research factories produce Research cards. Scientists also produce Research, without an operator. These cards spend like money, use no hand space, and unlock New Chemicals.",
target: "colony",
},
question(
"requirement",
"What must the payment include?",
"A New Chemicals factory costs 60. Is having a Research card enough, or must you spend it as part of those 60 credits?",
"Spend one Research card per factory"
),
actionStep(
"build",
"Use Research to build New Chemicals",
"Buy one New Chemicals factory. Its 60-credit payment must include your Research card; its value counts toward the 60. Confirm, then Assign operators…. Move an operator from one Ore factory to the new factory and End turn. Keep Water and Research staffed.",
(action) =>
action.kind === "move" &&
action.move.action === "endTurn" &&
action.move.buys.length === 1 &&
action.move.buys[0]?.buy === "factory" &&
action.move.buys[0].factory === "newChemicals" &&
(action.move.buys[0].count ?? 1) === 1 &&
[2, 3, 4].every((i) => action.move.action === "endTurn" && action.move.manned.includes(i)),
(state) => state.game.players[0]!.done
),
actionStep(
"production",
"Collect the stronger production",
"Your new factory is staffed and worth 3 VP. Watch the next round to receive a New Chemicals card, along with fresh Research for a future factory.",
isWatch,
(state) => state.game.round === 11,
"lesson-choices"
),
],
choices: { requirement: answers("Keep a Research card in my hand", "Spend one Research card per factory") },
watch: { production: "Collect New Chemicals production" },
completion: {
title: "Research funds your next expansion",
text: "New Chemicals cards are worth 14–26 credits. Each new factory costs 60 and consumes at least one Research card. You do not need to own a Laboratory if you obtain Research another way, such as Scientists.",
},
},
{
...shell("mega-production"),
title: "Choose steady production",
description: "Trade four random production cards for one fixed-value Mega card.",
initialState: megaState,
steps: [
{
id: "intro",
title: "Four factories, one choice",
text: "Four staffed Water factories let you choose a Mega Water card worth exactly 30 instead of four random Water cards. Decide before seeing this round’s new values. Titanium and New Chemicals factories can also produce Mega cards in groups of four.",
target: "colony",
},
actionStep(
"mega",
"Take one Mega Water",
"Use + to choose one Mega Water, then confirm Take 1 mega. A fixed 30 removes the uncertainty of four draws. Keeping all four singles would give separate cards that are easier to split across purchases.",
(action) => action.kind === "move" && action.move.action === "mega" && action.move.take.water === 1,
(state) => state.game.players[0]!.hand.some((card) => card.m && card.t === "water" && card.v === 30)
),
question(
"space",
"How much storage does it use?",
"Mega Water is one physical card, but it replaces four ordinary cards. How many spaces does it count toward your hand limit?",
"4"
),
],
choices: { space: answers("1", "4", "30") },
completion: {
title: "Reliable income has a trade-off",
text: "Your Mega card is worth 30 and uses four spaces. It is spent whole, with no change. Everyone can see its printed value; ordinary production card values stay private.",
},
},
{
...shell("victory"),
title: "Finish with the most VP",
description: "Reach 75 VP and play through the end of the final round.",
initialState: victoryState,
steps: [
{
id: "intro",
title: "A prepared final round",
text: "You have 70 VP: 65 from upgrades and 5 from staffed Water factories. Ecoplants adds 5 VP. Reach 75 and this will be the last round. The player with the most VP when the round finishes wins.",
target: "colony",
},
question(
"score",
"Does saving money score points?",
"You also hold a 60-credit Moon Ore card. Does keeping it in your hand add 60 VP?",
"No, only staffed factories and upgrades score"
),
actionStep(
"open",
"Win Ecoplants",
"Open the Ecoplants auction at 30. Ada and Leo cannot beat that bid with their remaining cards, so they pass automatically.",
(action) =>
action.kind === "move" &&
action.move.action === "auction" &&
action.move.marketIndex === 0 &&
action.move.bid === 30,
(state) => state.game.phase === "auctionPayment",
"market"
),
actionStep(
"pay",
"Reach 75 VP",
"Pay with the suggested 30-credit Orbital Medicine card. Ecoplants adds 5 VP and makes colonists cheaper. Watch your score rise from 70 to 75.",
isMove("pay"),
(state) => victoryPoints(state.game.players[0]!) === 75
),
question(
"round",
"Is the game over immediately?",
"You now have 75 VP, but Ada and Leo still have turns this round. Could another player still finish with more VP and win?",
"Yes, finish the round first"
),
actionStep(
"finish",
"Finish the last round",
"Choose Assign operators…, keep all five factories staffed, then End turn. Ada and Leo will finish too. You have the highest score in this example.",
(action) => action.kind === "move" && action.move.action === "endTurn" && action.move.buys.length === 0,
(state) => state.game.ended
),
],
choices: {
score: answers("Yes, money becomes VP", "No, only staffed factories and upgrades score"),
round: answers("Yes, finish the round first", "No, the first to 75 wins immediately"),
},
completion: {
title: "Your colony wins with 75 VP",
text: "Build income early, use operators efficiently and turn that income into points. Reaching 75 triggers the final round’s end; it does not stop the other players from taking their remaining turns.",
},
},
];
export const tutorialChapters = lessons.map(({ id, version, title, description }) => ({
id,
version,
title,
description,
}));

View file

@ -0,0 +1,143 @@
import { mount, tick, unmount } from "svelte";
import { createTutorial, type TutorialMount } from "@boardgamers/protocol/tutorial";
import { mountTutorialGuide } from "@boardgamers/protocol/tutorial/dom";
import { stripSecret } from "outpost-engine/wrapper";
import type { GameState } from "outpost-engine";
import App from "../App.svelte";
import { ViewerStore } from "../lib/store.svelte";
import { lessons, type LessonAction } from "./lessons";
import "./tutorial.css";
export const mountTutorial: TutorialMount = async (target, { chapter, onProgress }) => {
const lesson = lessons.find((entry) => entry.id === chapter);
if (!lesson) {
throw Error("Unknown Outpost chapter");
}
target.className = "outpost-tutorial";
const top = document.createElement("div");
top.className = "tutorial-top";
const guide = document.createElement("div");
const choices = document.createElement("div");
choices.className = "tutorial-choices";
choices.dataset.tutorial = "lesson-choices";
choices.setAttribute("role", "group");
choices.setAttribute("aria-label", "Lesson answers");
const gameHost = document.createElement("div");
top.append(guide, choices);
target.append(top, gameHost);
let destroyed = false;
let animate = false;
let timer: ReturnType<typeof setTimeout> | undefined;
let finishDelay: (() => void) | undefined;
const store = new ViewerStore(
{
move(move) {
void play({ kind: "move", move });
return true;
},
openPlayer: () => false,
updatePreference: () => false,
fetchState: () => false,
fetchLog: () => false,
addLog: () => false,
replaceLog: () => false,
setReplayInfo: () => false,
},
false
);
store.playerIndex = 0;
store.chat.setDisabled(true);
let storage: Storage | undefined;
try {
storage = localStorage;
} catch {
storage = undefined;
}
const controller = await createTutorial({
...lesson,
storage,
onProgress,
async move(state, action) {
const frames: GameState[] = [];
const next = lesson.move(state, action, (frame) => frames.push(frame));
if (animate) {
for (const frame of frames) {
if (destroyed) {
break;
}
store.setState(stripSecret(frame, 0));
await tick();
await new Promise<void>((resolve) => {
finishDelay = resolve;
timer = setTimeout(resolve, matchMedia("(prefers-reduced-motion: reduce)").matches ? 0 : 700);
});
}
}
finishDelay = undefined;
return next;
},
});
async function play(action: LessonAction) {
if (destroyed || controller.snapshot.busy || controller.snapshot.completed) {
return;
}
animate = true;
try {
await controller.play(action);
} finally {
animate = false;
}
}
const app = mount(App, { target: gameHost, props: { store } });
const unsubscribe = controller.subscribe((snapshot) => {
if (!snapshot.busy) {
store.turnBuys = [];
store.setState(stripSecret(snapshot.state.game, 0));
}
const step = lesson.steps[snapshot.step]?.id ?? "complete";
target.dataset.step = step;
target.dataset.completed = String(snapshot.completed);
gameHost.inert =
snapshot.busy || snapshot.canContinue || snapshot.completed || !!lesson.choices?.[step] || !!lesson.watch?.[step];
choices.replaceChildren();
for (const choice of lesson.choices?.[step] ?? []) {
const button = document.createElement("button");
button.type = "button";
button.textContent = choice.label;
button.disabled = snapshot.busy;
button.onclick = () => {
void play({ kind: "answer", answer: choice.answer });
};
choices.append(button);
}
const watch = lesson.watch?.[step];
if (watch) {
const button = document.createElement("button");
button.type = "button";
button.textContent = watch;
button.disabled = snapshot.busy;
button.onclick = () => {
void play({ kind: "watch" });
};
choices.append(button);
}
choices.hidden = !choices.childElementCount;
});
await tick();
const cleanupGuide = mountTutorialGuide(guide, controller);
const resize = new ResizeObserver(() => {
target.style.setProperty("--tutorial-height", `${top.getBoundingClientRect().height}px`);
});
resize.observe(top);
return () => {
destroyed = true;
clearTimeout(timer);
finishDelay?.();
resize.disconnect();
cleanupGuide();
unsubscribe();
controller.destroy();
store.destroy();
void unmount(app);
};
};

View file

@ -0,0 +1,109 @@
.outpost-tutorial {
--tutorial-height: 180px;
}
.tutorial-top {
position: sticky;
top: 0;
z-index: 50;
padding: 8px 16px;
background: var(--bg);
}
.bgs-tutorial-guide {
max-width: 1368px;
margin: auto;
border: 1px solid var(--gold);
border-radius: var(--radius);
background: var(--bg-panel);
padding: 12px 16px;
}
.bgs-tutorial-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
color: var(--gold);
}
.bgs-tutorial-body p {
margin: 8px 0 12px;
max-width: 1050px;
}
.bgs-tutorial-controls,
.bgs-tutorial-playback,
.bgs-tutorial-help {
display: flex;
align-items: center;
gap: 6px;
}
.bgs-tutorial-controls {
flex-wrap: wrap;
}
.bgs-tutorial-playback,
.bgs-tutorial-help {
flex-wrap: nowrap;
}
.bgs-tutorial-transport {
display: inline-flex;
align-items: center;
justify-content: center;
width: 36px;
height: 36px;
flex: 0 0 36px;
padding: 0;
}
.bgs-tutorial-guide small {
display: block;
margin-top: 8px;
color: var(--text-dim);
font-size: 11px;
}
.bgs-tutorial-guide [role="alert"] {
color: #ffc8ad;
}
.outpost-tutorial [hidden] {
display: none;
}
.tutorial-choices {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin: 12px auto 4px;
width: fit-content;
max-width: 100%;
}
.tutorial-choices button {
border-color: var(--gold);
padding: 8px 12px;
font-weight: 600;
}
.bgs-tutorial-highlight {
outline: 2px solid var(--gold);
outline-offset: 4px;
}
.outpost-tutorial [data-tutorial] {
scroll-margin-top: calc(var(--tutorial-height) + 24px);
scroll-margin-bottom: 24px;
}
.outpost-tutorial .side {
top: calc(var(--tutorial-height) + 12px);
}
.outpost-tutorial .actionbar {
position: static;
}
@media (max-width: 720px) {
.tutorial-top {
padding: 6px 8px;
}
.bgs-tutorial-guide {
padding: 8px 10px;
font-size: 13px;
}
.bgs-tutorial-guide small {
display: none;
}
.bgs-tutorial-body p {
margin: 6px 0 8px;
}
.tutorial-choices {
margin-top: 8px;
}
}

View file

@ -4,53 +4,58 @@ import type { GameState, Move } from "outpost-engine";
import { createActionSounds } from "./lib/sounds";
import App from "./App.svelte";
import { ViewerStore } from "./lib/store.svelte";
import { mountTutorial } from "./tutorial/mount";
import "./lib/theme.css";
registerViewer<GameState, Move>("outpost", (commands) => {
const store = new ViewerStore(commands);
const sounds = createActionSounds();
const app = mount(App, {
target: commands.target,
props: { store, onPlayerClick: commands.openPlayer },
});
return {
chat: store.chat,
async onState(state) {
sounds.onState(state);
store.setState(state);
await tick();
},
onPlayer({ index }) {
store.playerIndex = index;
},
onAvatars(avatars) {
store.avatars = avatars;
},
onPreferences(preferences) {
store.preferences = preferences;
sounds.onPreferences(preferences);
},
onLog(log) {
store.onGamelog(log);
},
onReplayStart() {
sounds.onReplayStart();
store.startReplay();
},
onReplayTo(to) {
store.replayTo(to);
},
onReplayEnd() {
sounds.onReplayEnd();
store.endReplay();
},
destroy() {
store.destroy();
sounds.destroy();
void unmount(app);
},
};
});
registerViewer<GameState, Move>(
"outpost",
(commands) => {
const store = new ViewerStore(commands);
const sounds = createActionSounds();
const app = mount(App, {
target: commands.target,
props: { store, onPlayerClick: commands.openPlayer },
});
return {
chat: store.chat,
async onState(state) {
sounds.onState(state);
store.setState(state);
await tick();
},
onPlayer({ index }) {
store.playerIndex = index;
},
onAvatars(avatars) {
store.avatars = avatars;
},
onPreferences(preferences) {
store.preferences = preferences;
sounds.onPreferences(preferences);
},
onLog(log) {
store.onGamelog(log);
},
onReplayStart() {
sounds.onReplayStart();
store.startReplay();
},
onReplayTo(to) {
store.replayTo(to);
},
onReplayEnd() {
sounds.onReplayEnd();
store.endReplay();
},
destroy() {
store.destroy();
sounds.destroy();
void unmount(app);
},
};
},
{ tutorial: mountTutorial }
);
declare global {
interface Window {

10
pnpm-lock.yaml generated
View file

@ -40,8 +40,8 @@ importers:
packages/viewer:
dependencies:
'@boardgamers/protocol':
specifier: 0.2.2
version: 0.2.2
specifier: 0.3.1
version: 0.3.1
outpost-engine:
specifier: workspace:*
version: link:../engine
@ -67,8 +67,8 @@ importers:
packages:
'@boardgamers/protocol@0.2.2':
resolution: {integrity: sha512-5o5nPZW6CN6PysF0i90OR+B30djiFhAGutCZe5RKJV6h3RgqE36HA7l0pOpvhdHz8uYtqE0nmaPlc+2ZtYiM/A==}
'@boardgamers/protocol@0.3.1':
resolution: {integrity: sha512-FF8OUEvAZ+BKjZZ3Ab8Dw7oQh6TJOKMNkmRHqoabeE4clSp8lMRnHGGEakZdi7DplDJpstnya2fgBk2hX82UrA==}
'@jridgewell/gen-mapping@0.3.13':
resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}
@ -772,7 +772,7 @@ packages:
snapshots:
'@boardgamers/protocol@0.2.2':
'@boardgamers/protocol@0.3.1':
dependencies:
zod: 4.6.2

View file

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

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

@ -0,0 +1,127 @@
import assert from "node:assert/strict";
import { chromium } from "playwright";
import { previewServer } from "./tutorial-preview.mjs";
import { lessons } from "../packages/viewer/src/tutorial/lessons.ts";
const server = previewServer();
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}`;
const browser = await chromium.launch({ executablePath: process.env.OUTPOST_CHROMIUM_EXECUTABLE });
try {
for (const width of [1400, 390]) {
for (const lesson of lessons) {
const context = await browser.newContext({ viewport: { width, height: 950 }, reducedMotion: "reduce" });
const page = await context.newPage();
const errors = [];
page.on("pageerror", (error) => errors.push(error.message));
await page.route(`${base}/host`, (route) =>
route.fulfill({
contentType: "text/html",
body: `<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1"><style>body{margin:0}iframe{width:100%;height:100dvh;border:0;display:block}</style><iframe sandbox="allow-scripts allow-same-origin" src="${base}/?chapter=${lesson.id}"></iframe>`,
})
);
await page.goto(`${base}/host`);
const frame = page.frameLocator("iframe");
const root = frame.locator(".outpost-tutorial");
const guide = frame.locator(".bgs-tutorial-guide");
const button = (name) => frame.getByRole("button", { name, exact: true });
const step = (id) => frame.locator(`.outpost-tutorial[data-step="${id}"]`).waitFor();
const finishTurn = async () => {
await button("Assign operators…").click();
await button("End turn").click();
};
const purchase = async (name, cost) => {
await button(name).click();
await button(`Confirm (◈ ${cost})`).click();
};
const doStep = async (entry) => {
await step(entry.id);
if (!entry.complete) {
await guide.getByRole("button", { name: "Continue", exact: true }).click();
} else if (lesson.choices?.[entry.id]) {
const answer = lesson.choices[entry.id].find(
(choice) => !entry.validateMove(lesson.initialState(), { kind: "answer", answer: choice.answer })
);
await button(answer.label).click();
} else if (lesson.watch?.[entry.id]) {
await button(lesson.watch[entry.id]).click();
} else if (entry.id === "open") {
const name = lesson.id === "victory" ? "Ecoplants" : "Heavy Equipment";
await frame.locator(".market .ucard").filter({ hasText: name }).first().click();
await button(`Auction at ◈ ${lesson.id === "victory" ? 30 : 25}`).click();
} else if (entry.id === "raise" || entry.id === "bid") {
assert.equal(await frame.locator(".actionbar").count(), 0, "No empty panel while bidding");
await frame.locator('[data-tutorial="auction"].bgs-tutorial-highlight').waitFor();
if (entry.id === "raise") {
await frame.getByText("Ada bids 30", { exact: true }).waitFor();
assert.equal(await frame.getByText("Ada takes part in the sealed auction", { exact: true }).count(), 0);
await page.screenshot({ path: `/tmp/outpost-open-auction-${width}.png` });
}
const amount = entry.id === "raise" ? 31 : 60;
await frame.getByRole("spinbutton", { name: "Bid before discount" }).fill(String(amount));
await button(`Bid ◈ ${amount}`).click();
} else if (entry.id === "pay") {
await button(`Pay ◈ ${lesson.id === "victory" ? 30 : 31}`).click();
} else if (entry.id === "build" && lesson.id === "colony") {
await purchase("Water · ◈ 20", 20);
await button("Assign operators…").click();
const colony = frame.locator(".panel.me");
await colony.locator(".fgroup.res-ore .chip").first().click();
await colony.locator(".fgroup.res-water .chip:not(.manned)").click();
await button("End turn").click();
} else if (entry.id === "assign" || lesson.id === "new-chemicals") {
await purchase(
entry.id === "assign" ? "Robot · ◈ 10" : "New Chemicals · ◈ 60",
entry.id === "assign" ? 10 : 60
);
await button("Assign operators…").click();
const colony = frame.locator(".panel.me");
const ore = colony.locator(".fgroup.res-ore .chip");
await ore.nth(0).click();
if (entry.id === "assign") {
await ore.nth(1).click();
await colony.locator(".fgroup.res-titanium .chip:not(.manned)").first().click();
await colony.locator(".fgroup.res-titanium .chip:not(.manned)").first().click();
} else {
await colony.locator(".fgroup.res-newChemicals .chip").click();
}
await button("End turn").click();
} else if (entry.id === "discard") {
await button("Discard selected").click();
} else if (entry.id === "mega") {
await frame.locator(".mega-stepper").getByRole("button", { name: "+", exact: true }).click();
await button("Take 1 mega").click();
} else if (entry.id === "finish") {
await finishTurn();
} else {
throw Error(`Missing UI path: ${lesson.id}/${entry.id}`);
}
};
for (const [index, entry] of lesson.steps.entries()) {
await doStep(entry);
await step(lesson.steps[index + 1]?.id ?? "complete");
assert.equal(await frame.locator(".bgs-tutorial-guide [role=alert]").innerText(), "");
assert.equal(
await root.evaluate(() => document.documentElement.scrollWidth > innerWidth + 1),
false,
`${lesson.id}/${entry.id} horizontal overflow`
);
}
await page.screenshot({ path: `/tmp/outpost-tutorial-${lesson.id}-${width}.png` });
await page.reload();
await step("complete");
await guide.getByRole("button", { name: "Previous step", exact: true }).click();
await doStep(lesson.steps.at(-1));
await step("complete");
await guide.getByRole("button", { name: "Back to start", exact: true }).click();
await step("intro");
await page.screenshot({ path: `/tmp/outpost-tutorial-${lesson.id}-start-${width}.png` });
assert.deepEqual(errors, []);
console.log(`${width}px ${lesson.id}: real controls, sandbox, refresh, previous step, restart passed`);
await context.close();
}
}
} finally {
await browser.close();
server.close();
}

View file

@ -0,0 +1,33 @@
import { readFile } from "node:fs/promises";
import { createServer } from "node:http";
const files = {
"/bundle.js": new URL("../packages/viewer/dist/outpost-viewer.iife.js", import.meta.url),
"/bundle.css": new URL("../packages/viewer/dist/outpost-viewer.css", import.meta.url),
};
const html =
'<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Outpost tutorial</title><link rel="stylesheet" href="/bundle.css"><div id="app"></div><script src="/bundle.js"></script><script>outpost.launchTutorial("#app",{chapter:new URLSearchParams(location.search).get("chapter")||"colony"});</script>';
export function previewServer() {
return createServer(async (req, res) => {
const path = new URL(req.url, "http://localhost").pathname;
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Cache-Control", "no-store");
try {
if (files[path]) {
res.setHeader("Content-Type", path.endsWith(".css") ? "text/css" : "text/javascript");
res.end(await readFile(files[path]));
} else if (path === "/") {
res.setHeader("Content-Type", "text/html");
res.end(html);
} else {
res.writeHead(404).end();
}
} catch {
res.writeHead(500).end("Build the viewer first with pnpm build.");
}
});
}
if (import.meta.main) {
const port = Number(process.env.PORT || 5198);
previewServer().listen(port, "127.0.0.1", () => console.log(`Outpost tutorial: http://127.0.0.1:${port}/`));
}

214
tests/tutorial.spec.mjs Normal file
View file

@ -0,0 +1,214 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { createRequire } from "node:module";
import { lessons } from "../packages/viewer/src/tutorial/lessons.ts";
import {
bestPayment,
handValue,
victoryPoints,
countingHandSize,
productionRange,
PRODUCTION_DECKS,
RESOURCES,
} from "../packages/engine/dist/index.js";
import { stripSecret } from "../packages/engine/dist/wrapper.js";
const { createTutorial } = createRequire(new URL("../packages/viewer/package.json", import.meta.url))(
"@boardgamers/protocol/tutorial"
);
const move = (value) => ({ kind: "move", move: value });
const answer = (value) => ({ kind: "answer", answer: value });
const pay = (state, due) => move({ action: "pay", cards: bestPayment(state.game.players[0], due) });
const paths = {
colony: [
null,
answer("0"),
move({
action: "endTurn",
buys: [{ buy: "factory", factory: "water", cards: [0, 1, 2, 3] }],
manned: [1, 2, 3],
}),
{ kind: "watch" },
],
auctions: [
null,
move({ action: "auction", marketIndex: 0, bid: 25 }),
move({ action: "bid", amount: 31 }),
(state) => pay(state, 31),
],
"sealed-bids": [null, move({ action: "bid", amount: 60 }), answer("31"), (state) => pay(state, 31)],
staffing: [
null,
answer("3"),
move({ action: "endTurn", buys: [{ buy: "robots", count: 1, cards: [0] }], manned: [2, 3, 4, 5] }),
{ kind: "watch" },
],
storage: [null, answer("12"), move({ action: "discard", cards: [0, 1] })],
"new-chemicals": [
null,
answer("Spend one Research card per factory"),
move({
action: "endTurn",
buys: [{ buy: "factory", factory: "newChemicals", cards: [0, 1, 2, 3, 4, 5] }],
manned: [1, 2, 3, 4],
}),
{ kind: "watch" },
],
"mega-production": [null, move({ action: "mega", take: { water: 1 } }), answer("4")],
victory: [
null,
answer("No, only staffed factories and upgrades score"),
move({ action: "auction", marketIndex: 0, bid: 30 }),
(state) => pay(state, 30),
answer("Yes, finish the round first"),
move({ action: "endTurn", buys: [], manned: [0, 1, 2, 3, 4] }),
],
};
function validateState(game) {
for (const resource of RESOURCES) {
const total =
game.decks[resource].length +
game.discards[resource].length +
game.players
.flatMap((p) => [...p.hand, ...(p.pendingMega ?? [])])
.filter((card) => card.t === resource && !card.m).length;
assert.equal(
total,
Object.values(PRODUCTION_DECKS[resource].distribution).reduce((sum, n) => sum + n, 0),
resource
);
}
for (const [upgrade, remaining] of Object.entries(game.supply)) {
assert.ok(remaining >= 0, `${upgrade} supply`);
assert.equal(
remaining +
game.market.filter((u) => u === upgrade).length +
game.players.reduce((sum, p) => sum + p.upgrades[upgrade], 0),
2,
upgrade
);
}
const view = stripSecret(game, 0);
assert.equal(view.seed, "");
assert.ok(
Object.values(view.decks)
.flat()
.every((value) => value === -1)
);
assert.ok(
view.players
.slice(1)
.flatMap((p) => p.hand)
.every((card) => card.m || card.v === -1)
);
}
for (const lesson of lessons) {
test(`${lesson.id}: legal play, checkpoints, private information and deterministic reload`, async () => {
const saved = new Map();
const options = {
...lesson,
storage: { getItem: (key) => saved.get(key) ?? null, setItem: (key, value) => saved.set(key, value) },
};
let controller = await createTutorial(options);
validateState(controller.snapshot.state.game);
for (const [index, entry] of paths[lesson.id].entries()) {
const before = controller.snapshot.state;
if (entry === null) {
await controller.continue();
} else {
await controller.play(typeof entry === "function" ? entry(before) : entry);
}
assert.equal(controller.snapshot.error, "");
assert.equal(controller.snapshot.step, index + 1);
validateState(controller.snapshot.state.game);
const after = structuredClone(controller.snapshot.state);
controller.destroy();
controller = await createTutorial(options);
assert.deepEqual(controller.snapshot.state, after);
assert.equal(controller.snapshot.step, index + 1);
await controller.previousStep();
assert.deepEqual(controller.snapshot.state, before);
if (entry === null) {
await controller.continue();
} else {
await controller.play(typeof entry === "function" ? entry(before) : entry);
}
assert.deepEqual(controller.snapshot.state, after);
}
assert.ok(controller.snapshot.completed);
const game = controller.snapshot.state.game;
if (lesson.id === "colony") {
assert.equal(game.players[0].spent, 21);
assert.equal(productionRange(lesson.initialState().game.players[0]).avg, 13);
for (const player of game.players.slice(0, 2)) {
assert.equal(player.population, 3);
assert.equal(player.factories.length, 4);
assert.equal(victoryPoints(player), 3);
assert.equal(productionRange(player).avg, 17);
assert.deepEqual(player.hand.map((card) => card.t).sort(), ["ore", "water", "water"]);
}
} else if (lesson.id === "sealed-bids") {
assert.equal(game.players[0].spent, 31);
assert.equal(handValue(game.players[0]), 9);
} else if (lesson.id === "staffing") {
assert.equal(victoryPoints(game.players[0]), 11);
assert.deepEqual(game.players[0].hand.map((card) => card.t).sort(), [
"titanium",
"titanium",
"titanium",
"water",
]);
} else if (lesson.id === "storage") {
assert.equal(game.players[0].hand.length, 12);
assert.equal(countingHandSize(game.players[0]), 10);
} else if (lesson.id === "new-chemicals") {
assert.equal(game.players[0].hand.filter((card) => card.t === "newChemicals").length, 1);
assert.equal(game.players[0].hand.filter((card) => card.t === "research").length, 1);
} else if (lesson.id === "mega-production") {
assert.equal(handValue(game.players[0]), 30);
assert.equal(countingHandSize(game.players[0]), 4);
} else if (lesson.id === "victory") {
assert.ok(game.ended);
assert.equal(victoryPoints(game.players[0]), 75);
}
controller.destroy();
});
}
test("wrong answers and unrelated moves leave the lesson unchanged", async () => {
const controller = await createTutorial(lessons[0]);
await controller.continue();
const before = structuredClone(controller.snapshot.state);
await controller.play(answer("1"));
assert.equal(controller.snapshot.error, "Not quite. Try another answer.");
assert.deepEqual(controller.snapshot.state, before);
await controller.play(answer("0"));
await controller.play(move({ action: "endTurn", buys: [], manned: [0, 1, 2] }));
assert.ok(controller.snapshot.error);
assert.deepEqual(controller.snapshot.state.game, before.game);
controller.destroy();
});
test("New Chemicals cannot be paid for without spending Research", () => {
const lesson = lessons.find((l) => l.id === "new-chemicals");
const state = lesson.initialState();
state.game.players[0].hand.push({ t: "moonOre", v: 60 });
const before = structuredClone(state);
assert.throws(
() =>
lesson.move(
state,
move({
action: "endTurn",
buys: [{ buy: "factory", factory: "newChemicals", cards: [6] }],
manned: [1, 2, 3, 4],
})
),
/research card/
);
assert.deepEqual(state, before);
});
test("sealed bids and blind Mega draws stay private until resolution", () => {
const game = lessons.find((l) => l.id === "sealed-bids").initialState().game;
assert.equal(stripSecret(game, 0).auction.bids[1], -1);
const mega = lessons.find((l) => l.id === "mega-production").initialState().game;
assert.ok(stripSecret(mega, 0).players[0].pendingMega.every((card) => card.v === -1));
});