Add guided Container tutorials and clearer auction controls
This commit is contained in:
parent
9601fac15e
commit
4eb331d601
19 changed files with 1650 additions and 43 deletions
16
pnpm-lock.yaml
generated
16
pnpm-lock.yaml
generated
|
|
@ -86,8 +86,8 @@ importers:
|
|||
viewer:
|
||||
dependencies:
|
||||
'@boardgamers/protocol':
|
||||
specifier: 0.2.2
|
||||
version: 0.2.2
|
||||
specifier: 0.3.1
|
||||
version: 0.3.1
|
||||
container-engine:
|
||||
specifier: workspace:../engine
|
||||
version: link:../engine
|
||||
|
|
@ -134,6 +134,9 @@ importers:
|
|||
'@types/node':
|
||||
specifier: ^13.13.52
|
||||
version: 13.13.52
|
||||
'@types/webpack-env':
|
||||
specifier: ^1.18.8
|
||||
version: 1.18.8
|
||||
'@typescript-eslint/parser':
|
||||
specifier: ^4.26.1
|
||||
version: 4.33.0(eslint@7.32.0(supports-color@6.1.0))(supports-color@6.1.0)(typescript@5.9.3)
|
||||
|
|
@ -179,6 +182,9 @@ importers:
|
|||
vue-template-compiler:
|
||||
specifier: ^2.6.11
|
||||
version: 2.7.16
|
||||
zod:
|
||||
specifier: ^4.6.2
|
||||
version: 4.6.2
|
||||
|
||||
packages:
|
||||
'@achrinza/node-ipc@9.2.2':
|
||||
|
|
@ -1036,10 +1042,10 @@ packages:
|
|||
}
|
||||
engines: { node: '>=6.9.0' }
|
||||
|
||||
'@boardgamers/protocol@0.2.2':
|
||||
'@boardgamers/protocol@0.3.1':
|
||||
resolution:
|
||||
{
|
||||
integrity: sha512-5o5nPZW6CN6PysF0i90OR+B30djiFhAGutCZe5RKJV6h3RgqE36HA7l0pOpvhdHz8uYtqE0nmaPlc+2ZtYiM/A==,
|
||||
integrity: sha512-FF8OUEvAZ+BKjZZ3Ab8Dw7oQh6TJOKMNkmRHqoabeE4clSp8lMRnHGGEakZdi7DplDJpstnya2fgBk2hX82UrA==,
|
||||
}
|
||||
|
||||
'@cspotcode/source-map-support@0.8.1':
|
||||
|
|
@ -11580,7 +11586,7 @@ snapshots:
|
|||
'@babel/helper-string-parser': 7.29.7
|
||||
'@babel/helper-validator-identifier': 7.29.7
|
||||
|
||||
'@boardgamers/protocol@0.2.2':
|
||||
'@boardgamers/protocol@0.3.1':
|
||||
dependencies:
|
||||
zod: 4.6.2
|
||||
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ allowBuilds:
|
|||
autoInstallPeers: false
|
||||
|
||||
minimumReleaseAgeExclude:
|
||||
- '@boardgamers/protocol@0.2.2'
|
||||
- '@boardgamers/protocol@0.2.2 || 0.3.0 || 0.3.1'
|
||||
|
||||
# The cli-plugin-typescript fork-ts-checker shim does a bare
|
||||
# require('@vue/compiler-sfc') expecting the vue-3 parse shape ({descriptor}).
|
||||
|
|
|
|||
|
|
@ -1,35 +1,41 @@
|
|||
# container-viewer
|
||||
# Container viewer
|
||||
|
||||
## Project setup
|
||||
From the repository root, install with `pnpm install`.
|
||||
|
||||
```
|
||||
yarn install
|
||||
## Local development
|
||||
|
||||
```sh
|
||||
pnpm --dir viewer serve
|
||||
```
|
||||
|
||||
### Compiles and hot-reloads for development
|
||||
Add `?chapter=supply-chain` to open a tutorial. The other chapter IDs are
|
||||
`buildings`, `selling`, `bidding`, `keep-cargo` and `scoring`.
|
||||
|
||||
```
|
||||
yarn serve
|
||||
## Build and check
|
||||
|
||||
```sh
|
||||
pnpm --dir viewer check
|
||||
pnpm --dir viewer test:tutorial
|
||||
NODE_OPTIONS=--openssl-legacy-provider pnpm --dir viewer package
|
||||
pnpm --dir viewer test:browser
|
||||
pnpm --dir viewer test:tutorial:browser
|
||||
```
|
||||
|
||||
### Compiles and minifies for production
|
||||
Browser checks use Playwright Chromium. Set `CHROMIUM_EXECUTABLE` if using an
|
||||
existing installation. `pnpm --dir viewer preview:tutorial` serves the built
|
||||
viewer on port 5197.
|
||||
|
||||
```
|
||||
yarn build
|
||||
```
|
||||
The Vue 2 type checker needs `zod` available directly in this workspace to resolve
|
||||
the protocol's schema types through pnpm's symlinks. It is a development dependency.
|
||||
|
||||
### Run your unit tests
|
||||
## Tutorials on BGS
|
||||
|
||||
```
|
||||
yarn test:unit
|
||||
```
|
||||
Upload the same JS and CSS as the ordinary viewer. The `container` global exposes
|
||||
both `launch` and `launchTutorial`. Chapter metadata is exported as `chapterCards`
|
||||
from `src/tutorial/lessons.ts`; enter these IDs, versions, titles and descriptions
|
||||
in the BGS version's Tutorial settings.
|
||||
|
||||
### Lints and fixes files
|
||||
|
||||
```
|
||||
yarn lint
|
||||
```
|
||||
|
||||
### Customize configuration
|
||||
|
||||
See [Configuration Reference](https://cli.vuejs.org/config/).
|
||||
Lessons run the real engine locally with deterministic opponents and private
|
||||
player views. The extra lesson controls make drag actions accessible on mobile.
|
||||
Chapter progress survives refresh. Playback controls return to the previous step,
|
||||
replay the current step or go back to the start. No live game or chat messages are sent.
|
||||
|
|
|
|||
|
|
@ -12,10 +12,14 @@
|
|||
"test:unit": "vue-cli-service test:unit",
|
||||
"package": "vue-cli-service build --target lib --name container-viewer src/wrapper.ts",
|
||||
"prepublishOnly": "npm run package",
|
||||
"test:browser": "node scripts/protocol-smoke.mjs"
|
||||
"test:browser": "node scripts/protocol-smoke.mjs",
|
||||
"test:tutorial": "node --test tests/tutorial/lessons.cjs",
|
||||
"check": "tsc --noEmit",
|
||||
"test:tutorial:browser": "node scripts/tutorial-smoke.mjs",
|
||||
"preview:tutorial": "node scripts/tutorial-preview.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@boardgamers/protocol": "0.2.2",
|
||||
"@boardgamers/protocol": "0.3.1",
|
||||
"container-engine": "workspace:../engine",
|
||||
"core-js": "^3.6.5",
|
||||
"lodash": "^4.17.19",
|
||||
|
|
@ -33,6 +37,7 @@
|
|||
"@types/lodash": "^4.14.154",
|
||||
"@types/mocha": "^5.2.4",
|
||||
"@types/node": "^13.13.52",
|
||||
"@types/webpack-env": "^1.18.8",
|
||||
"@typescript-eslint/parser": "^4.26.1",
|
||||
"@vue/cli-plugin-babel": "~4.4.0",
|
||||
"@vue/cli-plugin-typescript": "~4.4.0",
|
||||
|
|
@ -47,7 +52,8 @@
|
|||
"sass": "^1.26.5",
|
||||
"sass-loader": "^8.0.2",
|
||||
"typescript": "^5.9.3",
|
||||
"vue-template-compiler": "^2.6.11"
|
||||
"vue-template-compiler": "^2.6.11",
|
||||
"zod": "^4.6.2"
|
||||
},
|
||||
"files": [
|
||||
"src",
|
||||
|
|
|
|||
|
|
@ -137,6 +137,8 @@ try {
|
|||
host.emit('chat:appended', [incoming]);
|
||||
}, incoming);
|
||||
assert.match(await panel.locator('summary').textContent(), /1 unread/);
|
||||
// Visibility follows the chat panel's animation-frame measurement.
|
||||
await page.locator('.chat-shortcut').waitFor({ state: 'visible' });
|
||||
assert.equal(await page.locator('.chat-shortcut').isVisible(), true, 'unread messages show the shortcut');
|
||||
assert.equal(await list.locator('article').count(), 36, 'duplicate append is ignored');
|
||||
await page.evaluate((messages) => host.emit('chat:messages', messages), [...messages, incoming]);
|
||||
|
|
|
|||
37
viewer/scripts/tutorial-preview.mjs
Normal file
37
viewer/scripts/tutorial-preview.mjs
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import { readFile } from 'node:fs/promises';
|
||||
import { createServer } from 'node:http';
|
||||
import { createRequire } from 'node:module';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
const require = createRequire(import.meta.url);
|
||||
const viewer = new URL('../', import.meta.url);
|
||||
const files = {
|
||||
'/bundle.js': fileURLToPath(new URL('dist/container-viewer.umd.min.js', viewer)),
|
||||
'/bundle.css': fileURLToPath(new URL('dist/container-viewer.css', viewer)),
|
||||
'/vue.js': require.resolve('vue/dist/vue.min.js'),
|
||||
};
|
||||
const html =
|
||||
'<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Container tutorial</title><link rel="stylesheet" href="/bundle.css"><div id="app"></div><script src="/vue.js"></script><script src="/bundle.js"></script><script>container.launchTutorial("#app",{chapter:new URLSearchParams(location.search).get("chapter")||"supply-chain"});</script>';
|
||||
const server = createServer(async (req, res) => {
|
||||
const path = new URL(req.url, 'http://localhost').pathname;
|
||||
try {
|
||||
res.setHeader('Access-Control-Allow-Origin', '*');
|
||||
res.setHeader('Cache-Control', 'no-store');
|
||||
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.statusCode = 404;
|
||||
res.end('Not found');
|
||||
}
|
||||
} catch {
|
||||
res.statusCode = 500;
|
||||
res.end('Build the viewer with pnpm package first.');
|
||||
}
|
||||
});
|
||||
const port = Number(process.env.PORT || 5197);
|
||||
server.listen(port, '127.0.0.1', () =>
|
||||
console.log(`Container tutorial: http://127.0.0.1:${port}/?chapter=supply-chain`)
|
||||
);
|
||||
125
viewer/scripts/tutorial-smoke.mjs
Normal file
125
viewer/scripts/tutorial-smoke.mjs
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { createServer } from 'node:http';
|
||||
import { createRequire } from 'node:module';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { chromium } from 'playwright';
|
||||
const require = createRequire(import.meta.url);
|
||||
const viewer = new URL('../', import.meta.url);
|
||||
const files = {
|
||||
'/bundle.js': fileURLToPath(new URL('dist/container-viewer.umd.min.js', viewer)),
|
||||
'/bundle.css': fileURLToPath(new URL('dist/container-viewer.css', viewer)),
|
||||
'/vue.js': require.resolve('vue/dist/vue.min.js'),
|
||||
};
|
||||
const html =
|
||||
'<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><link rel="stylesheet" href="/bundle.css"><div id="app"></div><script src="/vue.js"></script><script src="/bundle.js"></script><script>container.launchTutorial("#app",{chapter:new URLSearchParams(location.search).get("chapter")||"supply-chain"});</script>';
|
||||
const server = createServer(async (req, res) => {
|
||||
const request = new URL(req.url, 'http://localhost');
|
||||
const path = request.pathname;
|
||||
if (request.searchParams.has('embedded')) {
|
||||
res.setHeader('content-type', 'text/html');
|
||||
res.end(
|
||||
'<!doctype html><meta name=viewport content=width=device-width,initial-scale=1><iframe style=width:100%;height:900px sandbox="allow-scripts allow-same-origin" src="/?chapter=bidding"></iframe>'
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (files[path]) {
|
||||
res.setHeader('content-type', path.endsWith('.css') ? 'text/css' : 'text/javascript');
|
||||
res.end(await readFile(files[path]));
|
||||
} else {
|
||||
res.setHeader('content-type', 'text/html');
|
||||
res.end(html);
|
||||
}
|
||||
});
|
||||
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
const origin = `http://127.0.0.1:${server.address().port}`;
|
||||
const browser = await chromium.launch({ executablePath: process.env.CHROMIUM_EXECUTABLE });
|
||||
try {
|
||||
for (const width of [1400, 390]) {
|
||||
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));
|
||||
for (const chapter of ['supply-chain', 'buildings', 'selling', 'bidding', 'keep-cargo', 'scoring']) {
|
||||
await page.goto(`${origin}/?chapter=${chapter}`);
|
||||
const guide = page.locator('.bgs-tutorial-guide');
|
||||
await guide.waitFor();
|
||||
for (let step = 0; step < 24; step++) {
|
||||
const heading = await guide.locator('.bgs-tutorial-heading strong').innerText();
|
||||
if (heading === 'Chapter complete') break;
|
||||
const next = guide.getByRole('button', { name: 'Continue', exact: true });
|
||||
if (await next.isEnabled()) await next.click();
|
||||
else if (await page.locator('.tutorial-bid').count()) {
|
||||
await page.locator('.tutorial-bid input').fill(heading.includes('add $2') ? '2' : '8');
|
||||
await page.locator('.tutorial-bid button').click();
|
||||
} else if (heading.includes('What does keeping') || heading.includes('What does selling')) {
|
||||
await page
|
||||
.locator('.tutorial-actions')
|
||||
.getByRole('button', { name: heading.includes('keeping') ? '$24' : '$12', exact: true })
|
||||
.click();
|
||||
} else if (heading.includes('Check all five')) {
|
||||
await page.locator('.tutorial-actions').getByRole('button', { name: '$5', exact: true }).click();
|
||||
await guide.getByRole('alert').waitFor();
|
||||
assert.equal(await guide.locator('.bgs-tutorial-heading strong').innerText(), heading);
|
||||
await page.locator('.tutorial-actions').getByRole('button', { name: '$10', exact: true }).click();
|
||||
} else if (heading.includes('entire colour'))
|
||||
await page
|
||||
.locator('.tutorial-actions')
|
||||
.getByRole('button', { name: 'dark green', exact: true })
|
||||
.click();
|
||||
else await page.locator('.tutorial-actions button').first().click();
|
||||
await page.waitForFunction(
|
||||
(previous) => document.querySelector('.bgs-tutorial-heading strong')?.textContent !== previous,
|
||||
heading
|
||||
);
|
||||
if (chapter === 'bidding' && heading.includes('Submit a sealed')) {
|
||||
assert.match(await page.locator('.tutorial-auction').innerText(), /Leo: Sealed/);
|
||||
await page.reload();
|
||||
await guide.waitFor();
|
||||
assert.match(
|
||||
await guide.locator('.bgs-tutorial-heading strong').innerText(),
|
||||
/Wait for the other bidder/
|
||||
);
|
||||
}
|
||||
}
|
||||
assert.equal(await guide.locator('.bgs-tutorial-heading strong').innerText(), 'Chapter complete');
|
||||
assert.equal(await guide.getByRole('button', { name: 'Continue', exact: true }).isEnabled(), false);
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth + 1), false);
|
||||
assert.equal(await page.locator('.container-chat').count(), 0);
|
||||
if (chapter === 'scoring') assert.match(await page.locator('.tutorial-result').innerText(), /\$54/);
|
||||
await page.screenshot({ path: `/tmp/container-tutorial-${chapter}-${width}.png`, fullPage: true });
|
||||
await page.reload();
|
||||
await guide.waitFor();
|
||||
assert.equal(await guide.locator('.bgs-tutorial-heading strong').innerText(), 'Chapter complete');
|
||||
console.log(JSON.stringify({ chapter, width, complete: true }));
|
||||
}
|
||||
await page.goto(`${origin}/?embedded=1`);
|
||||
const embedded = page.frameLocator('iframe');
|
||||
const embeddedGuide = embedded.locator('.bgs-tutorial-guide');
|
||||
await embeddedGuide.getByRole('button', { name: 'Back to start', exact: true }).click();
|
||||
await embeddedGuide.getByRole('button', { name: 'Continue', exact: true }).click();
|
||||
await embedded.locator('.tutorial-bid input').fill('8');
|
||||
await embedded.locator('.tutorial-bid button').click();
|
||||
await embedded
|
||||
.locator('.tutorial-actions')
|
||||
.getByRole('button', { name: 'Reveal the bids', exact: true })
|
||||
.click();
|
||||
await embedded.locator('.tutorial-bid input').fill('2');
|
||||
await embedded.locator('.tutorial-bid button').click();
|
||||
await embeddedGuide.getByText('5/7 · Reveal the additional bids', { exact: true }).waitFor();
|
||||
console.log(`Sandboxed auction ${width}px: additional bid submitted`);
|
||||
await page.goto(`${origin}/?chapter=selling`);
|
||||
await page.evaluate(() => {
|
||||
window.container.launch('#app');
|
||||
});
|
||||
assert.equal(await page.locator('.bgs-tutorial-guide').count(), 0);
|
||||
assert.equal(await page.locator('.game').count(), 1);
|
||||
await page.evaluate(() => window.container.launchTutorial('#app', { chapter: 'selling' }));
|
||||
assert.equal(await page.locator('.game').count(), 1);
|
||||
assert.deepEqual(errors, []);
|
||||
await context.close();
|
||||
}
|
||||
} finally {
|
||||
await browser.close();
|
||||
await new Promise((resolve) => server.close(resolve));
|
||||
}
|
||||
|
|
@ -176,6 +176,11 @@
|
|||
:transform="`translate(140, ${450 + 40 * i})`"
|
||||
:width="130"
|
||||
:text="'Accept ' + getName(bidder)"
|
||||
:tooltip="`Accept ${getName(bidder)}: receive $${
|
||||
2 * (G.players[bidder].bid + G.players[bidder].additionalBid)
|
||||
} ($${
|
||||
G.players[bidder].bid + G.players[bidder].additionalBid
|
||||
} bid + matching bank subsidy)`"
|
||||
@click="accept(bidder)"
|
||||
/>
|
||||
</template>
|
||||
|
|
@ -193,7 +198,8 @@
|
|||
<Button
|
||||
:transform="`translate(140, ${450 + 40 * G.highestBidders.length})`"
|
||||
:width="130"
|
||||
:text="'Decline'"
|
||||
:text="`Keep for $${highestOffer}`"
|
||||
:tooltip="`Decline all bids: pay $${highestOffer} to the bank and keep the cargo. No subsidy.`"
|
||||
:enabled="canDecline()"
|
||||
@click="decline()"
|
||||
/>
|
||||
|
|
@ -617,6 +623,12 @@ export default class Game extends Vue {
|
|||
@Prop()
|
||||
emitter!: EventEmitter;
|
||||
|
||||
@Prop()
|
||||
tutorialMove?: (move: Move) => void;
|
||||
|
||||
@Prop({ default: false })
|
||||
interactionDisabled!: boolean;
|
||||
|
||||
@Prop()
|
||||
@ProvideReactive()
|
||||
preferences!: Preferences;
|
||||
|
|
@ -1128,6 +1140,10 @@ export default class Game extends Vue {
|
|||
}
|
||||
|
||||
sendMove(move) {
|
||||
if (this.tutorialMove) {
|
||||
if (!this.interactionDisabled) this.tutorialMove(move);
|
||||
return;
|
||||
}
|
||||
// Send the WHOLE turn so far: the platform is stateless between calls and
|
||||
// replays the buffer from the last committed (saved) state.
|
||||
this.turnMoves.push(move);
|
||||
|
|
@ -1150,6 +1166,7 @@ export default class Game extends Vue {
|
|||
|
||||
get canMove() {
|
||||
return (
|
||||
!this.interactionDisabled &&
|
||||
this.player != null &&
|
||||
this.G &&
|
||||
this.G.currentPlayers.includes(this.player!) &&
|
||||
|
|
@ -1260,12 +1277,18 @@ export default class Game extends Vue {
|
|||
}
|
||||
|
||||
canUndo() {
|
||||
if (this.tutorialMove) return false;
|
||||
if (!this.canMove) return false;
|
||||
|
||||
// Undo scope = the current tentative turn: anything still in the buffer
|
||||
return this.turnMoves.length > 0;
|
||||
}
|
||||
|
||||
get highestOffer() {
|
||||
const bidder = this.G?.players[this.G.highestBidders[0]];
|
||||
return bidder ? bidder.bid + bidder.additionalBid : 0;
|
||||
}
|
||||
|
||||
canDecline() {
|
||||
if (!this.canMove) return false;
|
||||
|
||||
|
|
@ -1294,7 +1317,7 @@ export default class Game extends Vue {
|
|||
}
|
||||
|
||||
getStatusMessage() {
|
||||
if (!this.G || this.G.currentPlayers == []) {
|
||||
if (!this.G || ended(this.G)) {
|
||||
return 'Game ended!';
|
||||
} else if (this.player !== undefined && this.G?.currentPlayers.includes(this.player)) {
|
||||
if (this.G.players[this.player].availableMoves![MoveName.Bid]) {
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
<g :class="['button', { enabled }]" @click="enabled && $emit('click')">
|
||||
<rect :width="width" height="30" fill="gainsboro" stroke="black" rx="2" />
|
||||
<text text-anchor="middle" fill="black" :x="width / 2" y="16">{{ getText() }}</text>
|
||||
<title>{{ text }}</title>
|
||||
<title>{{ tooltip || text }}</title>
|
||||
</g>
|
||||
</template>
|
||||
<script lang="ts">
|
||||
|
|
@ -13,6 +13,9 @@ export default class Button extends Vue {
|
|||
@Prop()
|
||||
text?: string;
|
||||
|
||||
@Prop()
|
||||
tooltip?: string;
|
||||
|
||||
@Prop()
|
||||
width?: number;
|
||||
|
||||
|
|
|
|||
|
|
@ -146,6 +146,6 @@ export function installLocalChat(emitter: ChatEmitter): void {
|
|||
createdAt: new Date().toISOString(),
|
||||
},
|
||||
]);
|
||||
emitter.emit('chat:result', { requestId, ok: true });
|
||||
if (requestId) emitter.emit('chat:result', { requestId, ok: true });
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,10 +9,16 @@ import type { Preferences } from './types/ui-data';
|
|||
|
||||
let dispose: (() => void) | undefined;
|
||||
|
||||
export function destroyViewer() {
|
||||
const cleanup = dispose;
|
||||
dispose = undefined;
|
||||
cleanup?.();
|
||||
}
|
||||
|
||||
function launch(selector: string) {
|
||||
const target = document.querySelector(selector);
|
||||
if (!target) throw new Error(`Viewer mount point not found: ${selector}`);
|
||||
dispose?.();
|
||||
destroyViewer();
|
||||
const mountPoint = document.createElement('div');
|
||||
target.append(mountPoint);
|
||||
let params: {
|
||||
|
|
|
|||
|
|
@ -1,3 +1,6 @@
|
|||
import launchSelfContained from './self-contained';
|
||||
import { launchTutorial } from './wrapper';
|
||||
|
||||
launchSelfContained();
|
||||
const chapter = new URLSearchParams(location.search).get('chapter');
|
||||
if (chapter) void launchTutorial('#app', { chapter });
|
||||
else launchSelfContained();
|
||||
|
|
|
|||
|
|
@ -116,7 +116,7 @@ export function installActionSounds(emitter: Pick<ViewerEmitter<any, any>, 'on'>
|
|||
let previous: string[] | undefined;
|
||||
let replaying = false;
|
||||
emitter.on('update:preference', (pref) => {
|
||||
if (pref?.name === 'sound') {
|
||||
if (pref?.name === 'sound' && typeof pref.value === 'boolean') {
|
||||
setSoundEnabled(pref.value);
|
||||
}
|
||||
});
|
||||
|
|
|
|||
610
viewer/src/tutorial/lessons.ts
Normal file
610
viewer/src/tutorial/lessons.ts
Normal file
|
|
@ -0,0 +1,610 @@
|
|||
import type { TutorialOptions, TutorialStep } from '@boardgamers/protocol/tutorial';
|
||||
import type { GameState, Move } from 'container-engine';
|
||||
import { availableMoves, ended, move as engineMove, setup } from 'container-engine';
|
||||
import pointCards from 'container-engine/src/cards';
|
||||
import { ContainerColor as Color, ContainerPiece, Phase, ShipPosition } from 'container-engine/src/gamestate';
|
||||
import { MoveName } from 'container-engine/src/move';
|
||||
|
||||
export type TutorialAction = { kind: 'move'; move: Move } | { kind: 'watch' } | { kind: 'answer'; answer: string };
|
||||
export interface LessonState {
|
||||
game: GameState;
|
||||
answer?: string;
|
||||
}
|
||||
export interface Choice {
|
||||
label: string;
|
||||
action: TutorialAction;
|
||||
color?: string;
|
||||
}
|
||||
export interface Lesson extends Omit<TutorialOptions<LessonState, TutorialAction>, 'move'> {
|
||||
title: string;
|
||||
description: string;
|
||||
move(state: LessonState, action: TutorialAction, frame?: (game: GameState) => void): LessonState;
|
||||
choices(state: LessonState, step: string): Choice[];
|
||||
}
|
||||
const copy = <T>(value: T): T => JSON.parse(JSON.stringify(value));
|
||||
export const colors = [Color.White, Color.Orange, Color.Tan, Color.Brown, Color.Black];
|
||||
export const colorName = (color: Color) => (color === Color.Black ? 'dark green' : color);
|
||||
const play = (move: Move): TutorialAction => ({ kind: 'move', move });
|
||||
const watch: TutorialAction = { kind: 'watch' };
|
||||
const pass: Move = { name: MoveName.Pass, data: true };
|
||||
const sail = (data: ShipPosition): Move => ({ name: MoveName.Sail, data });
|
||||
const bid = (price: number): Move => ({ name: MoveName.Bid, data: true, extraData: { price } });
|
||||
function take(game: GameState, color: Color): ContainerPiece {
|
||||
const index = game.containersLeft.findIndex((piece) => piece.color === color);
|
||||
if (index < 0) throw Error(`No ${color} container left in the lesson setup.`);
|
||||
return game.containersLeft.splice(index, 1)[0];
|
||||
}
|
||||
function activate(game: GameState, seat: number) {
|
||||
game.currentPlayers = [seat];
|
||||
for (const player of game.players) {
|
||||
player.actions = player.id === seat ? 2 : 0;
|
||||
player.availableMoves = player.id === seat ? availableMoves(game, player) : null;
|
||||
}
|
||||
}
|
||||
function base(): GameState {
|
||||
const game = setup(3, { beginner: false }, 'container-tutorial-1');
|
||||
game.startingPlayer = 0;
|
||||
game.players.forEach((player, index) => {
|
||||
player.name = ['You', 'Ada', 'Leo'][index];
|
||||
player.pointCard = copy(pointCards[index]);
|
||||
game.factoriesLeft.push(...player.factories);
|
||||
game.containersLeft.push(...player.containersOnFactoryStore.map((entry) => entry.piece));
|
||||
player.containersOnFactoryStore = [];
|
||||
player.factories = [];
|
||||
});
|
||||
[Color.Orange, Color.White, Color.Black].forEach((color, index) => {
|
||||
const factory = game.factoriesLeft.findIndex((piece) => piece.color === color);
|
||||
game.players[index].factories.push(game.factoriesLeft.splice(factory, 1)[0]);
|
||||
});
|
||||
activate(game, 0);
|
||||
return game;
|
||||
}
|
||||
function sourceState(): LessonState {
|
||||
const game = base();
|
||||
game.players[1].containersOnFactoryStore.push({ piece: take(game, Color.White), price: 2, moved: false });
|
||||
activate(game, 0);
|
||||
return { game };
|
||||
}
|
||||
function buildingState(): LessonState {
|
||||
const state = sourceState();
|
||||
state.game.players[0].containersOnWarehouseStore.push({
|
||||
piece: take(state.game, Color.Brown),
|
||||
price: 4,
|
||||
moved: false,
|
||||
});
|
||||
activate(state.game, 0);
|
||||
return state;
|
||||
}
|
||||
function shippingState(keep = false): LessonState {
|
||||
const game = base();
|
||||
game.players[0].ship.containers = [take(game, Color.White), take(game, Color.White), take(game, Color.Orange)];
|
||||
game.players[0].ship.shipPosition = keep ? ShipPosition.OpenSea : ShipPosition.PlayerHarbor11;
|
||||
if (keep)
|
||||
game.players[0].containersOnIsland = [
|
||||
take(game, Color.Black),
|
||||
take(game, Color.Black),
|
||||
take(game, Color.Black),
|
||||
take(game, Color.Tan),
|
||||
take(game, Color.Brown),
|
||||
];
|
||||
activate(game, 0);
|
||||
return { game };
|
||||
}
|
||||
function biddingState(): LessonState {
|
||||
const game = base();
|
||||
game.players[1].ship.containers = [take(game, Color.White), take(game, Color.White), take(game, Color.Tan)];
|
||||
activate(game, 1);
|
||||
return { game: engineMove(game, sail(ShipPosition.Island), 1) };
|
||||
}
|
||||
function scoringState(): LessonState {
|
||||
const game = base();
|
||||
const you = game.players[0];
|
||||
you.containersOnIsland = [
|
||||
Color.Black,
|
||||
Color.Black,
|
||||
Color.Black,
|
||||
Color.White,
|
||||
Color.White,
|
||||
Color.Orange,
|
||||
Color.Tan,
|
||||
Color.Brown,
|
||||
].map((color) => take(game, color));
|
||||
you.containersOnWarehouseStore.push({ piece: take(game, Color.Brown), price: 4, moved: false });
|
||||
you.ship.containers.push(take(game, Color.White));
|
||||
you.loans.push(game.loansLeft.pop()!);
|
||||
// A prepared last turn: every orange/tan piece is in play, never deleted from the supply.
|
||||
for (const [seat, color] of [
|
||||
[1, Color.Orange],
|
||||
[2, Color.Tan],
|
||||
] as const) {
|
||||
while (game.containersLeft.some((piece) => piece.color === color))
|
||||
game.players[seat].containersOnIsland.push(take(game, color));
|
||||
}
|
||||
activate(game, 0);
|
||||
return { game };
|
||||
}
|
||||
|
||||
function run(id: string): Lesson['move'] {
|
||||
return (state, action, frame) => {
|
||||
let game = state.game;
|
||||
const apply = (move: Move, seat: number) => {
|
||||
game = engineMove(game, move, seat);
|
||||
frame?.(copy(game));
|
||||
};
|
||||
if (action.kind === 'answer') return { ...state, answer: action.answer };
|
||||
if (action.kind === 'move') {
|
||||
apply(action.move, 0);
|
||||
if (id === 'buildings' && action.move.name === MoveName.Pass) {
|
||||
apply(pass, 1);
|
||||
apply(pass, 2);
|
||||
}
|
||||
} else if (id === 'supply-chain') {
|
||||
apply(sail(ShipPosition.PlayerHarbor01), 1);
|
||||
const piece = game.players[0].containersOnWarehouseStore[0].piece;
|
||||
apply({ name: MoveName.BuyFromWarehouse, data: { player: 0, piece } }, 1);
|
||||
apply(pass, 1);
|
||||
apply(pass, 2);
|
||||
} else if (id === 'bidding') {
|
||||
if (game.phase === Phase.AcceptDecline) apply({ name: MoveName.Accept, data: 0 }, 1);
|
||||
else apply(bid(game.highestBidders.length ? 2 : 8), 2);
|
||||
} else {
|
||||
apply(bid(id === 'keep-cargo' ? 6 : 8), 1);
|
||||
apply(bid(id === 'keep-cargo' ? 4 : 6), 2);
|
||||
}
|
||||
return { ...state, game };
|
||||
};
|
||||
}
|
||||
function actionStep(
|
||||
id: string,
|
||||
title: string,
|
||||
text: string,
|
||||
allowed: (action: TutorialAction) => boolean,
|
||||
complete: (state: LessonState) => boolean,
|
||||
hint?: string
|
||||
): TutorialStep<LessonState, TutorialAction> {
|
||||
return {
|
||||
id,
|
||||
title,
|
||||
text,
|
||||
hint,
|
||||
target: 'lesson-actions',
|
||||
complete,
|
||||
validateMove: (_state, action) =>
|
||||
allowed(action) ? undefined : 'Follow the action described in this step, or use Replay step.',
|
||||
};
|
||||
}
|
||||
const isMove = (name: MoveName) => (action: TutorialAction) => action.kind === 'move' && action.move.name === name;
|
||||
const isWatch = (action: TutorialAction) => action.kind === 'watch';
|
||||
const choice = (label: string, move: Move): Choice => ({ label, action: play(move) });
|
||||
const watchChoice = (label: string): Choice[] => [{ label, action: watch }];
|
||||
const shell = (id: string) => ({ game: 'container', id, version: id === 'keep-cargo' ? 2 : 1, move: run(id) });
|
||||
|
||||
const supply: Lesson = {
|
||||
...shell('supply-chain'),
|
||||
title: 'From factory to ship',
|
||||
description: 'Produce, set prices, trade with another player and load a ship.',
|
||||
initialState: sourceState,
|
||||
steps: [
|
||||
{
|
||||
id: 'intro',
|
||||
title: 'Make money by trading',
|
||||
text: 'Factories produce containers. Other players buy them for their warehouses, then sell them to visiting ships. In this chapter, make a container and earn money from a trade. You cannot buy from your own stores.',
|
||||
target: 'business',
|
||||
},
|
||||
actionStep(
|
||||
'produce',
|
||||
'Produce and set a price',
|
||||
'Your orange factory can produce one orange container. Produce it and offer it for $2. Production costs $1, paid to the player before you, and uses your first action.',
|
||||
(action) =>
|
||||
action.kind === 'move' &&
|
||||
action.move.name === MoveName.Produce &&
|
||||
action.move.data === Color.Orange &&
|
||||
action.move.extraData.price === 2,
|
||||
(state) => state.game.players[0].produced.includes(Color.Orange)
|
||||
),
|
||||
actionStep(
|
||||
'buy',
|
||||
'Buy for your warehouse',
|
||||
'Use your second action to buy Ada’s white container for $2. Offer it from your warehouse for $4. The house-shaped row holds warehouse buildings. The squares below it hold containers for sale: their numbers are prices, not extra storage spaces. Your one warehouse holds one container.',
|
||||
(action) =>
|
||||
action.kind === 'move' &&
|
||||
action.move.name === MoveName.BuyFromFactory &&
|
||||
action.move.data.player === 1 &&
|
||||
action.move.extraData.price === 4,
|
||||
(state) => state.game.players[0].containersOnWarehouseStore.length === 1
|
||||
),
|
||||
actionStep(
|
||||
'finish',
|
||||
'Finish your turn',
|
||||
'Both actions are spent. In the normal game, Done confirms your purchases and prices. Until then, Undo can revise your turn. In a lesson, use the replay control to start this step again.',
|
||||
isMove(MoveName.Pass),
|
||||
(state) => state.game.currentPlayers[0] === 1
|
||||
),
|
||||
actionStep(
|
||||
'trade',
|
||||
'Watch Ada load her ship',
|
||||
'Ada sails into your harbour and buys the white container for $4. Loading immediately after sailing into a harbour costs no extra action. A ship holds up to five containers. Watch the white container move from your warehouse onto her ship.',
|
||||
isWatch,
|
||||
(state) => state.game.players[1].ship.containers.length === 1
|
||||
),
|
||||
],
|
||||
completion: {
|
||||
title: 'Your first trade is complete',
|
||||
text: 'You paid $2 and sold for $4: a $2 trading margin. After the $1 production cost, you have $21. Your orange container is still for sale. Ships must pass through open sea between harbours; reaching the island auctions the entire cargo.',
|
||||
},
|
||||
choices({ game }, step) {
|
||||
if (step === 'produce')
|
||||
return [
|
||||
choice('Produce orange · price $2', {
|
||||
name: MoveName.Produce,
|
||||
data: Color.Orange,
|
||||
extraData: { piece: game.containersLeft.find((piece) => piece.color === Color.Orange)!, price: 2 },
|
||||
}),
|
||||
];
|
||||
if (step === 'buy')
|
||||
return [
|
||||
choice('Buy white for $2 · sell at $4', {
|
||||
name: MoveName.BuyFromFactory,
|
||||
data: { player: 1, piece: game.players[1].containersOnFactoryStore[0].piece },
|
||||
extraData: { price: 4 },
|
||||
}),
|
||||
];
|
||||
if (step === 'finish') return [choice('Done', pass)];
|
||||
return step === 'trade' ? watchChoice('Watch Ada trade') : [];
|
||||
},
|
||||
};
|
||||
const buildings: Lesson = {
|
||||
...shell('buildings'),
|
||||
title: 'Factories and warehouses',
|
||||
description: 'Distinguish buildings from sale spaces, then expand production and storage.',
|
||||
initialState: buildingState,
|
||||
steps: [
|
||||
{
|
||||
id: 'intro',
|
||||
title: 'Buildings are not sale spaces',
|
||||
text: 'The circles hold factories; the house shapes hold warehouses. Numbers in empty building slots are purchase costs. The squares BELOW each building row hold containers for sale. Their numbers are your selling prices. They do not tell you how many containers you can store.',
|
||||
target: 'business',
|
||||
},
|
||||
actionStep(
|
||||
'warehouse',
|
||||
'Buy room for another container',
|
||||
'Your warehouse is full with one brown container. Each warehouse holds one container. Buy a second warehouse for $4 to increase capacity to two. Buying a building uses one action.',
|
||||
isMove(MoveName.BuyWarehouse),
|
||||
(state) => state.game.players[0].warehouses.length === 2
|
||||
),
|
||||
actionStep(
|
||||
'stock',
|
||||
'Use the new storage space',
|
||||
'Buy Ada’s white container for $2 and offer it for $3. You can now keep both the brown and white containers for visiting ships to buy. Buying a warehouse does not produce or include any containers.',
|
||||
(action) =>
|
||||
action.kind === 'move' &&
|
||||
action.move.name === MoveName.BuyFromFactory &&
|
||||
action.move.data.player === 1 &&
|
||||
action.move.extraData.price === 3,
|
||||
(state) => state.game.players[0].containersOnWarehouseStore.length === 2
|
||||
),
|
||||
actionStep(
|
||||
'finish',
|
||||
'Confirm these two actions',
|
||||
'You bought a warehouse, then stock for it. Choose Done. Ada and Leo will pass so you can try expanding your factory next.',
|
||||
isMove(MoveName.Pass),
|
||||
(state) => state.game.currentPlayers[0] === 0 && state.game.players[0].actions === 2
|
||||
),
|
||||
actionStep(
|
||||
'factory',
|
||||
'Buy a second factory for $6',
|
||||
'Your orange factory makes orange containers. Buy a white factory to produce a second colour. You may own only one factory of each colour. Each factory also adds two spaces to your factory sales stock.',
|
||||
(action) =>
|
||||
action.kind === 'move' && action.move.name === MoveName.BuyFactory && action.move.data === Color.White,
|
||||
(state) => state.game.players[0].factories.length === 2
|
||||
),
|
||||
actionStep(
|
||||
'orange',
|
||||
'Produce with both factories',
|
||||
'One production action can make one container per factory. Pay $1 for the entire action, even when using several factories. Start with orange and offer it for $2.',
|
||||
(action) =>
|
||||
action.kind === 'move' &&
|
||||
action.move.name === MoveName.Produce &&
|
||||
action.move.data === Color.Orange &&
|
||||
action.move.extraData.price === 2,
|
||||
(state) => state.game.players[0].produced.includes(Color.Orange)
|
||||
),
|
||||
actionStep(
|
||||
'white',
|
||||
'Add white in the same action',
|
||||
'Now produce white and offer it for $3. This is still the same production action, with no extra $1 payment. More factories produce more stock; more warehouses let you buy and resell more stock from other players.',
|
||||
(action) =>
|
||||
action.kind === 'move' &&
|
||||
action.move.name === MoveName.Produce &&
|
||||
action.move.data === Color.White &&
|
||||
action.move.extraData.price === 3,
|
||||
(state) => state.game.players[0].produced.includes(Color.White)
|
||||
),
|
||||
],
|
||||
completion: {
|
||||
title: 'You expanded both businesses',
|
||||
text: 'You have two factories and two warehouses, with $7 left. Your factories can make two colours and store four containers in total. Your warehouses hold two containers bought from other players. Building prices and container sale prices are separate.',
|
||||
},
|
||||
choices({ game }, step) {
|
||||
if (step === 'warehouse')
|
||||
return [
|
||||
choice('Buy warehouse · pay $4', {
|
||||
name: MoveName.BuyWarehouse,
|
||||
data: true,
|
||||
extraData: game.warehousesLeft[0],
|
||||
}),
|
||||
];
|
||||
if (step === 'stock')
|
||||
return [
|
||||
choice('Buy white for $2 · sell at $3', {
|
||||
name: MoveName.BuyFromFactory,
|
||||
data: { player: 1, piece: game.players[1].containersOnFactoryStore[0].piece },
|
||||
extraData: { price: 3 },
|
||||
}),
|
||||
];
|
||||
if (step === 'finish') return [choice('Done', pass)];
|
||||
if (step === 'factory')
|
||||
return [
|
||||
choice('Buy white factory · pay $6', {
|
||||
name: MoveName.BuyFactory,
|
||||
data: Color.White,
|
||||
extraData: game.factoriesLeft.find((piece) => piece.color === Color.White)!,
|
||||
}),
|
||||
];
|
||||
if (step === 'orange' || step === 'white') {
|
||||
const color = step === 'orange' ? Color.Orange : Color.White;
|
||||
const price = step === 'orange' ? 2 : 3;
|
||||
return [
|
||||
choice(`Produce ${step} · price $${price}`, {
|
||||
name: MoveName.Produce,
|
||||
data: color,
|
||||
extraData: { piece: game.containersLeft.find((piece) => piece.color === color)!, price },
|
||||
}),
|
||||
];
|
||||
}
|
||||
return [];
|
||||
},
|
||||
};
|
||||
const selling: Lesson = {
|
||||
...shell('selling'),
|
||||
title: 'Sail and sell your cargo',
|
||||
description: 'Start an auction, reveal the sealed bids and collect the bank subsidy.',
|
||||
initialState: () => shippingState(),
|
||||
steps: [
|
||||
{
|
||||
id: 'intro',
|
||||
title: 'One auction for the whole ship',
|
||||
text: 'Your ship is already loaded at Ada’s harbour. Two white containers and one orange container will be sold together. You are the seller: everyone else bids, then you decide whether to sell or buy the cargo yourself.',
|
||||
target: 'cargo',
|
||||
},
|
||||
actionStep(
|
||||
'sea',
|
||||
'Harbour → open sea',
|
||||
'Sail into open sea. Moving directly from one harbour to another is not allowed. This uses one of your two actions.',
|
||||
isMove(MoveName.Sail),
|
||||
(state) => state.game.players[0].ship.shipPosition === ShipPosition.OpenSea
|
||||
),
|
||||
actionStep(
|
||||
'island',
|
||||
'Open sea → island',
|
||||
'Sail to the island to start the auction. An island auction ends your turn even if it was your first action. The seller does not submit a bid.',
|
||||
(action) =>
|
||||
action.kind === 'move' &&
|
||||
action.move.name === MoveName.Sail &&
|
||||
action.move.data === ShipPosition.Island,
|
||||
(state) => state.game.phase === Phase.Bid
|
||||
),
|
||||
actionStep(
|
||||
'bids',
|
||||
'Secret bids, then a reveal',
|
||||
'Ada and Leo each choose one secret bid for all three containers. They cannot see the other bid before both are submitted. A bid of $0 is allowed. Watch their bids reveal together.',
|
||||
isWatch,
|
||||
(state) => state.game.phase === Phase.AcceptDecline
|
||||
),
|
||||
actionStep(
|
||||
'accept',
|
||||
'Accept $8 and receive $16',
|
||||
'Ada offered $8; Leo offered $6. Accept Ada’s highest bid. She pays you $8 and gets all three containers on her island. The bank adds another $8: you receive $16 in total.',
|
||||
(action) => action.kind === 'move' && action.move.name === MoveName.Accept && action.move.data === 1,
|
||||
(state) => state.game.players[1].containersOnIsland.length === 3
|
||||
),
|
||||
],
|
||||
completion: {
|
||||
title: 'The subsidy rewards shipping',
|
||||
text: 'You now have $36. Ada paid $8, Leo paid nothing, and your empty ship stays at the island. The next player’s turn begins. The bank subsidy goes only to the seller when another player buys the cargo.',
|
||||
},
|
||||
choices(_state, step) {
|
||||
if (step === 'sea') return [choice('Sail to open sea', sail(ShipPosition.OpenSea))];
|
||||
if (step === 'island') return [choice('Sail to the island', sail(ShipPosition.Island))];
|
||||
if (step === 'bids') return watchChoice('Watch the sealed bids');
|
||||
return step === 'accept' ? [choice('Accept Ada · receive $16', { name: MoveName.Accept, data: 1 })] : [];
|
||||
},
|
||||
};
|
||||
const bidding: Lesson = {
|
||||
...shell('bidding'),
|
||||
title: 'Bid, raise and break a tie',
|
||||
description: 'Make a sealed offer, add a tie-break bid and see who pays.',
|
||||
initialState: biddingState,
|
||||
steps: [
|
||||
{
|
||||
id: 'intro',
|
||||
title: 'Now you are the buyer',
|
||||
text: 'Ada has brought two white containers and one tan container to the island. On your secret card they are worth $26 before the most-numerous-colour discard. Bid for the whole shipment, and remember the seller may keep it. Your cash and value card are private.',
|
||||
target: 'value-card',
|
||||
},
|
||||
actionStep(
|
||||
'bid',
|
||||
'Submit a sealed bid of $8',
|
||||
'Enter 8 and choose Bid. Your offer is hidden from Leo until he has also bid. You only pay if Ada ultimately sells the cargo to you. You cannot bid more cash than you hold.',
|
||||
(action) =>
|
||||
action.kind === 'move' && action.move.name === MoveName.Bid && action.move.extraData.price === 8,
|
||||
(state) => state.game.players[0].bid === 8
|
||||
),
|
||||
actionStep(
|
||||
'reveal',
|
||||
'Wait for the other bidder',
|
||||
'Your $8 is submitted. Watch Leo submit his sealed bid; both first-round offers are then revealed.',
|
||||
isWatch,
|
||||
(state) => state.game.highestBidders.length === 2
|
||||
),
|
||||
actionStep(
|
||||
'raise',
|
||||
'A tie: add $2',
|
||||
'You and Leo both offered $8. Only the tied highest bidders bid again. Enter 2 as your additional bid: your new total will be $10, not $2. You may add $0, but cannot lower your first bid.',
|
||||
(action) =>
|
||||
action.kind === 'move' && action.move.name === MoveName.Bid && action.move.extraData.price === 2,
|
||||
(state) => state.game.players[0].additionalBid === 2
|
||||
),
|
||||
actionStep(
|
||||
'second-reveal',
|
||||
'Reveal the additional bids',
|
||||
'Your extra $2 is secret until Leo submits his addition. Watch the second reveal.',
|
||||
isWatch,
|
||||
(state) => state.game.phase === Phase.AcceptDecline
|
||||
),
|
||||
{
|
||||
id: 'still-tied',
|
||||
title: 'Still tied? The seller chooses',
|
||||
text: 'Leo also added $2, so both total bids are $10. There is no third bidding round. Ada may accept either tied highest bidder, or pay $10 to the bank and keep the cargo.',
|
||||
target: 'auction-summary',
|
||||
},
|
||||
actionStep(
|
||||
'seller',
|
||||
'Watch Ada choose your offer',
|
||||
'Ada chooses you. You pay only your total bid of $10; the extra bid is not charged again. Leo pays nothing.',
|
||||
isWatch,
|
||||
(state) => state.game.players[0].containersOnIsland.length === 3
|
||||
),
|
||||
],
|
||||
completion: {
|
||||
title: 'You won the cargo, not the game yet',
|
||||
text: 'You have $10 cash and three island containers. Ada received $20 including the subsidy. Future purchases determine which colour you discard at scoring: collecting lots of valuable white containers without balancing your colours can wipe out their value.',
|
||||
},
|
||||
choices(_state, step) {
|
||||
return ['reveal', 'second-reveal'].includes(step)
|
||||
? watchChoice('Reveal the bids')
|
||||
: step === 'seller'
|
||||
? watchChoice('Watch Ada choose')
|
||||
: [];
|
||||
},
|
||||
};
|
||||
const keeping: Lesson = {
|
||||
...shell('keep-cargo'),
|
||||
title: 'Keep the cargo yourself',
|
||||
description: 'Decline the bids, pay the bank and compare the cost with selling.',
|
||||
initialState: () => shippingState(true),
|
||||
steps: [
|
||||
{
|
||||
id: 'intro',
|
||||
title: 'Decline does not cancel the auction',
|
||||
text: 'You already have three dark-green containers, one tan and one brown on your island. The ship’s white and orange containers would complete your five-colour set. This time, practise buying your own shipment.',
|
||||
target: 'cargo',
|
||||
},
|
||||
actionStep(
|
||||
'island',
|
||||
'Offer your shipment',
|
||||
'Sail to the island. Ada and Leo will bid for the entire cargo, just as in the previous auction.',
|
||||
(action) =>
|
||||
action.kind === 'move' &&
|
||||
action.move.name === MoveName.Sail &&
|
||||
action.move.data === ShipPosition.Island,
|
||||
(state) => state.game.phase === Phase.Bid
|
||||
),
|
||||
actionStep(
|
||||
'bids',
|
||||
'Reveal the offers',
|
||||
'Wait for both sealed bids before deciding what to do with your shipment.',
|
||||
isWatch,
|
||||
(state) => state.game.phase === Phase.AcceptDecline
|
||||
),
|
||||
actionStep(
|
||||
'keep-value',
|
||||
'What does keeping add?',
|
||||
'The two white containers are worth $20. The orange is worth $10 because it completes your five-colour set. Keeping adds $30 in containers, but costs $6 paid to the bank. What is the net gain?',
|
||||
(action) => action.kind === 'answer' && action.answer === '24',
|
||||
(state) => state.answer === '24',
|
||||
'$30 in containers minus the $6 payment.'
|
||||
),
|
||||
actionStep(
|
||||
'sell-value',
|
||||
'What does selling earn?',
|
||||
'Ada pays her $6 bid and the bank matches it. How much cash do you receive in total?',
|
||||
(action) => action.kind === 'answer' && action.answer === '12',
|
||||
(state) => state.answer === '12',
|
||||
'Add the $6 bid and the $6 bank subsidy.'
|
||||
),
|
||||
actionStep(
|
||||
'decline',
|
||||
'Pay $6 to keep it',
|
||||
'Keeping gains $24 of final value. Selling earns $12 cash. In this position, keeping is worth $12 more. Keep the cargo: pay $6 to the bank and add all three containers to your island. You receive no subsidy.',
|
||||
isMove(MoveName.Decline),
|
||||
(state) => state.game.players[0].ship.containers.length === 0
|
||||
),
|
||||
],
|
||||
completion: {
|
||||
title: 'Cargo instead of cash',
|
||||
text: 'You have $14 left and a full five-colour set. Your orange 5/10 container now qualifies for $10; the three dark-green containers are your most numerous colour and will be discarded. You must afford the highest bid to keep a shipment. Loans provide $10, cost $1 interest each turn and leave an $11 deduction each if unpaid at the end.',
|
||||
},
|
||||
choices(_state, step) {
|
||||
if (step === 'island') return [choice('Sail to the island', sail(ShipPosition.Island))];
|
||||
if (step === 'bids') return watchChoice('Reveal the bids');
|
||||
if (step === 'keep-value' || step === 'sell-value') {
|
||||
const answers = step === 'keep-value' ? ['24', '30', '36'] : ['6', '12', '18'];
|
||||
return answers.map((answer) => ({ label: `$${answer}`, action: { kind: 'answer', answer } }));
|
||||
}
|
||||
return step === 'decline' ? [choice('Keep cargo · pay $6', { name: MoveName.Decline, data: true })] : [];
|
||||
},
|
||||
};
|
||||
const scoring: Lesson = {
|
||||
...shell('scoring'),
|
||||
title: 'What actually scores?',
|
||||
description: 'Discard your most numerous colour, value a full set and count the final money.',
|
||||
initialState: scoringState,
|
||||
steps: [
|
||||
{
|
||||
id: 'intro',
|
||||
title: 'The last turn',
|
||||
text: 'Two colours in the supply are now empty. That ends the game after the current player finishes their turn. Your island has 3 dark green, 2 white, 1 orange, 1 tan and 1 brown. Your secret card determines their value, not what you paid at auction.',
|
||||
target: 'score-preview',
|
||||
},
|
||||
actionStep(
|
||||
'set',
|
||||
'Check all five colours first',
|
||||
'You have every colour before discarding. What is each orange 5/10 container worth: $5 or $10?',
|
||||
(action) => action.kind === 'answer' && action.answer === '10',
|
||||
(state) => state.answer === '10',
|
||||
'The full-set bonus is checked before removing the most numerous colour.'
|
||||
),
|
||||
actionStep(
|
||||
'discard',
|
||||
'Which entire colour is removed?',
|
||||
'Choose the colour you have the most of on your island. Every container of that colour scores $0. Count the containers, regardless of their value. If several colours tie, the 5/10 colour must go if involved; otherwise BGS removes the lowest-valued tied colour.',
|
||||
(action) => action.kind === 'answer' && action.answer === Color.Black,
|
||||
(state) => state.answer === Color.Black
|
||||
),
|
||||
actionStep(
|
||||
'finish',
|
||||
'Finish the game and count',
|
||||
'The three dark-green containers contribute $0. White earns $20, orange $10, tan $6 and brown $4: $40 from the island. Add $20 cash, $2 for your warehouse container and $3 for the container on your ship; subtract $11 for your loan. Factory stock and buildings score nothing. Choose Done to see the final result.',
|
||||
isMove(MoveName.Pass),
|
||||
(state) => ended(state.game)
|
||||
),
|
||||
],
|
||||
completion: {
|
||||
title: 'You finish with $54',
|
||||
text: 'Your final total is: $20 + $40 + $2 + $3 − $11 = $54. The highest final total wins. Aim for profitable trade and useful island cargo, while watching which colour will be discarded. The final-score table below shows every component.',
|
||||
},
|
||||
choices(_state, step) {
|
||||
if (step === 'set')
|
||||
return ['5', '10'].map((answer) => ({ label: `$${answer}`, action: { kind: 'answer', answer } }));
|
||||
if (step === 'discard')
|
||||
return colors.map((color) => ({
|
||||
label: colorName(color),
|
||||
color,
|
||||
action: { kind: 'answer', answer: color },
|
||||
}));
|
||||
return step === 'finish' ? [choice('Done · score the game', pass)] : [];
|
||||
},
|
||||
};
|
||||
export const lessons: Lesson[] = [supply, buildings, selling, bidding, keeping, scoring];
|
||||
export const chapterCards = lessons.map(({ id, version, title, description }) => ({ id, version, title, description }));
|
||||
334
viewer/src/tutorial/mount.ts
Normal file
334
viewer/src/tutorial/mount.ts
Normal file
|
|
@ -0,0 +1,334 @@
|
|||
import { createTutorial, TutorialMount, TutorialSnapshot } from '@boardgamers/protocol/tutorial';
|
||||
import { mountTutorialGuide } from '@boardgamers/protocol/tutorial/dom';
|
||||
import { GameState, Move, stripSecret } from 'container-engine';
|
||||
import { Phase } from 'container-engine/src/gamestate';
|
||||
import { MoveName } from 'container-engine/src/move';
|
||||
import { EventEmitter } from 'events';
|
||||
import Vue from 'vue';
|
||||
import Game from '../components/Game.vue';
|
||||
import { colorName, colors, lessons, LessonState, TutorialAction } from './lessons';
|
||||
import './tutorial.css';
|
||||
|
||||
export const mountTutorial: TutorialMount = async (target, { chapter, onProgress }) => {
|
||||
const found = lessons.find((entry) => entry.id === chapter);
|
||||
if (!found) throw Error('Unknown Container chapter');
|
||||
const lesson = found;
|
||||
target.className = 'container-tutorial';
|
||||
function element<K extends keyof HTMLElementTagNameMap>(tag: K, className = '', text = '') {
|
||||
const node = document.createElement(tag);
|
||||
node.className = className;
|
||||
node.textContent = text;
|
||||
return node;
|
||||
}
|
||||
const top = element('div', 'tutorial-top');
|
||||
const guide = element('div', 'tutorial-guide');
|
||||
const controls = element('div', 'tutorial-actions');
|
||||
controls.dataset.tutorial = 'lesson-actions';
|
||||
controls.setAttribute('aria-label', 'Lesson actions');
|
||||
const left = element('div');
|
||||
left.append(guide, controls);
|
||||
const summary = element('aside', 'tutorial-summary');
|
||||
const gameHost = element('div', 'tutorial-game');
|
||||
const result = element('section', 'tutorial-result');
|
||||
top.append(left, summary);
|
||||
target.append(top, gameHost, result);
|
||||
const emitter = new EventEmitter();
|
||||
const params = {
|
||||
state: null as GameState | null,
|
||||
player: 0,
|
||||
emitter,
|
||||
preferences: Vue.observable({ sound: false, disableHelp: false }),
|
||||
interactionDisabled: false,
|
||||
tutorialMove: (move: Move) => {
|
||||
void play({ kind: 'move', move });
|
||||
},
|
||||
};
|
||||
const app = new Vue({ render: (h) => h(Game, { props: params }) }).$mount(gameHost.appendChild(element('div')));
|
||||
let destroyed = false;
|
||||
let animate = false;
|
||||
let latest: TutorialSnapshot<LessonState>;
|
||||
let previous: LessonState | undefined;
|
||||
let animationTimer: number | undefined;
|
||||
let finishAnimation: (() => void) | undefined;
|
||||
async function present(game: GameState) {
|
||||
if (destroyed) return;
|
||||
// Atomic tutorial moves are checkpoints; the ordinary viewer's turn buffer is not used here.
|
||||
params.state = { ...structuredClone(stripSecret(game, 0)), newTurn: true };
|
||||
app.$forceUpdate();
|
||||
await app.$nextTick();
|
||||
}
|
||||
let storage: Storage | undefined;
|
||||
try {
|
||||
storage = localStorage;
|
||||
} catch {
|
||||
/* Progress is optional. */
|
||||
}
|
||||
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;
|
||||
await present(frame);
|
||||
await new Promise<void>((resolve) => {
|
||||
finishAnimation = resolve;
|
||||
animationTimer = window.setTimeout(
|
||||
resolve,
|
||||
window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 0 : 850
|
||||
);
|
||||
});
|
||||
finishAnimation = undefined;
|
||||
}
|
||||
}
|
||||
return next;
|
||||
},
|
||||
});
|
||||
async function play(action: TutorialAction) {
|
||||
if (latest.busy || latest.canContinue || latest.completed || destroyed) return;
|
||||
animate = true;
|
||||
try {
|
||||
await controller.play(action);
|
||||
} finally {
|
||||
animate = false;
|
||||
}
|
||||
}
|
||||
function swatch(color: string) {
|
||||
const chip = element('span', 'tutorial-container');
|
||||
chip.style.backgroundColor = color;
|
||||
chip.setAttribute('aria-hidden', 'true');
|
||||
return chip;
|
||||
}
|
||||
function renderSummary(snapshot: TutorialSnapshot<LessonState>) {
|
||||
const game = stripSecret(snapshot.state.game, 0);
|
||||
const you = game.players[0];
|
||||
summary.replaceChildren();
|
||||
summary.append(
|
||||
element('h2', '', `${game.phase === Phase.GameEnd ? 'Your final total' : 'Your cash'}: $${you.money}`)
|
||||
);
|
||||
const values = element('div', 'tutorial-values');
|
||||
values.dataset.tutorial = 'value-card';
|
||||
values.append(element('h3', '', 'Your secret value card'));
|
||||
for (const entry of you.pointCard!.containerValues) {
|
||||
const item = element('span', 'tutorial-value');
|
||||
item.append(
|
||||
swatch(entry.containerColor),
|
||||
document.createTextNode(entry.baseValue === 5 ? '$5/10' : `$${entry.baseValue}`)
|
||||
);
|
||||
item.title = `${colorName(entry.containerColor)}: ${
|
||||
entry.baseValue === 5 ? '$10 with all five colours; otherwise $5' : `$${entry.baseValue} each`
|
||||
}`;
|
||||
values.append(item);
|
||||
}
|
||||
if (!['supply-chain', 'buildings'].includes(lesson.id)) summary.append(values);
|
||||
if (['supply-chain', 'buildings'].includes(lesson.id)) {
|
||||
const business = element('div', 'tutorial-business');
|
||||
business.dataset.tutorial = 'business';
|
||||
business.append(element('h3', '', 'Your buildings and stock'));
|
||||
const table = element('table');
|
||||
const heading = element('tr');
|
||||
heading.append(element('th', '', 'Buildings'), element('th', '', 'Containers for sale'));
|
||||
table.append(heading);
|
||||
for (const [label, capacity, pieces, prices] of [
|
||||
[
|
||||
`${you.factories.length} ${you.factories.length === 1 ? 'factory' : 'factories'}`,
|
||||
you.factories.length * 2,
|
||||
you.containersOnFactoryStore.map((item) => item.piece),
|
||||
'$1–4',
|
||||
],
|
||||
[
|
||||
`${you.warehouses.length} ${you.warehouses.length === 1 ? 'warehouse' : 'warehouses'}`,
|
||||
you.warehouses.length,
|
||||
you.containersOnWarehouseStore.map((item) => item.piece),
|
||||
'$2–6',
|
||||
],
|
||||
] as const) {
|
||||
const row = element('tr');
|
||||
const stock = element('td');
|
||||
stock.append(element('div', '', `${pieces.length}/${capacity} spaces used`));
|
||||
pieces.forEach((piece) => stock.append(swatch(piece.color)));
|
||||
stock.append(element('small', '', `Your sale prices: ${prices}`));
|
||||
row.append(element('th', '', label), stock);
|
||||
table.append(row);
|
||||
}
|
||||
business.append(table);
|
||||
summary.append(business);
|
||||
}
|
||||
const owner =
|
||||
game.auctioningPlayer != null && game.auctioningPlayer >= 0
|
||||
? game.auctioningPlayer
|
||||
: lesson.id === 'bidding'
|
||||
? 1
|
||||
: 0;
|
||||
const cargo = element('div', 'tutorial-cargo');
|
||||
cargo.dataset.tutorial = 'cargo';
|
||||
cargo.append(
|
||||
element('h3', '', `${game.players[owner].name === 'You' ? 'Your' : game.players[owner].name + '’s'} ship`)
|
||||
);
|
||||
for (const piece of game.players[owner].ship.containers) cargo.append(swatch(piece.color));
|
||||
if (!game.players[owner].ship.containers.length) cargo.append(element('span', 'tutorial-muted', 'Empty'));
|
||||
summary.append(cargo);
|
||||
if (game.phase === Phase.Bid || game.phase === Phase.AcceptDecline) {
|
||||
const auction = element('div', 'tutorial-auction');
|
||||
auction.dataset.tutorial = 'auction-summary';
|
||||
auction.append(element('h3', '', 'Auction · entire shipment'));
|
||||
for (const player of game.players) {
|
||||
let label = 'Seller';
|
||||
if (player.id !== owner) {
|
||||
const firstKnown = player.id === 0 || player.showBid;
|
||||
const additionalKnown = player.showAdditionalBid || player.id === 0;
|
||||
label = firstKnown ? `$${player.bid}` : 'Sealed';
|
||||
if (game.highestBidders.length && (player.additionalBid || player.showAdditionalBid))
|
||||
label += additionalKnown
|
||||
? ` + $${player.additionalBid} = $${player.bid + player.additionalBid}`
|
||||
: ' + sealed';
|
||||
if (game.currentPlayers.includes(player.id)) label += ' · choosing';
|
||||
}
|
||||
auction.append(element('p', '', `${player.name}: ${label}`));
|
||||
}
|
||||
summary.append(auction);
|
||||
}
|
||||
if (you.containersOnIsland.length) {
|
||||
const island = element('div', 'tutorial-island');
|
||||
island.dataset.tutorial = 'score-preview';
|
||||
island.append(element('h3', '', 'Your island'));
|
||||
for (const color of colors) {
|
||||
const count = you.containersOnIsland.filter((piece) => piece.color === color).length;
|
||||
if (!count) continue;
|
||||
const row = element('div', 'tutorial-island-row');
|
||||
if (lesson.id === 'scoring' && snapshot.state.answer === color) row.classList.add('discarded');
|
||||
row.append(swatch(color), element('span', '', `${count} ${colorName(color)}`));
|
||||
if (row.classList.contains('discarded')) row.append(element('strong', '', 'discarded · $0'));
|
||||
island.append(row);
|
||||
}
|
||||
summary.append(island);
|
||||
}
|
||||
result.replaceChildren();
|
||||
result.hidden = game.phase !== Phase.GameEnd;
|
||||
if (!result.hidden) {
|
||||
result.append(element('h2', '', 'Final score'));
|
||||
const table = element('table');
|
||||
const labels = [
|
||||
'Cash',
|
||||
'White containers',
|
||||
'Orange containers',
|
||||
'Tan containers',
|
||||
'Brown containers',
|
||||
'Dark-green containers',
|
||||
'Most numerous colour removed',
|
||||
'Warehouse stock',
|
||||
'Ship cargo',
|
||||
'Unpaid loans',
|
||||
];
|
||||
you.finalScoreBreakdown?.forEach((value, index) => {
|
||||
const row = element('tr');
|
||||
row.append(
|
||||
element('th', '', labels[index]),
|
||||
element('td', '', value.replace('darkslategray', 'dark green'))
|
||||
);
|
||||
table.append(row);
|
||||
});
|
||||
const row = element('tr', 'tutorial-total');
|
||||
row.append(element('th', '', 'Your final total'), element('td', '', `$${you.money}`));
|
||||
table.append(row);
|
||||
result.append(table);
|
||||
const winner = game.players.reduce((best, player) => (player.money > best.money ? player : best));
|
||||
result.append(
|
||||
element('p', '', `${winner.name === 'You' ? 'You win' : winner.name + ' wins'} with $${winner.money}.`)
|
||||
);
|
||||
}
|
||||
}
|
||||
let controlStep = -1;
|
||||
function renderControls(snapshot: TutorialSnapshot<LessonState>) {
|
||||
const step = lesson.steps[snapshot.step]?.id ?? '';
|
||||
// Preserve the typed bid and focus when validation reports an error.
|
||||
if (controlStep !== snapshot.step) {
|
||||
controls.replaceChildren();
|
||||
controlStep = snapshot.step;
|
||||
if (lesson.id === 'bidding' && (step === 'bid' || step === 'raise')) {
|
||||
const form = element('div', 'tutorial-bid');
|
||||
form.setAttribute('role', 'group');
|
||||
form.setAttribute('aria-label', step === 'raise' ? 'Additional bid' : 'Your sealed bid');
|
||||
const label = element('label', '', step === 'raise' ? 'Additional bid' : 'Your sealed bid');
|
||||
const input = element('input');
|
||||
input.type = 'number';
|
||||
input.inputMode = 'numeric';
|
||||
input.min = '0';
|
||||
input.step = '1';
|
||||
input.required = true;
|
||||
input.max = String(snapshot.state.game.players[0].money - snapshot.state.game.players[0].bid);
|
||||
input.value = '';
|
||||
input.id = 'tutorial-bid-amount';
|
||||
label.htmlFor = input.id;
|
||||
const submit = element('button', '', step === 'raise' ? 'Add to my bid' : 'Bid');
|
||||
submit.type = 'button';
|
||||
const total = element('span', 'tutorial-muted');
|
||||
const update = () => {
|
||||
total.textContent =
|
||||
step === 'raise'
|
||||
? `Total: $8 + $${Number(input.value) || 0} = $${8 + (Number(input.value) || 0)}`
|
||||
: '';
|
||||
};
|
||||
input.addEventListener('input', update);
|
||||
update();
|
||||
form.append(label, input, submit, total);
|
||||
const sendBid = () => {
|
||||
if (!input.reportValidity()) return;
|
||||
void play({
|
||||
kind: 'move',
|
||||
move: { name: MoveName.Bid, data: true, extraData: { price: Number(input.value) } },
|
||||
});
|
||||
};
|
||||
submit.addEventListener('click', sendBid);
|
||||
input.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
sendBid();
|
||||
}
|
||||
});
|
||||
controls.append(form);
|
||||
} else {
|
||||
for (const choice of lesson.choices(snapshot.state, step)) {
|
||||
const button = element('button');
|
||||
button.type = 'button';
|
||||
if (choice.color) button.append(swatch(choice.color));
|
||||
button.append(document.createTextNode(choice.label));
|
||||
button.addEventListener('click', () => {
|
||||
void play(choice.action);
|
||||
});
|
||||
controls.append(button);
|
||||
}
|
||||
}
|
||||
}
|
||||
controls.querySelectorAll<HTMLInputElement | HTMLButtonElement>('input, button').forEach((control) => {
|
||||
control.disabled = snapshot.busy || snapshot.completed;
|
||||
});
|
||||
controls.hidden = !controls.childElementCount;
|
||||
}
|
||||
const off = controller.subscribe((snapshot) => {
|
||||
latest = snapshot;
|
||||
params.interactionDisabled = snapshot.busy || snapshot.canContinue || snapshot.completed;
|
||||
if (snapshot.state !== previous) {
|
||||
previous = snapshot.state;
|
||||
void present(snapshot.state.game);
|
||||
renderSummary(snapshot);
|
||||
}
|
||||
app.$forceUpdate();
|
||||
renderControls(snapshot);
|
||||
});
|
||||
const removeGuide = mountTutorialGuide(guide, controller);
|
||||
return () => {
|
||||
destroyed = true;
|
||||
clearTimeout(animationTimer);
|
||||
finishAnimation?.();
|
||||
removeGuide();
|
||||
off();
|
||||
controller.destroy();
|
||||
emitter.removeAllListeners();
|
||||
app.$destroy();
|
||||
target.replaceChildren();
|
||||
};
|
||||
};
|
||||
303
viewer/src/tutorial/tutorial.css
Normal file
303
viewer/src/tutorial/tutorial.css
Normal file
|
|
@ -0,0 +1,303 @@
|
|||
.container-tutorial {
|
||||
max-width: 1600px;
|
||||
margin: auto;
|
||||
padding: 20px;
|
||||
color: #203a45;
|
||||
font: 16px/1.5 system-ui, sans-serif;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.container-tutorial * {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.tutorial-top {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1.7fr) minmax(280px, 1fr);
|
||||
gap: 24px;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
.container-tutorial h2 {
|
||||
font-size: 20px;
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
.container-tutorial h3 {
|
||||
font-size: 14px;
|
||||
margin: 0 0 8px;
|
||||
}
|
||||
.container-tutorial button {
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
border: 1px solid #8aadb4;
|
||||
border-radius: 6px;
|
||||
padding: 8px 12px;
|
||||
background: #f3f8f5;
|
||||
color: #203a45;
|
||||
min-height: 40px;
|
||||
}
|
||||
.container-tutorial button:hover {
|
||||
background: #c4dce0;
|
||||
}
|
||||
.container-tutorial button:focus-visible,
|
||||
.container-tutorial input:focus-visible {
|
||||
outline: 3px solid #126d8c;
|
||||
outline-offset: 3px;
|
||||
}
|
||||
.container-tutorial button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: default;
|
||||
}
|
||||
.bgs-tutorial-guide {
|
||||
border-top: 4px solid #337b8b;
|
||||
background: #f5f8ee;
|
||||
border-radius: 8px;
|
||||
padding: 18px 20px;
|
||||
}
|
||||
.bgs-tutorial-heading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
.bgs-tutorial-heading strong {
|
||||
font-size: 20px;
|
||||
}
|
||||
.bgs-tutorial-body p {
|
||||
margin: 14px 0;
|
||||
max-width: 75ch;
|
||||
}
|
||||
.bgs-tutorial-body [role='alert'] {
|
||||
color: #a52916;
|
||||
font-weight: 600;
|
||||
}
|
||||
.bgs-tutorial-controls,
|
||||
.bgs-tutorial-playback {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.bgs-tutorial-playback,
|
||||
.bgs-tutorial-help {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: nowrap;
|
||||
gap: 6px;
|
||||
}
|
||||
.container-tutorial .bgs-tutorial-transport {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
padding: 0;
|
||||
flex: 0 0 40px;
|
||||
}
|
||||
.bgs-tutorial-help:empty {
|
||||
display: none;
|
||||
}
|
||||
.bgs-tutorial-body small {
|
||||
display: block;
|
||||
color: #49656d;
|
||||
margin-top: 12px;
|
||||
}
|
||||
.tutorial-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
margin-top: 16px;
|
||||
width: fit-content;
|
||||
max-width: 100%;
|
||||
}
|
||||
.tutorial-actions[hidden],
|
||||
.tutorial-result[hidden] {
|
||||
display: none;
|
||||
}
|
||||
.tutorial-actions button {
|
||||
background: #245969;
|
||||
color: white;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
}
|
||||
.tutorial-actions button:hover {
|
||||
background: #32778b;
|
||||
}
|
||||
.tutorial-bid {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
.tutorial-bid label {
|
||||
font-weight: 650;
|
||||
}
|
||||
.tutorial-bid input {
|
||||
font: inherit;
|
||||
background: white;
|
||||
color: #203a45;
|
||||
border: 1px solid #8aadb4;
|
||||
border-radius: 5px;
|
||||
width: 90px;
|
||||
min-height: 42px;
|
||||
padding: 7px;
|
||||
}
|
||||
.tutorial-summary {
|
||||
border-left: 1px solid #8aadb4;
|
||||
padding-left: 24px;
|
||||
}
|
||||
.tutorial-summary h2 {
|
||||
font-size: 18px;
|
||||
}
|
||||
.tutorial-values,
|
||||
.tutorial-cargo,
|
||||
.tutorial-auction,
|
||||
.tutorial-island {
|
||||
margin: 14px 0;
|
||||
}
|
||||
.tutorial-value {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
margin: 0 12px 6px 0;
|
||||
}
|
||||
.tutorial-container {
|
||||
display: inline-block;
|
||||
width: 28px;
|
||||
height: 15px;
|
||||
border: 1px solid #243a42;
|
||||
border-radius: 2px;
|
||||
background-image: repeating-linear-gradient(90deg, transparent 0 5px, #0002 5px 6px);
|
||||
vertical-align: middle;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.tutorial-cargo .tutorial-container {
|
||||
margin-right: 5px;
|
||||
}
|
||||
.tutorial-auction p {
|
||||
margin: 3px 0;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.tutorial-island-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 2px 0;
|
||||
}
|
||||
.tutorial-island-row.discarded > span {
|
||||
opacity: 0.45;
|
||||
text-decoration: line-through;
|
||||
}
|
||||
.tutorial-island-row strong {
|
||||
font-size: 13px;
|
||||
color: #97351f;
|
||||
}
|
||||
.tutorial-muted {
|
||||
color: #506c75;
|
||||
font-size: 14px;
|
||||
}
|
||||
.container-tutorial .bgs-tutorial-highlight {
|
||||
outline: 3px solid #bf790f;
|
||||
outline-offset: 3px;
|
||||
border-radius: 3px;
|
||||
}
|
||||
.tutorial-result {
|
||||
padding: 22px 0;
|
||||
max-width: 800px;
|
||||
margin: auto;
|
||||
}
|
||||
.tutorial-result table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
background: #f5f8ee;
|
||||
}
|
||||
.tutorial-result th,
|
||||
.tutorial-result td {
|
||||
padding: 9px 14px;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid #c3d3d0;
|
||||
}
|
||||
.tutorial-result th {
|
||||
font-weight: 500;
|
||||
}
|
||||
.tutorial-result td {
|
||||
text-align: right;
|
||||
}
|
||||
.tutorial-total {
|
||||
font-weight: 750;
|
||||
background: #c3dfd2;
|
||||
}
|
||||
@media (max-width: 700px) {
|
||||
.container-tutorial {
|
||||
padding: 12px;
|
||||
}
|
||||
.tutorial-top {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
}
|
||||
.tutorial-summary {
|
||||
border-left: 0;
|
||||
border-top: 1px solid #8aadb4;
|
||||
margin-top: 16px;
|
||||
width: fit-content;
|
||||
max-width: 100%;
|
||||
}
|
||||
.bgs-tutorial-guide {
|
||||
padding: 14px;
|
||||
}
|
||||
.bgs-tutorial-heading strong {
|
||||
font-size: 17px;
|
||||
}
|
||||
.bgs-tutorial-body p {
|
||||
font-size: 15px;
|
||||
}
|
||||
.bgs-tutorial-playback {
|
||||
margin-left: 0;
|
||||
}
|
||||
.container-tutorial .statusBar {
|
||||
font-size: 13px;
|
||||
height: auto;
|
||||
min-height: 40px;
|
||||
line-height: 1.4;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px;
|
||||
}
|
||||
.tutorial-result {
|
||||
font-size: 13px;
|
||||
}
|
||||
.tutorial-result th,
|
||||
.tutorial-result td {
|
||||
padding: 7px;
|
||||
}
|
||||
}
|
||||
|
||||
/* SVG use copies do not follow the source's CSS transform transition. */
|
||||
.container-tutorial #scene > use {
|
||||
display: none;
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.container-tutorial .piece {
|
||||
transition: none !important;
|
||||
}
|
||||
}
|
||||
|
||||
.tutorial-business table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 14px;
|
||||
}
|
||||
.tutorial-business th,
|
||||
.tutorial-business td {
|
||||
text-align: left;
|
||||
padding: 8px 10px 8px 0;
|
||||
vertical-align: top;
|
||||
border-bottom: 1px solid #8aadb455;
|
||||
}
|
||||
.tutorial-business small {
|
||||
display: block;
|
||||
color: #506c75;
|
||||
}
|
||||
.tutorial-business .tutorial-container {
|
||||
margin: 5px 3px 0 0;
|
||||
}
|
||||
|
|
@ -1,8 +1,17 @@
|
|||
// Import vue component
|
||||
import launch from './launch';
|
||||
import { createTutorialLauncher, TutorialLaunchOptions } from '@boardgamers/protocol/tutorial';
|
||||
import launchGame, { destroyViewer } from './launch';
|
||||
import { mountTutorial } from './tutorial/mount';
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
(window as any).container = { launch };
|
||||
const tutorial = createTutorialLauncher(mountTutorial);
|
||||
export function launch(selector: string) {
|
||||
tutorial.destroy();
|
||||
return launchGame(selector);
|
||||
}
|
||||
export function launchTutorial(selector: string, options: TutorialLaunchOptions) {
|
||||
destroyViewer();
|
||||
return tutorial.launch(selector, options);
|
||||
}
|
||||
if (typeof window !== 'undefined') {
|
||||
(window as any).container = { launch, launchTutorial };
|
||||
}
|
||||
|
||||
export default launch;
|
||||
|
|
|
|||
132
viewer/tests/tutorial/lessons.cjs
Normal file
132
viewer/tests/tutorial/lessons.cjs
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
const assert = require('node:assert/strict');
|
||||
const { test } = require('node:test');
|
||||
require('../../../engine/node_modules/ts-node').register({
|
||||
transpileOnly: true,
|
||||
compilerOptions: { module: 'CommonJS', moduleResolution: 'Node', target: 'ES2022', importHelpers: false },
|
||||
});
|
||||
const { createTutorial } = require('@boardgamers/protocol/tutorial');
|
||||
const { stripSecret } = require('../../../engine/src/engine');
|
||||
const { lessons } = require('../../src/tutorial/lessons');
|
||||
const expectedCash = { 'supply-chain': 21, buildings: 7, selling: 36, bidding: 10, 'keep-cargo': 14, scoring: 54 };
|
||||
function memory() {
|
||||
const entries = new Map();
|
||||
return { getItem: (key) => entries.get(key) ?? null, setItem: (key, value) => entries.set(key, value) };
|
||||
}
|
||||
function actionFor(lesson, snapshot) {
|
||||
const step = lesson.steps[snapshot.step].id;
|
||||
if (step === 'bid' || step === 'raise')
|
||||
return { kind: 'move', move: { name: 'bid', data: true, extraData: { price: step === 'bid' ? 8 : 2 } } };
|
||||
const choices = lesson.choices(snapshot.state, step);
|
||||
if (step === 'keep-value' || step === 'sell-value')
|
||||
return choices.find((choice) => choice.label === (step === 'keep-value' ? '$24' : '$12')).action;
|
||||
if (step === 'set') return choices.find((choice) => choice.label === '$10').action;
|
||||
if (step === 'discard') return choices.find((choice) => choice.label === 'dark green').action;
|
||||
assert.equal(choices.length, 1, `${lesson.id}/${step} needs one expected action`);
|
||||
return choices[0].action;
|
||||
}
|
||||
for (const lesson of lessons) {
|
||||
test(`${lesson.id}: complete using legal engine moves and restore the saved result`, async () => {
|
||||
const storage = memory();
|
||||
const controller = await createTutorial({ ...lesson, storage });
|
||||
let turns = 0;
|
||||
while (!controller.snapshot.completed && ++turns < 25) {
|
||||
const snapshot = controller.snapshot;
|
||||
const ok = snapshot.canContinue
|
||||
? await controller.continue()
|
||||
: await controller.play(actionFor(lesson, snapshot));
|
||||
assert.equal(ok, true, `${lesson.id}/${lesson.steps[snapshot.step].id}: ${controller.snapshot.error}`);
|
||||
const game = controller.snapshot.state.game;
|
||||
const pieces = [
|
||||
...game.containersLeft,
|
||||
...game.players.flatMap((player) => [
|
||||
...player.ship.containers,
|
||||
...player.containersOnIsland,
|
||||
...player.containersOnFactoryStore.map((item) => item.piece),
|
||||
...player.containersOnWarehouseStore.map((item) => item.piece),
|
||||
]),
|
||||
];
|
||||
assert.equal(pieces.length, 60, 'all containers remain in play or in the supply');
|
||||
assert.equal(new Set(pieces.map((piece) => piece.id)).size, 60, 'no duplicated pieces');
|
||||
}
|
||||
assert.equal(controller.snapshot.completed, true);
|
||||
assert.equal(controller.snapshot.canContinue, false, 'the last action completes without an extra Continue');
|
||||
assert.equal(controller.snapshot.state.game.players[0].money, expectedCash[lesson.id]);
|
||||
const restored = await createTutorial({ ...lesson, storage });
|
||||
assert.deepEqual(restored.snapshot.state, controller.snapshot.state);
|
||||
assert.equal(restored.snapshot.completed, true);
|
||||
if (lesson.id === 'scoring') {
|
||||
assert.deepEqual(
|
||||
controller.snapshot.state.game.players.map((player) => player.money),
|
||||
[54, 20, 20]
|
||||
);
|
||||
assert.equal(controller.snapshot.state.game.players[0].finalScoreBreakdown[6], '-$6');
|
||||
}
|
||||
controller.destroy();
|
||||
restored.destroy();
|
||||
});
|
||||
}
|
||||
test('bidding hides the sealed offers, sums the tie-break and pauses before the seller chooses', async () => {
|
||||
const lesson = lessons.find((lesson) => lesson.id === 'bidding');
|
||||
const controller = await createTutorial(lesson);
|
||||
await controller.continue();
|
||||
assert.equal(
|
||||
await controller.play({ kind: 'move', move: { name: 'bid', data: true, extraData: { price: -1 } } }),
|
||||
false
|
||||
);
|
||||
assert.equal(controller.snapshot.state.game.players[0].money, 20);
|
||||
await controller.play(actionFor(lesson, controller.snapshot));
|
||||
let publicView = stripSecret(controller.snapshot.state.game, 2);
|
||||
assert.equal(publicView.players[0].bid, 0);
|
||||
assert.equal(publicView.players[0].pointCard, null);
|
||||
assert.equal(publicView.players[0].money, 0);
|
||||
await controller.play({ kind: 'watch' });
|
||||
assert.deepEqual(controller.snapshot.state.game.highestBidders, [0, 2]);
|
||||
await controller.play(actionFor(lesson, controller.snapshot));
|
||||
publicView = stripSecret(controller.snapshot.state.game, 2);
|
||||
assert.equal(publicView.players[0].bid, 8);
|
||||
assert.equal(publicView.players[0].additionalBid, 0);
|
||||
await controller.play({ kind: 'watch' });
|
||||
assert.equal(controller.snapshot.state.game.phase, 'acceptDecline');
|
||||
assert.deepEqual(controller.snapshot.state.game.highestBidders, [0, 2]);
|
||||
assert.equal(
|
||||
controller.snapshot.state.game.players[0].bid + controller.snapshot.state.game.players[0].additionalBid,
|
||||
10
|
||||
);
|
||||
assert.equal(controller.snapshot.state.game.players[0].containersOnIsland.length, 0);
|
||||
controller.destroy();
|
||||
});
|
||||
test('incorrect scoring answers do not progress, and Retry restores the current exercise', async () => {
|
||||
const lesson = lessons.find((lesson) => lesson.id === 'scoring');
|
||||
const controller = await createTutorial(lesson);
|
||||
await controller.continue();
|
||||
assert.equal(await controller.play({ kind: 'answer', answer: '5' }), false);
|
||||
assert.equal(controller.snapshot.step, 1);
|
||||
await controller.play({ kind: 'answer', answer: '10' });
|
||||
assert.equal(await controller.play({ kind: 'answer', answer: 'white' }), false);
|
||||
assert.equal(controller.snapshot.step, 2);
|
||||
await controller.restartStep();
|
||||
assert.equal(controller.snapshot.step, 2);
|
||||
await controller.play({ kind: 'answer', answer: 'darkslategray' });
|
||||
await controller.play(actionFor(lesson, controller.snapshot));
|
||||
assert.equal(controller.snapshot.completed, true);
|
||||
await controller.restart();
|
||||
assert.equal(controller.snapshot.step, 0);
|
||||
assert.equal(controller.snapshot.state.game.players[0].money, 20);
|
||||
controller.destroy();
|
||||
});
|
||||
|
||||
test('the keep-or-sell questions compare the net value before the actual choice', async () => {
|
||||
const lesson = lessons.find((lesson) => lesson.id === 'keep-cargo');
|
||||
const c = await createTutorial(lesson);
|
||||
await c.continue();
|
||||
await c.play(actionFor(lesson, c.snapshot));
|
||||
await c.play({ kind: 'watch' });
|
||||
assert.equal(await c.play({ kind: 'answer', answer: '30' }), false, 'Keeping must subtract the payment');
|
||||
assert.equal(await c.play({ kind: 'answer', answer: '24' }), true);
|
||||
assert.equal(await c.play({ kind: 'answer', answer: '6' }), false, 'Selling includes the matching subsidy');
|
||||
assert.equal(await c.play({ kind: 'answer', answer: '12' }), true);
|
||||
assert.equal(c.snapshot.state.game.players[0].money, 20, 'Answers do not execute the auction');
|
||||
await c.play(actionFor(lesson, c.snapshot));
|
||||
assert.equal(c.snapshot.state.game.players[0].money, 14);
|
||||
assert.equal(c.snapshot.state.game.players[0].containersOnIsland.length, 8);
|
||||
});
|
||||
|
|
@ -39,6 +39,8 @@ module.exports = {
|
|||
config.resolve.alias.set('@boardgamers/protocol/viewer', join(protocolDist, 'viewer.js'));
|
||||
config.resolve.alias.set('@boardgamers/protocol/chat/dom$', join(protocolDist, 'chat-dom.js'));
|
||||
config.resolve.alias.set('@boardgamers/protocol/chat$', join(protocolDist, 'chat.js'));
|
||||
config.resolve.alias.set('@boardgamers/protocol/tutorial/dom$', join(protocolDist, 'tutorial-dom.js'));
|
||||
config.resolve.alias.set('@boardgamers/protocol/tutorial$', join(protocolDist, 'tutorial.js'));
|
||||
// vue-cli's svg rule uses plain file-loader (always emits files); replace it
|
||||
// with url-loader so the icons are inlined. Reuse the url-loader already
|
||||
// resolved for the images rule (it is not hoisted to our node_modules).
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue