Add Power Grid endgame achievements for coordinator review
This commit is contained in:
parent
abe1c841bd
commit
c8aae01636
9 changed files with 557 additions and 28 deletions
63
docs/achievements.md
Normal file
63
docs/achievements.md
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
# Power Grid achievements (review candidate)
|
||||
|
||||
This feature is **not published**. The engine version remains 2.0.31 pending coordinator review and release version allocation. No viewer or production assets change.
|
||||
|
||||
## Contract
|
||||
|
||||
`engine/wrapper.ts` exports the optional `achievementDefinitions()` and `achievements(data)` hooks. Both use the published `@boardgamers/protocol@0.11.0` `/engine` types. The manifest has revision 1. IDs are stable game-local identifiers: do not rename or reuse them after publication. Future definition changes require a manifest revision bump. Icons are omitted, allowing platform fallback icons; no asset upload is needed.
|
||||
|
||||
The input is the deserialized, authoritative saved `GameState`, not a viewer payload or client-supplied achievement claim. Evaluation is pure, repeatable, and does not store counters or mutate state. Results use player-array indexes as seats. The hook returns nothing for unfinished, tentative, analysis/simulation, or fewer-than-two-player states. Power Grid has no standalone solo rules; a human against bots competes normally and receives an explicit win/loss outcome.
|
||||
|
||||
Final `citiesPowered` is the engine's official fuel-constrained, network-capped score, calculated after Building. There is no final plant-use round. Portfolio feats measure owned printed capacity, not generated electricity. Money is the final balance, including any map-specific end payouts.
|
||||
|
||||
Winning follows the existing three tie breakers: powered cities, money, built cities. Exact tied leaders are co-winners (`outcome: "win"`); all other eligible seats have `outcome: "loss"`. Bots and dropped players remain in the standings, but engine-known AI and dropped seats receive no results. Non-winning feats are independent of victory.
|
||||
|
||||
## Manifest
|
||||
|
||||
| ID | Name | Condition at completion |
|
||||
| ------------------- | ----------------- | ---------------------------------------------------------------------------- |
|
||||
| `grid-champion` | Grid Champion | Win (including shared first place). |
|
||||
| `head-to-head` | Head to Head | Win with two seats. |
|
||||
| `full-table` | Full Table | Win with six seats. |
|
||||
| `germany-champion` | Germany Champion | Win on Germany. |
|
||||
| `usa-champion` | USA Champion | Win on USA. |
|
||||
| `france-champion` | France Champion | Win on France. |
|
||||
| `japan-champion` | Japan Champion | Win on Japan. |
|
||||
| `power-fifteen` | Power Fifteen | Able to power at least 15 owned cities. |
|
||||
| `power-eighteen` | Power Eighteen | Able to power at least 18 owned cities. |
|
||||
| `fully-supplied` | Fully Supplied | Able to power every owned city, with at least 10 owned. |
|
||||
| `network-seventeen` | Network Seventeen | Own at least 17 cities. |
|
||||
| `network-twenty` | Network Twenty | Own at least 20 cities. |
|
||||
| `cash-reserve` | Cash Reserve | At least 100 Elektro. |
|
||||
| `deep-reserves` | Deep Reserves | At least 200 Elektro. |
|
||||
| `wind-farm` | Wind Farm | Owned Wind plants total at least 8 printed capacity. |
|
||||
| `atomic-power` | Atomic Power | Owned Uranium plants total at least 8 printed capacity, excluding Australia. |
|
||||
|
||||
`PowerPlantType.Nuclear` means fuel-free fusion in this engine and does not count as wind or uranium-fuelled capacity. On Australia, Uranium plants are mines, not generators. Conditions use types/output rather than card numbers so alternate and shuffled decks work too. Map feats use the resolved `data.map.name`, including games created with Random map selection.
|
||||
|
||||
## Server eligibility boundary
|
||||
|
||||
Power Grid state contains neither platform account identities nor cancellation metadata. The existing BGS achievement capture/adjudication path must remain enabled: it captures first natural completion only, rejects cancelled/claimed-win/edited-solo games, and excludes platform bot/dropped/quit seats before persisting human awards. In particular, BGS does **not** propagate `isBot` into Power Grid's `isAI`; `isAI === false` alone is not proof of a human account. Do not call these hooks directly to persist user awards outside that server path. Host-side evidence and award deduplication remain authoritative.
|
||||
|
||||
Analysis constructors and moves mark their copies with `achievementAnalysis: true`; full wrapper replay preserves this exclusion. Older analyses may not have the marker, so the host's analysis isolation is still required. Ordinary historical replay is a pure engine operation, not permission to backfill achievements.
|
||||
|
||||
## Review verification
|
||||
|
||||
- Full engine suite: **625 passing**, including **50 achievement tests**.
|
||||
- Engine build and published protocol 0.11.0 manifest/result schema validation: passed.
|
||||
- Engine lint: passed with existing warning-level findings, no errors.
|
||||
- Viewer unit suite: **102 passing**.
|
||||
- Viewer production package and bundle-size check: passed (`NODE_OPTIONS=--openssl-legacy-provider pnpm --filter powergrid-viewer package`).
|
||||
- Frozen pnpm installation, changed-file formatting, and whitespace checks: passed.
|
||||
- A read-only review confirmed the win rules and that the capacity/network thresholds are reachable with actual plants and house limits.
|
||||
|
||||
An earlier full engine run concurrent with builds hit two 2-second replay-test timeouts; the final full run passed with the normal timeout. Viewer tests were also rerun successfully after an overlapping engine clean/build temporarily removed their imports. No gameplay assertions were relaxed.
|
||||
|
||||
## Validation and release prerequisites
|
||||
|
||||
- Run `pnpm install --frozen-lockfile`, `pnpm --filter powergrid-engine test`, and `pnpm --filter powergrid-engine test:achievements` (builds and validates the compiled hooks with the published protocol's runtime schemas).
|
||||
- Engine TypeScript is pinned to the 4.9 minor line to resolve the protocol's CommonJS `.d.cts` declarations while retaining compatibility with the existing ESLint parser and Node type declarations. The legacy npm lockfile is already stale; pnpm and `engine/pnpm-lock.yaml` are authoritative.
|
||||
- Review all 16 IDs/descriptions, thresholds, tie semantics, and human-versus-bot policy with the coordinator.
|
||||
- Validate the compiled hooks against protocol manifest/result schemas and the actual BGS install/adjudication path before release, including cancellation, bot/account filtering, duplicate completion, and edited-solo exclusions. Unit tests cannot substitute for server-owned eligibility checks.
|
||||
- After approval, allocate an engine release version, fetch/integrate the latest canonical release, rerun relevant checks, and publish through the existing engine release workflow. Verify the installed artifact contains both hooks and the expected manifest revision. No artwork is required.
|
||||
- Only when authorized to publish: follow AGENTS.md's corresponding source/lockfile/version commit, canonical release-branch push, public mirror update, and remote-delivery verification requirements. This feature branch intentionally performs none of those production actions.
|
||||
|
|
@ -24,9 +24,11 @@
|
|||
"build": "npm run clean && tsc",
|
||||
"clean": "rm -Rf dist",
|
||||
"lint": "eslint . --ext .ts",
|
||||
"test": "mocha -r ts-node/register src/*.spec.ts"
|
||||
"test": "mocha -r ts-node/register src/*.spec.ts",
|
||||
"test:achievements": "npm run build && node scripts/check-achievements.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@boardgamers/protocol": "0.11.0",
|
||||
"delaunator": "^4.0.0",
|
||||
"lodash": "^4.17.15",
|
||||
"seedrandom": "^3.0.5"
|
||||
|
|
@ -48,7 +50,7 @@
|
|||
"eslint-plugin-standard": "^4.0.1",
|
||||
"mocha": "^5.0.4",
|
||||
"ts-node": "^10.0.0",
|
||||
"typescript": "^4.3.5"
|
||||
"typescript": "~4.9.5"
|
||||
},
|
||||
"files": [
|
||||
"index.ts",
|
||||
|
|
|
|||
70
engine/pnpm-lock.yaml
generated
70
engine/pnpm-lock.yaml
generated
|
|
@ -1,6 +1,7 @@
|
|||
lockfileVersion: 5.4
|
||||
|
||||
specifiers:
|
||||
'@boardgamers/protocol': 0.11.0
|
||||
'@types/chai': ^4.1.2
|
||||
'@types/delaunator': ^5.0.0
|
||||
'@types/lodash': ^4.14.149
|
||||
|
|
@ -20,9 +21,10 @@ specifiers:
|
|||
mocha: ^5.0.4
|
||||
seedrandom: ^3.0.5
|
||||
ts-node: ^10.0.0
|
||||
typescript: ^4.3.5
|
||||
typescript: ~4.9.5
|
||||
|
||||
dependencies:
|
||||
'@boardgamers/protocol': 0.11.0
|
||||
delaunator: 4.0.1
|
||||
lodash: 4.17.21
|
||||
seedrandom: 3.0.5
|
||||
|
|
@ -34,8 +36,8 @@ devDependencies:
|
|||
'@types/mocha': 2.2.48
|
||||
'@types/node': 13.13.52
|
||||
'@types/seedrandom': 2.4.29
|
||||
'@typescript-eslint/eslint-plugin': 4.33.0_3s5uzttgihg5npsrml7yxot2u4
|
||||
'@typescript-eslint/parser': 4.33.0_ormy72tqrapqsntr3tx5lktgaq
|
||||
'@typescript-eslint/eslint-plugin': 4.33.0_mwzqnpd2hrrrc77iluqlfbmau4
|
||||
'@typescript-eslint/parser': 4.33.0_ctsd2flwymlv6mmuvfrerpxqom
|
||||
chai: 4.3.4
|
||||
eslint: 6.8.0
|
||||
eslint-plugin-import: 2.23.4_inh3l5yejh4yosh34bfcghfssa
|
||||
|
|
@ -43,8 +45,8 @@ devDependencies:
|
|||
eslint-plugin-promise: 4.3.1
|
||||
eslint-plugin-standard: 4.1.0_eslint@6.8.0
|
||||
mocha: 5.2.0
|
||||
ts-node: 10.0.0_p45ebbtpha2zic2ooe2cmqv2ru
|
||||
typescript: 4.3.5
|
||||
ts-node: 10.0.0_t4ean5glospg25dwgpqr53g2si
|
||||
typescript: 4.9.5
|
||||
|
||||
packages:
|
||||
/@babel/code-frame/7.14.5:
|
||||
|
|
@ -77,6 +79,15 @@ packages:
|
|||
js-tokens: 4.0.0
|
||||
dev: true
|
||||
|
||||
/@boardgamers/protocol/0.11.0:
|
||||
resolution:
|
||||
{
|
||||
integrity: sha512-YQ54+aVOIZvxUJvFmUbZR7xSBEgQaemstPdmYKVGCUHCviRX2UXRLgqLSQl6PFhr++lUT+Nynbf+p7h19zN+/g==,
|
||||
}
|
||||
dependencies:
|
||||
zod: 4.6.7
|
||||
dev: false
|
||||
|
||||
/@nodelib/fs.scandir/2.1.5:
|
||||
resolution:
|
||||
{
|
||||
|
|
@ -191,7 +202,7 @@ packages:
|
|||
}
|
||||
dev: true
|
||||
|
||||
/@typescript-eslint/eslint-plugin/4.33.0_3s5uzttgihg5npsrml7yxot2u4:
|
||||
/@typescript-eslint/eslint-plugin/4.33.0_mwzqnpd2hrrrc77iluqlfbmau4:
|
||||
resolution:
|
||||
{
|
||||
integrity: sha512-aINiAxGVdOl1eJyVjaWn/YcVAq4Gi/Yo35qHGCnqbWVz61g39D0h23veY/MA0rFFGfxK7TySg2uwDeNv+JgVpg==,
|
||||
|
|
@ -205,8 +216,8 @@ packages:
|
|||
typescript:
|
||||
optional: true
|
||||
dependencies:
|
||||
'@typescript-eslint/experimental-utils': 4.33.0_ormy72tqrapqsntr3tx5lktgaq
|
||||
'@typescript-eslint/parser': 4.33.0_ormy72tqrapqsntr3tx5lktgaq
|
||||
'@typescript-eslint/experimental-utils': 4.33.0_ctsd2flwymlv6mmuvfrerpxqom
|
||||
'@typescript-eslint/parser': 4.33.0_ctsd2flwymlv6mmuvfrerpxqom
|
||||
'@typescript-eslint/scope-manager': 4.33.0
|
||||
debug: 4.3.1
|
||||
eslint: 6.8.0
|
||||
|
|
@ -214,13 +225,13 @@ packages:
|
|||
ignore: 5.1.8
|
||||
regexpp: 3.2.0
|
||||
semver: 7.3.5
|
||||
tsutils: 3.21.0_typescript@4.3.5
|
||||
typescript: 4.3.5
|
||||
tsutils: 3.21.0_typescript@4.9.5
|
||||
typescript: 4.9.5
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
dev: true
|
||||
|
||||
/@typescript-eslint/experimental-utils/4.33.0_ormy72tqrapqsntr3tx5lktgaq:
|
||||
/@typescript-eslint/experimental-utils/4.33.0_ctsd2flwymlv6mmuvfrerpxqom:
|
||||
resolution:
|
||||
{
|
||||
integrity: sha512-zeQjOoES5JFjTnAhI5QY7ZviczMzDptls15GFsI6jyUOq0kOf9+WonkhtlIhh0RgHRnqj5gdNxW5j1EvAyYg6Q==,
|
||||
|
|
@ -232,7 +243,7 @@ packages:
|
|||
'@types/json-schema': 7.0.7
|
||||
'@typescript-eslint/scope-manager': 4.33.0
|
||||
'@typescript-eslint/types': 4.33.0
|
||||
'@typescript-eslint/typescript-estree': 4.33.0_typescript@4.3.5
|
||||
'@typescript-eslint/typescript-estree': 4.33.0_typescript@4.9.5
|
||||
eslint: 6.8.0
|
||||
eslint-scope: 5.1.1
|
||||
eslint-utils: 3.0.0_eslint@6.8.0
|
||||
|
|
@ -241,7 +252,7 @@ packages:
|
|||
- typescript
|
||||
dev: true
|
||||
|
||||
/@typescript-eslint/parser/4.33.0_ormy72tqrapqsntr3tx5lktgaq:
|
||||
/@typescript-eslint/parser/4.33.0_ctsd2flwymlv6mmuvfrerpxqom:
|
||||
resolution:
|
||||
{
|
||||
integrity: sha512-ZohdsbXadjGBSK0/r+d87X0SBmKzOq4/S5nzK6SBgJspFo9/CUDJ7hjayuze+JK7CZQLDMroqytp7pOcFKTxZA==,
|
||||
|
|
@ -256,10 +267,10 @@ packages:
|
|||
dependencies:
|
||||
'@typescript-eslint/scope-manager': 4.33.0
|
||||
'@typescript-eslint/types': 4.33.0
|
||||
'@typescript-eslint/typescript-estree': 4.33.0_typescript@4.3.5
|
||||
'@typescript-eslint/typescript-estree': 4.33.0_typescript@4.9.5
|
||||
debug: 4.3.1
|
||||
eslint: 6.8.0
|
||||
typescript: 4.3.5
|
||||
typescript: 4.9.5
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
dev: true
|
||||
|
|
@ -283,7 +294,7 @@ packages:
|
|||
engines: { node: ^8.10.0 || ^10.13.0 || >=11.10.1 }
|
||||
dev: true
|
||||
|
||||
/@typescript-eslint/typescript-estree/4.33.0_typescript@4.3.5:
|
||||
/@typescript-eslint/typescript-estree/4.33.0_typescript@4.9.5:
|
||||
resolution:
|
||||
{
|
||||
integrity: sha512-rkWRY1MPFzjwnEVHsxGemDzqqddw2QbTJlICPD9p9I9LfsO8fdmfQPOX3uKfUaGRDFJbfrtm/sXhVXN4E+bzCA==,
|
||||
|
|
@ -301,8 +312,8 @@ packages:
|
|||
globby: 11.1.0
|
||||
is-glob: 4.0.1
|
||||
semver: 7.3.5
|
||||
tsutils: 3.21.0_typescript@4.3.5
|
||||
typescript: 4.3.5
|
||||
tsutils: 3.21.0_typescript@4.9.5
|
||||
typescript: 4.9.5
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
dev: true
|
||||
|
|
@ -906,7 +917,7 @@ packages:
|
|||
eslint-import-resolver-webpack:
|
||||
optional: true
|
||||
dependencies:
|
||||
'@typescript-eslint/parser': 4.33.0_ormy72tqrapqsntr3tx5lktgaq
|
||||
'@typescript-eslint/parser': 4.33.0_ctsd2flwymlv6mmuvfrerpxqom
|
||||
debug: 3.2.7
|
||||
eslint-import-resolver-node: 0.3.4
|
||||
pkg-dir: 2.0.0
|
||||
|
|
@ -941,7 +952,7 @@ packages:
|
|||
'@typescript-eslint/parser':
|
||||
optional: true
|
||||
dependencies:
|
||||
'@typescript-eslint/parser': 4.33.0_ormy72tqrapqsntr3tx5lktgaq
|
||||
'@typescript-eslint/parser': 4.33.0_ctsd2flwymlv6mmuvfrerpxqom
|
||||
array-includes: 3.1.3
|
||||
array.prototype.flat: 1.2.4
|
||||
debug: 2.6.9
|
||||
|
|
@ -2542,7 +2553,7 @@ packages:
|
|||
is-number: 7.0.0
|
||||
dev: true
|
||||
|
||||
/ts-node/10.0.0_p45ebbtpha2zic2ooe2cmqv2ru:
|
||||
/ts-node/10.0.0_t4ean5glospg25dwgpqr53g2si:
|
||||
resolution:
|
||||
{
|
||||
integrity: sha512-ROWeOIUvfFbPZkoDis0L/55Fk+6gFQNZwwKPLinacRl6tsxstTF1DbAcLKkovwnpKMVvOMHP1TIbnwXwtLg1gg==,
|
||||
|
|
@ -2570,7 +2581,7 @@ packages:
|
|||
diff: 4.0.2
|
||||
make-error: 1.3.6
|
||||
source-map-support: 0.5.19
|
||||
typescript: 4.3.5
|
||||
typescript: 4.9.5
|
||||
yn: 3.1.1
|
||||
dev: true
|
||||
|
||||
|
|
@ -2593,7 +2604,7 @@ packages:
|
|||
}
|
||||
dev: true
|
||||
|
||||
/tsutils/3.21.0_typescript@4.3.5:
|
||||
/tsutils/3.21.0_typescript@4.9.5:
|
||||
resolution:
|
||||
{
|
||||
integrity: sha512-mHKK3iUXL+3UF6xL5k0PEhKRUBKPBCv/+RkEOpjRWxxx27KKRBmmA60A9pgOUvMi8GKhRMPEmjBRPzs2W7O1OA==,
|
||||
|
|
@ -2603,7 +2614,7 @@ packages:
|
|||
typescript: '>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta'
|
||||
dependencies:
|
||||
tslib: 1.14.1
|
||||
typescript: 4.3.5
|
||||
typescript: 4.9.5
|
||||
dev: true
|
||||
|
||||
/type-check/0.3.2:
|
||||
|
|
@ -2637,10 +2648,10 @@ packages:
|
|||
engines: { node: '>=8' }
|
||||
dev: true
|
||||
|
||||
/typescript/4.3.5:
|
||||
/typescript/4.9.5:
|
||||
resolution:
|
||||
{
|
||||
integrity: sha512-DqQgihaQ9cUrskJo9kIyW/+g0Vxsk8cDtZ52a3NGh0YNTfpUSArXSohyUGnvbPazEPLu398C0UxmKSOrPumUzA==,
|
||||
integrity: sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==,
|
||||
}
|
||||
engines: { node: '>=4.2.0' }
|
||||
hasBin: true
|
||||
|
|
@ -2746,3 +2757,10 @@ packages:
|
|||
}
|
||||
engines: { node: '>=6' }
|
||||
dev: true
|
||||
|
||||
/zod/4.6.7:
|
||||
resolution:
|
||||
{
|
||||
integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==,
|
||||
}
|
||||
dev: false
|
||||
|
|
|
|||
23
engine/scripts/check-achievements.mjs
Normal file
23
engine/scripts/check-achievements.mjs
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { achievementManifestSchema, achievementResultsSchema } from '@boardgamers/protocol/achievements';
|
||||
import wrapper from '../dist/wrapper.js';
|
||||
|
||||
// Exercise the published protocol's runtime validators against the compiled BGS
|
||||
// entry point, not local copies of the contract or TypeScript-only assertions.
|
||||
const manifest = wrapper.achievementDefinitions();
|
||||
achievementManifestSchema.parse(manifest);
|
||||
assert.equal(manifest.revision, 1);
|
||||
assert.equal(manifest.achievements.length, 16);
|
||||
for (const fixture of ['GermanyRecharged', 'USAOriginal']) {
|
||||
const data = JSON.parse(readFileSync(new URL(`../src/fixtures/${fixture}.json`, import.meta.url), 'utf8'));
|
||||
const completed = wrapper.replay(data);
|
||||
const results = wrapper.achievements(completed);
|
||||
achievementResultsSchema(manifest, completed.players.length).parse(results);
|
||||
assert.equal(results.length, completed.players.length);
|
||||
assert.deepEqual(
|
||||
results.map((result) => result.outcome),
|
||||
wrapper.rankings(completed).map((rank) => (rank === 1 ? 'win' : 'loss'))
|
||||
);
|
||||
}
|
||||
console.log('Published protocol 0.11.0 validates compiled achievement manifest and fixture results.');
|
||||
311
engine/src/achievements.spec.ts
Normal file
311
engine/src/achievements.spec.ts
Normal file
|
|
@ -0,0 +1,311 @@
|
|||
import { expect } from 'chai';
|
||||
import { cloneDeep } from 'lodash';
|
||||
import 'mocha';
|
||||
import * as wrapper from '../wrapper';
|
||||
import { achievementDefinitions, achievements } from './achievements';
|
||||
import { createAnalysisScenario } from './analysis';
|
||||
import { setup } from './engine';
|
||||
import GermanyRecharged from './fixtures/GermanyRecharged.json';
|
||||
import USAOriginal from './fixtures/USAOriginal.json';
|
||||
import { GameState, MapName, Phase, Player, PowerPlantType } from './gamestate';
|
||||
import { LogMove } from './log';
|
||||
|
||||
const ids = [
|
||||
'grid-champion',
|
||||
'head-to-head',
|
||||
'full-table',
|
||||
'germany-champion',
|
||||
'usa-champion',
|
||||
'france-champion',
|
||||
'japan-champion',
|
||||
'power-fifteen',
|
||||
'power-eighteen',
|
||||
'fully-supplied',
|
||||
'network-seventeen',
|
||||
'network-twenty',
|
||||
'cash-reserve',
|
||||
'deep-reserves',
|
||||
'wind-farm',
|
||||
'atomic-power',
|
||||
];
|
||||
|
||||
// Deliberately synthetic final positions: setup supplies the complete state shape,
|
||||
// but these boundary tests do not claim their scores came from legal game play.
|
||||
function finalState(count = 2, map: MapName = 'Germany'): GameState {
|
||||
const state = setup(count, { map }, 'achievement-boundaries');
|
||||
state.phase = Phase.GameEnd;
|
||||
state.newTurn = true;
|
||||
state.currentPlayers = [];
|
||||
state.players.forEach((p) => {
|
||||
p.citiesPowered = 0;
|
||||
p.money = 0;
|
||||
p.cities = [];
|
||||
p.powerPlants = [];
|
||||
});
|
||||
return state;
|
||||
}
|
||||
|
||||
function cities(player: Player, count: number) {
|
||||
player.cities = Array.from({ length: count }, (_, i) => ({ name: `Synthetic city ${i}`, position: 0 }));
|
||||
}
|
||||
|
||||
function earned(state: GameState, seat = 0): string[] {
|
||||
return achievements(state).find((result) => result.seat === seat)!.earned;
|
||||
}
|
||||
|
||||
function freezeDeep(value: unknown) {
|
||||
if (value && typeof value === 'object' && !Object.isFrozen(value)) {
|
||||
Object.values(value).forEach(freezeDeep);
|
||||
Object.freeze(value);
|
||||
}
|
||||
}
|
||||
|
||||
describe('achievements', function () {
|
||||
this.timeout(30000);
|
||||
|
||||
it('publishes all 16 stable IDs in a fresh revisioned manifest', () => {
|
||||
const manifest = achievementDefinitions();
|
||||
expect(manifest.revision).to.equal(1);
|
||||
expect(manifest.achievements.map((a) => a.id)).to.deep.equal(ids);
|
||||
expect(new Set(ids).size).to.equal(16);
|
||||
manifest.achievements.forEach((a) => {
|
||||
expect(a.name).to.be.a('string').and.not.equal('');
|
||||
expect(a.description).to.be.a('string').and.not.equal('');
|
||||
});
|
||||
const original = cloneDeep(manifest);
|
||||
manifest.achievements[0].name = 'Changed by host';
|
||||
manifest.achievements.pop();
|
||||
expect(achievementDefinitions()).to.deep.equal(original);
|
||||
expect(wrapper.achievementDefinitions()).to.deep.equal(original);
|
||||
});
|
||||
|
||||
for (const map of ['Germany', 'USA', 'France', 'Japan'] as MapName[]) {
|
||||
for (const count of [2, 6]) {
|
||||
it(`awards only the ${map} and ${count}-seat win predicates to the winner`, () => {
|
||||
const state = finalState(count, map);
|
||||
state.players[1].citiesPowered = 1;
|
||||
const expected = [
|
||||
'grid-champion',
|
||||
count === 2 ? 'head-to-head' : 'full-table',
|
||||
`${map.toLowerCase()}-champion`,
|
||||
];
|
||||
expect(earned(state, 1)).to.deep.equal(expected);
|
||||
expect(earned(state)).to.deep.equal([]);
|
||||
expect(achievements(state).map((r) => r.outcome)).to.deep.equal(
|
||||
state.players.map((_, seat) => (seat === 1 ? 'win' : 'loss'))
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (const [id, field, threshold] of [
|
||||
['power-fifteen', 'power', 15],
|
||||
['power-eighteen', 'power', 18],
|
||||
['network-seventeen', 'cities', 17],
|
||||
['network-twenty', 'cities', 20],
|
||||
['cash-reserve', 'money', 100],
|
||||
['deep-reserves', 'money', 200],
|
||||
] as const) {
|
||||
for (const value of [threshold - 1, threshold, threshold + 1]) {
|
||||
it(`${id}: ${field} ${value} is ${value >= threshold ? 'eligible' : 'ineligible'}`, () => {
|
||||
const state = finalState();
|
||||
// A losing player can still earn every non-victory achievement.
|
||||
state.players[1].citiesPowered = 100;
|
||||
if (field === 'cities') cities(state.players[0], value);
|
||||
else if (field === 'power') state.players[0].citiesPowered = value;
|
||||
else state.players[0].money = value;
|
||||
expect(earned(state).includes(id)).to.equal(value >= threshold);
|
||||
expect(achievements(state)[0].outcome).to.equal('loss');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (const [network, power, eligible] of [
|
||||
[9, 9, false],
|
||||
[10, 9, false],
|
||||
[10, 10, true],
|
||||
[10, 11, false],
|
||||
[11, 11, true],
|
||||
] as const) {
|
||||
it(`fully supplied requires at least ten cities and exact supply (${network}/${power})`, () => {
|
||||
const state = finalState();
|
||||
cities(state.players[0], network);
|
||||
state.players[0].citiesPowered = power;
|
||||
expect(earned(state).includes('fully-supplied')).to.equal(eligible);
|
||||
});
|
||||
}
|
||||
|
||||
for (const [type, id] of [
|
||||
[PowerPlantType.Wind, 'wind-farm'],
|
||||
[PowerPlantType.Uranium, 'atomic-power'],
|
||||
] as const) {
|
||||
for (const capacity of [7, 8, 9]) {
|
||||
it(`${id} sums owned capacity at ${capacity}, independent of fuel and powered cities`, () => {
|
||||
const state = finalState();
|
||||
state.players[0].powerPlants = [
|
||||
{ number: 100, type, cost: 2, citiesPowered: 3 },
|
||||
{ number: 101, type, cost: 2, citiesPowered: capacity - 3 },
|
||||
];
|
||||
expect(earned(state).includes(id)).to.equal(capacity >= 8);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
it('does not count Australian uranium mines or fusion as uranium-fuelled or wind plants', () => {
|
||||
const state = finalState(2, 'Australia');
|
||||
state.players[0].powerPlants = [{ number: 50, type: PowerPlantType.Uranium, cost: 2, citiesPowered: 8 }];
|
||||
expect(earned(state)).not.to.include('atomic-power');
|
||||
expect(earned(state).filter((id) => id.endsWith('-champion'))).to.deep.equal(['grid-champion']);
|
||||
for (const map of ['Australia', 'Germany'] as MapName[]) {
|
||||
const fusion = finalState(2, map);
|
||||
fusion.players[0].powerPlants = [{ number: 50, type: PowerPlantType.Nuclear, cost: 0, citiesPowered: 8 }];
|
||||
expect(earned(fusion)).not.to.include('atomic-power');
|
||||
expect(earned(fusion)).not.to.include('wind-farm');
|
||||
}
|
||||
});
|
||||
|
||||
it('uses power, then money, then cities for ranks, with exact co-winners', () => {
|
||||
const state = finalState(6);
|
||||
const scores = [
|
||||
[18, 100, 20],
|
||||
[18, 100, 20],
|
||||
[18, 100, 19],
|
||||
[18, 99, 21],
|
||||
[17, 200, 22],
|
||||
[16, 300, 23],
|
||||
];
|
||||
scores.forEach(([power, money, network], seat) => {
|
||||
state.players[seat].citiesPowered = power;
|
||||
state.players[seat].money = money;
|
||||
cities(state.players[seat], network);
|
||||
});
|
||||
expect(wrapper.rankings(state)).to.deep.equal([1, 1, 3, 4, 5, 6]);
|
||||
expect(achievements(state).map((r) => r.outcome)).to.deep.equal(['win', 'win', 'loss', 'loss', 'loss', 'loss']);
|
||||
expect(earned(state, 0)).to.include('grid-champion');
|
||||
expect(earned(state, 1)).to.include('grid-champion');
|
||||
expect(earned(state, 2)).not.to.include('grid-champion');
|
||||
});
|
||||
|
||||
for (const flag of ['isAI', 'isDropped'] as const) {
|
||||
it(`omits ${flag} seats without removing them from competition or renumbering seats`, () => {
|
||||
const state = finalState(3);
|
||||
state.players[0][flag] = true;
|
||||
state.players[0].citiesPowered = 20;
|
||||
expect(achievements(state).map((r) => [r.seat, r.outcome])).to.deep.equal([
|
||||
[1, 'loss'],
|
||||
[2, 'loss'],
|
||||
]);
|
||||
state.players[1].citiesPowered = 20;
|
||||
expect(achievements(state).map((r) => [r.seat, r.outcome])).to.deep.equal([
|
||||
[1, 'win'],
|
||||
[2, 'loss'],
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
for (const win of [false, true]) {
|
||||
it(`reports an explicit ${win ? 'win' : 'loss'} for the only human against bots`, () => {
|
||||
const state = finalState(6);
|
||||
state.players.forEach((p, seat) => {
|
||||
p.isAI = seat !== 3;
|
||||
p.citiesPowered = 10;
|
||||
});
|
||||
state.players[3].citiesPowered = win ? 11 : 9;
|
||||
const result = achievements(state);
|
||||
expect(result).to.have.length(1);
|
||||
expect(result[0].seat).to.equal(3);
|
||||
expect(result[0].outcome).to.equal(win ? 'win' : 'loss');
|
||||
expect(result[0].earned.includes('full-table')).to.equal(win);
|
||||
});
|
||||
}
|
||||
|
||||
it('excludes unfinished, tentative, hypothetical and analysis states', () => {
|
||||
expect(achievements(setup(2, {}, 'unfinished'))).to.deep.equal([]);
|
||||
const state = finalState();
|
||||
state.newTurn = false;
|
||||
expect(achievements(state)).to.deep.equal([]);
|
||||
state.newTurn = true;
|
||||
state.analysisMoney = 'hypothetical';
|
||||
expect(achievements(state)).to.deep.equal([]);
|
||||
delete state.analysisMoney;
|
||||
state.achievementAnalysis = true;
|
||||
expect(achievements(state)).to.deep.equal([]);
|
||||
const singleton = finalState();
|
||||
singleton.players.splice(1);
|
||||
expect(achievements(singleton)).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it('marks both analysis constructors, even without hypothetical money, and excludes their final states', () => {
|
||||
const source = setup(3, {}, 'analysis-achievements');
|
||||
const branches = [
|
||||
wrapper.createAnalysis(source, { to: source.log.length, sourceEnded: false }),
|
||||
wrapper.createAnalysisScenario(source, { seed: 'interactive' }),
|
||||
createAnalysisScenario(source, { seed: 'simulation' }),
|
||||
];
|
||||
for (const branch of branches) {
|
||||
expect(branch.achievementAnalysis).to.equal(true);
|
||||
delete branch.analysisMoney;
|
||||
branch.phase = Phase.GameEnd;
|
||||
branch.newTurn = true;
|
||||
expect(achievements(branch)).to.deep.equal([]);
|
||||
}
|
||||
expect(source.achievementAnalysis).to.equal(undefined);
|
||||
});
|
||||
|
||||
it('preserves analysis exclusion through replay and marks analysis moves on legacy branches', async () => {
|
||||
const source = setup(3, {}, 'legacy-analysis-achievements');
|
||||
const branch = wrapper.createAnalysis(source, { to: source.log.length, sourceEnded: false });
|
||||
expect(wrapper.replay(branch).achievementAnalysis).to.equal(true);
|
||||
const legacy = await wrapper.analysisMove(source, [], 0);
|
||||
expect(legacy.achievementAnalysis).to.equal(true);
|
||||
legacy.phase = Phase.GameEnd;
|
||||
legacy.newTurn = true;
|
||||
expect(achievements(legacy)).to.deep.equal([]);
|
||||
expect(source.achievementAnalysis).to.equal(undefined);
|
||||
});
|
||||
|
||||
it('is pure on deeply frozen input and returns fresh arrays and records', () => {
|
||||
const state = finalState();
|
||||
state.players[0].money = 200;
|
||||
const before = cloneDeep(state);
|
||||
freezeDeep(state);
|
||||
const first = achievements(state);
|
||||
const second = achievements(state);
|
||||
expect(state).to.deep.equal(before);
|
||||
expect(first).to.deep.equal(second);
|
||||
expect(first).not.to.equal(second);
|
||||
first.forEach((result, seat) => {
|
||||
expect(result).not.to.equal(second[seat]);
|
||||
expect(result.earned).not.to.equal(second[seat].earned);
|
||||
});
|
||||
first[0].earned.push('host-mutation');
|
||||
first[0].outcome = 'loss';
|
||||
expect(achievements(state)).to.deep.equal(second);
|
||||
expect(wrapper.achievements(state)).to.deep.equal(second);
|
||||
});
|
||||
|
||||
for (const [name, fixture, expectedRanks] of [
|
||||
['GermanyRecharged', GermanyRecharged, [4, 2, 3, 1]],
|
||||
['USAOriginal', USAOriginal, [1, 3, 2]],
|
||||
] as const) {
|
||||
it(`replays authentic ${name} and awards only after its legal final transition`, async () => {
|
||||
const original = cloneDeep(fixture) as unknown as GameState;
|
||||
const replayed = wrapper.replay(cloneDeep(original));
|
||||
expect(wrapper.ended(replayed)).to.equal(true);
|
||||
expect(wrapper.rankings(replayed)).to.deep.equal(expectedRanks);
|
||||
expect(achievements(replayed)).to.deep.equal(achievements(original));
|
||||
expect(achievements(replayed).map((r) => r.outcome)).to.deep.equal(
|
||||
expectedRanks.map((rank) => (rank === 1 ? 'win' : 'loss'))
|
||||
);
|
||||
const lastMoveIndex = original.log.reduce((last, item, i) => (item.type === 'move' ? i : last), -1);
|
||||
const beforeEnd = wrapper.replay(cloneDeep(original), { to: lastMoveIndex });
|
||||
expect(wrapper.ended(beforeEnd)).to.equal(false);
|
||||
expect(achievements(beforeEnd)).to.deep.equal([]);
|
||||
const last = original.log[lastMoveIndex] as LogMove;
|
||||
const finished = await wrapper.move(beforeEnd, last.move, last.player);
|
||||
expect(wrapper.ended(finished)).to.equal(true);
|
||||
expect(finished.newTurn).to.equal(true);
|
||||
expect(achievements(finished)).to.deep.equal(achievements(replayed));
|
||||
});
|
||||
}
|
||||
});
|
||||
104
engine/src/achievements.ts
Normal file
104
engine/src/achievements.ts
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
import type { AchievementDefinition, AchievementManifest, SeatAchievements } from '@boardgamers/protocol/engine';
|
||||
import { ended, playersSortedByScore } from './engine';
|
||||
import { GameState, Player, PowerPlantType } from './gamestate';
|
||||
|
||||
const definitions: AchievementDefinition[] = [
|
||||
{ id: 'grid-champion', name: 'Grid Champion', description: 'Win a game of Power Grid.' },
|
||||
{ id: 'head-to-head', name: 'Head to Head', description: 'Win a two-player game.' },
|
||||
{ id: 'full-table', name: 'Full Table', description: 'Win a six-player game.' },
|
||||
{ id: 'germany-champion', name: 'Germany Champion', description: 'Win on the Germany map.' },
|
||||
{ id: 'usa-champion', name: 'USA Champion', description: 'Win on the USA map.' },
|
||||
{ id: 'france-champion', name: 'France Champion', description: 'Win on the France map.' },
|
||||
{ id: 'japan-champion', name: 'Japan Champion', description: 'Win on the Japan map.' },
|
||||
{
|
||||
id: 'power-fifteen',
|
||||
name: 'Power Fifteen',
|
||||
description: 'Finish able to power at least 15 cities in your network.',
|
||||
},
|
||||
{
|
||||
id: 'power-eighteen',
|
||||
name: 'Power Eighteen',
|
||||
description: 'Finish able to power at least 18 cities in your network.',
|
||||
},
|
||||
{
|
||||
id: 'fully-supplied',
|
||||
name: 'Fully Supplied',
|
||||
description: 'Finish able to power every city in a network of at least 10 cities.',
|
||||
},
|
||||
{
|
||||
id: 'network-seventeen',
|
||||
name: 'Network Seventeen',
|
||||
description: 'Finish with at least 17 cities in your network.',
|
||||
},
|
||||
{ id: 'network-twenty', name: 'Network Twenty', description: 'Finish with at least 20 cities in your network.' },
|
||||
{ id: 'cash-reserve', name: 'Cash Reserve', description: 'Finish with at least 100 Elektro.' },
|
||||
{ id: 'deep-reserves', name: 'Deep Reserves', description: 'Finish with at least 200 Elektro.' },
|
||||
{
|
||||
id: 'wind-farm',
|
||||
name: 'Wind Farm',
|
||||
description: 'Finish owning wind plants with a combined capacity of at least 8 cities.',
|
||||
},
|
||||
{
|
||||
id: 'atomic-power',
|
||||
name: 'Atomic Power',
|
||||
description:
|
||||
'Finish owning uranium-fuelled power plants with a combined capacity of at least 8 cities. Australian uranium mines do not count.',
|
||||
},
|
||||
];
|
||||
|
||||
export function achievementDefinitions(): AchievementManifest {
|
||||
// A host may cache or modify its copy without changing future evaluations.
|
||||
return { revision: 1, achievements: definitions.map((definition) => ({ ...definition })) };
|
||||
}
|
||||
|
||||
function tied(a: Player, b: Player): boolean {
|
||||
return a.citiesPowered === b.citiesPowered && a.money === b.money && a.cities.length === b.cities.length;
|
||||
}
|
||||
|
||||
/** Evaluate only authoritative final state; BGS additionally gates cancelled tables and account eligibility. */
|
||||
export function achievements(data: GameState): SeatAchievements[] {
|
||||
if (
|
||||
!ended(data) ||
|
||||
data.newTurn === false ||
|
||||
data.analysisMoney ||
|
||||
data.achievementAnalysis ||
|
||||
data.players.length < 2
|
||||
)
|
||||
return [];
|
||||
|
||||
// Keep bots and dropped players in the standings: never promote a human who lost to one.
|
||||
const leader = playersSortedByScore(data)[0];
|
||||
const results: SeatAchievements[] = [];
|
||||
data.players.forEach((player, seat) => {
|
||||
if (player.isAI || player.isDropped) return;
|
||||
const win = tied(player, leader);
|
||||
const capacity = (type: PowerPlantType) =>
|
||||
player.powerPlants
|
||||
.filter((plant) => plant.type === type)
|
||||
.reduce((sum, plant) => sum + plant.citiesPowered, 0);
|
||||
const earned: string[] = [];
|
||||
if (win) {
|
||||
earned.push('grid-champion');
|
||||
if (data.players.length === 2) earned.push('head-to-head');
|
||||
if (data.players.length === 6) earned.push('full-table');
|
||||
const maps: Record<string, string> = {
|
||||
Germany: 'germany-champion',
|
||||
USA: 'usa-champion',
|
||||
France: 'france-champion',
|
||||
Japan: 'japan-champion',
|
||||
};
|
||||
if (maps[data.map.name]) earned.push(maps[data.map.name]);
|
||||
}
|
||||
if (player.citiesPowered >= 15) earned.push('power-fifteen');
|
||||
if (player.citiesPowered >= 18) earned.push('power-eighteen');
|
||||
if (player.cities.length >= 10 && player.citiesPowered === player.cities.length) earned.push('fully-supplied');
|
||||
if (player.cities.length >= 17) earned.push('network-seventeen');
|
||||
if (player.cities.length >= 20) earned.push('network-twenty');
|
||||
if (player.money >= 100) earned.push('cash-reserve');
|
||||
if (player.money >= 200) earned.push('deep-reserves');
|
||||
if (capacity(PowerPlantType.Wind) >= 8) earned.push('wind-farm');
|
||||
if (data.map.name !== 'Australia' && capacity(PowerPlantType.Uranium) >= 8) earned.push('atomic-power');
|
||||
results.push({ seat, earned, outcome: win ? 'win' : 'loss' });
|
||||
});
|
||||
return results;
|
||||
}
|
||||
|
|
@ -336,6 +336,7 @@ export function createAnalysisScenario(
|
|||
// sampled or source commitment may make a choice on a human's behalf.
|
||||
s.currentPlayers = s.playerOrder.filter((id) => !s.players[id].skipAuction);
|
||||
}
|
||||
s.achievementAnalysis = true;
|
||||
s.seed = seed;
|
||||
s.hiddenLog = [];
|
||||
delete s.automation;
|
||||
|
|
|
|||
|
|
@ -197,6 +197,8 @@ export enum Phase {
|
|||
}
|
||||
|
||||
export interface GameState {
|
||||
/** Analysis/simulation branches are never eligible for achievements. */
|
||||
achievementAnalysis?: true;
|
||||
/** Interactive sandbox cash, initialized once; never attached to live games. */
|
||||
analysisMoney?: 'hypothetical';
|
||||
/** Seats whose sandbox cash starts from known money rather than an assumption. */
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ import {
|
|||
setPremoves,
|
||||
} from './src/premoves';
|
||||
import { asserts } from './src/utils';
|
||||
export { achievementDefinitions, achievements } from './src/achievements';
|
||||
export { MAX_ANALYSIS_MONEY } from './src/analysis-money';
|
||||
export type { SetAnalysisMoney } from './src/analysis-money';
|
||||
export { ended, scores, stripSecret } from './src/engine';
|
||||
|
|
@ -284,6 +285,7 @@ export function replay(G: GameState, { to = Infinity }: { to?: number } = {}): G
|
|||
}
|
||||
if (oldG.revisedPowering) G.revisedPowering = { ...oldG.revisedPowering };
|
||||
}
|
||||
if (oldG.achievementAnalysis) G.achievementAnalysis = true;
|
||||
delete G.pendingMessages;
|
||||
return G;
|
||||
}
|
||||
|
|
@ -389,6 +391,7 @@ export function logSlice(G: GameState, options?: { player?: number; start?: numb
|
|||
export function createAnalysis(data: GameState, { to }: { to: number; sourceEnded: boolean }): GameState {
|
||||
if (!Number.isInteger(to) || to < 0 || to > data.log.length) throw new Error('Invalid history position');
|
||||
const copy = replay(JSON.parse(JSON.stringify(data)), { to });
|
||||
copy.achievementAnalysis = true;
|
||||
delete copy.automation;
|
||||
for (const player of copy.players) {
|
||||
player.isDropped = false;
|
||||
|
|
@ -417,6 +420,7 @@ export async function analysisMove(
|
|||
throw new Error('Only an active player can edit analysis money');
|
||||
const command = buffer[0] as SetAnalysisMoney;
|
||||
const copy = cloneDeep(data);
|
||||
copy.achievementAnalysis = true;
|
||||
const previous = copy.players[command.data?.player]?.money;
|
||||
applyAnalysisMoney(copy, command.data);
|
||||
copy.log.push({
|
||||
|
|
@ -427,6 +431,7 @@ export async function analysisMove(
|
|||
return copy;
|
||||
}
|
||||
data = cloneDeep(data);
|
||||
data.achievementAnalysis = true;
|
||||
if (isPremoveCommand(input)) throw new Error('Premoves are not available in an analysis');
|
||||
delete data.automation;
|
||||
// Deliberately bypass the live wrapper: clearing premoves alone does not
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue