Add Container final-state per-game achievements

This commit is contained in:
coyotte508 2026-11-14 00:43:53 +00:00
commit 24031837d9
8 changed files with 333 additions and 7 deletions

72
docs/achievements.md Normal file
View file

@ -0,0 +1,72 @@
# Container per-game achievements (review candidate)
The engine wrapper exports the optional `achievementDefinitions()` and
`achievements(GameState)` hooks using the published `@boardgamers/protocol/engine`
0.11.0 types. Manifest revision is **1**. IDs are permanent; never reuse them for
another condition. Icons are omitted intentionally (platform generic fallback).
## Manifest
All conditions require a committed, completed 3–5-player game. Non-win feats do
not require a victory.
| ID | Condition |
| ------------------ | ------------------------------------------------------------- |
| `win` | Sole winner after final score and island-container tiebreaker |
| `win-three-player` | Win a three-player game |
| `win-four-player` | Win a four-player game |
| `win-five-player` | Win a five-player game |
| `debt-free-win` | Win with zero outstanding loans |
| `score-100` | Final score at least 100 |
| `score-150` | Final score at least 150 |
| `debt-free` | Zero outstanding loans at completion |
| `three-factories` | Own at least three factories at completion |
| `four-factories` | Own four factories (the legal maximum) at completion |
| `three-warehouses` | Own at least three warehouses at completion |
| `five-warehouses` | Own five warehouses at completion |
| `island-five` | At least five containers on the island at completion |
| `island-ten` | At least ten containers on the island at completion |
| `island-diversity` | All five container colors on the island at completion |
| `full-ship` | Five containers aboard the ship at completion |
| `warehouse-six` | At least six containers in the warehouse store at completion |
## Rules and authority
This is Container, not Gaia Project. The engine ends after two supply colors run
out, at the relevant turn/auction boundary. Settlement replaces `player.money`
with the final score, including island values, warehouse stock ($2 each), cargo
($3 each), and loan penalties ($11 each). The hook reads that settled value; it
never applies scoring a second time or mistakes it for remaining cash.
The existing wrapper ranks by score then island-container count. Achievements
use those same comparisons, but do **not** use array/seat order to break an exact
tie: tied leaders get `draw`, others `loss`, and no win achievements are granted.
Bot and dropped seats receive no rows, but their results remain opponents'
results; filtering eligibility cannot turn a loss into a win. Player count means
original seats, including bots/drops. Singleton/unsupported games get no rows.
Island holdings come from auctions (including retaining one's own cargo), but do
not prove any particular number of auction victories or deliveries. There are no
historical shipping, auction, production or borrowing feats. In particular,
`debt-free` does not claim the player never borrowed. No log, objective card,
secret breakdown or extra evidence is exposed or required. Hooks do not mutate
inputs, and each manifest call returns a fresh object graph.
## Integration prerequisites / release boundary
- BGS must call the hook with the authoritative completed serialized state, map
zero-based seats to eligible human accounts, and reject cancelled, analysis,
tutorial and otherwise ineligible games using platform metadata. This engine
has no cancellation flag or account IDs. The hook additionally filters the
engine's `isAI` and `isDropped` flags.
- Install published protocol **0.11.0** using the committed lockfile. No local
unpublished protocol dependency is used.
- Coordinator review/activation is required. This branch does not upload to BGS,
activate a manifest, bump release versions, or push to the release branch.
- Later publication must follow `AGENTS.md` delivery requirements.
Tests play legal seeded 3/4/5-player games through completion, serialize and
replay them, check immutable/idempotent evaluation, and separately vary final
states to cover all thresholds, exact ties, the tiebreaker, eligibility and
unsupported/unfinished inputs. Synthetic boundary variations are explicitly not
presented as legal game replays.

View file

@ -23,6 +23,7 @@
"test": "mocha -r ts-node/register src/**/*.spec.ts src/*.spec.ts"
},
"dependencies": {
"@boardgamers/protocol": "0.11.0",
"@types/lodash": "^4.14.149",
"@types/seedrandom": "^2.4.27",
"lodash": "^4.17.15",

View file

@ -0,0 +1,178 @@
import type { Engine } from '@boardgamers/protocol/engine';
import { expect } from 'chai';
import { cloneDeep } from 'lodash';
import seedrandom from 'seedrandom';
import * as wrapper from '../wrapper';
import { setup } from './engine';
import { containerColors, GameState, Phase } from './gamestate';
// Compile against the published optional hooks, not a local protocol imitation.
const hooks: Pick<Engine<GameState>, 'achievementDefinitions' | 'achievements'> = wrapper;
function complete(players: number): GameState {
const random = Math.random;
Math.random = seedrandom(`achievements-${players}`);
try {
let G = setup(players, {}, `achievements-${players}`);
for (let i = 0; i < 20000 && !wrapper.ended(G); i++) {
G = wrapper.moveAI(G, G.currentPlayers[0]);
}
expect(wrapper.ended(G), 'legal moves reach completion').to.equal(true);
return JSON.parse(JSON.stringify(G));
} finally {
Math.random = random;
}
}
function freeze<T>(value: T): T {
if (value && typeof value === 'object') {
Object.values(value).forEach(freeze);
Object.freeze(value);
}
return value;
}
describe('per-game achievements', function () {
this.timeout(60000);
const completed: GameState[] = [];
before(() => {
for (const count of [3, 4, 5]) completed.push(complete(count));
});
it('publishes a fresh, stable, secret-free revision-one manifest', () => {
expect(hooks.achievementDefinitions).to.be.a('function');
const manifest = wrapper.achievementDefinitions();
expect(manifest.revision).to.equal(1);
expect(manifest.achievements).to.have.length(17);
expect(new Set(manifest.achievements.map((d) => d.id)).size).to.equal(17);
for (const definition of manifest.achievements) {
expect(definition.id).to.match(/^[a-z0-9]+(?:-[a-z0-9]+)*$/);
expect(definition.id.length).to.be.at.most(64);
expect(definition.name).not.to.equal('');
expect(definition.description).not.to.equal('');
}
manifest.achievements[0].id = 'changed';
expect(wrapper.achievementDefinitions().achievements[0].id).to.equal('win');
});
it('evaluates legally completed serialized 3/4/5-player games without mutation', () => {
const ids = wrapper.achievementDefinitions().achievements.map((d) => d.id);
for (const G of completed) {
const before = JSON.stringify(G);
const result = wrapper.achievements(freeze(G));
expect(result).to.have.length(G.players.length);
expect(wrapper.achievements(G)).to.deep.equal(result);
expect(JSON.stringify(G)).to.equal(before);
const best = [...G.players].sort(
(a, b) => b.money - a.money || b.containersOnIsland.length - a.containersOnIsland.length
)[0];
for (const row of result) {
expect(Object.keys(row).sort()).to.deep.equal(['earned', 'outcome', 'seat']);
row.earned.forEach((id) => expect(ids).to.include(id));
if (row.outcome === 'win') {
expect(row.seat).to.equal(best.id);
expect(row.earned).to.include(
`win-${['', '', '', 'three', 'four', 'five'][G.players.length]}-player`
);
}
}
// Replaying the legal log independently reaches exactly the same awards.
expect(wrapper.achievements(wrapper.replay(G))).to.deep.equal(result);
}
});
it('rejects ongoing, tentative, unsupported singleton, and unsettled states', () => {
expect(wrapper.achievements(setup(3, {}, 'ongoing'))).to.deep.equal([]);
for (const change of [
(G: GameState) => (G.phase = Phase.Move),
(G: GameState) => (G.newTurn = false),
(G: GameState) => (G.players = G.players.slice(0, 1)),
(G: GameState) => (G.currentPlayers = [0]),
(G: GameState) => (G.players[0].money = NaN),
]) {
const G = cloneDeep(completed[0]);
change(G);
expect(wrapper.achievements(G)).to.deep.equal([]);
}
});
// These are isolated final-state boundary variations, not claimed legal replays.
it('uses the island tiebreaker, draws exact ties, and never promotes humans over bots/drops', () => {
const G = cloneDeep(completed[0]);
G.players.forEach((p) => {
p.money = 100;
p.containersOnIsland = [];
});
expect(wrapper.achievements(G).map((r) => r.outcome)).to.deep.equal(['draw', 'draw', 'draw']);
expect(wrapper.achievements(G).every((r) => !r.earned.includes('win'))).to.equal(true);
G.players[0].containersOnIsland = [{ id: 'C0', color: containerColors[0] }];
expect(wrapper.achievements(G).map((r) => r.outcome)).to.deep.equal(['win', 'loss', 'loss']);
G.players[0].isAI = true;
G.players[1].isDropped = true;
expect(wrapper.achievements(G).map((r) => [r.seat, r.outcome])).to.deep.equal([[2, 'loss']]);
expect(wrapper.achievements(G)[0].earned).to.include('score-100');
G.players[2].isDropped = true;
expect(wrapper.achievements(G)).to.deep.equal([]);
});
it('checks every numeric and diversity boundary independently of winning', () => {
const G = cloneDeep(completed[0]);
const p = G.players[0];
G.players[1].money = 1000;
G.players[2].money = 999;
const earned = () => wrapper.achievements(G)[0].earned;
const boundary = (id: string, threshold: number, set: (n: number) => void) => {
set(threshold - 1);
expect(earned(), `${id} below`).not.to.include(id);
set(threshold);
expect(earned(), `${id} at`).to.include(id);
expect(earned()).not.to.include('win');
};
boundary('score-100', 100, (n) => (p.money = n));
boundary('score-150', 150, (n) => (p.money = n));
for (const [id, n] of [
['three-factories', 3],
['four-factories', 4],
] as const)
boundary(
id,
n,
(n) => (p.factories = Array.from({ length: n }, (_, i) => ({ id: `F${i}`, color: containerColors[i] })))
);
for (const [id, n] of [
['three-warehouses', 3],
['five-warehouses', 5],
] as const)
boundary(id, n, (n) => (p.warehouses = Array.from({ length: n }, (_, i) => ({ id: `W${i}` }))));
const containers = (n: number) =>
Array.from({ length: n }, (_, i) => ({ id: `C${i}` as const, color: containerColors[i % 5] }));
boundary('island-five', 5, (n) => (p.containersOnIsland = containers(n)));
boundary('island-ten', 10, (n) => (p.containersOnIsland = containers(n)));
p.containersOnIsland = containers(4);
expect(earned()).not.to.include('island-diversity');
p.containersOnIsland = containers(5);
expect(earned()).to.include('island-diversity');
boundary('full-ship', 5, (n) => (p.ship.containers = containers(n)));
boundary(
'warehouse-six',
6,
(n) => (p.containersOnWarehouseStore = containers(n).map((piece) => ({ piece, price: 2, moved: false })))
);
p.loans = [{ id: 'L0' }];
expect(earned()).not.to.include('debt-free');
p.loans = [];
expect(earned()).to.include('debt-free');
expect(earned()).not.to.include('debt-free-win');
p.money = 1001;
expect(earned()).to.include('debt-free-win');
p.loans = [{ id: 'L0' }];
expect(earned()).not.to.include('debt-free-win');
expect(earned()).to.include('win');
// Hidden objectives and history are not needed to evaluate any feat.
const expected = earned();
p.pointCard = null;
delete p.finalScoreBreakdown;
G.log = [];
expect(earned()).to.deep.equal(expected);
});
});

View file

@ -0,0 +1,71 @@
import type { AchievementManifest, SeatAchievements } from '@boardgamers/protocol/engine';
import { ended } from './engine';
import type { GameState, Player } from './gamestate';
// Final holdings only: neither lastMove nor the current auction proves lifetime feats.
const definitions = [
['win', 'Shipping Magnate', 'Win a completed game of Container.'],
['win-three-player', 'Three-Company Champion', 'Win a completed three-player game.'],
['win-four-player', 'Four-Company Champion', 'Win a completed four-player game.'],
['win-five-player', 'Five-Company Champion', 'Win a completed five-player game.'],
['debt-free-win', 'Solvent Champion', 'Win a completed game with no outstanding loans.'],
['score-100', 'Healthy Balance Sheet', 'Finish with a final score of at least 100.'],
['score-150', 'Economic Powerhouse', 'Finish with a final score of at least 150.'],
['debt-free', 'Books Balanced', 'Finish with no outstanding loans.'],
['three-factories', 'Industrial Expansion', 'Finish owning at least three factories.'],
['four-factories', 'Factory Network', 'Finish owning four factories.'],
['three-warehouses', 'Distribution Network', 'Finish owning at least three warehouses.'],
['five-warehouses', 'Warehouse Empire', 'Finish owning five warehouses.'],
['island-five', 'Island Investor', 'Finish with at least five containers on your island.'],
['island-ten', 'Island Portfolio', 'Finish with at least ten containers on your island.'],
['island-diversity', 'A Colorful Portfolio', 'Finish with all five container colors on your island.'],
['full-ship', 'Loaded Freighter', 'Finish with five containers aboard your ship.'],
['warehouse-six', 'Stocked for Trade', 'Finish with at least six containers in your warehouse store.'],
];
export function achievementDefinitions(): AchievementManifest {
return {
revision: 1,
achievements: definitions.map(([id, name, description]) => ({ id, name, description })),
};
}
/** Money is already the settled score after GameEnd; do not score it again. */
function compare(a: Player, b: Player): number {
return a.money - b.money || a.containersOnIsland.length - b.containersOnIsland.length;
}
export function achievements(G: GameState): SeatAchievements[] {
// Container supports 3–5 seats. There is no solo victory or engine cancellation
// flag. External cancellations, analysis games and account eligibility are BGS gates.
if (!ended(G) || G.newTurn === false || G.players.length < 3 || G.players.length > 5) return [];
if (G.currentPlayers.length || G.players.some((p) => !Number.isFinite(p.money))) return [];
const best = G.players.reduce((a, b) => (compare(a, b) >= 0 ? a : b));
const tied = G.players.filter((p) => compare(p, best) === 0).length > 1;
return G.players
.map((p, seat): SeatAchievements => {
const outcome = compare(p, best) !== 0 ? 'loss' : tied ? 'draw' : 'win';
const win = outcome === 'win';
const earned = [
['win', win],
['win-three-player', win && G.players.length === 3],
['win-four-player', win && G.players.length === 4],
['win-five-player', win && G.players.length === 5],
['debt-free-win', win && p.loans.length === 0],
['score-100', p.money >= 100],
['score-150', p.money >= 150],
['debt-free', p.loans.length === 0],
['three-factories', p.factories.length >= 3],
['four-factories', p.factories.length === 4],
['three-warehouses', p.warehouses.length >= 3],
['five-warehouses', p.warehouses.length === 5],
['island-five', p.containersOnIsland.length >= 5],
['island-ten', p.containersOnIsland.length >= 10],
['island-diversity', new Set(p.containersOnIsland.map((c) => c.color)).size === 5],
['full-ship', p.ship.containers.length === 5],
['warehouse-six', p.containersOnWarehouseStore.length >= 6],
] as const;
return { seat, earned: earned.filter(([, met]) => met).map(([id]) => id), outcome };
})
.filter(({ seat }) => !G.players[seat].isAI && !G.players[seat].isDropped);
}

View file

@ -87,6 +87,7 @@ export function factions(G: GameState) {
return G.players.map((pl) => engine.playerColors[pl.id]);
}
export { achievementDefinitions, achievements } from './src/achievements';
export { ended, scores, stripSecret } from './src/engine';
/**

13
pnpm-lock.yaml generated
View file

@ -27,6 +27,9 @@ importers:
engine:
dependencies:
'@boardgamers/protocol':
specifier: 0.11.0
version: 0.11.0
'@types/lodash':
specifier: ^4.14.149
version: 4.17.25
@ -86,8 +89,8 @@ importers:
viewer:
dependencies:
'@boardgamers/protocol':
specifier: 0.10.0
version: 0.10.0
specifier: 0.11.0
version: 0.11.0
container-engine:
specifier: workspace:../engine
version: link:../engine
@ -1042,10 +1045,10 @@ packages:
}
engines: { node: '>=6.9.0' }
'@boardgamers/protocol@0.10.0':
'@boardgamers/protocol@0.11.0':
resolution:
{
integrity: sha512-U+nOK8xeQANvjzwacHirBW+ItDf9AOmHLtkoyTI/XYFCOpL6lPsEgCbmcxnmkXv2a1/lgtVN3WpSERHUqkQkXw==,
integrity: sha512-YQ54+aVOIZvxUJvFmUbZR7xSBEgQaemstPdmYKVGCUHCviRX2UXRLgqLSQl6PFhr++lUT+Nynbf+p7h19zN+/g==,
}
'@cspotcode/source-map-support@0.8.1':
@ -11587,7 +11590,7 @@ snapshots:
'@babel/helper-string-parser': 7.29.7
'@babel/helper-validator-identifier': 7.29.7
'@boardgamers/protocol@0.10.0':
'@boardgamers/protocol@0.11.0':
dependencies:
zod: 4.6.2

View file

@ -18,7 +18,7 @@ allowBuilds:
autoInstallPeers: false
minimumReleaseAgeExclude:
- '@boardgamers/protocol@0.2.2 || 0.3.0 || 0.3.1 || 0.3.3 || 0.4.0 || 0.4.2 || 0.5.0 || 0.6.0 || 0.6.1 || 0.6.2 || 0.8.1 || 0.10.0'
- '@boardgamers/protocol@0.2.2 || 0.3.0 || 0.3.1 || 0.3.3 || 0.4.0 || 0.4.2 || 0.5.0 || 0.6.0 || 0.6.1 || 0.6.2 || 0.8.1 || 0.10.0 || 0.11.0'
# The cli-plugin-typescript fork-ts-checker shim does a bare
# require('@vue/compiler-sfc') expecting the vue-3 parse shape ({descriptor}).
# It declares no such dependency, so resolution falls back to pnpm's hidden

View file

@ -19,7 +19,7 @@
"preview:tutorial": "node scripts/tutorial-preview.mjs"
},
"dependencies": {
"@boardgamers/protocol": "0.10.0",
"@boardgamers/protocol": "0.11.0",
"container-engine": "workspace:../engine",
"core-js": "^3.6.5",
"lodash": "^4.17.19",