Add playable Powergrid tutorials and city income reference (#155)
* Add playable Powergrid tutorials and city income reference * Space houses that share a city count so each one stays readable The income row shortened the city-count cells, and the house markers were packed to fit: 6px between columns against a 12px-wide house, and 3px between rows. Two players on the same number — the ordinary case for most of a game — overlapped by half and read as a single smudge; five or six at the start of a game read as one blob. Lay them out bottom-aligned in the cell instead, growing upward from the income strip so the number above stays legible, a house-width between columns and a house-height between rows. Five or six sharing go three wide rather than three tall: a third row starts at the top of the cell and hides the number completely, which is every game's opening position. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * Lift dialogs above the status bar and complete the payment table The status bar is sticky at z-index 10 and every modal sat at z-index 1, so the bar painted over the top of any open dialog. Modals open 10vh down and the bar is a fixed 40px, so on a short viewport — a phone held sideways — the bar landed across the dialog's own header and covered the close button, leaving no way out of the dialog at all. Put the modal above it; the bar is then dimmed behind the overlay like the rest of the page. The payment table counted to citiesToEndGame, which stopped one column short of the number that ends the game, and a player can finish holding more cities than that by building in the same phase as whoever triggered the end. Render the whole table instead, so it agrees with the city track on the board. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: John Gold <goldjohn6@gmail.com> Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
parent
93d1490a4f
commit
5f2406ebb9
25 changed files with 1547 additions and 49 deletions
2
.github/workflows/viewer-test.yml
vendored
2
.github/workflows/viewer-test.yml
vendored
|
|
@ -35,5 +35,7 @@ jobs:
|
|||
- run: pnpm build
|
||||
- run: pnpm --dir ../engine build
|
||||
- run: pnpm package
|
||||
- run: pnpm test:tutorial
|
||||
- run: pnpm exec playwright install --with-deps chromium
|
||||
- run: pnpm test:browser
|
||||
- run: pnpm test:tutorial:browser
|
||||
|
|
|
|||
|
|
@ -33,3 +33,25 @@ yarn lint
|
|||
### Customize configuration
|
||||
|
||||
See [Configuration Reference](https://cli.vuejs.org/config/).
|
||||
|
||||
## Playable tutorials
|
||||
|
||||
Seven independent chapters cover auctions, fuel, connections, income, plant replacement, Steps 2/3 and final scoring. They use Germany with classic rules, deterministic positions and scripted opponents. Actions go through the real engine; only the learner's filtered state reaches the board.
|
||||
|
||||
From the repository root:
|
||||
|
||||
```sh
|
||||
pnpm --dir engine build
|
||||
pnpm --dir viewer test:tutorial
|
||||
NODE_OPTIONS=--openssl-legacy-provider pnpm --dir viewer package
|
||||
pnpm --dir viewer test:tutorial:browser
|
||||
pnpm --dir viewer preview:tutorial
|
||||
```
|
||||
|
||||
Open <http://127.0.0.1:5199/?chapter=auctions>. Other chapter IDs are `resources`, `network`, `income`, `upgrades`, `steps` and `final-round`.
|
||||
|
||||
The ordinary viewer bundle exposes both `powergrid.launch` and `powergrid.launchTutorial`. Upload the usual JS/CSS and configure the tutorial chapters on the same BGS game version. `pnpm --dir viewer tutorial:manifest` prints the chapter metadata. No second bundle or engine release is required.
|
||||
|
||||
Lessons live in `src/tutorial/lessons.ts`. Keep their IDs stable and increase a chapter's version when changing its setup or accepted actions would invalidate saved progress. Test normal board clicks, refresh, rewind and completion on desktop and mobile before release.
|
||||
|
||||
See the [desktop and mobile screenshots](docs/tutorials/README.md) for examples of the tutorial UI.
|
||||
|
|
|
|||
21
viewer/docs/tutorials/README.md
Normal file
21
viewer/docs/tutorials/README.md
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
# Tutorial screenshots
|
||||
|
||||
Captured from the local tutorial preview using the same bundle as the ordinary viewer.
|
||||
|
||||
## Desktop
|
||||
|
||||
The connections chapter highlights the city to build while keeping the normal board controls.
|
||||
|
||||

|
||||
|
||||
## City track
|
||||
|
||||
Houses mark cities built. The row below shows total income for that number of powered cities; the track wraps to two rows on portrait phones.
|
||||
|
||||

|
||||
|
||||
## Mobile
|
||||
|
||||
The income chapter distinguishes the three cities built from the two actually supplied with electricity.
|
||||
|
||||
<img src="mobile.png" alt="Income chapter at 390 pixels wide" width="390" />
|
||||
BIN
viewer/docs/tutorials/desktop.png
Normal file
BIN
viewer/docs/tutorials/desktop.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 243 KiB |
BIN
viewer/docs/tutorials/income-track.png
Normal file
BIN
viewer/docs/tutorials/income-track.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 17 KiB |
BIN
viewer/docs/tutorials/mobile.png
Normal file
BIN
viewer/docs/tutorials/mobile.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 198 KiB |
|
|
@ -16,10 +16,14 @@
|
|||
"test:unit": "vue-cli-service test:unit",
|
||||
"package": "vue-cli-service build --target lib --name powergrid-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",
|
||||
"test:tutorial:browser": "node scripts/tutorial-smoke.mjs",
|
||||
"preview:tutorial": "node scripts/tutorial-preview.mjs",
|
||||
"tutorial:manifest": "node scripts/tutorial-manifest.cjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@boardgamers/protocol": "0.2.2",
|
||||
"@boardgamers/protocol": "0.3.3",
|
||||
"core-js": "^3.6.5",
|
||||
"lodash": "^4.17.19",
|
||||
"powergrid-engine": "workspace:../engine",
|
||||
|
|
@ -27,7 +31,8 @@
|
|||
"tslib": "^2.2.0",
|
||||
"vue": "^2.6.11",
|
||||
"vue-class-component": "^7.2.3",
|
||||
"vue-property-decorator": "^9.1.2"
|
||||
"vue-property-decorator": "^9.1.2",
|
||||
"zod": "4.6.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/assert": "^1.4.7",
|
||||
|
|
@ -35,6 +40,8 @@
|
|||
"@types/events": "^3.0.0",
|
||||
"@types/lodash": "^4.14.154",
|
||||
"@types/mocha": "^5.2.4",
|
||||
"@types/node": "15.3.0",
|
||||
"@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",
|
||||
|
|
|
|||
21
viewer/pnpm-lock.yaml
generated
21
viewer/pnpm-lock.yaml
generated
|
|
@ -1,7 +1,7 @@
|
|||
lockfileVersion: 5.4
|
||||
|
||||
specifiers:
|
||||
'@boardgamers/protocol': 0.2.2
|
||||
'@boardgamers/protocol': 0.3.3
|
||||
'@types/assert': ^1.4.7
|
||||
'@types/chai': ^4.2.11
|
||||
'@types/events': ^3.0.0
|
||||
|
|
@ -29,9 +29,12 @@ specifiers:
|
|||
vue-class-component: ^7.2.3
|
||||
vue-property-decorator: ^9.1.2
|
||||
vue-template-compiler: ^2.6.11
|
||||
'@types/node': 15.3.0
|
||||
'@types/webpack-env': 1.18.8
|
||||
zod: 4.6.4
|
||||
|
||||
dependencies:
|
||||
'@boardgamers/protocol': 0.2.2
|
||||
'@boardgamers/protocol': 0.3.3
|
||||
core-js: 3.12.1
|
||||
lodash: 4.17.21
|
||||
powergrid-engine: link:../engine
|
||||
|
|
@ -40,6 +43,7 @@ dependencies:
|
|||
vue: 2.6.12
|
||||
vue-class-component: 7.2.6_vue@2.6.12
|
||||
vue-property-decorator: 9.1.2_fxccklctoeetzhv4zjyvg2we5e
|
||||
zod: 4.6.4
|
||||
|
||||
devDependencies:
|
||||
'@types/assert': 1.5.4
|
||||
|
|
@ -61,6 +65,8 @@ devDependencies:
|
|||
sass-loader: 8.0.2_sass@1.32.13
|
||||
typescript: 5.9.3
|
||||
vue-template-compiler: 2.6.12
|
||||
'@types/node': 15.3.0
|
||||
'@types/webpack-env': 1.18.8
|
||||
|
||||
packages:
|
||||
/@babel/code-frame/7.12.11:
|
||||
|
|
@ -1458,10 +1464,10 @@ packages:
|
|||
to-fast-properties: 2.0.0
|
||||
dev: true
|
||||
|
||||
/@boardgamers/protocol/0.2.2:
|
||||
/@boardgamers/protocol/0.3.3:
|
||||
resolution:
|
||||
{
|
||||
integrity: sha512-5o5nPZW6CN6PysF0i90OR+B30djiFhAGutCZe5RKJV6h3RgqE36HA7l0pOpvhdHz8uYtqE0nmaPlc+2ZtYiM/A==,
|
||||
integrity: sha512-AS+x84WHXRudW6xt/s/5I3xYmNTQFbZEBp3V+41w0I2RirSr2fWjYnYf0p11nwTbZ6G5upivKz/sjYLtk8HOYA==,
|
||||
}
|
||||
dependencies:
|
||||
zod: 4.6.4
|
||||
|
|
@ -13149,3 +13155,10 @@ packages:
|
|||
integrity: sha512-AXSD6hvGdvRjajG/l1cC+d6IrhH+sjmPKtYeQdJIK8MFJl3LyClzS+o/YsVC+zQZPupAaeH5skwwm8YqYH7BqA==,
|
||||
}
|
||||
dev: false
|
||||
|
||||
/@types/webpack-env/1.18.8:
|
||||
resolution:
|
||||
{
|
||||
integrity: sha512-G9eAoJRMLjcvN4I08wB5I7YofOb/kaJNd5uoCMX+LbKXTPCF+ZIHuqTnFaK9Jz1rgs035f9JUPUhNFtqgucy/A==,
|
||||
}
|
||||
dev: true
|
||||
|
|
|
|||
13
viewer/scripts/tutorial-manifest.cjs
Normal file
13
viewer/scripts/tutorial-manifest.cjs
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
require('../../engine/node_modules/ts-node').register({
|
||||
transpileOnly: true,
|
||||
compiler: require.resolve('typescript'),
|
||||
compilerOptions: { module: 'CommonJS', moduleResolution: 'Node', target: 'ES2022', importHelpers: false },
|
||||
});
|
||||
const { lessons } = require('../src/tutorial/lessons');
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{ chapters: lessons.map(({ id, version, title, description }) => ({ id, version, title, description })) },
|
||||
null,
|
||||
2
|
||||
)
|
||||
);
|
||||
41
viewer/scripts/tutorial-preview.mjs
Normal file
41
viewer/scripts/tutorial-preview.mjs
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
import { createServer } from 'node:http';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { createRequire } from 'node:module';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const files = {
|
||||
'/bundle.js': fileURLToPath(new URL('../dist/powergrid-viewer.umd.min.js', import.meta.url)),
|
||||
'/bundle.css': fileURLToPath(new URL('../dist/powergrid-viewer.css', import.meta.url)),
|
||||
'/vue.js': require.resolve('vue/dist/vue.min.js'),
|
||||
};
|
||||
const html = `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Powergrid tutorials</title><link rel="stylesheet" href="/bundle.css"><style>body{margin:0;background:#f0f1e9}</style></head><body><div id="app"></div><script src="/vue.js"></script><script src="/bundle.js"></script><script>
|
||||
const chapters=['auctions','resources','network','income','upgrades','steps','final-round'];
|
||||
const chapter=new URL(location.href).searchParams.get('chapter')||chapters[0];
|
||||
const index=chapters.indexOf(chapter);
|
||||
powergrid.launchTutorial('#app',{chapter,onProgress:progress=>window.progress=progress,nextChapter:index<chapters.length-1?{id:chapters[index+1],title:'Next chapter',open:()=>location.search='?chapter='+chapters[index+1]}:undefined});
|
||||
</script></body></html>`;
|
||||
export function previewServer() {
|
||||
return createServer(async (req, res) => {
|
||||
const path = new URL(req.url, 'http://localhost').pathname;
|
||||
try {
|
||||
const file = files[path];
|
||||
if (path !== '/' && !file) {
|
||||
res.writeHead(404).end();
|
||||
return;
|
||||
}
|
||||
res.writeHead(200, {
|
||||
'access-control-allow-origin': '*',
|
||||
'cache-control': 'no-store',
|
||||
'content-type': path === '/' ? 'text/html' : path.endsWith('.css') ? 'text/css' : 'text/javascript',
|
||||
});
|
||||
res.end(file ? await readFile(file) : html);
|
||||
} catch (error) {
|
||||
res.writeHead(500).end(String(error));
|
||||
}
|
||||
});
|
||||
}
|
||||
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
||||
const port = Number(process.env.PORT || 5199);
|
||||
previewServer().listen(port, '127.0.0.1', () => console.log(`Tutorial preview: http://127.0.0.1:${port}`));
|
||||
}
|
||||
130
viewer/scripts/tutorial-smoke.mjs
Normal file
130
viewer/scripts/tutorial-smoke.mjs
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import { chromium } from 'playwright';
|
||||
import { previewServer } from './tutorial-preview.mjs';
|
||||
|
||||
const server = previewServer();
|
||||
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
const url = `http://127.0.0.1:${server.address().port}`;
|
||||
const browser = await chromium.launch({
|
||||
headless: true,
|
||||
...(process.env.CHROMIUM_PATH ? { executablePath: process.env.CHROMIUM_PATH } : {}),
|
||||
});
|
||||
const errors = [];
|
||||
try {
|
||||
for (const width of [1280, 390]) {
|
||||
const context = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: 'reduce' });
|
||||
const page = await context.newPage();
|
||||
page.on('pageerror', (error) => errors.push(String(error)));
|
||||
page.on('console', (message) => {
|
||||
if (message.type() === 'error') errors.push(message.text());
|
||||
});
|
||||
async function ready() {
|
||||
await page.waitForFunction(
|
||||
() => document.querySelector('button[aria-label="Back to start"]')?.disabled === false
|
||||
);
|
||||
}
|
||||
async function click(locator) {
|
||||
await locator.click();
|
||||
await ready();
|
||||
}
|
||||
const button = (name) => page.getByRole('button', { name, exact: true });
|
||||
const card = (area, number) =>
|
||||
page
|
||||
.locator(`[data-tutorial="${area}"] g.canClick`)
|
||||
.filter({ has: page.locator('text').filter({ hasText: new RegExp(`^${number}$`) }) })
|
||||
.first();
|
||||
const city = (name) =>
|
||||
page
|
||||
.locator('circle.canClick[pointer-events="all"]')
|
||||
.filter({ has: page.locator('title').filter({ hasText: new RegExp(`^${name}`) }) });
|
||||
const done = () => page.locator('[data-tutorial="turn"] g.enabled').filter({ hasText: 'Done' }).first();
|
||||
const fuel = () => page.locator('[data-tutorial="resources"] g.canClick').first();
|
||||
async function start(chapter) {
|
||||
await page.goto(`${url}/?chapter=${chapter}`);
|
||||
await page.locator('#scene').waitFor();
|
||||
await ready();
|
||||
const rect = await page.locator('#scene').boundingBox();
|
||||
assert.ok(rect.width > 300 && rect.height > 100, 'the actual game board is rendered');
|
||||
assert.ok(
|
||||
await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1),
|
||||
'no horizontal overflow'
|
||||
);
|
||||
}
|
||||
async function completed(chapter) {
|
||||
await page.waitForFunction(() => window.progress?.completed === true);
|
||||
await page.reload();
|
||||
await page.waitForFunction(() => window.progress?.completed === true);
|
||||
assert.equal(await button('Continue').count(), 0, 'no extra Continue at completion');
|
||||
if (chapter !== 'final-round') assert.equal(await button('Next chapter').isVisible(), true);
|
||||
await click(button('Previous step'));
|
||||
assert.equal(await page.evaluate(() => window.progress.completed), false);
|
||||
}
|
||||
await start('auctions');
|
||||
await click(button('Continue'));
|
||||
await click(card('plants', 4));
|
||||
await click(page.locator('.calculator g').filter({ hasText: 'OK' }));
|
||||
await click(page.locator('.calculator g').filter({ hasText: 'OK' }));
|
||||
await click(button('Watch the remaining auctions'));
|
||||
await completed('auctions');
|
||||
|
||||
await start('resources');
|
||||
await click(button('Continue'));
|
||||
await click(fuel());
|
||||
await click(fuel());
|
||||
await click(button('$2'));
|
||||
assert.equal(await page.getByRole('alert').isVisible(), true);
|
||||
await click(button('$3'));
|
||||
assert.match(await page.locator('.bgs-tutorial-feedback').innerText(), /Correct!/);
|
||||
await click(fuel());
|
||||
await click(fuel());
|
||||
await click(done());
|
||||
await completed('resources');
|
||||
|
||||
await start('network');
|
||||
await click(city('Essen'));
|
||||
await click(city('Duisburg'));
|
||||
await click(button('$12'));
|
||||
await click(city('Dusseldorf'));
|
||||
await click(done());
|
||||
await completed('network');
|
||||
|
||||
await start('income');
|
||||
await click(card('players', 4));
|
||||
await click(card('players', 13));
|
||||
await page.waitForTimeout(1100); // The ordinary viewer briefly locks Done after powering.
|
||||
await click(done());
|
||||
await click(button('Watch income and market upkeep'));
|
||||
await click(button('You'));
|
||||
await completed('income');
|
||||
|
||||
await start('upgrades');
|
||||
await click(card('plants', 25));
|
||||
await click(page.getByRole('button').filter({ hasText: /25/ }));
|
||||
await click(card('players', 4));
|
||||
await completed('upgrades');
|
||||
|
||||
await start('steps');
|
||||
await click(city('Kassel'));
|
||||
await click(done());
|
||||
await click(button('No'));
|
||||
await click(button('Finish the round'));
|
||||
await click(button('All 6'));
|
||||
await completed('steps');
|
||||
|
||||
await start('final-round');
|
||||
await click(button('Continue'));
|
||||
await click(page.locator('[data-tutorial="map"] circle.canClick[pointer-events="all"]').first());
|
||||
await click(button('Ada'));
|
||||
await click(done());
|
||||
// The normal game's score overlay may be open; it must not prevent completion.
|
||||
await page.waitForFunction(() => window.progress?.completed === true);
|
||||
assert.match(await page.locator('.bgs-tutorial-body').innerText(), /Ada wins with 16/);
|
||||
await page.screenshot({ path: `/tmp/powergrid-tutorial-${width}.png`, fullPage: true });
|
||||
assert.deepEqual(errors, []);
|
||||
console.log(`Seven chapters completed through the real viewer at ${width}px`);
|
||||
await context.close();
|
||||
}
|
||||
} finally {
|
||||
await browser.close();
|
||||
await new Promise((resolve) => server.close(resolve));
|
||||
}
|
||||
|
|
@ -26,6 +26,8 @@
|
|||
ref="cityCount"
|
||||
:transform="`translate(${G.map.cityCountPosition[0]}, ${G.map.cityCountPosition[1]})`"
|
||||
:playerColors="playerColors"
|
||||
:paymentTable="G.paymentTable"
|
||||
:compact="stacked"
|
||||
:citiesToEndGame="G.citiesToEndGame"
|
||||
:citiesToStep2="G.map.name === 'Manhattan' ? undefined : G.citiesToStep2"
|
||||
/>
|
||||
|
|
@ -72,7 +74,7 @@
|
|||
</template>
|
||||
</g>
|
||||
|
||||
<g ref="slotPowerPlantMarket" :transform="slotT('powerPlantMarket')">
|
||||
<g ref="slotPowerPlantMarket" data-tutorial="plants" :transform="slotT('powerPlantMarket')">
|
||||
<PowerPlantMarket
|
||||
ref="powerPlantMarket"
|
||||
:transform="`translate(${G.map.powerPlantMarketPosition[0]}, ${G.map.powerPlantMarketPosition[1]})`"
|
||||
|
|
@ -89,12 +91,13 @@
|
|||
/>
|
||||
</g>
|
||||
|
||||
<g ref="slotMap" :transform="slotT('map')">
|
||||
<g ref="slotMap" data-tutorial="map" :transform="slotT('map')">
|
||||
<Map
|
||||
ref="map"
|
||||
:transform="mapTransform"
|
||||
:playerColors="playerColors"
|
||||
:cities="G.map.cities"
|
||||
:tutorialCity="tutorialCity"
|
||||
:connections="G.map.connections"
|
||||
:polygons="G.map.polygons"
|
||||
:buildableCities="getBuildableCities()"
|
||||
|
|
@ -147,7 +150,7 @@
|
|||
<ResourceViewButton :showTrack="showResourceTrack" @select="setResourceView($event)" />
|
||||
</g>
|
||||
|
||||
<g ref="slotResources" :transform="slotT('resources')">
|
||||
<g ref="slotResources" data-tutorial="resources" :transform="slotT('resources')">
|
||||
<!-- On a phone the printed price track is a strip of unreadable
|
||||
columns, so the stacked layout defaults to one box per buyable
|
||||
source. It is still only a default: the switch above this row
|
||||
|
|
@ -356,13 +359,14 @@
|
|||
|
||||
<g
|
||||
ref="slotButtons"
|
||||
data-tutorial="turn"
|
||||
:transform="slotT('buttons') || `translate(${G.map.buttonsPosition[0]}, ${G.map.buttonsPosition[1]})`"
|
||||
>
|
||||
<PassButton
|
||||
transform="translate(15, 15)"
|
||||
:enabled="canPass()"
|
||||
:highlightButton="canPass() && !preferences.disableHelp"
|
||||
:text="canUndo() ? 'Done' : 'Pass'"
|
||||
:text="tutorialMove || canUndo() ? 'Done' : 'Pass'"
|
||||
@click="checkPass()"
|
||||
/>
|
||||
<UndoButton
|
||||
|
|
@ -388,7 +392,7 @@
|
|||
/>
|
||||
</g>
|
||||
|
||||
<g ref="slotPlayerBoards" :transform="slotT('playerBoards')">
|
||||
<g ref="slotPlayerBoards" data-tutorial="players" :transform="slotT('playerBoards')">
|
||||
<template v-for="(playerIndex, i) in adjustedPlayerOrder">
|
||||
<PlayerBoard
|
||||
:key="'B' + playerIndex"
|
||||
|
|
@ -720,16 +724,21 @@
|
|||
<strong>Payment Table</strong>
|
||||
<div class="table-scroll">
|
||||
<table class="payment-table">
|
||||
<!-- The whole table, so this agrees with the city track on the
|
||||
board. Counting to citiesToEndGame stopped one column short
|
||||
of the number that ends the game — and a player can finish
|
||||
holding more cities than that, having built in the same
|
||||
phase as whoever triggered it. -->
|
||||
<tr>
|
||||
<td><strong>Cities</strong></td>
|
||||
<template v-for="index in G.citiesToEndGame">
|
||||
<td :key="'cities' + index">{{ index - 1 }}</td>
|
||||
<td><strong>Powered cities</strong></td>
|
||||
<template v-for="(income, count) in G.paymentTable">
|
||||
<td :key="'cities' + count">{{ count }}</td>
|
||||
</template>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><strong>Payment</strong></td>
|
||||
<template v-for="index in G.citiesToEndGame">
|
||||
<td :key="'payment' + index">${{ G.paymentTable[index - 1] }}</td>
|
||||
<template v-for="(income, count) in G.paymentTable">
|
||||
<td :key="'payment' + count">${{ income }}</td>
|
||||
</template>
|
||||
</tr>
|
||||
</table>
|
||||
|
|
@ -935,6 +944,15 @@ export default class Game extends Vue {
|
|||
@Prop()
|
||||
emitter!: EventEmitter;
|
||||
|
||||
@Prop({ default: false })
|
||||
interactionDisabled!: boolean;
|
||||
|
||||
@Prop()
|
||||
tutorialMove?: (move: Move) => void;
|
||||
|
||||
@Prop()
|
||||
tutorialCity?: string;
|
||||
|
||||
@Prop()
|
||||
avatars!: string[];
|
||||
|
||||
|
|
@ -1022,6 +1040,17 @@ export default class Game extends Vue {
|
|||
|
||||
@Watch('state', { immediate: true })
|
||||
onStateChanged(state: GameState) {
|
||||
if (this.tutorialMove) {
|
||||
// Tutorial moves are individual engine checkpoints, not server turn buffers.
|
||||
// Rewinds must also clear temporary UI selections from a later step.
|
||||
this.turnMoves = [];
|
||||
this.G = null;
|
||||
this.confirmVisible = this.discardVisible = this.endScoreVisible = false;
|
||||
this.soleBuyerPlant = null;
|
||||
this.totalBid = 0;
|
||||
this.replaceState(state);
|
||||
return;
|
||||
}
|
||||
if (state && state.newTurn !== false) {
|
||||
// Committed state. Usually this clears the turn buffer (our own turn came
|
||||
// back committed), but during the simultaneous Bureaucracy phase it can be
|
||||
|
|
@ -1610,7 +1639,12 @@ export default class Game extends Vue {
|
|||
}
|
||||
|
||||
sendMove(move) {
|
||||
if (this.paused) {
|
||||
if (this.paused || this.interactionDisabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.tutorialMove) {
|
||||
this.tutorialMove(move);
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -1716,6 +1750,7 @@ export default class Game extends Vue {
|
|||
|
||||
canMove() {
|
||||
return (
|
||||
!this.interactionDisabled &&
|
||||
this.player != undefined &&
|
||||
this.G &&
|
||||
this.G.currentPlayers.includes(this.player!) &&
|
||||
|
|
@ -2625,7 +2660,12 @@ text {
|
|||
.modal {
|
||||
display: none; /* Hidden by default */
|
||||
position: fixed; /* Stay in place */
|
||||
z-index: 1; /* Sit on top */
|
||||
// Above the sticky status bar (z-index 10), which is painted by the page behind
|
||||
// the overlay rather than through it. The modal opens 10vh down and the bar is a
|
||||
// fixed 40px, so on a short viewport — a phone held sideways — the bar landed on
|
||||
// the dialog's own header and covered the close button, leaving no way out of the
|
||||
// dialog at all.
|
||||
z-index: 20;
|
||||
padding-top: 10vh; /* Location of the box */
|
||||
left: 0;
|
||||
top: 0;
|
||||
|
|
|
|||
|
|
@ -1,40 +1,72 @@
|
|||
<template>
|
||||
<g>
|
||||
<rect width="730" height="50" x="10" y="10" rx="3" fill="goldenrod" />
|
||||
<template v-for="index in 21">
|
||||
<g class="city-count-track">
|
||||
<g v-for="row in compact ? 2 : 1" :key="'row' + row" :transform="`translate(0, ${(row - 1) * 70})`">
|
||||
<rect :width="compact ? 367 : 730" height="68" x="10" y="10" rx="3" fill="goldenrod" />
|
||||
<rect :width="compact ? 359 : 722" height="20" x="14" y="56" rx="2" fill="#365343" />
|
||||
</g>
|
||||
<g
|
||||
v-for="(income, count) in paymentTable"
|
||||
:key="count"
|
||||
:transform="`translate(${cellX(count)}, ${cellY(count)})`"
|
||||
>
|
||||
<title>
|
||||
{{ count }} powered {{ count === 1 ? 'city' : 'cities' }}: ${{ income }} total income, before any map
|
||||
penalties. Houses mark cities built.
|
||||
</title>
|
||||
<rect
|
||||
:key="'playerCityCount' + index"
|
||||
width="28"
|
||||
height="38"
|
||||
:x="46 + 33 * (index - 1)"
|
||||
y="16"
|
||||
x="13"
|
||||
y="14"
|
||||
rx="2"
|
||||
fill="darkgoldenrod"
|
||||
:stroke="index == citiesToStep2 || index == citiesToEndGame ? '#916a08' : 'darkgoldenrod'"
|
||||
:stroke="count == citiesToStep2 || count == citiesToEndGame ? '#916a08' : 'darkgoldenrod'"
|
||||
stroke-width="2px"
|
||||
/>
|
||||
<text
|
||||
:key="'playerCityCountText' + index"
|
||||
text-anchor="middle"
|
||||
style="font-size: 24px; font-family: monospace"
|
||||
letter-spacing="-2"
|
||||
:x="59 + 33 * (index - 1)"
|
||||
y="35"
|
||||
x="26"
|
||||
y="27"
|
||||
fill="gold"
|
||||
>
|
||||
{{ index }}
|
||||
{{ count }}
|
||||
</text>
|
||||
</template>
|
||||
<template v-for="house in houses">
|
||||
<line v-if="count % (compact ? 11 : 22) > 0" x1="10.5" x2="10.5" y1="61" y2="71" stroke="#607765" />
|
||||
<text
|
||||
class="city-income"
|
||||
x="27"
|
||||
y="66"
|
||||
text-anchor="middle"
|
||||
style="font-size: 15px; dominant-baseline: central"
|
||||
fill="#fff3cf"
|
||||
>
|
||||
{{ income }}
|
||||
</text>
|
||||
</g>
|
||||
<!-- Keep row placement synchronous so the portrait layout measures the new track bounds. -->
|
||||
<g
|
||||
v-for="house in houses"
|
||||
:key="house.id"
|
||||
:transform="`translate(${cellX(house.cityCount)}, ${cellY(house.cityCount)})`"
|
||||
>
|
||||
<House
|
||||
:key="house.id"
|
||||
:pieceId="house.id"
|
||||
:targetState="{ x: house.x, y: house.y }"
|
||||
:owner="house.owner"
|
||||
:ownerName="house.ownerName"
|
||||
:color="house.color"
|
||||
:scale="0.03"
|
||||
/>
|
||||
</template>
|
||||
</g>
|
||||
<g class="city-income-legend" :transform="`translate(0, ${compact ? 157 : 87})`">
|
||||
<circle cx="21" cy="0" r="7" fill="#365343" />
|
||||
<text x="21" text-anchor="middle" font-size="11" fill="#fff3cf">$</text>
|
||||
<text x="33" y="0" style="font-size: 13px; dominant-baseline: central" fill="#29432e">
|
||||
Total income for powered cities
|
||||
</text>
|
||||
</g>
|
||||
</g>
|
||||
</template>
|
||||
|
||||
|
|
@ -44,6 +76,15 @@ import { Vue, Component, Prop } from 'vue-property-decorator';
|
|||
import { House } from '../pieces';
|
||||
import { Piece } from '../../types/ui-data';
|
||||
|
||||
// The House piece at the 0.03 scale this track draws it, rounded to whole units: the
|
||||
// path spans 3-396 x 4-456, so 12 x 14 on the board. Used as the grid pitch below.
|
||||
const HOUSE_WIDTH = 12;
|
||||
const HOUSE_HEIGHT = 14;
|
||||
// The cell rect the template draws at x 13 y 14, 28 x 38 — houses are placed against
|
||||
// its bottom edge, clear of the income strip that starts 4 units below it.
|
||||
const CELL_CENTRE_X = 27;
|
||||
const CELL_BOTTOM = 52;
|
||||
|
||||
@Component({
|
||||
components: {
|
||||
House
|
||||
|
|
@ -53,8 +94,18 @@ export default class CityCount extends Vue {
|
|||
@Prop() citiesToStep2?: number;
|
||||
@Prop() citiesToEndGame?: number;
|
||||
@Prop() playerColors?: string[];
|
||||
@Prop({ required: true }) paymentTable!: number[];
|
||||
@Prop({ default: false }) compact!: boolean;
|
||||
|
||||
houses: Piece[] = [];
|
||||
houses: (Piece & { cityCount: number })[] = [];
|
||||
|
||||
cellX(count: number) {
|
||||
return 33 * (this.compact ? count % 11 : count);
|
||||
}
|
||||
|
||||
cellY(count: number) {
|
||||
return this.compact ? Math.floor(count / 11) * 70 : 0;
|
||||
}
|
||||
|
||||
createPieces(gameState: GameState) {
|
||||
this.houses = [];
|
||||
|
|
@ -63,18 +114,33 @@ export default class CityCount extends Vue {
|
|||
|
||||
gameState.players.forEach((player, pi) => adjustCityCount[player.cities.length].push(pi));
|
||||
gameState.players.forEach((player, pi) => {
|
||||
let x = (adjustCityCount[player.cities.length].length == 1 ? 23 : 20) + 33 * player.cities.length;
|
||||
x += (adjustCityCount[player.cities.length].indexOf(pi) % 2) * 6;
|
||||
// Players sharing a count get a grid, bottom-aligned in the cell so it grows
|
||||
// upward from the income strip and leaves the digit above readable. At the
|
||||
// old 6px/3px offsets even TWO players on the same number — the ordinary
|
||||
// case all game — overlapped by half and read as one smudge.
|
||||
//
|
||||
// Five or six share go three wide rather than three tall: a third row starts
|
||||
// at the top of the cell and hides the number completely, which is every
|
||||
// game's opening position. Three columns only have to overlap by a few
|
||||
// pixels, and the cells are spaced wider than they are drawn.
|
||||
const sharing = adjustCityCount[player.cities.length];
|
||||
const seat = sharing.indexOf(pi);
|
||||
const cols = sharing.length > 4 ? 3 : 2;
|
||||
const pitch = cols === 3 ? 9 : HOUSE_WIDTH;
|
||||
const rows = Math.ceil(sharing.length / cols);
|
||||
|
||||
this.houses.push({
|
||||
id: pi + '_cityCount',
|
||||
x: x,
|
||||
y:
|
||||
15 +
|
||||
(adjustCityCount[player.cities.length].indexOf(pi) * 30) /
|
||||
adjustCityCount[player.cities.length].length,
|
||||
cityCount: player.cities.length,
|
||||
// CELL_CENTRE_X/BOTTOM are the darkgoldenrod cell drawn in the template.
|
||||
x:
|
||||
sharing.length == 1
|
||||
? CELL_CENTRE_X - HOUSE_WIDTH / 2
|
||||
: CELL_CENTRE_X - ((cols - 1) * pitch + HOUSE_WIDTH) / 2 + (seat % cols) * pitch,
|
||||
y: CELL_BOTTOM - rows * HOUSE_HEIGHT + Math.floor(seat / cols) * HOUSE_HEIGHT,
|
||||
color: this.playerColors![pi],
|
||||
owner: pi,
|
||||
ownerName: player.name,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -193,6 +193,7 @@
|
|||
<circle
|
||||
v-if="city.connectionCost == null"
|
||||
:key="city.name + '_circle2'"
|
||||
:data-tutorial="city.name === tutorialCity ? 'destination' : undefined"
|
||||
:class="[{ canClick: canBuild(city) || canPickRegion(city) }]"
|
||||
r="20"
|
||||
:cx="city.x"
|
||||
|
|
@ -460,6 +461,21 @@
|
|||
stroke-linecap="round"
|
||||
/>
|
||||
</g>
|
||||
<g v-if="guidedCity" pointer-events="none">
|
||||
<circle :cx="guidedCity.x" :cy="guidedCity.y" r="29" fill="none" stroke="#a96600" stroke-width="4" />
|
||||
<text
|
||||
:x="guidedCity.x"
|
||||
:y="guidedCity.y - 37"
|
||||
text-anchor="middle"
|
||||
fill="#233745"
|
||||
stroke="#fffef5"
|
||||
stroke-width="6"
|
||||
paint-order="stroke"
|
||||
font-size="19"
|
||||
font-weight="600"
|
||||
v-text="guidedCity.name"
|
||||
/>
|
||||
</g>
|
||||
</g>
|
||||
</template>
|
||||
|
||||
|
|
@ -481,6 +497,8 @@ const CITY_RING_RADIUS = 25;
|
|||
},
|
||||
})
|
||||
export default class Map extends Vue {
|
||||
@Prop() tutorialCity?: string;
|
||||
get guidedCity() { return this.cities?.find((city) => city.name === this.tutorialCity); }
|
||||
@Prop() polygons?: Polygon[];
|
||||
@Prop() cities?: City[];
|
||||
@Prop() connections?: Connection[];
|
||||
|
|
@ -553,6 +571,7 @@ export default class Map extends Vue {
|
|||
y: city.y + offsetY,
|
||||
color: this.playerColors![pi],
|
||||
owner: pi,
|
||||
ownerName: player.name,
|
||||
scale: pieceScale,
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@
|
|||
stroke-width="12"
|
||||
stroke-miterlimit="10"
|
||||
/>
|
||||
<title>{{ ownerName }}'s House</title>
|
||||
<title>{{ houseTitle }}</title>
|
||||
</g>
|
||||
</template>
|
||||
<script lang="ts">
|
||||
|
|
@ -50,5 +50,11 @@ export default class House extends Mixins(Piece) {
|
|||
|
||||
@Prop()
|
||||
ownerName?: string;
|
||||
|
||||
get houseTitle() {
|
||||
if (this.owner !== undefined && this.owner === this.player) return 'Your House';
|
||||
if (this.ownerName) return `${this.ownerName}'s House`;
|
||||
return this.owner === undefined ? 'House' : `Player ${this.owner + 1}'s House`;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
|
|
|||
|
|
@ -69,6 +69,32 @@ export function mountGameChat(emitter: ViewerEmitter<any, any>, host: Element):
|
|||
shortcutCount.className = 'chat-shortcut-count';
|
||||
shortcut.append(shortcutCount);
|
||||
(host.querySelector('.chat-tabs-host') || slot).append(shortcut);
|
||||
function positionShortcut() {
|
||||
shortcut.style.bottom = '';
|
||||
if (shortcut.hidden) return;
|
||||
const box = shortcut.getBoundingClientRect();
|
||||
let top = box.top;
|
||||
const controls = Array.from(host.querySelectorAll('#scene g.button'))
|
||||
.map((control) => control.getBoundingClientRect())
|
||||
.filter((control) => control.left < box.right && control.right > box.left)
|
||||
.sort((a, b) => b.top - a.top);
|
||||
for (const control of controls) {
|
||||
if (control.top < top + box.height && control.bottom > top) top = control.top - box.height - 8;
|
||||
}
|
||||
if (top !== box.top) shortcut.style.bottom = `${window.innerHeight - top - box.height}px`;
|
||||
}
|
||||
let positionFrame: number | undefined;
|
||||
function scheduleShortcutPosition() {
|
||||
if (positionFrame !== undefined) return;
|
||||
positionFrame = window.requestAnimationFrame(() => {
|
||||
positionFrame = undefined;
|
||||
positionShortcut();
|
||||
});
|
||||
}
|
||||
window.addEventListener('scroll', scheduleShortcutPosition, { passive: true });
|
||||
window.addEventListener('resize', scheduleShortcutPosition);
|
||||
const layoutObserver = new ResizeObserver(scheduleShortcutPosition);
|
||||
layoutObserver.observe(host);
|
||||
const feeds = host.querySelector<HTMLElement>('.journal-and-chat');
|
||||
const tabs = document.createElement('nav');
|
||||
tabs.className = 'game-feed-tabs';
|
||||
|
|
@ -114,6 +140,7 @@ export function mountGameChat(emitter: ViewerEmitter<any, any>, host: Element):
|
|||
shortcut.hidden = chatVisible || !count;
|
||||
shortcut.setAttribute('aria-label', `Open ${label}`);
|
||||
chatTab.textContent = label;
|
||||
positionShortcut();
|
||||
}
|
||||
shortcut.onclick = () => {
|
||||
selectFeed('chat');
|
||||
|
|
@ -149,6 +176,10 @@ export function mountGameChat(emitter: ViewerEmitter<any, any>, host: Element):
|
|||
dispose.push(() => tabs.remove());
|
||||
return () => {
|
||||
dispose.forEach((cleanup) => cleanup());
|
||||
window.removeEventListener('scroll', scheduleShortcutPosition);
|
||||
window.removeEventListener('resize', scheduleShortcutPosition);
|
||||
layoutObserver.disconnect();
|
||||
if (positionFrame !== undefined) window.cancelAnimationFrame(positionFrame);
|
||||
view.destroy();
|
||||
shortcut.remove();
|
||||
style.remove();
|
||||
|
|
@ -192,6 +223,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 });
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,11 @@ import { shouldAdoptLogState } from './util/turn-buffer';
|
|||
|
||||
let dispose: (() => void) | undefined;
|
||||
|
||||
export function destroyViewer() {
|
||||
dispose?.();
|
||||
dispose = undefined;
|
||||
}
|
||||
|
||||
function launch(selector: string) {
|
||||
const target = document.querySelector(selector);
|
||||
if (!target) throw new Error(`Viewer mount point not found: ${selector}`);
|
||||
|
|
|
|||
|
|
@ -102,7 +102,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);
|
||||
}
|
||||
});
|
||||
|
|
|
|||
646
viewer/src/tutorial/lessons.ts
Normal file
646
viewer/src/tutorial/lessons.ts
Normal file
|
|
@ -0,0 +1,646 @@
|
|||
import type { TutorialOptions, TutorialStep } from '@boardgamers/protocol/tutorial';
|
||||
import type { GameState, Move } from 'powergrid-engine';
|
||||
import { availableMoves, move as engineMove, setup } from 'powergrid-engine';
|
||||
import { Phase, PowerPlantType, ResourceType } from 'powergrid-engine/src/gamestate';
|
||||
import { map as germany } from 'powergrid-engine/src/maps/germany';
|
||||
import { MoveName } from 'powergrid-engine/src/move';
|
||||
import { powerPlants as plants } from 'powergrid-engine/src/powerPlants';
|
||||
|
||||
export type Action = { kind: 'move'; move: Move } | { kind: 'watch' } | { kind: 'answer'; answer: string };
|
||||
export interface LessonState {
|
||||
game: GameState;
|
||||
answer?: string;
|
||||
watched: number;
|
||||
}
|
||||
export interface Choice {
|
||||
label: string;
|
||||
action: Action;
|
||||
}
|
||||
export interface Lesson extends Omit<TutorialOptions<LessonState, Action>, 'move'> {
|
||||
title: string;
|
||||
description: string;
|
||||
move(state: LessonState, action: Action, frame?: (game: GameState) => void): LessonState;
|
||||
choices(state: LessonState, step: string): Choice[];
|
||||
}
|
||||
const copy = <T>(value: T): T => JSON.parse(JSON.stringify(value));
|
||||
const pass: Move = { name: MoveName.Pass, data: true };
|
||||
const plant = (number: number) => copy(plants.find((p) => p.number === number)!);
|
||||
const bid = (data: number): Move => ({ name: MoveName.Bid, data });
|
||||
const choose = (data: number): Move => ({ name: MoveName.ChoosePowerPlant, data });
|
||||
const you = (s: LessonState) => s.game.players[0];
|
||||
const has = (s: LessonState, number: number) => you(s).powerPlants.some((p) => p.number === number);
|
||||
const inPhase = (phase: Phase) => (s: LessonState) => s.game.phase === phase;
|
||||
|
||||
function activate(game: GameState, phase: Phase, seats: number[]) {
|
||||
game.phase = phase;
|
||||
game.currentPlayers = seats;
|
||||
game.players.forEach((p) => {
|
||||
p.availableMoves = seats.includes(p.id) ? availableMoves(game, p) : null;
|
||||
});
|
||||
}
|
||||
function base(): GameState {
|
||||
// Three adjacent regions, including the Ruhr's inexpensive starting connections.
|
||||
const map = copy(germany);
|
||||
map.cities = map.cities.filter((c) => ['green', 'red', 'brown'].includes(c.region));
|
||||
const names = new Set(map.cities.map((c) => c.name));
|
||||
map.connections = map.connections.filter((c) => c.nodes.every((n) => names.has(n)));
|
||||
const game = setup(3, { map: 'Germany', variant: 'original', showMoney: true }, 'powergrid-tutorial-1');
|
||||
// Keep the engine's computed layout while fixing the regions used by the lessons.
|
||||
game.map.cities = map.cities;
|
||||
game.map.connections = map.connections;
|
||||
game.players.forEach((p, i) => {
|
||||
p.name = ['You', 'Ada', 'Leo'][i];
|
||||
});
|
||||
return game;
|
||||
}
|
||||
function own(game: GameState, seat: number, numbers: number[]) {
|
||||
const p = game.players[seat];
|
||||
p.powerPlants = numbers.map(plant);
|
||||
p.powerPlantsNotUsed = [...numbers];
|
||||
for (const type of ['coal', 'oil', 'garbage', 'uranium', 'hybrid'] as const) p[`${type}Capacity`] = 0;
|
||||
for (const card of p.powerPlants) {
|
||||
const key = (
|
||||
{
|
||||
[PowerPlantType.Coal]: 'coal',
|
||||
[PowerPlantType.Oil]: 'oil',
|
||||
[PowerPlantType.Garbage]: 'garbage',
|
||||
[PowerPlantType.Uranium]: 'uranium',
|
||||
[PowerPlantType.Hybrid]: 'hybrid',
|
||||
} as const
|
||||
)[card.type];
|
||||
if (key) p[`${key}Capacity`] += card.cost * 2;
|
||||
}
|
||||
game.actualMarket = game.actualMarket.filter((p) => !numbers.includes(p.number));
|
||||
game.futureMarket = game.futureMarket.filter((p) => !numbers.includes(p.number));
|
||||
game.powerPlantsDeck = game.powerPlantsDeck.filter((p) => !numbers.includes(p.number));
|
||||
}
|
||||
function market(game: GameState, numbers: number[]) {
|
||||
game.actualMarket = numbers.slice(0, game.step === 3 ? 6 : 4).map(plant);
|
||||
game.futureMarket = game.step === 3 ? [] : numbers.slice(4).map(plant);
|
||||
const held = game.players.flatMap((p) => p.powerPlants.map((p) => p.number));
|
||||
game.powerPlantsDeck = plants.filter((p) => !numbers.includes(p.number) && !held.includes(p.number)).map(copy);
|
||||
game.cardsLeft = game.powerPlantsDeck.length;
|
||||
}
|
||||
function cities(game: GameState, seat: number, names: string[]) {
|
||||
game.players[seat].cities = names.map((name) => ({
|
||||
name,
|
||||
position: game.players.filter((p) => p.id !== seat && p.cities.some((c) => c.name === name)).length,
|
||||
}));
|
||||
game.players[seat].housesLeft = 22 - names.length;
|
||||
}
|
||||
function fuel(game: GameState, seat: number, resource: ResourceType, count: number) {
|
||||
const key = `${resource}Left` as const;
|
||||
const needed = count - game.players[seat][key];
|
||||
const fromSupply = Math.min(game[`${resource}Supply`], needed);
|
||||
game[`${resource}Supply`] -= fromSupply;
|
||||
game[`${resource}Market`] -= needed - fromSupply;
|
||||
game.players[seat][key] = count;
|
||||
}
|
||||
function state(game: GameState): LessonState {
|
||||
return { game, watched: 0 };
|
||||
}
|
||||
function midgame(phase: Phase): GameState {
|
||||
const game = base();
|
||||
game.round = 4;
|
||||
game.playerOrder = [2, 1, 0];
|
||||
own(game, 0, [4]);
|
||||
own(game, 1, [3]);
|
||||
own(game, 2, [5]);
|
||||
market(game, [6, 7, 8, 9, 10, 11, 12, 13]);
|
||||
activate(game, phase, [0]);
|
||||
return game;
|
||||
}
|
||||
function run(game: GameState, move: Move, seat: number, frame?: (game: GameState) => void) {
|
||||
engineMove(game, copy(move), seat);
|
||||
frame?.(copy(game));
|
||||
}
|
||||
function finishOtherAuctions(game: GameState, frame?: (game: GameState) => void) {
|
||||
for (let guard = 0; game.phase === Phase.Auction && guard < 30; guard++) {
|
||||
const seat = game.currentPlayers[0];
|
||||
if (seat === 0) throw Error('The learner still has an auction decision.');
|
||||
const moves = game.players[seat].availableMoves!;
|
||||
const next = moves.ChoosePowerPlant
|
||||
? choose(moves.ChoosePowerPlant[0])
|
||||
: moves.Bid && !game.currentBid
|
||||
? bid(moves.Bid[0])
|
||||
: pass;
|
||||
run(game, next, seat, frame);
|
||||
}
|
||||
if (game.phase === Phase.Auction) throw Error('Auction script did not finish.');
|
||||
}
|
||||
function finishIncome(game: GameState, frame?: (game: GameState) => void) {
|
||||
for (let guard = 0; game.phase === Phase.Bureaucracy && guard < 20; guard++) {
|
||||
const seat = game.currentPlayers[0];
|
||||
const usable = game.players[seat].availableMoves?.UsePowerPlant?.[0];
|
||||
run(game, usable ? { name: MoveName.UsePowerPlant, data: usable } : pass, seat, frame);
|
||||
}
|
||||
if (game.phase === Phase.Bureaucracy) throw Error('Income script did not finish.');
|
||||
}
|
||||
function apply(id: string, original: LessonState, action: Action, frame?: (game: GameState) => void): LessonState {
|
||||
const next = copy(original);
|
||||
next.answer = undefined;
|
||||
const game = next.game;
|
||||
if (action.kind === 'answer') next.answer = action.answer;
|
||||
else if (action.kind === 'watch') {
|
||||
next.watched++;
|
||||
if (id === 'auctions') finishOtherAuctions(game, frame);
|
||||
else if (id === 'income') finishIncome(game, frame);
|
||||
else if (id === 'steps') {
|
||||
finishIncome(game, frame);
|
||||
// The engine handles the Step 3 card drawn during market upkeep.
|
||||
}
|
||||
} else {
|
||||
run(game, action.move, 0, frame);
|
||||
if (id === 'auctions' && action.move.name === MoveName.Bid) {
|
||||
if (action.move.data === 4) {
|
||||
run(game, bid(5), 1, frame);
|
||||
run(game, pass, 2, frame);
|
||||
} else if (action.move.data === 6) run(game, pass, 1, frame);
|
||||
}
|
||||
if (['network', 'steps', 'final-round'].includes(id) && action.move.name === MoveName.Pass) {
|
||||
while (game.phase === Phase.Building && !game.currentPlayers.includes(0))
|
||||
run(game, pass, game.currentPlayers[0], frame);
|
||||
}
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
type Step = TutorialStep<LessonState, Action>;
|
||||
function actionStep(
|
||||
id: string,
|
||||
title: string,
|
||||
text: string | ((s: LessonState) => string),
|
||||
accepts: (a: Action, s: LessonState) => boolean,
|
||||
complete: (s: LessonState) => boolean,
|
||||
target?: string
|
||||
): Step {
|
||||
return {
|
||||
id,
|
||||
title,
|
||||
text,
|
||||
target,
|
||||
complete,
|
||||
validateMove: (s, a) =>
|
||||
accepts(a, s) ? undefined : 'Follow this step first. ' + (typeof text === 'string' ? text : text(s)),
|
||||
};
|
||||
}
|
||||
const moveIs = (name: MoveName, data?: unknown) => (a: Action) =>
|
||||
a.kind === 'move' &&
|
||||
a.move.name === name &&
|
||||
(data === undefined || JSON.stringify(a.move.data) === JSON.stringify(data));
|
||||
function quiz(id: string, title: string, text: string, answer: string, success: string): Step {
|
||||
return {
|
||||
id,
|
||||
title,
|
||||
text,
|
||||
complete: (s) => s.answer === answer,
|
||||
validateMove: (_s, a) => (a.kind === 'answer' && a.answer === answer ? undefined : 'Not quite. ' + text),
|
||||
success,
|
||||
};
|
||||
}
|
||||
function answers(...labels: string[]): Choice[] {
|
||||
return labels.map((label) => ({ label, action: { kind: 'answer', answer: label } }));
|
||||
}
|
||||
const watch = (label: string): Choice[] => [{ label, action: { kind: 'watch' } }];
|
||||
const watchIs = (a: Action) => a.kind === 'watch';
|
||||
function chapter(
|
||||
id: string,
|
||||
title: string,
|
||||
description: string,
|
||||
initialState: () => LessonState,
|
||||
steps: Step[],
|
||||
completion: { title: string; text: string },
|
||||
choices: Lesson['choices'] = () => []
|
||||
): Lesson {
|
||||
return {
|
||||
game: 'powergrid',
|
||||
id,
|
||||
title,
|
||||
description,
|
||||
version: 1,
|
||||
initialState,
|
||||
steps,
|
||||
completion,
|
||||
move: (s, a, frame) => apply(id, s, a, frame),
|
||||
choices,
|
||||
};
|
||||
}
|
||||
|
||||
export const lessons: Lesson[] = [
|
||||
chapter(
|
||||
'auctions',
|
||||
'Your first power plant',
|
||||
'Read a plant, start an auction and decide how far to bid.',
|
||||
() => state(base()),
|
||||
[
|
||||
{
|
||||
id: 'welcome',
|
||||
title: 'Build a network that you can power',
|
||||
text: 'Buy power plants, buy their fuel, connect cities, then earn income by supplying electricity. At the end, the player who can power the most cities wins. These lessons use Germany and the classic rules with two scripted opponents.',
|
||||
},
|
||||
actionStep(
|
||||
'choose',
|
||||
'Choose plant 4',
|
||||
'Only the four plants in the current market are for sale. Plant 4 burns 2 coal to power 1 city. Its large number is its minimum opening price, not its output. Click plant 4.',
|
||||
moveIs(MoveName.ChoosePowerPlant, 4),
|
||||
(s) => s.game.chosenPowerPlant?.number === 4,
|
||||
'plants'
|
||||
),
|
||||
actionStep(
|
||||
'open',
|
||||
'Open at $4',
|
||||
'Confirm an opening bid of $4 using the auction calculator. Keep some cash for fuel and connections.',
|
||||
moveIs(MoveName.Bid, 4),
|
||||
(s) => s.game.currentBid === 5,
|
||||
'plants'
|
||||
),
|
||||
actionStep(
|
||||
'raise',
|
||||
'Ada offers $5',
|
||||
'Leo has passed. Raise to $6. Once you pass in an auction, you cannot rejoin that auction, but you may compete for a later plant.',
|
||||
moveIs(MoveName.Bid, 6),
|
||||
(s) => has(s, 4),
|
||||
'plants'
|
||||
),
|
||||
actionStep(
|
||||
'others',
|
||||
'One plant per round',
|
||||
'You paid $6 and have $44 left. You cannot buy another plant this round. Watch Ada and Leo buy theirs. Plants are drawn and sorted again after each purchase.',
|
||||
watchIs,
|
||||
inPhase(Phase.Resources)
|
||||
),
|
||||
],
|
||||
{
|
||||
title: 'Ready to buy fuel',
|
||||
text: 'A higher plant number does not necessarily mean better value. Compare its fuel cost and output, then leave money for the rest of the round. In Recharged games, the discount token sets the cheapest market plant’s opening bid to $1, regardless of its printed number.',
|
||||
},
|
||||
(_s, step) => (step === 'others' ? watch('Watch the remaining auctions') : [])
|
||||
),
|
||||
|
||||
chapter(
|
||||
'resources',
|
||||
'Fuel and rising prices',
|
||||
'Buy coal, see prices rise and learn your storage limit.',
|
||||
() => {
|
||||
const game = midgame(Phase.Resources);
|
||||
game.coalSupply += game.coalMarket - 20;
|
||||
game.coalMarket = 20;
|
||||
activate(game, Phase.Resources, [0]);
|
||||
return state(game);
|
||||
},
|
||||
[
|
||||
{
|
||||
id: 'order',
|
||||
title: 'Last in player order buys first',
|
||||
text: 'Fuel is bought in reverse player order. You are last on the order track, so you buy first. Plant 4 needs 2 coal each time it runs and can store 4, enough for two rounds.',
|
||||
},
|
||||
actionStep(
|
||||
'coal-one',
|
||||
'Buy one coal',
|
||||
'Click one coal in the resource market. Each token has its own price, and the cheapest available token is bought first.',
|
||||
(a) =>
|
||||
a.kind === 'move' &&
|
||||
a.move.name === MoveName.BuyResource &&
|
||||
a.move.data.resource === ResourceType.Coal,
|
||||
(s) => you(s).coalLeft === 1,
|
||||
'resources'
|
||||
),
|
||||
actionStep(
|
||||
'coal-two',
|
||||
'Enough for this round',
|
||||
'Buy a second coal. You now have the 2 coal needed to run plant 4 once.',
|
||||
(a) =>
|
||||
a.kind === 'move' &&
|
||||
a.move.name === MoveName.BuyResource &&
|
||||
a.move.data.resource === ResourceType.Coal,
|
||||
(s) => you(s).coalLeft === 2,
|
||||
'resources'
|
||||
),
|
||||
quiz(
|
||||
'price',
|
||||
'What does the next coal cost?',
|
||||
'The two $2 coal are gone. Look at the next occupied market space. What will one more coal cost?',
|
||||
'$3',
|
||||
'Correct! As cheap tokens disappear, later buyers pay more.'
|
||||
),
|
||||
actionStep(
|
||||
'reserve',
|
||||
'Store fuel for next round',
|
||||
'Buy 2 more coal, one at a time. They cost $3 each. This fills your plant’s storage: 4 coal in total.',
|
||||
(a) =>
|
||||
a.kind === 'move' &&
|
||||
a.move.name === MoveName.BuyResource &&
|
||||
a.move.data.resource === ResourceType.Coal,
|
||||
(s) => you(s).coalLeft === 4,
|
||||
'resources'
|
||||
),
|
||||
actionStep(
|
||||
'done',
|
||||
'Finish buying',
|
||||
'You spent $10 and have $40 left. You cannot store a fifth coal or buy fuel that none of your plants can use. Click Done to let Ada buy.',
|
||||
moveIs(MoveName.Pass),
|
||||
(s) => !s.game.currentPlayers.includes(0),
|
||||
'turn'
|
||||
),
|
||||
],
|
||||
{
|
||||
title: 'Fuel is a shared market',
|
||||
text: 'Stored fuel carries over. Used fuel returns to the supply, and the market is refilled after income. Hybrid plants can burn a mix of coal and oil, with one shared storage limit. Wind plants need no fuel.',
|
||||
},
|
||||
(_s, step) => (step === 'price' ? answers('$1', '$2', '$3') : [])
|
||||
),
|
||||
|
||||
chapter(
|
||||
'network',
|
||||
'Connect your cities',
|
||||
'Pay for a city and the cheapest route from your network.',
|
||||
() => {
|
||||
const game = midgame(Phase.Building);
|
||||
own(game, 0, [8]);
|
||||
market(game, [6, 7, 9, 10, 11, 12, 13, 14]);
|
||||
activate(game, Phase.Building, [0]);
|
||||
return state(game);
|
||||
},
|
||||
[
|
||||
actionStep(
|
||||
'first',
|
||||
'Start in Essen',
|
||||
'Your first city costs $10, with no connection fee. Click Essen on the map. In Step 1, each city has room for only one player.',
|
||||
(a) => a.kind === 'move' && a.move.name === MoveName.Build && a.move.data.name === 'Essen',
|
||||
(s) => you(s).cities.length === 1,
|
||||
'destination'
|
||||
),
|
||||
actionStep(
|
||||
'second',
|
||||
'A free connection',
|
||||
'Connect Duisburg. The route from Essen costs $0, so you pay only the $10 city fee. You may connect several cities in one turn.',
|
||||
(a) => a.kind === 'move' && a.move.name === MoveName.Build && a.move.data.name === 'Duisburg',
|
||||
(s) => you(s).cities.length === 2,
|
||||
'destination'
|
||||
),
|
||||
quiz(
|
||||
'route',
|
||||
'What would Düsseldorf cost?',
|
||||
'Düsseldorf has an empty $10 space. The cheapest connection from your network costs $2. What is the total?',
|
||||
'$12',
|
||||
'Correct! $10 for the city plus $2 for the connection.'
|
||||
),
|
||||
actionStep(
|
||||
'third',
|
||||
'Connect Düsseldorf',
|
||||
'Click Düsseldorf and pay $12. The game finds the cheapest route from any city you already own. Routes may pass through other cities without buying a house there.',
|
||||
(a) => a.kind === 'move' && a.move.name === MoveName.Build && a.move.data.name === 'Dusseldorf',
|
||||
(s) => you(s).cities.length === 3,
|
||||
'destination'
|
||||
),
|
||||
actionStep(
|
||||
'done',
|
||||
'Keep some cash',
|
||||
'You have $18 left. Plant 8 can power only 2 of your 3 cities, so expansion alone will not increase this round’s income. Click Done to finish building.',
|
||||
moveIs(MoveName.Pass),
|
||||
inPhase(Phase.Bureaucracy),
|
||||
'turn'
|
||||
),
|
||||
],
|
||||
{
|
||||
title: 'Your network is growing',
|
||||
text: 'Building also follows reverse player order. Plan both your routes and your generating capacity. You can leave cities unpowered; they remain in your network.',
|
||||
},
|
||||
(_s, step) => (step === 'route' ? answers('$2', '$10', '$12') : [])
|
||||
),
|
||||
|
||||
chapter(
|
||||
'income',
|
||||
'Power cities and earn income',
|
||||
'Run your plants, collect income and understand the next turn order.',
|
||||
() => {
|
||||
const game = midgame(Phase.Bureaucracy);
|
||||
own(game, 0, [4, 13]);
|
||||
market(game, [6, 7, 8, 9, 10, 11, 12, 14]);
|
||||
cities(game, 0, ['Essen', 'Duisburg', 'Dusseldorf']);
|
||||
cities(game, 1, ['Hamburg', 'Kiel']);
|
||||
cities(game, 2, ['Hannover']);
|
||||
fuel(game, 0, ResourceType.Coal, 2);
|
||||
fuel(game, 1, ResourceType.Oil, 2);
|
||||
fuel(game, 2, ResourceType.Coal, 2);
|
||||
game.players[0].money = 18;
|
||||
activate(game, Phase.Bureaucracy, [0, 1, 2]);
|
||||
return state(game);
|
||||
},
|
||||
[
|
||||
actionStep(
|
||||
'coal',
|
||||
'Run your coal plant',
|
||||
'Click your plant 4. It consumes 2 coal and supplies 1 city. Each plant can run once per round; you cannot pay extra fuel to run it twice.',
|
||||
(a) => a.kind === 'move' && a.move.name === MoveName.UsePowerPlant && a.move.data.powerPlant === 4,
|
||||
(s) => !you(s).powerPlantsNotUsed.includes(4),
|
||||
'players'
|
||||
),
|
||||
actionStep(
|
||||
'wind',
|
||||
'Free wind power',
|
||||
'Click plant 13. It needs no fuel and supplies 1 more city, bringing your total to 2.',
|
||||
(a) => a.kind === 'move' && a.move.name === MoveName.UsePowerPlant && a.move.data.powerPlant === 13,
|
||||
(s) => you(s).citiesPowered === 2,
|
||||
'players'
|
||||
),
|
||||
actionStep(
|
||||
'pay',
|
||||
'Collect $33',
|
||||
'The $ amounts on the city track show total income: 0 powered cities earns $10, 1 earns $22, 2 earn $33, and 3 earn $44. Your houses mark 3 cities built, but you powered only 2, so collect $33. Click Done.',
|
||||
moveIs(MoveName.Pass),
|
||||
(s) => you(s).money === 51,
|
||||
'turn'
|
||||
),
|
||||
actionStep(
|
||||
'others',
|
||||
'Finish the round',
|
||||
'Watch Ada and Leo run their plants and collect income. The resource market then refills and the plant market changes.',
|
||||
watchIs,
|
||||
(s) => s.game.round === 5
|
||||
),
|
||||
quiz(
|
||||
'order',
|
||||
'Who chooses an auction first?',
|
||||
'You have 3 cities, Ada has 2 and Leo has 1. Most cities goes first; a tie is broken by the highest-numbered plant. Who goes first next round?',
|
||||
'You',
|
||||
'Correct! You choose an auction first, but buy fuel and build last.'
|
||||
),
|
||||
],
|
||||
{
|
||||
title: 'Keep the whole round in mind',
|
||||
text: 'A large network puts you early in the auction order and late in resource buying and building. Sometimes waiting to expand saves money. Even powering no cities normally earns $10.',
|
||||
},
|
||||
(_s, step) =>
|
||||
step === 'others'
|
||||
? watch('Watch income and market upkeep')
|
||||
: step === 'order'
|
||||
? answers('You', 'Ada', 'Leo')
|
||||
: []
|
||||
),
|
||||
|
||||
chapter(
|
||||
'upgrades',
|
||||
'Replace an old power plant',
|
||||
'Upgrade your output while respecting the three-plant limit.',
|
||||
() => {
|
||||
const game = midgame(Phase.Auction);
|
||||
own(game, 0, [4, 8, 13]);
|
||||
market(game, [25, 26, 27, 28, 29, 30, 31, 32]);
|
||||
game.playerOrder = [0, 1, 2];
|
||||
game.players[1].skipAuction = game.players[2].skipAuction = true;
|
||||
activate(game, Phase.Auction, [0]);
|
||||
return state(game);
|
||||
},
|
||||
[
|
||||
actionStep(
|
||||
'buy',
|
||||
'Buy plant 25',
|
||||
'Ada and Leo have already bought this round. Choose plant 25 and confirm the $25 purchase. It uses 2 coal to power 5 cities, compared with just 1 city for plant 4.',
|
||||
moveIs(MoveName.ChoosePowerPlant, 25),
|
||||
(s) => has(s, 25),
|
||||
'plants'
|
||||
),
|
||||
actionStep(
|
||||
'discard',
|
||||
'Keep your best three',
|
||||
'In a three-player game you may keep 3 plants. Click your old plant 4 to discard it. You get no refund. Stored fuel can move to compatible plants, but excess fuel must be discarded.',
|
||||
moveIs(MoveName.DiscardPowerPlant, 4),
|
||||
(s) => !has(s, 4),
|
||||
'players'
|
||||
),
|
||||
],
|
||||
{
|
||||
title: 'More output, less fuel',
|
||||
text: 'Your remaining plants can supply up to 8 cities: 2 + 1 + 5. You still need enough cities and fuel to use that output. The two-player classic game allows 4 plants instead of 3.',
|
||||
}
|
||||
),
|
||||
|
||||
chapter(
|
||||
'steps',
|
||||
'When the game opens up',
|
||||
'Trigger Step 2 and see how Step 3 changes cities and the plant market.',
|
||||
() => {
|
||||
const game = midgame(Phase.Building);
|
||||
cities(game, 0, ['Essen', 'Duisburg', 'Dusseldorf', 'Dortmund', 'Münster', 'Osnabrück']);
|
||||
cities(game, 1, ['Hamburg', 'Kiel']);
|
||||
cities(game, 2, ['Hannover']);
|
||||
market(game, [18, 19, 20, 21, 22, 23, 24, 25]);
|
||||
game.powerPlantsDeck = [plant(26), plant(99)];
|
||||
game.cardsLeft = game.powerPlantsDeck.length;
|
||||
activate(game, Phase.Building, [0]);
|
||||
return state(game);
|
||||
},
|
||||
[
|
||||
actionStep(
|
||||
'seventh',
|
||||
'Connect your seventh city',
|
||||
'Rounds repeat; Steps are larger changes during the game. Here Step 2 will start once someone has 7 cities, after everyone finishes building. Connect Kassel.',
|
||||
(a) => a.kind === 'move' && a.move.name === MoveName.Build && a.move.data.name === 'Kassel',
|
||||
(s) => you(s).cities.length === 7,
|
||||
'destination'
|
||||
),
|
||||
actionStep(
|
||||
'finish',
|
||||
'Finish the building phase',
|
||||
'Click Done. Ada and Leo will also finish, and the game will enter Step 2.',
|
||||
moveIs(MoveName.Pass),
|
||||
(s) => s.game.step === 2,
|
||||
'turn'
|
||||
),
|
||||
quiz(
|
||||
'second-space',
|
||||
'Now two players fit in a city',
|
||||
'In Step 2, a second player may build in an occupied city. That second space costs $15, plus the connection. An empty city still costs $10. Can you build a second house of your own in Essen?',
|
||||
'No',
|
||||
'Correct! Each player may have only one house in each city.'
|
||||
),
|
||||
actionStep(
|
||||
'step-three',
|
||||
'The Step 3 card',
|
||||
'This example is near the end of the plant deck. Finish income and watch the Step 3 card appear during market upkeep.',
|
||||
watchIs,
|
||||
(s) => s.game.step === 3
|
||||
),
|
||||
quiz(
|
||||
'market',
|
||||
'All six are available',
|
||||
'Step 3 allows a third player in each city for $20 plus connections. The plant market has 6 cards and no future market. How many of those plants can be chosen for auction?',
|
||||
'All 6',
|
||||
'Correct! All six market plants are available in Step 3.'
|
||||
),
|
||||
],
|
||||
{
|
||||
title: 'Watch the Step, not just the round',
|
||||
text: 'Step 2 opens second city spaces; Step 3 opens third spaces and the whole plant market. Resource refill rates also change. Other maps and player counts may use different thresholds.',
|
||||
},
|
||||
(_s, step) =>
|
||||
step === 'second-space'
|
||||
? answers('Yes', 'No')
|
||||
: step === 'step-three'
|
||||
? watch('Finish the round')
|
||||
: step === 'market'
|
||||
? answers('Only 4', 'All 6')
|
||||
: []
|
||||
),
|
||||
|
||||
chapter(
|
||||
'final-round',
|
||||
'Who actually wins?',
|
||||
'Trigger the end and compare cities built with cities powered.',
|
||||
() => {
|
||||
const game = midgame(Phase.Building);
|
||||
game.step = 3;
|
||||
game.round = 10;
|
||||
own(game, 0, [20, 29, 32]);
|
||||
own(game, 1, [25, 36, 44]);
|
||||
own(game, 2, [13, 18, 22]);
|
||||
market(game, [30, 31, 33, 34, 35, 37]);
|
||||
const names = game.map.cities.map((c) => c.name);
|
||||
cities(game, 0, names.slice(0, 16));
|
||||
cities(game, 1, names.slice(0, 16));
|
||||
cities(game, 2, names.slice(0, 15));
|
||||
fuel(game, 0, ResourceType.Coal, 4);
|
||||
fuel(game, 0, ResourceType.Oil, 3);
|
||||
fuel(game, 1, ResourceType.Coal, 5);
|
||||
game.players[0].money = 100;
|
||||
activate(game, Phase.Building, [0]);
|
||||
return state(game);
|
||||
},
|
||||
[
|
||||
{
|
||||
id: 'ending',
|
||||
title: 'One last building phase',
|
||||
text: 'On this three-player map, reaching 17 cities triggers the end after everyone finishes building. You and Ada each have 16 cities. You can power 15; Ada can power 16. Building another house will not improve your plants.',
|
||||
},
|
||||
actionStep(
|
||||
'trigger',
|
||||
'Connect a seventeenth city',
|
||||
'Connect any affordable city you do not own. The other players still get to finish this building phase.',
|
||||
(a) => a.kind === 'move' && a.move.name === MoveName.Build,
|
||||
(s) => you(s).cities.length === 17,
|
||||
'map'
|
||||
),
|
||||
quiz(
|
||||
'predict',
|
||||
'Who is ahead?',
|
||||
'You now have 17 cities but can power only 15. Ada has 16 cities and enough plants and fuel to power all 16. Who will win if nobody builds further?',
|
||||
'Ada',
|
||||
'Correct! Powered cities decide the winner, not houses placed.'
|
||||
),
|
||||
actionStep(
|
||||
'finish',
|
||||
'See the result',
|
||||
'Click Done. Ada and Leo will finish without building. The game checks everyone’s plants and stored fuel automatically.',
|
||||
moveIs(MoveName.Pass),
|
||||
inPhase(Phase.GameEnd),
|
||||
'turn'
|
||||
),
|
||||
],
|
||||
{
|
||||
title: 'Power wins the game',
|
||||
text: 'Ada wins with 16 powered cities, ahead of your 15. Remaining cash breaks a tie in powered cities. There is no ordinary income payment at the end, so buy the fuel you need before the final building phase.',
|
||||
},
|
||||
(_s, step) => (step === 'predict' ? answers('You', 'Ada', 'Leo') : [])
|
||||
),
|
||||
];
|
||||
158
viewer/src/tutorial/mount.ts
Normal file
158
viewer/src/tutorial/mount.ts
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
import { createTutorial, TutorialMount, TutorialSnapshot } from '@boardgamers/protocol/tutorial';
|
||||
import { mountTutorialGuide } from '@boardgamers/protocol/tutorial/dom';
|
||||
import { EventEmitter } from 'events';
|
||||
import { GameState, stripSecret } from 'powergrid-engine';
|
||||
import Vue from 'vue';
|
||||
import Game from '../components/Game.vue';
|
||||
import { Action, lessons, LessonState } from './lessons';
|
||||
import './tutorial.css';
|
||||
|
||||
export const mountTutorial: TutorialMount = async (target, { chapter, onProgress, nextChapter }) => {
|
||||
const lesson = lessons.find((entry) => entry.id === chapter);
|
||||
if (!lesson) throw Error('Unknown Powergrid chapter');
|
||||
target.className = 'powergrid-tutorial';
|
||||
const guide = document.createElement('section');
|
||||
const controls = document.createElement('div');
|
||||
controls.className = 'tutorial-answers';
|
||||
controls.setAttribute('aria-label', 'Lesson answers');
|
||||
const summary = document.createElement('div');
|
||||
summary.className = 'tutorial-summary';
|
||||
const board = document.createElement('div');
|
||||
board.className = 'tutorial-board';
|
||||
target.append(guide, controls, summary, board);
|
||||
const emitter = new EventEmitter();
|
||||
const params = {
|
||||
state: null as GameState | null,
|
||||
player: 0,
|
||||
avatars: ['Y', 'A', 'L'].map(
|
||||
(initial) =>
|
||||
'data:image/svg+xml,' +
|
||||
encodeURIComponent(
|
||||
`<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48"><circle cx="24" cy="24" r="23" fill="#233745"/><text x="24" y="31" text-anchor="middle" font-family="sans-serif" font-size="24" fill="white">${initial}</text></svg>`
|
||||
)
|
||||
),
|
||||
tutorialCity: undefined as string | undefined,
|
||||
emitter,
|
||||
preferences: Vue.observable({
|
||||
sound: false,
|
||||
disableHelp: false,
|
||||
adjustPlayerOrder: false,
|
||||
undoWholeTurn: true,
|
||||
fitToScreen: true,
|
||||
stackOnPortrait: true,
|
||||
portraitResourceTrack: false,
|
||||
}),
|
||||
interactionDisabled: false,
|
||||
tutorialMove: (move) => {
|
||||
void play({ kind: 'move', move });
|
||||
},
|
||||
};
|
||||
const app = new Vue({ render: (h) => h(Game, { props: params }) }).$mount(
|
||||
board.appendChild(document.createElement('div'))
|
||||
);
|
||||
let destroyed = false;
|
||||
let animate = false;
|
||||
let timer: number | undefined;
|
||||
let finishFrame: (() => void) | undefined;
|
||||
let latest: TutorialSnapshot<LessonState>;
|
||||
let previous: LessonState | undefined;
|
||||
async function present(game: GameState) {
|
||||
if (destroyed) return;
|
||||
params.state = { ...window.structuredClone(stripSecret(game, 0)), newTurn: true };
|
||||
app.$forceUpdate();
|
||||
await app.$nextTick();
|
||||
}
|
||||
let storage: Storage | undefined;
|
||||
try {
|
||||
storage = localStorage;
|
||||
} catch {
|
||||
/* Saving is optional. */
|
||||
}
|
||||
const controller = await createTutorial({
|
||||
...lesson,
|
||||
storage,
|
||||
onProgress,
|
||||
async move(state, action) {
|
||||
const frames: GameState[] = [];
|
||||
const result = 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) => {
|
||||
finishFrame = resolve;
|
||||
timer = window.setTimeout(
|
||||
resolve,
|
||||
window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 0 : 450
|
||||
);
|
||||
});
|
||||
finishFrame = undefined;
|
||||
}
|
||||
return result;
|
||||
},
|
||||
});
|
||||
async function play(action: Action) {
|
||||
if (destroyed || latest.busy || latest.completed || latest.canContinue) return;
|
||||
animate = true;
|
||||
try {
|
||||
await controller.play(action);
|
||||
} finally {
|
||||
animate = false;
|
||||
}
|
||||
}
|
||||
let controlStep = -1;
|
||||
const off = controller.subscribe((snapshot) => {
|
||||
latest = snapshot;
|
||||
params.tutorialCity = (
|
||||
{ first: 'Essen', second: 'Duisburg', third: 'Dusseldorf', seventh: 'Kassel' } as Record<string, string>
|
||||
)[lesson.steps[snapshot.step]?.id ?? ''];
|
||||
params.interactionDisabled = snapshot.busy || snapshot.completed || snapshot.canContinue;
|
||||
if (previous !== snapshot.state) {
|
||||
previous = snapshot.state;
|
||||
void present(snapshot.state.game);
|
||||
const player = snapshot.state.game.players[0];
|
||||
summary.replaceChildren();
|
||||
for (const text of [
|
||||
`Germany · Classic rules · Round ${snapshot.state.game.round}`,
|
||||
`Cash: $${player.money}`,
|
||||
`Cities: ${player.cities.length}`,
|
||||
`Plant output: ${player.powerPlants.reduce((n, p) => n + p.citiesPowered, 0)}`,
|
||||
`Fuel: ${player.coalLeft} coal · ${player.oilLeft} oil`,
|
||||
]) {
|
||||
const item = document.createElement('span');
|
||||
item.textContent = text;
|
||||
summary.append(item);
|
||||
}
|
||||
}
|
||||
if (controlStep !== snapshot.step) {
|
||||
controlStep = snapshot.step;
|
||||
controls.replaceChildren();
|
||||
for (const choice of lesson.choices(snapshot.state, lesson.steps[snapshot.step]?.id ?? '')) {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.textContent = choice.label;
|
||||
button.onclick = () => {
|
||||
void play(choice.action);
|
||||
};
|
||||
controls.append(button);
|
||||
}
|
||||
controls.hidden = !controls.childElementCount;
|
||||
}
|
||||
controls.querySelectorAll('button').forEach((button) => {
|
||||
button.disabled = snapshot.busy || snapshot.completed;
|
||||
});
|
||||
app.$forceUpdate();
|
||||
});
|
||||
const removeGuide = mountTutorialGuide(guide, controller, { nextChapter });
|
||||
return () => {
|
||||
destroyed = true;
|
||||
clearTimeout(timer);
|
||||
finishFrame?.();
|
||||
removeGuide();
|
||||
off();
|
||||
controller.destroy();
|
||||
emitter.removeAllListeners();
|
||||
app.$destroy();
|
||||
target.replaceChildren();
|
||||
};
|
||||
};
|
||||
135
viewer/src/tutorial/tutorial.css
Normal file
135
viewer/src/tutorial/tutorial.css
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
.powergrid-tutorial {
|
||||
max-width: 1600px;
|
||||
margin: auto;
|
||||
padding: 16px;
|
||||
color: #233745;
|
||||
background: #f0f1e9;
|
||||
font: 16px/1.5 system-ui, sans-serif;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.powergrid-tutorial .bgs-tutorial-guide {
|
||||
background: #fffef5;
|
||||
border: 1px solid #c6cbc4;
|
||||
border-top: 4px solid #3c758a;
|
||||
border-radius: 8px;
|
||||
padding: 16px 20px;
|
||||
}
|
||||
.powergrid-tutorial .bgs-tutorial-heading {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: baseline;
|
||||
gap: 12px;
|
||||
}
|
||||
.powergrid-tutorial .bgs-tutorial-heading strong {
|
||||
font-size: 20px;
|
||||
}
|
||||
.powergrid-tutorial .bgs-tutorial-body p {
|
||||
max-width: 90ch;
|
||||
margin: 12px 0;
|
||||
}
|
||||
.powergrid-tutorial .bgs-tutorial-body small {
|
||||
color: #566870;
|
||||
display: block;
|
||||
margin: 12px 0;
|
||||
}
|
||||
.powergrid-tutorial .bgs-tutorial-body [role='alert'] {
|
||||
color: #a3311d;
|
||||
font-weight: 600;
|
||||
}
|
||||
.powergrid-tutorial .bgs-tutorial-feedback {
|
||||
background: #e0f0df;
|
||||
border-left: 4px solid #45824b;
|
||||
padding: 10px 14px;
|
||||
margin: 12px 0;
|
||||
}
|
||||
.powergrid-tutorial .bgs-tutorial-controls,
|
||||
.powergrid-tutorial .bgs-tutorial-playback,
|
||||
.powergrid-tutorial .bgs-tutorial-help,
|
||||
.powergrid-tutorial .tutorial-answers {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.powergrid-tutorial .bgs-tutorial-playback {
|
||||
flex-wrap: nowrap;
|
||||
}
|
||||
.powergrid-tutorial .bgs-tutorial-help:empty {
|
||||
display: none;
|
||||
}
|
||||
.powergrid-tutorial button {
|
||||
font: inherit;
|
||||
border: 1px solid #96afb5;
|
||||
border-radius: 6px;
|
||||
padding: 8px 12px;
|
||||
min-height: 40px;
|
||||
background: #edf3f2;
|
||||
color: #234250;
|
||||
cursor: pointer;
|
||||
}
|
||||
.powergrid-tutorial button:hover:not(:disabled) {
|
||||
background: #d8e8ea;
|
||||
}
|
||||
.powergrid-tutorial button:focus-visible {
|
||||
outline: 3px solid #267f9f;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.powergrid-tutorial button:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: default;
|
||||
}
|
||||
.powergrid-tutorial .bgs-tutorial-transport {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 40px;
|
||||
flex: 0 0 40px;
|
||||
padding: 0;
|
||||
}
|
||||
.powergrid-tutorial .bgs-tutorial-next-chapter {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
height: 40px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.powergrid-tutorial .bgs-tutorial-guide [hidden],
|
||||
.powergrid-tutorial .tutorial-answers[hidden] {
|
||||
display: none;
|
||||
}
|
||||
.powergrid-tutorial .tutorial-answers {
|
||||
margin-top: 12px;
|
||||
}
|
||||
.powergrid-tutorial .tutorial-summary {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px 24px;
|
||||
padding: 14px 4px;
|
||||
font-size: 13px;
|
||||
color: #536568;
|
||||
}
|
||||
.powergrid-tutorial .tutorial-board {
|
||||
background: white;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.powergrid-tutorial .bgs-tutorial-highlight {
|
||||
outline: 3px solid #d28913;
|
||||
outline-offset: 3px;
|
||||
}
|
||||
@media (max-width: 600px) {
|
||||
.powergrid-tutorial {
|
||||
padding: 8px;
|
||||
font-size: 14px;
|
||||
}
|
||||
.powergrid-tutorial .bgs-tutorial-guide {
|
||||
padding: 12px;
|
||||
}
|
||||
.powergrid-tutorial .bgs-tutorial-heading strong {
|
||||
font-size: 17px;
|
||||
}
|
||||
.powergrid-tutorial .tutorial-summary {
|
||||
gap: 5px 12px;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,8 +1,19 @@
|
|||
// Import vue component
|
||||
import launch from './launch';
|
||||
import { createTutorialLauncher, TutorialLaunchOptions } from '@boardgamers/protocol/tutorial';
|
||||
import launchGame, { destroyViewer } from './launch';
|
||||
import { mountTutorial } from './tutorial/mount';
|
||||
|
||||
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).powergrid = { launch };
|
||||
(window as any).powergrid = { launch, launchTutorial };
|
||||
}
|
||||
|
||||
export default launch;
|
||||
|
|
|
|||
130
viewer/tests/tutorial/lessons.cjs
Normal file
130
viewer/tests/tutorial/lessons.cjs
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
const assert = require('node:assert/strict');
|
||||
const { test } = require('node:test');
|
||||
require('../../../engine/node_modules/ts-node').register({
|
||||
transpileOnly: true,
|
||||
compiler: require.resolve('typescript'),
|
||||
compilerOptions: { module: 'CommonJS', moduleResolution: 'Node', target: 'ES2022', importHelpers: false },
|
||||
});
|
||||
const { createTutorial } = require('@boardgamers/protocol/tutorial');
|
||||
const { stripSecret, playersSortedByScore } = require('../../../engine/src/engine');
|
||||
const { lessons } = require('../../src/tutorial/lessons');
|
||||
const answer = (answer) => ({ kind: 'answer', answer });
|
||||
const play = (name, data) => ({ kind: 'move', move: { name, data } });
|
||||
function actionFor(lesson, snapshot) {
|
||||
const step = lesson.steps[snapshot.step].id;
|
||||
const game = snapshot.state.game;
|
||||
const choices = lesson.choices(snapshot.state, step);
|
||||
if (choices.length === 1) return choices[0].action;
|
||||
const correct = { price: '$3', route: '$12', order: 'You', 'second-space': 'No', market: 'All 6', predict: 'Ada' };
|
||||
if (correct[step]) return answer(correct[step]);
|
||||
if (lesson.id === 'auctions')
|
||||
return step === 'choose' ? play('ChoosePowerPlant', 4) : play('Bid', step === 'open' ? 4 : 6);
|
||||
if (lesson.id === 'resources' && step !== 'done') return play('BuyResource', { resource: 'coal' });
|
||||
if (lesson.id === 'income' && ['coal', 'wind'].includes(step))
|
||||
return play(
|
||||
'UsePowerPlant',
|
||||
game.players[0].availableMoves.UsePowerPlant.find((p) => p.powerPlant === (step === 'coal' ? 4 : 13))
|
||||
);
|
||||
if (lesson.id === 'upgrades') return step === 'buy' ? play('ChoosePowerPlant', 25) : play('DiscardPowerPlant', 4);
|
||||
if (['first', 'second', 'third', 'seventh', 'trigger'].includes(step)) {
|
||||
const names = { first: 'Essen', second: 'Duisburg', third: 'Dusseldorf', seventh: 'Kassel' };
|
||||
const offered = game.players[0].availableMoves.Build;
|
||||
const data = step === 'trigger' ? offered[0] : offered.find((c) => c.name === names[step]);
|
||||
assert.ok(data, `${lesson.id}/${step}: city must be offered by the engine`);
|
||||
return play('Build', data);
|
||||
}
|
||||
return play('Pass', true);
|
||||
}
|
||||
function memory() {
|
||||
const entries = new Map();
|
||||
return { getItem: (key) => entries.get(key) ?? null, setItem: (key, value) => entries.set(key, value) };
|
||||
}
|
||||
for (const lesson of lessons)
|
||||
test(`${lesson.id}: legal walkthrough, rewind and reload`, async () => {
|
||||
const storage = memory();
|
||||
const controller = await createTutorial({ ...lesson, storage });
|
||||
let actions = 0;
|
||||
while (!controller.snapshot.completed && ++actions < 30) {
|
||||
const before = controller.snapshot;
|
||||
const ok = before.canContinue
|
||||
? await controller.continue()
|
||||
: await controller.play(actionFor(lesson, before));
|
||||
assert.equal(ok, true, `${lesson.id}/${lesson.steps[before.step].id}: ${controller.snapshot.error}`);
|
||||
const game = controller.snapshot.state.game;
|
||||
for (const resource of ['coal', 'oil', 'garbage', 'uranium']) {
|
||||
assert.ok(game[resource + 'Supply'] >= 0, `${resource} supply cannot be negative`);
|
||||
assert.ok(game[resource + 'Market'] >= 0);
|
||||
assert.equal(
|
||||
game[resource + 'Supply'] +
|
||||
game[resource + 'Market'] +
|
||||
game.players.reduce((n, p) => n + p[resource + 'Left'], 0),
|
||||
resource === 'uranium' ? 12 : 24
|
||||
);
|
||||
}
|
||||
const hidden = stripSecret(game, 0);
|
||||
assert.deepEqual(hidden.powerPlantsDeck, []);
|
||||
assert.equal(hidden.seed, 'secret');
|
||||
assert.deepEqual(hidden.hiddenLog, []);
|
||||
for (const p of game.players) {
|
||||
assert.ok(p.money >= 0);
|
||||
assert.equal(new Set(p.cities.map((c) => c.name)).size, p.cities.length);
|
||||
assert.ok(p.cities.every((c) => game.map.cities.some((m) => m.name === c.name)));
|
||||
}
|
||||
// Every checkpoint, not only a completed chapter, must survive a reload.
|
||||
const restored = await createTutorial({ ...lesson, storage });
|
||||
assert.deepEqual(restored.snapshot.state, controller.snapshot.state);
|
||||
assert.equal(restored.snapshot.step, controller.snapshot.step);
|
||||
restored.destroy();
|
||||
}
|
||||
assert.equal(controller.snapshot.completed, true);
|
||||
assert.equal(controller.snapshot.canContinue, false);
|
||||
const game = controller.snapshot.state.game;
|
||||
if (lesson.id === 'auctions')
|
||||
assert.deepEqual(
|
||||
game.players.map((p) => p.powerPlants.length),
|
||||
[1, 1, 1]
|
||||
);
|
||||
if (lesson.id === 'resources') assert.equal(game.players[0].money, 40);
|
||||
if (lesson.id === 'network') assert.equal(game.players[0].money, 18);
|
||||
if (lesson.id === 'income') {
|
||||
assert.equal(game.players[0].money, 51);
|
||||
assert.deepEqual(game.playerOrder, [0, 1, 2]);
|
||||
}
|
||||
if (lesson.id === 'upgrades')
|
||||
assert.deepEqual(
|
||||
game.players[0].powerPlants.map((p) => p.number),
|
||||
[8, 13, 25]
|
||||
);
|
||||
if (lesson.id === 'steps') {
|
||||
assert.equal(game.step, 3);
|
||||
assert.equal(game.actualMarket.length, 6);
|
||||
assert.equal(game.futureMarket.length, 0);
|
||||
}
|
||||
if (lesson.id === 'final-round') {
|
||||
assert.equal(playersSortedByScore(game)[0].id, 1);
|
||||
assert.deepEqual(
|
||||
game.players.map((p) => p.citiesPowered),
|
||||
[15, 16, 5]
|
||||
);
|
||||
}
|
||||
await controller.previousStep();
|
||||
assert.equal(controller.snapshot.completed, false);
|
||||
await controller.restart();
|
||||
assert.deepEqual(controller.snapshot.state, lesson.initialState());
|
||||
controller.destroy();
|
||||
});
|
||||
test('wrong answers and unrelated or illegal moves preserve the game', async () => {
|
||||
const lesson = lessons.find((l) => l.id === 'resources');
|
||||
const controller = await createTutorial(lesson);
|
||||
await controller.continue();
|
||||
const before = JSON.stringify(controller.snapshot.state);
|
||||
assert.equal(await controller.play(play('BuyResource', { resource: 'uranium' })), false);
|
||||
assert.equal(JSON.stringify(controller.snapshot.state), before);
|
||||
await controller.play(play('BuyResource', { resource: 'coal' }));
|
||||
await controller.play(play('BuyResource', { resource: 'coal' }));
|
||||
assert.equal(await controller.play(answer('$2')), false);
|
||||
assert.ok(controller.snapshot.error);
|
||||
assert.equal(await controller.play(answer('$3')), true);
|
||||
assert.match(controller.snapshot.feedback, /^Correct!/);
|
||||
controller.destroy();
|
||||
});
|
||||
|
|
@ -12,7 +12,7 @@
|
|||
"noImplicitAny": false,
|
||||
"sourceMap": true,
|
||||
"baseUrl": ".",
|
||||
"types": ["webpack-env", "mocha", "chai"],
|
||||
"types": ["webpack-env", "mocha", "chai", "node"],
|
||||
"paths": {
|
||||
"@/*": ["src/*"]
|
||||
},
|
||||
|
|
|
|||
|
|
@ -46,6 +46,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