Compare commits

...

131 commits

Author SHA1 Message Date
4d80267e7e Record verified Container viewer 2.1.4 release
Some checks are pending
All / prettier (push) Waiting to run
2026-11-19 09:18:31 +00:00
5403d54479 Release Container viewer 2.1.4 bank interaction polish 2026-11-19 09:15:29 +00:00
8a85ab8ec3 Highlight returned cargo tray while awaiting player selection 2026-11-19 09:09:45 +00:00
f9a3804512 Move bid draft cargo, frame returned containers above bank and simplify win logs 2026-11-19 09:02:40 +00:00
b66e79aa9a Record verified bank settlement animation release 2026-11-19 08:47:32 +00:00
13bbb63b65 Animate bank settlement into holdings and release viewer 2.1.3 2026-11-19 08:46:42 +00:00
a8022adeef Record verified Container viewer 2.1.2 BGS release 2026-11-19 08:36:17 +00:00
0d5ad24c22 Release Container viewer 2.1.2 tutorial and bank usability improvements 2026-11-19 08:32:16 +00:00
283bea6170 Use board destinations for bank returns, animate cargo and group lessons 2026-11-19 08:26:17 +00:00
46b44cdc7b Let Offshore cargo tutorial load both holding containers 2026-11-19 08:12:41 +00:00
5928bcb798 fix(viewer): show bank settlement winners with player badges 2026-11-19 08:11:24 +00:00
ae3b904cee Update offshore loading tutorial translations 2026-11-19 08:10:06 +00:00
98acf13cb4 Record verified Offshore Island BGS release 2026-11-19 00:58:52 +00:00
e224cf7c78 Fix cross-origin locale imports and release viewer 2.1.1 2026-11-19 00:54:53 +00:00
0a111ad296 Release Offshore Island engine 2.2.0 and viewer 2.1.0 2026-11-19 00:48:16 +00:00
a0d46a4daa Add interactive Offshore tutorials and translate expansion text into all supported languages 2026-11-19 00:37:48 +00:00
2509441ec8 Disallow Offshore bids on empty reward lots 2026-11-19 00:21:43 +00:00
1e12a2c314 Render undo arrows inline instead of loading external SVG images 2026-11-19 00:16:04 +00:00
096b472c5f Keep bank bid-area labels visible when bidding is unavailable 2026-11-19 00:05:54 +00:00
053c00fd17 Style bank journal entries and automatically resolve forced payments 2026-11-19 00:00:38 +00:00
e99b9ccc66 Highlight eligible storage zones during bank container bidding 2026-11-18 23:47:01 +00:00
18fc0a90aa Preview container bids inside bank lots with a single draft action 2026-11-18 23:40:04 +00:00
bfa8389a99 Focus bank cargo bidding on board pieces and cancel zero cash drafts locally 2026-11-18 23:29:02 +00:00
c790257286 Center docked ships vertically in bank berths 2026-11-18 23:18:46 +00:00
1580a03be6 Restore open bank berths with player-colored borders and cargo inside 2026-11-18 23:15:57 +00:00
2782601446 Show bank rewards, bids and waiting cargo in player-colored harbors 2026-11-18 22:52:56 +00:00
e7b9c48c09 Compact bank bidding controls and highlight selected lots 2026-11-18 22:28:16 +00:00
928d227f36 Use player bid tokens and simplify the offshore harbor 2026-11-18 22:17:59 +00:00
d360520964 Clarify bank lots and amounts and place harbor alongside bank 2026-11-18 22:08:52 +00:00
b042edaaa5 Integrate Offshore bank into SVG board and migrate viewer to Vite 2026-11-18 21:57:16 +00:00
a7064f9c53 Add optional Offshore Island expansion, bank UI, bots and achievements 2026-11-18 21:16:06 +00:00
93194c8b2b Record verified Container 2.1.10 artwork activation receipt 2026-11-14 13:01:56 +00:00
7170c8a0bb Add original Container achievement art and asset refs for revision 3 2026-11-14 12:13:27 +00:00
99e60d5e8f Raise island holding achievement to fifteen for revision 2 review 2026-11-14 01:02:02 +00:00
b8eb716a6d Release Container engine 2.1.8 with reviewed achievements 2026-11-14 00:54:38 +00:00
6ae62e067c Replace impossible warehouse achievement with legally attained five-stock feat 2026-11-14 00:50:16 +00:00
24031837d9 Add Container final-state per-game achievements 2026-11-14 00:43:53 +00:00
66632f1697 Order revealed sealed bids by seat and release viewer 2.0.16 2026-11-12 22:06:10 +00:00
cae924287c Fix sealed bid lastMove leak and release engine 2.1.7 2026-11-10 16:25:15 +00:00
3244b59d09 Add manually authored Simplified Chinese game UI 2026-10-20 14:16:36 +02:00
a721a0080e Release container engine 2.1.6
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 12:44:28 +02:00
daf3a1cc70 Let BGS replay the engine to an earlier position
BGS's undo against bots (and its admin replays) call replay(data, { to })
and expect logLength to then equal `to`, but replay ignored `to`: an undo
failed, or did nothing during an auction. With `to`, replay now rebuilds
the position after the first `to` visible log entries, from a deep copy.
Hidden-log moves all come after the visible log and are left out, so
replaying to the visible length of a running auction reopens it without
its sealed bids and bid-phase loans: the human and the bots bid again.
That position is a regular turn, not a live update (BGS then lets the bots
due play), with no announcements left. Without `to`, the full replay is
unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 12:00:03 +02:00
f806bdef1f Offer "Undo my move" in games against bots
BGS lets the only human of a game against bots take back their last saved
move (protocol 0.10.0). The board toolbar's undo slot shows an "Undo my
move" control while BGS reports it available and the current turn has no
unsaved moves (those keep the in-turn undo); it stays hidden for spectators,
in analysis, during replays and in lessons. Clicking it asks BGS to undo,
which then sends the earlier state: going back in history discards the
local selection, bid drafts and confirmations.

The dev app mimics BGS's undo against its AI players. Also fixes the import
order that failed the prettier check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 11:32:52 +02:00
76ea16358e Prefill pending bids and retain confirmation when revising auction additions 2026-10-05 16:26:09 +02:00
4578009179 feat: allow revising pending sealed auction bids 2026-10-05 01:36:02 +02:00
a24bf7205a Fix formatting checks and document BGS source delivery 2026-10-04 11:33:06 +02:00
d21684430a Use shared BGS preferred colourblind player symbols 2026-10-02 11:20:54 +02:00
d0c9537cca Support custom player colours across the Container viewer 2026-10-02 01:38:31 +02:00
8ccc2a1396 Publish auction journal improvements and Supporter badges 2026-10-01 23:56:32 +02:00
41993b8131 Merge commit '4bcf010be1' into feature/safe-analysis-scenarios 2026-09-30 14:26:32 +02:00
d14d57437a fix: hand floating chat reminders over to the BGS rail 2026-09-30 14:25:54 +02:00
8c53d1b10e Format existing locale regression test for CI 2026-09-30 08:21:52 +02:00
4bcf010be1 Format existing locale regression test for CI 2026-09-30 08:21:31 +02:00
d7397ac7bf Fix mobile final score scrolling and keep close control visible 2026-09-30 08:19:39 +02:00
94125e186a Fix mobile final score scrolling and keep close control visible 2026-09-30 08:19:13 +02:00
ca275d6a37 Load languages on demand and publish complete viewer bundles 2026-09-30 00:27:37 +02:00
d514215313 docs: add Boardgamers play link 2026-09-28 22:47:05 +02:00
2f0c4a0503 fix: use protocol 0.6.2 and remove chat scroll backports 2026-09-28 19:51:14 +02:00
c7d3678785 Release container engine 2.1.3 2026-09-27 19:32:16 +02:00
925cacfa55 Fail closed when public cash cannot be reconstructed 2026-09-27 19:22:40 +02:00
a2c2439425 Simulate private state for ongoing analysis 2026-09-27 19:14:27 +02:00
212b56cd3c Preserve chat and journal position while scrolling history 2026-09-27 10:05:36 +02:00
4a8dbc0feb fix: preserve mobile scrolling and cancel reversed loan moves 2026-09-27 09:20:39 +02:00
89009f7781 Add Persian viewer and tutorial translations 2026-09-27 00:53:48 +02:00
af8beebb2c fix(viewer): prevent translated button overlap and restore unread chat 2026-09-26 12:01:23 +02:00
762a9f71fe fix(viewer): review contextual translations and localize whole journal entries 2026-09-25 21:37:55 +02:00
f931ca59d6 fix(viewer): keep translated calculator controls within their keys 2026-09-25 18:28:54 +02:00
c197b42042 feat(viewer): support the shared color-blind preference 2026-09-25 17:38:35 +02:00
9436db2f7a feat(viewer): localize interface and tutorials in 15 languages 2026-09-25 16:29:21 +02:00
e57d24cdfe feat(viewer): add player hover cards and board thumbnails 2026-09-24 11:44:11 +02:00
f189ee4863 fix(viewer): show container action bar only on mobile 2026-09-22 08:45:53 +02:00
e562533c97 feat(viewer): support editing chat messages 2026-09-21 22:40:07 +02:00
3666bb0948 fix(viewer): make chat translation controls compact 2026-09-21 21:53:03 +02:00
8664228bc8 Support translated chat and platform analysis defaults 2026-09-21 20:32:09 +02:00
c88540c103 Keep the mobile board scrollable and let chat scroll into view 2026-09-21 16:40:06 +02:00
fed212b4a6
Merge pull request #11 from boardgamers/feat/game-analysis
Support saved analyses of finished Container games
2026-09-21 16:17:37 +02:00
347702289f Check mobile chat through its tab in browser smoke tests 2026-09-21 15:35:56 +02:00
30cdb46757 Support saved analyses of finished Container games 2026-09-21 15:30:16 +02:00
b8c88babf4 Square panel corners along the screen edges 2026-09-20 00:19:06 +02:00
25091017ec Tab between journal and chat on mobile 2026-09-20 00:14:47 +02:00
f801e92906 Preserve chat when mobile controls mount and remove redundant drag listeners 2026-09-20 00:10:16 +02:00
cae59283d7 Match mobile controls to Container board styling 2026-09-19 21:00:29 +02:00
4b6ac3c431 Make mobile container purchases possible without cross-board dragging 2026-09-19 20:41:39 +02:00
74d7bdabf7 Format native tutorial browser test 2026-09-17 16:17:47 +02:00
c226c43b76 Teach tutorial actions through the game board 2026-09-17 16:12:18 +02:00
ed21bfe073 Fix journal scrolling on refresh and match chat height 2026-09-17 14:22:08 +02:00
aaaaca312e Use shared tutorial feedback and next-chapter controls 2026-09-16 09:30:38 +02:00
9b206d180a Clarify tutorial scoring and acknowledge correct answers 2026-09-16 08:14:05 +02:00
4eb331d601 Add guided Container tutorials and clearer auction controls 2026-09-15 23:02:22 +02:00
9601fac15e Show floating chat shortcut only for unread messages 2026-09-15 11:50:39 +02:00
70e14de86c
Use shared BGS viewer and chat protocol (#10)
* Use shared BGS viewer and chat protocol

* Use shared chat panel with Container styling

* Update shared chat visibility and show date separators

* Keep typing after completing a chat mention
2026-09-13 22:54:10 +02:00
ff733404c2 Reset unread badges when chat history is replaced 2026-09-11 20:44:38 +02:00
668bf58909 Remove local review notes and metadata template 2026-09-10 23:04:55 +02:00
8f8cf6867f Send chat directly without sandbox-blocked form submissions 2026-09-10 22:43:31 +02:00
51f8041dda Move chat shortcut clear of BGS settings control 2026-09-10 22:23:52 +02:00
fd39276159 Place chat beside journal and add off-screen unread shortcut 2026-09-10 22:21:18 +02:00
09081dec4a Add click-to-move controls, readable journal and chat, and action sounds 2026-09-10 22:13:47 +02:00
93983c3fe3
Merge pull request #9 from boardgamers/moon/tentative-turns
Tentative-turn model: per-turn time increments, free undo, append-only log (engine+viewer 2.0.0)
2026-08-17 12:11:47 +02:00
87d81d14d0 build: pin @vue/compiler-sfc for the cli-plugin-typescript shim
The shim's bare require expects the vue-3 parse shape but declares no
dependency, so it resolved through pnpm's hidden hoist — which could pick
vue 2.7's legacy-shaped 2.7.16 (CI) or 3.5.41 (local) depending on layout.
packageExtensions makes it deterministic.
2026-08-17 10:04:13 +00:00
7484d8eef0 build: disable pnpm autoInstallPeers — vue3 compiler-sfc leak broke fresh builds 2026-08-17 10:00:14 +00:00
0566dcaab3 ci: modernize workflows (node 24, pnpm 11), single workspace lockfile
The per-directory v5.3 lockfiles were stale against the 2.0.0 package.jsons and
unreadable by the workflows' pnpm 5 anyway; the root v9 workspace lockfile is
authoritative. Reformat sources for prettier-plugin-organize-imports v3 and
ignore build artifacts.
2026-08-17 09:55:09 +00:00
1278df32e4 viewer: make the log modal readable in dark mode
The modal kept its own light backgrounds (#fefefe content, #ccc/#fff log
rows) but let the text color inherit from the page, so the platform's dark
mode rendered it white-on-gray. Pin an explicit dark text color on
.modal-content — the viewer styles everything else with fixed colors too —
so the log (and the other modals) are readable in both themes.
2026-08-17 09:50:30 +00:00
7a54e8e2dd viewer: don't re-apply matching tentative echoes
After a drag-drop the viewer paints a local preview of the move synchronously,
then the server's tentative echo of the same turn buffer arrived a few hundred
ms later and went through replaceState again. Rebuilding every piece while the
drop animation was still in flight made the piece show at its destination
instantly while also tweening there from the drop point. Matching echoes now
short-circuit like stale ones already did — they only trigger the move sound,
which used to be the echo replace's job (local previews are silent).

Also delay the self-contained harness's tentative echo by 300ms so it lands
mid-animation like on the real platform instead of masking such races.
2026-08-17 09:50:20 +00:00
1b6d749e31 viewer: apply preference toggles immediately
The preferences object handed to Game as a prop was a plain object owned by
launch(), and Vue 2 does not deep-observe prop values coming from a
non-reactive parent. Toggling sound or the drag/drop help indicators mutated
an unobserved object, so the UI only caught up on the next unrelated
re-render (in practice: after a refresh). Make the object a Vue.observable
and merge platform preference pushes into it instead of replacing it, so both
the in-game toggles and platform updates paint immediately.
2026-08-17 09:50:03 +00:00
fd23b5c996 viewer: inline icons and audio into the built bundles
Production deploys upload only dist/container-viewer.umd.min.js and
dist/container-viewer.css to S3; the lib build emitted the toolbar icons to
dist/img/*.svg and the sounds to dist/media/* and referenced them by relative
URL, so they all 404'd on the platform (v2 worked only because jsdelivr served
the whole npm package). Swap the svg rule's file-loader for url-loader and
raise the images/media inline limits so every asset becomes a data URI inside
the two uploaded files.
2026-08-17 09:49:53 +00:00
f0c6f0bba0 Add Playwright MCP to gitignore 2026-08-17 08:27:41 +00:00
3f9d7d51b8 viewer: ignore tentative-state echoes that don't match the turn buffer
A move response's tentative state replaced the local preview
unconditionally. If the user had undone down to an empty buffer (which
re-emits nothing) or already made another move, a late echo transiently
showed a phantom or regressed move (and a wrong sidebar log) until the
next response landed.

Only accept a tentative state whose visible log extends the committed log
by exactly the buffered moves, in order — validated against the engine:
every tentative echo satisfies this (all tentative moves are visible-log
moves; bids and bid-phase loans go to the hidden log but commit
immediately and never take this path). Stale echoes are dropped; the echo
for the current buffer, if one is in flight, follows anyway.
2026-08-16 21:32:04 +00:00
511ce1728a engine!: remove the dead reconstructState export
Its only consumer was the wrapper's Undo handling, deleted when the
tentative-turn model replaced destructive undo; nothing in the engine or
the viewer sources references it anymore (full replays go through
wrapper.replay). Removing a public API is fine for the 2.0.0 major.
2026-08-16 21:31:01 +00:00
c72ebf77bd engine: seed upkeep container seizures from the game seed
Upkeep seizures picked containers with a bare Math.random, breaking the
platform guarantee that the same seed yields the same game and making
wrapper.replay diverge from the original whenever a seizure occurred
(seizures are log *events*, not moves, so nothing recorded the choice).

Seed a per-upkeep seedrandom stream from the persisted game seed plus the
visible log length — which uniquely identifies the upkeep within the game,
since each upkeep immediately follows its own Pass/Accept/Decline log
entry — so both live play and full replays reproduce the same seizures.

Typing removeRandom along the way exposed that warehouse/factory-store
seizure messages read .color on a ContainerOnStore (always undefined);
they now correctly read .piece.color.
2026-08-16 21:30:32 +00:00
46534ebd30 engine: stop dropPlayer from clobbering simultaneous bidders
dropPlayer unconditionally called nextPlayer, which resets currentPlayers
to a single player. During an auction (currentPlayers = all pending
bidders) dropping one bidder handed the turn to the auctioneer — who has
no available moves yet — wedging the game and discarding the other
bidders' pending turns. It also advanced the turn even when the dropped
player was not up at all, and skipped the next player's upkeep
(actions/available moves) in the move phase.

Now the drop auto-plays only the dropped player's own pending decision
through the regular engine path — Bid bash in the bid phase (including the
additional-bid round), Accept the highest bid as auctioneer, Pass in the
move phase — and touches nothing if the player is not up. The engine's
existing isDropped filters take care of skipping them afterwards.

Also make the highest-bid computation ignore dropped players' bids: a
dropped bidder's stale high bid used to poison Math.max, leaving
highestBidders empty and crashing the accept/decline phase.
2026-08-16 21:29:01 +00:00
501a33103c engine: replay hidden-log moves in wrapper.replay
A state saved mid-bid-phase keeps its newest moves (bids, bid-phase loans)
in G.hiddenLog — they are only flushed to G.log when the accept/decline
phase starts. replay() only walked G.log, so an admin full-replay of such
a save silently lost the bids and diverged.

Whenever hiddenLog is non-empty it holds exactly the moves made after the
last visible log entry, in order (the visible log freezes during the bid
phase), so replaying [...log, ...hiddenLog] reconstructs the state
faithfully. logSlice's truncated-log replay now explicitly drops the
hidden log, since it reconstructs a historical state predating it.
2026-08-16 21:27:11 +00:00
7c94bc75b7 engine: cover a 3-player auction bid tie with an additional-bid round
Scripted 3-player game into a simultaneous-bidders auction; asserts every
bid is a single-move committed turn, the tie opens an additional-bid round
among the tied bidders, bids stay in the hidden log until the tie resolves,
and the accept settles the right amounts.
2026-08-16 21:26:39 +00:00
e36715fedc engine: reject turn buffers that continue past a turn boundary
The whole-turn buffer is replayed from the committed state; committing is
what grants the mover their per-turn time increment. In the degenerate
all-others-dropped case a buffer like [..., Pass, ...more] is a sequence of
individually legal moves spanning several turns — it would commit them all
for a single increment. Throw as soon as a committed move is followed by
more buffer elements.

Also log an error when moveAI's 500-iteration force-commit safety net
fires, so a would-be livelock is visible in server logs instead of being
silently masked.

Tests: malformed buffer rejection (nothing half-applied leaks) and
multi-turn buffer rejection.
2026-08-16 21:26:05 +00:00
edfebe1b18 tests: cover the tentative-turn model
Engine (wrapper.spec.ts), simulating the platform (persist only what toSave
returns):

- mid-turn buffers are tentative (toSave undefined, nothing persisted) and
  the full turn commits when it completes
- bare move objects are accepted as one-element buffers; empty buffers are
  never saved
- undo-by-truncation: replaying a shortened buffer from the committed base
  equals never having made the popped move (including undoing to empty with
  no server call)
- scripted 2-player auction: sail-to-island commits immediately, a bid is a
  single-move committed turn, the auctioneer's mid-turn loan stays tentative,
  accept/decline commit and cannot be undone once control passes on
- the saved log length never shrinks across committed states
- moveAI always returns saveable states across a random 25-turn game;
  dropPlayer results are committed

Viewer: replace the dead example unit test (missing HelloWorld component)
with a real Calculator test so vue-cli-service test:unit passes.
2026-08-16 21:06:28 +00:00
6dc34d919c viewer: tentative-turn buffer instead of engine Undo moves
- Game.vue keeps turnMoves (the current turn's atomic moves) alongside the
  last committed state; every action emits the FULL buffer as the move
  payload, and the local preview replays the buffer with fake engine moves
- undo pops the buffer: re-emits the shortened turn if non-empty, or just
  resets the preview to the committed state with no server call (nothing was
  ever persisted for the turn)
- the buffer is cleared whenever a committed state (newTurn !== false)
  arrives from the platform, or when a local move completes the turn
- undo button availability = non-empty buffer (the Undo engine move is gone)
- launch.ts feeds the state embedded in move responses (logSlice().state) to
  the game — that's the only channel through which tentative states arrive —
  and falls back to fetchState otherwise
- self-contained dev mode mimics the platform: replays the buffer from the
  committed state and only persists committed results
- bump to 2.0.0 (pairs with container-engine 2.x)
2026-08-16 21:03:05 +00:00
f805997466 viewer: fix pre-existing build breakage
The viewer no longer compiled (bitrot surfaced by vue 2.7 + typescript 4.9 +
pnpm 11 strict hoisting):

- delete shims-tsx.d.ts: vue 2.7 ships its own JSX typings, ours duplicated
  the IntrinsicElements index signature
- type UIData.dragged structurally (Vue & { pieceType, pieceId }) instead of
  using a .vue module import as a type, which TS 4.9 rejects
- add csstype (vue's types import it; no longer hoisted) and @types/node +
  'node' in tsconfig types (self-contained.ts uses process.env)
2026-08-16 20:58:01 +00:00
da7491450c engine: replace destructive undo with tentative-turn model
- wrapper move() now accepts the whole current turn as a Move[] buffer
  (bare move objects still accepted) and replays it from the committed state
- new toSave(): returns undefined while the turn is tentative so the platform
  neither persists mid-turn states nor grants time increments for them
- engine tracks commitment in G.newTurn: tentative iff the last visible log
  entry is a move by a player still in currentPlayers; Pass/Accept/Decline/Bid
  always commit (bids and bid-phase loans live in the hidden log and were
  never undoable)
- delete MoveName.Undo entirely (move type, engine case, available-moves
  offerings): the saved log is now append-only
- wrapper moveAI() plays atomic moves until the turn commits (bot driver and
  dropPlayer auto-play require committed states); dropPlayer marks committed
- logSlice() now includes the stripped state so the acting player's viewer
  receives tentative states via the move response
- bump to 2.0.0 (new major: move payload shape changed, Undo removed)
2026-08-16 20:55:44 +00:00
c11163e3ff chore: unbreak tooling (pnpm 11 lockfile, dep build allow-list, organize-imports plugin)
- pnpm 11 rewrites the v5 lockfile on install and refuses to run unreviewed
  dependency build scripts; declare them explicitly (all disabled — everything
  installs and builds fine without them) so installs and the pre-commit hook pass
- upgrade prettier-plugin-organize-imports 1.x -> 3.x: the old version crashes
  against typescript 4.9 (host.fileExists is not a function), breaking lint-staged
- ignore the local .pnpm-store
2026-08-16 20:55:41 +00:00
github-actions
c6c69d7940 Engine v1.0.11
Some checks are pending
Engine - Test / lint_and_test (push) Waiting to run
All / prettier (push) Waiting to run
2026-08-12 20:11:41 +00:00
6482fd5032 🔧 Fix repository.url for npm OIDC provenance 2026-08-12 22:10:15 +02:00
5db663ef30
Update README.md 2026-08-12 22:05:05 +02:00
018c609016 Migrate CI to OIDC trusted publishing 2026-08-12 22:00:34 +02:00
fc8be2c90d
Merge pull request #8 from boardgamers/moon/container-expose-moveai
feat: export moveAI for bot players
2026-08-12 21:47:04 +02:00
95a7522c3d ✨ (engine) Export moveAI for bot players 2026-08-12 21:40:04 +02:00
github-actions
8d5195e227 Viewer v1.1.6
Some checks are pending
All / prettier (push) Waiting to run
2021-12-01 22:58:57 +00:00
coyotte508
4c2a11c70c 📱 (viewer) Set max width 2021-12-01 23:42:27 +01:00
github-actions
1aff080a90 Viewer v1.1.5
Some checks are pending
All / prettier (push) Waiting to run
2021-12-01 22:09:32 +00:00
coyotte508
9d8ca1e244 ✨ (viewer) Signal preference updates 2021-12-01 23:05:52 +01:00
github-actions
9d8a2b90b2 Engine v1.0.10
Some checks are pending
Engine - Test / lint_and_test (push) Waiting to run
All / prettier (push) Waiting to run
2021-10-23 13:04:05 +00:00
github-actions
402445a617 Engine v1.0.9
Some checks are pending
Engine - Test / lint_and_test (push) Waiting to run
All / prettier (push) Waiting to run
2021-10-23 07:20:49 +00:00
coyotte508
297815defa ✨ (engine) Expose player colors to BGS 2021-10-23 09:06:50 +02:00
189 changed files with 37319 additions and 16314 deletions

View file

@ -8,7 +8,7 @@ on:
default: patch
env:
node_version: 14
node_version: 24
defaults:
run:
@ -17,24 +17,26 @@ defaults:
jobs:
version_and_release:
runs-on: ubuntu-latest
permissions:
contents: write # git push --follow-tags
id-token: write # OIDC trusted publishing
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- name: Use Node.js ${{ env.node_version }}
uses: actions/setup-node@v2
uses: actions/setup-node@v4
with:
node-version: ${{ env.node_version }}
# setting a registry enables the NODE_AUTH_TOKEN env variable where we can set an npm token. REQUIRED
# registry-url is required so npm publish targets the public npm registry
registry-url: 'https://registry.npmjs.org'
- uses: pnpm/action-setup@v1.2.1
with:
version: 5.17.1
- run: npm install -g pnpm@11
- run: pnpm install
- run: git config --global user.name github-actions
- run: git config --global user.email bot@github.com
- run: yarn config set version-git-message "Engine v%s"
- run: yarn version --${{ github.event.inputs.newversion }}
- run: sed -i 's:container-engine:@boardgamers/container-engine:' package.json
- run: pnpm publish --access public --no-git-checks .
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
# pnpm 10.16+ supports OIDC trusted publishing; publish via npx so we don't have to bump
# the repo-wide pnpm. No NODE_AUTH_TOKEN is set, so publishing authenticates with the
# OIDC token instead of the (now-rejected) npm token.
- run: npx -y pnpm@latest publish . --access public --no-git-checks
- run: git push --follow-tags

View file

@ -17,13 +17,13 @@ jobs:
lint_and_test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '12'
- uses: pnpm/action-setup@v1.2.1
node-version: '24'
- uses: pnpm/action-setup@v4
with:
version: 5.17.1
version: 11
- run: pnpm install
- run: pnpm build
- run: pnpm lint

View file

@ -5,10 +5,12 @@ jobs:
prettier:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
- uses: pnpm/action-setup@v1.2.1
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
version: 5.17.1
node-version: '24'
- uses: pnpm/action-setup@v4
with:
version: 11
- run: pnpm install
- run: pnpm run prettier-check

View file

@ -8,7 +8,7 @@ on:
default: patch
env:
node_version: 14
node_version: 24
defaults:
run:
@ -17,24 +17,25 @@ defaults:
jobs:
version_and_release:
runs-on: ubuntu-latest
permissions:
contents: write # git push --follow-tags
id-token: write # OIDC trusted publishing
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- name: Use Node.js ${{ env.node_version }}
uses: actions/setup-node@v2
uses: actions/setup-node@v4
with:
node-version: ${{ env.node_version }}
# setting a registry enables the NODE_AUTH_TOKEN env variable where we can set an npm token. REQUIRED
# registry-url is required so npm publish targets the public npm registry
registry-url: 'https://registry.npmjs.org'
- uses: pnpm/action-setup@v1.2.1
with:
version: 5.17.1
- run: pnpm install
- run: npm install -g pnpm@11
- run: pnpm install --frozen-lockfile
- run: git config --global user.name github-actions
- run: git config --global user.email bot@github.com
- run: yarn config set version-git-message "Viewer v%s"
- run: yarn version --${{ github.event.inputs.newversion }}
- run: sed -i 's:"container-viewer":"@boardgamers/container-viewer":' package.json
- run: pnpm publish --access public --no-git-checks .
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
# pnpm supports OIDC trusted publishing and rewrites workspace dependencies.
# No NODE_AUTH_TOKEN: publishing authenticates with the OIDC token.
- run: pnpm publish . --access public --no-git-checks
- run: git push --follow-tags

View file

@ -4,12 +4,18 @@ on:
paths:
- '.github/workflows/viewer-test.yml'
- 'viewer/**'
- 'engine/**'
- 'pnpm-lock.yaml'
- 'pnpm-workspace.yaml'
branches:
- master
pull_request:
paths:
- '.github/workflows/viewer-test.yml'
- 'viewer/**'
- 'engine/**'
- 'pnpm-lock.yaml'
- 'pnpm-workspace.yaml'
defaults:
run:
@ -19,14 +25,22 @@ jobs:
test_and_build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '14'
- uses: pnpm/action-setup@v1.2.1
node-version: '24'
- uses: pnpm/action-setup@v4
with:
version: 5.17.1
- run: pnpm install
# - run: pnpm lint
# - run: pnpm test
version: 11
- run: pnpm install --frozen-lockfile
- run: pnpm --dir .. test:locales
- run: pnpm check
- run: pnpm test:unit
- run: pnpm test:tutorial
- run: pnpm build
- run: pnpm --dir ../engine build
- run: pnpm package
- run: pnpm exec playwright install --with-deps chromium
- run: pnpm test:browser
- run: pnpm test:offshore:browser
- run: pnpm test:tutorial:browser

4
.gitignore vendored
View file

@ -1 +1,5 @@
node_modules
.pnpm-store
.playwright-mcp
*.tgz

View file

@ -1,4 +1,11 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
pnpm run lint-staged
# The system pnpm is a corepack shim running pnpm 11, which fails on this repo's
# old (v5) lockfile. Prefer a repo-local pnpm 5 if one is installed.
PNPM="$(git rev-parse --git-dir)/pnpm-local.sh"
if [ ! -x "$PNPM" ]; then
PNPM="pnpm"
fi
"$PNPM" run lint-staged

4
.prettierignore Normal file
View file

@ -0,0 +1,4 @@
dist/
.vscode/
.local/

15
AGENTS.md Normal file
View file

@ -0,0 +1,15 @@
# Agent instructions
## BGS publication and Git delivery
Whenever changes are published to BGS, commit the corresponding source, tests,
dependency/lockfile changes and version bumps, then push them to this repository's
`main` or `master` release branch in the same task. A BGS upload or a push only to
a feature branch does not complete delivery. This is standing authorization to
commit and push published changes without asking for separate confirmation.
Fetch and integrate the latest release-branch changes, run the relevant repository
checks, and push without force. Update any public mirrors required by this repo's
existing workflow too. Keep credentials, generated artifacts excluded by the repo,
and unrelated unfinished work out of the commit. Verify the remote branch contains
the delivered commit and report any blocker instead of claiming delivery.

View file

@ -1,7 +1,5 @@
# Container
[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/boardgamers/container)
Mono repo containing the viewer & the engine for Gaia Container
Checkout their READMEs:
@ -9,9 +7,11 @@ Checkout their READMEs:
- [engine](./engine/README.md)
- [viewer](./viewer/README.md)
## Demo
## Play online at
Check out [boardgamers.space](https://www.boardgamers.space)! Reach out to us if you want to contribute.
[boardgamers.space](https://boardgamers.space/boardgame/container)
Reach out to us if you want to contribute.
## Install
@ -27,3 +27,7 @@ npm run serve
```
It will use the engine in its sibling folder
Optional expansion: see [Offshore Island rules, setup, and release notes](docs/offshore-island.md).
Viewer releases: see [uploading the complete viewer build](docs/viewer-publishing.md).

View file

@ -0,0 +1,69 @@
# Container achievement artwork — revision 3
Issue: https://codeberg.org/boardgamers/boardgamers/issues/595
Original industrial geometric artwork for all 17 current awards. This is artwork
and asset-reference maintenance only. Engine 2.1.9 → 2.1.10; achievement manifest
revision 2 → 3; protocol remains 0.11.0. `island-fifteen` is retained; retired
`island-five` and `warehouse-six` are not restored. Definitions, descriptions,
eligibility and evaluator remain identical to canonical baseline
`99e60d5e8f4111f0435d9ea911e2431ec8ef2f7f`.
## Provenance and reproduction
All geometry was authored for this release, under the repository's MIT license.
No downloaded imagery, commercial illustrations, external icons, or font outlines
are used. The five cargo colors correspond to `ContainerColor` in
`engine/src/gamestate.ts`: orange, brown, white, darkslategray, tan. This is
original implementation artwork, not official physical-edition art.
Editable geometry: `scripts/generate-achievement-art.py` and the exported SVGs.
The renderer uses Python 3.12, CairoSVG 2.8.2 and Pillow 11.3.0. Install these in an
isolated environment, then run from the repository root:
```sh
python scripts/generate-achievement-art.py
python scripts/test-achievement-art.py
pnpm --dir engine test
pnpm --dir engine build
```
`manifest.json` provides the exact stable asset keys, SVG and PNG filenames,
SHA-256 hashes, generator hash, source baseline and provenance. PNG uploads are
256 × 256 RGBA. Contact sheets show actual-size 32/48/64px badges on light and
dark backgrounds. All forms fit the circular badge; color is supplemented by
shape and, for cargo diversity, distinct internal patterns. No text font is
required for the geometric score/holding digits.
## Semantic inventory
- `win`: laden freighter and victory pennant.
- `win-three-player`, `win-four-player`, `win-five-player`: exactly three/four/five
separate company quay/offices surround the winning ship. These are company
counters, not cargo colors. Triangle, square and pentagonal harbor layouts.
- `debt-free-win`: ship, victory pennant and checked loan ledger.
- `score-100`: cash and cargo-value columns in a final-account spread.
- `score-150`: expanded industrial skyline and proceeds around the final account;
structural progression, not simply a changed numeral.
- `debt-free`: checked loan ledger without victory imagery.
- `three-factories`, `four-factories`: exactly three/four sawtooth-roof factories,
with chimneys and triangle/square production connections.
- `three-warehouses`, `five-warehouses`: exactly three/five gable-roof depots,
distinguished from factories, along a road or around a loading courtyard.
- `island-fifteen`, `island-ten`: three/two rows of five cargo containers on a
shoreline. Supporting digits denote the minimum holdings, not extra awards.
- `island-diversity`: all five actual color identities, each with a different
redundant pattern, on an island.
- `full-ship`: five occupied cargo slots on a freighter hull.
- `warehouse-five`: five occupied storage positions in one large warehouse
cutaway, distinct from five owned warehouse buildings.
## Release gate
Source is prepared on isolated `moon/achievement-art-2026`; canonical release
remote is `git@github.com:boardgamers/container`, branch `master`. `origin` was
fetched and integrated before implementation. No additional configured mirror or
mirror publication workflow was found. No asset upload or engine activation is
part of this authoring stage. Publication requires fresh independent code and
actual image review approval from the coordinator. The exact tested package and
review logs are retained outside tracked sources; the worktree is retained.

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 128 128"><circle cx="64" cy="64" r="62" fill="#132e3b" stroke="#f4b34a" stroke-width="3"/><g transform="translate(49 0) scale(0.68)"><rect x="35" y="28" width="58" height="70" fill="#f5e8ce" stroke="#f4b34a" stroke-width="3"/><path d="M45 43 H81 M45 53 H74 M45 63 H68" fill="none" stroke="#132e3b" stroke-width="4" stroke-linejoin="round" stroke-linecap="round"/><g transform="translate(53 73) scale(1)"><path d="M0 10 L8 18 L25 0" fill="none" stroke="#58bab4" stroke-width="6" stroke-linejoin="round" stroke-linecap="round"/></g></g><path d="M27 53 V28" fill="none" stroke="#f5e8ce" stroke-width="3" stroke-linejoin="round" stroke-linecap="round"/><path d="M29 28 H51 L44 35 L51 42 H29 Z" fill="#f4b34a"/><g transform="translate(0 23) scale(0.9)"><path d="M20 75 H109 L96 91 H34 Z" fill="#f5e8ce" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/><rect x="24" y="52" width="15" height="22" fill="#58bab4" stroke="#132e3b" stroke-width="2"/><rect x="27" y="46" width="6" height="6" fill="#f5e8ce" stroke="#132e3b" stroke-width="2"/><rect x="27" y="57" width="8" height="6" fill="#132e3b" stroke="#132e3b" stroke-width="0"/><rect x="43" y="59" width="22" height="15" fill="#e98437" stroke="#132e3b" stroke-width="1.5"/><path d="M50.333333333333336 62 V71 M57.666666666666664 62 V71" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="67" y="59" width="22" height="15" fill="#c7a16c" stroke="#132e3b" stroke-width="1.5"/><path d="M74.33333333333333 62 V71 M81.66666666666667 62 V71" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><path d="M28 99 H48 L54 95 H75 L81 99 H101" fill="none" stroke="#58bab4" stroke-width="3" stroke-linejoin="round" stroke-linecap="round"/></g></svg>

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 128 128"><circle cx="64" cy="64" r="62" fill="#132e3b" stroke="#f4b34a" stroke-width="3"/><rect x="35" y="28" width="58" height="70" fill="#f5e8ce" stroke="#f4b34a" stroke-width="3"/><path d="M45 43 H81 M45 53 H74 M45 63 H68" fill="none" stroke="#132e3b" stroke-width="4" stroke-linejoin="round" stroke-linecap="round"/><g transform="translate(53 73) scale(1)"><path d="M0 10 L8 18 L25 0" fill="none" stroke="#58bab4" stroke-width="6" stroke-linejoin="round" stroke-linecap="round"/></g><path d="M26 37 H20 V103 H81 V107" fill="none" stroke="#58bab4" stroke-width="3" stroke-linejoin="round" stroke-linecap="round"/></svg>

After

Width:  |  Height:  |  Size: 701 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 128 128"><circle cx="64" cy="64" r="62" fill="#132e3b" stroke="#f4b34a" stroke-width="3"/><path d="M39 41 H88 V90 H39 Z" fill="none" stroke="#f4b34a" stroke-width="5" stroke-linejoin="round" stroke-linecap="round"/><g transform="translate(28 26) scale(0.75)"><path d="M0 12 L14 0 L28 12 V34 H0 Z" fill="#f5e8ce" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/><rect x="6" y="16" width="16" height="18" fill="#58bab4" stroke="#132e3b" stroke-width="2"/><path d="M9 22 H19 M9 27 H19" fill="none" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/></g><g transform="translate(53 21) scale(0.75)"><path d="M0 12 L14 0 L28 12 V34 H0 Z" fill="#f5e8ce" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/><rect x="6" y="16" width="16" height="18" fill="#58bab4" stroke="#132e3b" stroke-width="2"/><path d="M9 22 H19 M9 27 H19" fill="none" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/></g><g transform="translate(78 26) scale(0.75)"><path d="M0 12 L14 0 L28 12 V34 H0 Z" fill="#f5e8ce" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/><rect x="6" y="16" width="16" height="18" fill="#58bab4" stroke="#132e3b" stroke-width="2"/><path d="M9 22 H19 M9 27 H19" fill="none" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/></g><g transform="translate(29 76) scale(0.75)"><path d="M0 12 L14 0 L28 12 V34 H0 Z" fill="#f5e8ce" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/><rect x="6" y="16" width="16" height="18" fill="#58bab4" stroke="#132e3b" stroke-width="2"/><path d="M9 22 H19 M9 27 H19" fill="none" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/></g><g transform="translate(78 76) scale(0.75)"><path d="M0 12 L14 0 L28 12 V34 H0 Z" fill="#f5e8ce" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/><rect x="6" y="16" width="16" height="18" fill="#58bab4" stroke="#132e3b" stroke-width="2"/><path d="M9 22 H19 M9 27 H19" fill="none" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/></g></svg>

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 128 128"><circle cx="64" cy="64" r="62" fill="#132e3b" stroke="#f4b34a" stroke-width="3"/><path d="M41 43 H86 V87 H41 Z" fill="none" stroke="#58bab4" stroke-width="5" stroke-linejoin="round" stroke-linecap="round"/><g transform="translate(26 22) scale(0.95)"><rect x="3" y="0" width="6" height="23" fill="#f4b34a" stroke="#132e3b" stroke-width="2"/><path d="M0 17 L12 9 V17 L24 9 V33 H0 Z" fill="#f5e8ce" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/><rect x="5" y="23" width="5" height="10" fill="#58bab4" stroke="#132e3b" stroke-width="2"/><rect x="15" y="23" width="5" height="10" fill="#58bab4" stroke="#132e3b" stroke-width="2"/></g><g transform="translate(78 22) scale(0.95)"><rect x="3" y="0" width="6" height="23" fill="#f4b34a" stroke="#132e3b" stroke-width="2"/><path d="M0 17 L12 9 V17 L24 9 V33 H0 Z" fill="#f5e8ce" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/><rect x="5" y="23" width="5" height="10" fill="#58bab4" stroke="#132e3b" stroke-width="2"/><rect x="15" y="23" width="5" height="10" fill="#58bab4" stroke="#132e3b" stroke-width="2"/></g><g transform="translate(26 73) scale(0.95)"><rect x="3" y="0" width="6" height="23" fill="#f4b34a" stroke="#132e3b" stroke-width="2"/><path d="M0 17 L12 9 V17 L24 9 V33 H0 Z" fill="#f5e8ce" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/><rect x="5" y="23" width="5" height="10" fill="#58bab4" stroke="#132e3b" stroke-width="2"/><rect x="15" y="23" width="5" height="10" fill="#58bab4" stroke="#132e3b" stroke-width="2"/></g><g transform="translate(78 73) scale(0.95)"><rect x="3" y="0" width="6" height="23" fill="#f4b34a" stroke="#132e3b" stroke-width="2"/><path d="M0 17 L12 9 V17 L24 9 V33 H0 Z" fill="#f5e8ce" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/><rect x="5" y="23" width="5" height="10" fill="#58bab4" stroke="#132e3b" stroke-width="2"/><rect x="15" y="23" width="5" height="10" fill="#58bab4" stroke="#132e3b" stroke-width="2"/></g></svg>

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 128 128"><circle cx="64" cy="64" r="62" fill="#132e3b" stroke="#f4b34a" stroke-width="3"/><path d="M20 75 H109 L96 91 H34 Z" fill="#f5e8ce" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/><rect x="24" y="52" width="15" height="22" fill="#58bab4" stroke="#132e3b" stroke-width="2"/><rect x="27" y="46" width="6" height="6" fill="#f5e8ce" stroke="#132e3b" stroke-width="2"/><rect x="27" y="57" width="8" height="6" fill="#132e3b" stroke="#132e3b" stroke-width="0"/><rect x="41" y="60" width="12" height="14" fill="#e98437" stroke="#132e3b" stroke-width="1.5"/><path d="M45.0 63 V71 M49.0 63 V71" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="54" y="60" width="12" height="14" fill="#976444" stroke="#132e3b" stroke-width="1.5"/><path d="M58.0 63 V71 M62.0 63 V71" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="67" y="60" width="12" height="14" fill="#f5e8ce" stroke="#132e3b" stroke-width="1.5"/><path d="M71.0 63 V71 M75.0 63 V71" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="80" y="60" width="12" height="14" fill="#31414a" stroke="#f5e8ce" stroke-width="1.5"/><path d="M84.0 63 V71 M88.0 63 V71" fill="none" stroke="#f5e8ce" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="93" y="60" width="12" height="14" fill="#c7a16c" stroke="#132e3b" stroke-width="1.5"/><path d="M97.0 63 V71 M101.0 63 V71" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><path d="M28 99 H48 L54 95 H75 L81 99 H101" fill="none" stroke="#58bab4" stroke-width="3" stroke-linejoin="round" stroke-linecap="round"/><path d="M43 47 H104 M43 43 V51 M104 43 V51" fill="none" stroke="#f4b34a" stroke-width="3" stroke-linejoin="round" stroke-linecap="round"/></svg>

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 128 128"><circle cx="64" cy="64" r="62" fill="#132e3b" stroke="#f4b34a" stroke-width="3"/><path d="M17 70 L27 40 L63 29 L101 44 L111 76 L95 96 L37 99 Z" fill="#58bab4" stroke="#f5e8ce" stroke-width="3" stroke-linejoin="round" stroke-linecap="round"/><path d="M21 104 H43 M85 104 H104" fill="none" stroke="#58bab4" stroke-width="3" stroke-linejoin="round" stroke-linecap="round"/><rect x="36" y="43" width="21" height="19" fill="#e98437" stroke="#132e3b" stroke-width="1.5"/><path d="M39 59 L54 46" fill="none" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/><rect x="67" y="43" width="21" height="19" fill="#976444" stroke="#132e3b" stroke-width="1.5"/><path d="M70 46 L85 59" fill="none" stroke="#f5e8ce" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/><rect x="24" y="68" width="21" height="19" fill="#f5e8ce" stroke="#132e3b" stroke-width="1.5"/><path d="M34.5 70 V85" fill="none" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/><rect x="54" y="68" width="21" height="19" fill="#31414a" stroke="#f5e8ce" stroke-width="1.5"/><path d="M57 77.5 H72" fill="none" stroke="#f5e8ce" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/><rect x="84" y="68" width="21" height="19" fill="#c7a16c" stroke="#132e3b" stroke-width="1.5"/><path d="M87 71 L94.5 84 L102 71" fill="none" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 128 128"><circle cx="64" cy="64" r="62" fill="#132e3b" stroke="#f4b34a" stroke-width="3"/><path d="M17 70 L27 40 L63 29 L101 44 L111 76 L95 96 L37 99 Z" fill="#58bab4" stroke="#f5e8ce" stroke-width="3" stroke-linejoin="round" stroke-linecap="round"/><path d="M21 104 H43 M85 104 H104" fill="none" stroke="#58bab4" stroke-width="3" stroke-linejoin="round" stroke-linecap="round"/><rect x="27" y="43" width="13" height="14" fill="#e98437" stroke="#132e3b" stroke-width="1.5"/><path d="M31.333333333333332 46 V54 M35.666666666666664 46 V54" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="42" y="43" width="13" height="14" fill="#976444" stroke="#132e3b" stroke-width="1.5"/><path d="M46.333333333333336 46 V54 M50.666666666666664 46 V54" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="57" y="43" width="13" height="14" fill="#f5e8ce" stroke="#132e3b" stroke-width="1.5"/><path d="M61.333333333333336 46 V54 M65.66666666666667 46 V54" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="72" y="43" width="13" height="14" fill="#31414a" stroke="#f5e8ce" stroke-width="1.5"/><path d="M76.33333333333333 46 V54 M80.66666666666667 46 V54" fill="none" stroke="#f5e8ce" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="87" y="43" width="13" height="14" fill="#c7a16c" stroke="#132e3b" stroke-width="1.5"/><path d="M91.33333333333333 46 V54 M95.66666666666667 46 V54" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="27" y="60" width="13" height="14" fill="#e98437" stroke="#132e3b" stroke-width="1.5"/><path d="M31.333333333333332 63 V71 M35.666666666666664 63 V71" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="42" y="60" width="13" height="14" fill="#976444" stroke="#132e3b" stroke-width="1.5"/><path d="M46.333333333333336 63 V71 M50.666666666666664 63 V71" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="57" y="60" width="13" height="14" fill="#f5e8ce" stroke="#132e3b" stroke-width="1.5"/><path d="M61.333333333333336 63 V71 M65.66666666666667 63 V71" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="72" y="60" width="13" height="14" fill="#31414a" stroke="#f5e8ce" stroke-width="1.5"/><path d="M76.33333333333333 63 V71 M80.66666666666667 63 V71" fill="none" stroke="#f5e8ce" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="87" y="60" width="13" height="14" fill="#c7a16c" stroke="#132e3b" stroke-width="1.5"/><path d="M91.33333333333333 63 V71 M95.66666666666667 63 V71" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="27" y="77" width="13" height="14" fill="#e98437" stroke="#132e3b" stroke-width="1.5"/><path d="M31.333333333333332 80 V88 M35.666666666666664 80 V88" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="42" y="77" width="13" height="14" fill="#976444" stroke="#132e3b" stroke-width="1.5"/><path d="M46.333333333333336 80 V88 M50.666666666666664 80 V88" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="57" y="77" width="13" height="14" fill="#f5e8ce" stroke="#132e3b" stroke-width="1.5"/><path d="M61.333333333333336 80 V88 M65.66666666666667 80 V88" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="72" y="77" width="13" height="14" fill="#31414a" stroke="#f5e8ce" stroke-width="1.5"/><path d="M76.33333333333333 80 V88 M80.66666666666667 80 V88" fill="none" stroke="#f5e8ce" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="87" y="77" width="13" height="14" fill="#c7a16c" stroke="#132e3b" stroke-width="1.5"/><path d="M91.33333333333333 80 V88 M95.66666666666667 80 V88" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="47" y="96" width="35" height="20" fill="#132e3b" stroke="#132e3b" stroke-width="0"/><g transform="translate(51 98) scale(1)"><g transform="translate(0 0) scale(1)"><path d="M1 3 L5 0 V14 M1 14 H9" fill="none" stroke="#f5e8ce" stroke-width="2.5" stroke-linejoin="round" stroke-linecap="round"/></g><g transform="translate(14 0) scale(1)"><path d="M9 0 H0 V7 H8 V14 H0" fill="none" stroke="#f5e8ce" stroke-width="2.5" stroke-linejoin="round" stroke-linecap="round"/></g></g></svg>

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 128 128"><circle cx="64" cy="64" r="62" fill="#132e3b" stroke="#f4b34a" stroke-width="3"/><path d="M17 70 L27 40 L63 29 L101 44 L111 76 L95 96 L37 99 Z" fill="#58bab4" stroke="#f5e8ce" stroke-width="3" stroke-linejoin="round" stroke-linecap="round"/><path d="M21 104 H43 M85 104 H104" fill="none" stroke="#58bab4" stroke-width="3" stroke-linejoin="round" stroke-linecap="round"/><rect x="27" y="43" width="13" height="14" fill="#e98437" stroke="#132e3b" stroke-width="1.5"/><path d="M31.333333333333332 46 V54 M35.666666666666664 46 V54" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="42" y="43" width="13" height="14" fill="#976444" stroke="#132e3b" stroke-width="1.5"/><path d="M46.333333333333336 46 V54 M50.666666666666664 46 V54" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="57" y="43" width="13" height="14" fill="#f5e8ce" stroke="#132e3b" stroke-width="1.5"/><path d="M61.333333333333336 46 V54 M65.66666666666667 46 V54" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="72" y="43" width="13" height="14" fill="#31414a" stroke="#f5e8ce" stroke-width="1.5"/><path d="M76.33333333333333 46 V54 M80.66666666666667 46 V54" fill="none" stroke="#f5e8ce" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="87" y="43" width="13" height="14" fill="#c7a16c" stroke="#132e3b" stroke-width="1.5"/><path d="M91.33333333333333 46 V54 M95.66666666666667 46 V54" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="27" y="60" width="13" height="14" fill="#e98437" stroke="#132e3b" stroke-width="1.5"/><path d="M31.333333333333332 63 V71 M35.666666666666664 63 V71" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="42" y="60" width="13" height="14" fill="#976444" stroke="#132e3b" stroke-width="1.5"/><path d="M46.333333333333336 63 V71 M50.666666666666664 63 V71" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="57" y="60" width="13" height="14" fill="#f5e8ce" stroke="#132e3b" stroke-width="1.5"/><path d="M61.333333333333336 63 V71 M65.66666666666667 63 V71" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="72" y="60" width="13" height="14" fill="#31414a" stroke="#f5e8ce" stroke-width="1.5"/><path d="M76.33333333333333 63 V71 M80.66666666666667 63 V71" fill="none" stroke="#f5e8ce" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="87" y="60" width="13" height="14" fill="#c7a16c" stroke="#132e3b" stroke-width="1.5"/><path d="M91.33333333333333 63 V71 M95.66666666666667 63 V71" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="47" y="96" width="35" height="20" fill="#132e3b" stroke="#132e3b" stroke-width="0"/><g transform="translate(51 98) scale(1)"><g transform="translate(0 0) scale(1)"><path d="M1 3 L5 0 V14 M1 14 H9" fill="none" stroke="#f5e8ce" stroke-width="2.5" stroke-linejoin="round" stroke-linecap="round"/></g><g transform="translate(14 0) scale(1)"><path d="M0 0 H8 V14 H0 Z" fill="none" stroke="#f5e8ce" stroke-width="2.5" stroke-linejoin="round" stroke-linecap="round"/></g></g></svg>

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 128 128"><circle cx="64" cy="64" r="62" fill="#132e3b" stroke="#f4b34a" stroke-width="3"/><rect x="40" y="26" width="22" height="17" fill="#e98437" stroke="#132e3b" stroke-width="1.5"/><path d="M47.333333333333336 29 V40 M54.666666666666664 29 V40" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="70" y="26" width="20" height="17" fill="#f4b34a" stroke="#132e3b" stroke-width="2"/><path d="M75 34 H85" fill="none" stroke="#132e3b" stroke-width="3" stroke-linejoin="round" stroke-linecap="round"/><path d="M22 52 L61 47 L64 52 L67 47 L106 52 V88 L67 83 L64 88 L61 83 L22 88 Z" fill="#f5e8ce" stroke="#132e3b" stroke-width="3" stroke-linejoin="round" stroke-linecap="round"/><path d="M64 54 V81 M30 61 H52 M30 71 H52 M76 61 H97 M76 71 H97" fill="none" stroke="#58bab4" stroke-width="4" stroke-linejoin="round" stroke-linecap="round"/><g transform="translate(45 96) scale(0.95)"><g transform="translate(0 0) scale(1)"><path d="M1 3 L5 0 V14 M1 14 H9" fill="none" stroke="#f5e8ce" stroke-width="2.5" stroke-linejoin="round" stroke-linecap="round"/></g><g transform="translate(14 0) scale(1)"><path d="M0 0 H8 V14 H0 Z" fill="none" stroke="#f5e8ce" stroke-width="2.5" stroke-linejoin="round" stroke-linecap="round"/></g><g transform="translate(28 0) scale(1)"><path d="M0 0 H8 V14 H0 Z" fill="none" stroke="#f5e8ce" stroke-width="2.5" stroke-linejoin="round" stroke-linecap="round"/></g></g></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 128 128"><circle cx="64" cy="64" r="62" fill="#132e3b" stroke="#f4b34a" stroke-width="3"/><g transform="translate(28 20) scale(0.8)"><rect x="3" y="0" width="6" height="23" fill="#f4b34a" stroke="#132e3b" stroke-width="2"/><path d="M0 17 L12 9 V17 L24 9 V33 H0 Z" fill="#f5e8ce" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/><rect x="5" y="23" width="5" height="10" fill="#58bab4" stroke="#132e3b" stroke-width="2"/><rect x="15" y="23" width="5" height="10" fill="#58bab4" stroke="#132e3b" stroke-width="2"/></g><g transform="translate(53 14) scale(0.9)"><rect x="3" y="0" width="6" height="23" fill="#f4b34a" stroke="#132e3b" stroke-width="2"/><path d="M0 17 L12 9 V17 L24 9 V33 H0 Z" fill="#f5e8ce" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/><rect x="5" y="23" width="5" height="10" fill="#58bab4" stroke="#132e3b" stroke-width="2"/><rect x="15" y="23" width="5" height="10" fill="#58bab4" stroke="#132e3b" stroke-width="2"/></g><g transform="translate(82 24) scale(0.7)"><rect x="3" y="0" width="6" height="23" fill="#f4b34a" stroke="#132e3b" stroke-width="2"/><path d="M0 17 L12 9 V17 L24 9 V33 H0 Z" fill="#f5e8ce" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/><rect x="5" y="23" width="5" height="10" fill="#58bab4" stroke="#132e3b" stroke-width="2"/><rect x="15" y="23" width="5" height="10" fill="#58bab4" stroke="#132e3b" stroke-width="2"/></g><path d="M22 52 L61 47 L64 52 L67 47 L106 52 V88 L67 83 L64 88 L61 83 L22 88 Z" fill="#f5e8ce" stroke="#132e3b" stroke-width="3" stroke-linejoin="round" stroke-linecap="round"/><path d="M64 54 V81 M30 61 H52 M30 71 H52 M76 61 H97 M76 71 H97" fill="none" stroke="#58bab4" stroke-width="4" stroke-linejoin="round" stroke-linecap="round"/><rect x="22" y="87" width="17" height="7" fill="#f4b34a" stroke="#132e3b" stroke-width="2"/><rect x="89" y="87" width="17" height="7" fill="#f4b34a" stroke="#132e3b" stroke-width="2"/><g transform="translate(45 96) scale(0.95)"><g transform="translate(0 0) scale(1)"><path d="M1 3 L5 0 V14 M1 14 H9" fill="none" stroke="#f5e8ce" stroke-width="2.5" stroke-linejoin="round" stroke-linecap="round"/></g><g transform="translate(14 0) scale(1)"><path d="M9 0 H0 V7 H8 V14 H0" fill="none" stroke="#f5e8ce" stroke-width="2.5" stroke-linejoin="round" stroke-linecap="round"/></g><g transform="translate(28 0) scale(1)"><path d="M0 0 H8 V14 H0 Z" fill="none" stroke="#f5e8ce" stroke-width="2.5" stroke-linejoin="round" stroke-linecap="round"/></g></g></svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 128 128"><circle cx="64" cy="64" r="62" fill="#132e3b" stroke="#f4b34a" stroke-width="3"/><path d="M39 73 L64 40 L90 73 Z" fill="none" stroke="#58bab4" stroke-width="5" stroke-linejoin="round" stroke-linecap="round"/><g transform="translate(52 21) scale(1)"><rect x="3" y="0" width="6" height="23" fill="#f4b34a" stroke="#132e3b" stroke-width="2"/><path d="M0 17 L12 9 V17 L24 9 V33 H0 Z" fill="#f5e8ce" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/><rect x="5" y="23" width="5" height="10" fill="#58bab4" stroke="#132e3b" stroke-width="2"/><rect x="15" y="23" width="5" height="10" fill="#58bab4" stroke="#132e3b" stroke-width="2"/></g><g transform="translate(22 69) scale(1)"><rect x="3" y="0" width="6" height="23" fill="#f4b34a" stroke="#132e3b" stroke-width="2"/><path d="M0 17 L12 9 V17 L24 9 V33 H0 Z" fill="#f5e8ce" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/><rect x="5" y="23" width="5" height="10" fill="#58bab4" stroke="#132e3b" stroke-width="2"/><rect x="15" y="23" width="5" height="10" fill="#58bab4" stroke="#132e3b" stroke-width="2"/></g><g transform="translate(82 69) scale(1)"><rect x="3" y="0" width="6" height="23" fill="#f4b34a" stroke="#132e3b" stroke-width="2"/><path d="M0 17 L12 9 V17 L24 9 V33 H0 Z" fill="#f5e8ce" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/><rect x="5" y="23" width="5" height="10" fill="#58bab4" stroke="#132e3b" stroke-width="2"/><rect x="15" y="23" width="5" height="10" fill="#58bab4" stroke="#132e3b" stroke-width="2"/></g></svg>

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 128 128"><circle cx="64" cy="64" r="62" fill="#132e3b" stroke="#f4b34a" stroke-width="3"/><path d="M23 94 H106" fill="none" stroke="#f4b34a" stroke-width="5" stroke-linejoin="round" stroke-linecap="round"/><g transform="translate(20 48) scale(1)"><path d="M0 12 L14 0 L28 12 V34 H0 Z" fill="#f5e8ce" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/><rect x="6" y="16" width="16" height="18" fill="#58bab4" stroke="#132e3b" stroke-width="2"/><path d="M9 22 H19 M9 27 H19" fill="none" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/></g><g transform="translate(50 48) scale(1)"><path d="M0 12 L14 0 L28 12 V34 H0 Z" fill="#f5e8ce" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/><rect x="6" y="16" width="16" height="18" fill="#58bab4" stroke="#132e3b" stroke-width="2"/><path d="M9 22 H19 M9 27 H19" fill="none" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/></g><g transform="translate(80 48) scale(1)"><path d="M0 12 L14 0 L28 12 V34 H0 Z" fill="#f5e8ce" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/><rect x="6" y="16" width="16" height="18" fill="#58bab4" stroke="#132e3b" stroke-width="2"/><path d="M9 22 H19 M9 27 H19" fill="none" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/></g></svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 128 128"><circle cx="64" cy="64" r="62" fill="#132e3b" stroke="#f4b34a" stroke-width="3"/><path d="M17 49 L64 24 L111 49 V99 H17 Z" fill="#f5e8ce" stroke="#132e3b" stroke-width="3" stroke-linejoin="round" stroke-linecap="round"/><path d="M25 49 H103 M24 93 H104" fill="none" stroke="#58bab4" stroke-width="4" stroke-linejoin="round" stroke-linecap="round"/><rect x="24" y="67" width="15" height="21" fill="#e98437" stroke="#132e3b" stroke-width="1.5"/><path d="M29.0 70 V85 M34.0 70 V85" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="40" y="67" width="15" height="21" fill="#976444" stroke="#132e3b" stroke-width="1.5"/><path d="M45.0 70 V85 M50.0 70 V85" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="56" y="67" width="15" height="21" fill="#f5e8ce" stroke="#132e3b" stroke-width="1.5"/><path d="M61.0 70 V85 M66.0 70 V85" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="72" y="67" width="15" height="21" fill="#31414a" stroke="#f5e8ce" stroke-width="1.5"/><path d="M77.0 70 V85 M82.0 70 V85" fill="none" stroke="#f5e8ce" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="88" y="67" width="15" height="21" fill="#c7a16c" stroke="#132e3b" stroke-width="1.5"/><path d="M93.0 70 V85 M98.0 70 V85" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 128 128"><circle cx="64" cy="64" r="62" fill="#132e3b" stroke="#f4b34a" stroke-width="3"/><g transform="translate(64.0 25.0) scale(1)"><rect x="-10" y="-9" width="20" height="18" fill="#f5e8ce" stroke="#132e3b" stroke-width="2"/><rect x="-6" y="-5" width="4" height="5" fill="#132e3b" stroke="#132e3b" stroke-width="2"/><rect x="2" y="-5" width="4" height="5" fill="#132e3b" stroke="#132e3b" stroke-width="2"/><rect x="-8" y="9" width="16" height="8" fill="#f4b34a" stroke="#132e3b" stroke-width="2"/></g><g transform="translate(101.09 50.57) scale(1)"><rect x="-10" y="-9" width="20" height="18" fill="#f5e8ce" stroke="#132e3b" stroke-width="2"/><rect x="-6" y="-5" width="4" height="5" fill="#132e3b" stroke="#132e3b" stroke-width="2"/><rect x="2" y="-5" width="4" height="5" fill="#132e3b" stroke="#132e3b" stroke-width="2"/><rect x="-8" y="9" width="16" height="8" fill="#f4b34a" stroke="#132e3b" stroke-width="2"/></g><g transform="translate(86.92 91.93) scale(1)"><rect x="-10" y="-9" width="20" height="18" fill="#f5e8ce" stroke="#132e3b" stroke-width="2"/><rect x="-6" y="-5" width="4" height="5" fill="#132e3b" stroke="#132e3b" stroke-width="2"/><rect x="2" y="-5" width="4" height="5" fill="#132e3b" stroke="#132e3b" stroke-width="2"/><rect x="-8" y="9" width="16" height="8" fill="#f4b34a" stroke="#132e3b" stroke-width="2"/></g><g transform="translate(41.08 91.93) scale(1)"><rect x="-10" y="-9" width="20" height="18" fill="#f5e8ce" stroke="#132e3b" stroke-width="2"/><rect x="-6" y="-5" width="4" height="5" fill="#132e3b" stroke="#132e3b" stroke-width="2"/><rect x="2" y="-5" width="4" height="5" fill="#132e3b" stroke="#132e3b" stroke-width="2"/><rect x="-8" y="9" width="16" height="8" fill="#f4b34a" stroke="#132e3b" stroke-width="2"/></g><g transform="translate(26.91 50.57) scale(1)"><rect x="-10" y="-9" width="20" height="18" fill="#f5e8ce" stroke="#132e3b" stroke-width="2"/><rect x="-6" y="-5" width="4" height="5" fill="#132e3b" stroke="#132e3b" stroke-width="2"/><rect x="2" y="-5" width="4" height="5" fill="#132e3b" stroke="#132e3b" stroke-width="2"/><rect x="-8" y="9" width="16" height="8" fill="#f4b34a" stroke="#132e3b" stroke-width="2"/></g><g transform="translate(29 16) scale(0.55)"><path d="M20 75 H109 L96 91 H34 Z" fill="#f5e8ce" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/><rect x="24" y="52" width="15" height="22" fill="#58bab4" stroke="#132e3b" stroke-width="2"/><rect x="27" y="46" width="6" height="6" fill="#f5e8ce" stroke="#132e3b" stroke-width="2"/><rect x="27" y="57" width="8" height="6" fill="#132e3b" stroke="#132e3b" stroke-width="0"/><rect x="43" y="59" width="22" height="15" fill="#e98437" stroke="#132e3b" stroke-width="1.5"/><path d="M50.333333333333336 62 V71 M57.666666666666664 62 V71" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="67" y="59" width="22" height="15" fill="#c7a16c" stroke="#132e3b" stroke-width="1.5"/><path d="M74.33333333333333 62 V71 M81.66666666666667 62 V71" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><path d="M28 99 H48 L54 95 H75 L81 99 H101" fill="none" stroke="#58bab4" stroke-width="3" stroke-linejoin="round" stroke-linecap="round"/></g><g transform="translate(76 35) scale(0.65)"><path d="M0 25 V0" fill="none" stroke="#f5e8ce" stroke-width="3" stroke-linejoin="round" stroke-linecap="round"/><path d="M2 0 H24 L17 7 L24 14 H2 Z" fill="#f4b34a"/></g></svg>

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 128 128"><circle cx="64" cy="64" r="62" fill="#132e3b" stroke="#f4b34a" stroke-width="3"/><g transform="translate(64.0 25.0) scale(1)"><rect x="-10" y="-9" width="20" height="18" fill="#f5e8ce" stroke="#132e3b" stroke-width="2"/><rect x="-6" y="-5" width="4" height="5" fill="#132e3b" stroke="#132e3b" stroke-width="2"/><rect x="2" y="-5" width="4" height="5" fill="#132e3b" stroke="#132e3b" stroke-width="2"/><rect x="-8" y="9" width="16" height="8" fill="#f4b34a" stroke="#132e3b" stroke-width="2"/></g><g transform="translate(103.0 62.0) scale(1)"><rect x="-10" y="-9" width="20" height="18" fill="#f5e8ce" stroke="#132e3b" stroke-width="2"/><rect x="-6" y="-5" width="4" height="5" fill="#132e3b" stroke="#132e3b" stroke-width="2"/><rect x="2" y="-5" width="4" height="5" fill="#132e3b" stroke="#132e3b" stroke-width="2"/><rect x="-8" y="9" width="16" height="8" fill="#f4b34a" stroke="#132e3b" stroke-width="2"/></g><g transform="translate(64.0 99.0) scale(1)"><rect x="-10" y="-9" width="20" height="18" fill="#f5e8ce" stroke="#132e3b" stroke-width="2"/><rect x="-6" y="-5" width="4" height="5" fill="#132e3b" stroke="#132e3b" stroke-width="2"/><rect x="2" y="-5" width="4" height="5" fill="#132e3b" stroke="#132e3b" stroke-width="2"/><rect x="-8" y="9" width="16" height="8" fill="#f4b34a" stroke="#132e3b" stroke-width="2"/></g><g transform="translate(25.0 62.0) scale(1)"><rect x="-10" y="-9" width="20" height="18" fill="#f5e8ce" stroke="#132e3b" stroke-width="2"/><rect x="-6" y="-5" width="4" height="5" fill="#132e3b" stroke="#132e3b" stroke-width="2"/><rect x="2" y="-5" width="4" height="5" fill="#132e3b" stroke="#132e3b" stroke-width="2"/><rect x="-8" y="9" width="16" height="8" fill="#f4b34a" stroke="#132e3b" stroke-width="2"/></g><g transform="translate(29 16) scale(0.55)"><path d="M20 75 H109 L96 91 H34 Z" fill="#f5e8ce" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/><rect x="24" y="52" width="15" height="22" fill="#58bab4" stroke="#132e3b" stroke-width="2"/><rect x="27" y="46" width="6" height="6" fill="#f5e8ce" stroke="#132e3b" stroke-width="2"/><rect x="27" y="57" width="8" height="6" fill="#132e3b" stroke="#132e3b" stroke-width="0"/><rect x="43" y="59" width="22" height="15" fill="#e98437" stroke="#132e3b" stroke-width="1.5"/><path d="M50.333333333333336 62 V71 M57.666666666666664 62 V71" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="67" y="59" width="22" height="15" fill="#c7a16c" stroke="#132e3b" stroke-width="1.5"/><path d="M74.33333333333333 62 V71 M81.66666666666667 62 V71" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><path d="M28 99 H48 L54 95 H75 L81 99 H101" fill="none" stroke="#58bab4" stroke-width="3" stroke-linejoin="round" stroke-linecap="round"/></g><g transform="translate(76 35) scale(0.65)"><path d="M0 25 V0" fill="none" stroke="#f5e8ce" stroke-width="3" stroke-linejoin="round" stroke-linecap="round"/><path d="M2 0 H24 L17 7 L24 14 H2 Z" fill="#f4b34a"/></g></svg>

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 128 128"><circle cx="64" cy="64" r="62" fill="#132e3b" stroke="#f4b34a" stroke-width="3"/><g transform="translate(64.0 25.0) scale(1)"><rect x="-10" y="-9" width="20" height="18" fill="#f5e8ce" stroke="#132e3b" stroke-width="2"/><rect x="-6" y="-5" width="4" height="5" fill="#132e3b" stroke="#132e3b" stroke-width="2"/><rect x="2" y="-5" width="4" height="5" fill="#132e3b" stroke="#132e3b" stroke-width="2"/><rect x="-8" y="9" width="16" height="8" fill="#f4b34a" stroke="#132e3b" stroke-width="2"/></g><g transform="translate(97.77 80.5) scale(1)"><rect x="-10" y="-9" width="20" height="18" fill="#f5e8ce" stroke="#132e3b" stroke-width="2"/><rect x="-6" y="-5" width="4" height="5" fill="#132e3b" stroke="#132e3b" stroke-width="2"/><rect x="2" y="-5" width="4" height="5" fill="#132e3b" stroke="#132e3b" stroke-width="2"/><rect x="-8" y="9" width="16" height="8" fill="#f4b34a" stroke="#132e3b" stroke-width="2"/></g><g transform="translate(30.23 80.5) scale(1)"><rect x="-10" y="-9" width="20" height="18" fill="#f5e8ce" stroke="#132e3b" stroke-width="2"/><rect x="-6" y="-5" width="4" height="5" fill="#132e3b" stroke="#132e3b" stroke-width="2"/><rect x="2" y="-5" width="4" height="5" fill="#132e3b" stroke="#132e3b" stroke-width="2"/><rect x="-8" y="9" width="16" height="8" fill="#f4b34a" stroke="#132e3b" stroke-width="2"/></g><g transform="translate(29 16) scale(0.55)"><path d="M20 75 H109 L96 91 H34 Z" fill="#f5e8ce" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/><rect x="24" y="52" width="15" height="22" fill="#58bab4" stroke="#132e3b" stroke-width="2"/><rect x="27" y="46" width="6" height="6" fill="#f5e8ce" stroke="#132e3b" stroke-width="2"/><rect x="27" y="57" width="8" height="6" fill="#132e3b" stroke="#132e3b" stroke-width="0"/><rect x="43" y="59" width="22" height="15" fill="#e98437" stroke="#132e3b" stroke-width="1.5"/><path d="M50.333333333333336 62 V71 M57.666666666666664 62 V71" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="67" y="59" width="22" height="15" fill="#c7a16c" stroke="#132e3b" stroke-width="1.5"/><path d="M74.33333333333333 62 V71 M81.66666666666667 62 V71" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><path d="M28 99 H48 L54 95 H75 L81 99 H101" fill="none" stroke="#58bab4" stroke-width="3" stroke-linejoin="round" stroke-linecap="round"/></g><g transform="translate(76 35) scale(0.65)"><path d="M0 25 V0" fill="none" stroke="#f5e8ce" stroke-width="3" stroke-linejoin="round" stroke-linecap="round"/><path d="M2 0 H24 L17 7 L24 14 H2 Z" fill="#f4b34a"/></g></svg>

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 128 128"><circle cx="64" cy="64" r="62" fill="#132e3b" stroke="#f4b34a" stroke-width="3"/><path d="M57 48 V23" fill="none" stroke="#f5e8ce" stroke-width="3" stroke-linejoin="round" stroke-linecap="round"/><path d="M59 23 H81 L74 30 L81 37 H59 Z" fill="#f4b34a"/><path d="M20 75 H109 L96 91 H34 Z" fill="#f5e8ce" stroke="#132e3b" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/><rect x="24" y="52" width="15" height="22" fill="#58bab4" stroke="#132e3b" stroke-width="2"/><rect x="27" y="46" width="6" height="6" fill="#f5e8ce" stroke="#132e3b" stroke-width="2"/><rect x="27" y="57" width="8" height="6" fill="#132e3b" stroke="#132e3b" stroke-width="0"/><rect x="43" y="59" width="22" height="15" fill="#e98437" stroke="#132e3b" stroke-width="1.5"/><path d="M50.333333333333336 62 V71 M57.666666666666664 62 V71" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><rect x="67" y="59" width="22" height="15" fill="#c7a16c" stroke="#132e3b" stroke-width="1.5"/><path d="M74.33333333333333 62 V71 M81.66666666666667 62 V71" fill="none" stroke="#132e3b" stroke-width="1" stroke-linejoin="round" stroke-linecap="round"/><path d="M28 99 H48 L54 95 H75 L81 99 H101" fill="none" stroke="#58bab4" stroke-width="3" stroke-linejoin="round" stroke-linecap="round"/></svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 169 KiB

View file

@ -0,0 +1,149 @@
{
"game": "container",
"engineVersion": "2.1.10",
"revision": 3,
"baseline": "99e60d5e8f4111f0435d9ea911e2431ec8ef2f7f",
"issue": "https://codeberg.org/boardgamers/boardgamers/issues/595",
"license": "MIT",
"provenance": "Original programmatic geometric compositions; no external artwork or fonts. Palette follows the five ContainerColor identities in engine/src/gamestate.ts, not commercial artwork.",
"generator": "scripts/generate-achievement-art.py",
"generatorSha256": "312845271eb7dcef83d1955f3d14e279a5c3233f6626f2222f0baf088063034f",
"assets": [
{
"id": "win",
"key": "achievement-win",
"svg": "achievement-win.svg",
"png": "achievement-win.png",
"svgSha256": "d11d9bb626328c6023bc2a5009fdad6d6119e3756375c0174d8c7151c228b36d",
"pngSha256": "744bf07b069b16d981c1e3018c38e046414445ac3fa1d2bec0745de35ebe7751"
},
{
"id": "win-three-player",
"key": "achievement-win-three-player",
"svg": "achievement-win-three-player.svg",
"png": "achievement-win-three-player.png",
"svgSha256": "06b217b50a074d36b481d90c2f7608d941f513733841039aa64f7f9fb9faaa2d",
"pngSha256": "26a4e3649c81cf05cf10bdb1332771839dda848b823af41497d4b37ebd8cbc0d"
},
{
"id": "win-four-player",
"key": "achievement-win-four-player",
"svg": "achievement-win-four-player.svg",
"png": "achievement-win-four-player.png",
"svgSha256": "b9f13375b54488141caa474af7bee000bc9305e7c616bab09957c7d43d430687",
"pngSha256": "68f1e79e5aae6a1b181f9ef1c917fb3e5cfe86abd7412ac88484255056f36ab3"
},
{
"id": "win-five-player",
"key": "achievement-win-five-player",
"svg": "achievement-win-five-player.svg",
"png": "achievement-win-five-player.png",
"svgSha256": "a0fdd3379e426db9ff7351fce886c0a631141eca767dae4eb7ffb19f62a045de",
"pngSha256": "47c7de6e78fdfa732fe3117e369d07e14189677b8158a919023092de1f470217"
},
{
"id": "debt-free-win",
"key": "achievement-debt-free-win",
"svg": "achievement-debt-free-win.svg",
"png": "achievement-debt-free-win.png",
"svgSha256": "8a011eb7176b21643afb1c2d6ecac13c89272b818b5641335ff04d732d1683af",
"pngSha256": "048beb52a19ac31b9ddb5522a0fafb63f65b9324f6d132c15652ba14ccaa6655"
},
{
"id": "score-100",
"key": "achievement-score-100",
"svg": "achievement-score-100.svg",
"png": "achievement-score-100.png",
"svgSha256": "06fdba90883c865188097ef55757e1a9e6f06a019cbb82701291ca277797a3f3",
"pngSha256": "3f834e340991586e0d4ccf3b92908c088b14be2e12da68b7051f0b5603e121bc"
},
{
"id": "score-150",
"key": "achievement-score-150",
"svg": "achievement-score-150.svg",
"png": "achievement-score-150.png",
"svgSha256": "b5fff030c63d454169e0912700d37d467d070420af354259c5201b18a3c6ab70",
"pngSha256": "dde34191376692685a16dffd33e69334149c219468febf364662e213c5e5cff0"
},
{
"id": "debt-free",
"key": "achievement-debt-free",
"svg": "achievement-debt-free.svg",
"png": "achievement-debt-free.png",
"svgSha256": "01964ff720747fb102fce03f8d10325bd611e15da8ee7d52b1959ca78c84eddf",
"pngSha256": "21cfa1ae75584599dfe557b09a52b3ab87194c6ad132df38210bf75714a3162c"
},
{
"id": "three-factories",
"key": "achievement-three-factories",
"svg": "achievement-three-factories.svg",
"png": "achievement-three-factories.png",
"svgSha256": "e4181da5e344a7fdd742ad62120c1ebdbb89e65ad0ba5446731c274f363321ca",
"pngSha256": "8dab494df843f8ec260dec693423ffab7f71b13abfa5211118241eb3595135a5"
},
{
"id": "four-factories",
"key": "achievement-four-factories",
"svg": "achievement-four-factories.svg",
"png": "achievement-four-factories.png",
"svgSha256": "035d17b32e279c526cc925ffd4e02a6759b0a2a79a5b5674cd15a1899e5845e8",
"pngSha256": "204b1e154042612b0b93d81ccf2ff3488510a293843ea0b7e715f546ef72b727"
},
{
"id": "three-warehouses",
"key": "achievement-three-warehouses",
"svg": "achievement-three-warehouses.svg",
"png": "achievement-three-warehouses.png",
"svgSha256": "c61719e1cd65421e7ec224bd4d38e782f134c85ded040c75a96dc76668d62f97",
"pngSha256": "84ca3b3e7ff3384271e90d12a23cb10427db76b1a9988d90a6a307b5b468cf29"
},
{
"id": "five-warehouses",
"key": "achievement-five-warehouses",
"svg": "achievement-five-warehouses.svg",
"png": "achievement-five-warehouses.png",
"svgSha256": "9300a1a5844311ad9e746daaaae549ea9ddfa1a3e8439a27408c31bbf9597cee",
"pngSha256": "235e3ad728b327db538c899c3e8ed9af5c6520fb90f57ff45cacfe7846d2c75b"
},
{
"id": "island-fifteen",
"key": "achievement-island-fifteen",
"svg": "achievement-island-fifteen.svg",
"png": "achievement-island-fifteen.png",
"svgSha256": "00f99f6551100bdc0b1df2ba4bac918a74cf55ce82dd80af94f929576cd527b1",
"pngSha256": "96c9fd2d89bfa2ab0c0ef5414131575665a8afe6091baf08090a58b50635d00a"
},
{
"id": "island-ten",
"key": "achievement-island-ten",
"svg": "achievement-island-ten.svg",
"png": "achievement-island-ten.png",
"svgSha256": "e03931267faad0ada2ad82826d68447a128bea05e04bf4dddaf64ec389f9cb44",
"pngSha256": "83cca008b31fe8e2e1b47f36224e95116889c5bcb3d01222da00632e16628c83"
},
{
"id": "island-diversity",
"key": "achievement-island-diversity",
"svg": "achievement-island-diversity.svg",
"png": "achievement-island-diversity.png",
"svgSha256": "2bd2bfb4b9cde261a54af8c14bfabe453f3caf848d2c2e0c2041183f25584f53",
"pngSha256": "e01ebf35ee933677f24d5a32a9a95ace5cb578ee28384a521daa65a1d3999961"
},
{
"id": "full-ship",
"key": "achievement-full-ship",
"svg": "achievement-full-ship.svg",
"png": "achievement-full-ship.png",
"svgSha256": "25e695a850fc41dc712c67c3d1b55caac80e8cb0c7391fff9d6175e690763a3b",
"pngSha256": "3ea1d6fb4fa01d1cfcd8e40f8414e70a31fc2185380c8fd10a22e6321ddf8535"
},
{
"id": "warehouse-five",
"key": "achievement-warehouse-five",
"svg": "achievement-warehouse-five.svg",
"png": "achievement-warehouse-five.png",
"svgSha256": "f1f0ea5c55c8e52ec7edcfaca95ebe0874bea85e1edb5c2543401428bd55725d",
"pngSha256": "cffc0a10d81f0b99c896b834bce85cf846c1acefd66c52489fa9e06b6655cbcd"
}
]
}

View file

@ -0,0 +1,417 @@
{
"schema": 1,
"game": "container",
"status": "activated-and-verified",
"sourceCommit": "7170c8a0bbc56e9ebb514a863a1cfc4695e1ad47",
"envelopeSha256": "c5bcf87f3a20fdece6a3ea46ff2a76d2e78c6a9c99c8322be83190f3934c3c81",
"privateReceiptSha256": "f2c6038eeeb9f9a3e4262c64065d27f8ceaa18b7ee46d2868f066b47f2aee2d1",
"assets": {
"achievement-debt-free": {
"sourceSha256": "21cfa1ae75584599dfe557b09a52b3ab87194c6ad132df38210bf75714a3162c",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/container/achievement-debt-free/567e4e26932e793a/achievement-debt-free.webp",
"sha256": "567e4e26932e793a4f9b6fb5ad891960f691df64dfdaf58d886298cb14352587",
"size": 6526,
"format": "webp",
"width": 256,
"height": 256,
"verifiedAt": "2026-11-14T12:45:21.743Z",
"metadataPreserved": true
},
"achievement-debt-free-win": {
"sourceSha256": "048beb52a19ac31b9ddb5522a0fafb63f65b9324f6d132c15652ba14ccaa6655",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/container/achievement-debt-free-win/b8cc763a85fff7fd/achievement-debt-free-win.webp",
"sha256": "b8cc763a85fff7fdae46dd074e2af5fd3e900afef449c1292d0f6e2a581ae404",
"size": 7312,
"format": "webp",
"width": 256,
"height": 256,
"verifiedAt": "2026-11-14T12:45:21.774Z",
"metadataPreserved": true
},
"achievement-five-warehouses": {
"sourceSha256": "235e3ad728b327db538c899c3e8ed9af5c6520fb90f57ff45cacfe7846d2c75b",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/container/achievement-five-warehouses/91702c4cd6a7acb7/achievement-five-warehouses.webp",
"sha256": "91702c4cd6a7acb7a1ace20ca74165e877fc99175aae39e6eda8b40d5ee8b9a5",
"size": 7932,
"format": "webp",
"width": 256,
"height": 256,
"verifiedAt": "2026-11-14T12:45:21.801Z",
"metadataPreserved": true
},
"achievement-four-factories": {
"sourceSha256": "204b1e154042612b0b93d81ccf2ff3488510a293843ea0b7e715f546ef72b727",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/container/achievement-four-factories/0764b6407d158641/achievement-four-factories.webp",
"sha256": "0764b6407d15864127bb459e233cbf22e7b73c6fbe4962bbcee41a94f9eaa7f9",
"size": 7736,
"format": "webp",
"width": 256,
"height": 256,
"verifiedAt": "2026-11-14T12:45:21.827Z",
"metadataPreserved": true
},
"achievement-full-ship": {
"sourceSha256": "3ea1d6fb4fa01d1cfcd8e40f8414e70a31fc2185380c8fd10a22e6321ddf8535",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/container/achievement-full-ship/43795cf876cf56bf/achievement-full-ship.webp",
"sha256": "43795cf876cf56bf56deda833b25b2bb9f0ca4a91c9a6c9509fffe5558fabdc9",
"size": 7202,
"format": "webp",
"width": 256,
"height": 256,
"verifiedAt": "2026-11-14T12:45:22.095Z",
"metadataPreserved": true
},
"achievement-island-diversity": {
"sourceSha256": "e01ebf35ee933677f24d5a32a9a95ace5cb578ee28384a521daa65a1d3999961",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/container/achievement-island-diversity/a2c10818c891410d/achievement-island-diversity.webp",
"sha256": "a2c10818c891410d316045bc112b0fc546fba1d0b7d11c74ccfe0c006499df6d",
"size": 9012,
"format": "webp",
"width": 256,
"height": 256,
"verifiedAt": "2026-11-14T12:45:22.123Z",
"metadataPreserved": true
},
"achievement-island-fifteen": {
"sourceSha256": "96c9fd2d89bfa2ab0c0ef5414131575665a8afe6091baf08090a58b50635d00a",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/container/achievement-island-fifteen/f67a5934ab593970/achievement-island-fifteen.webp",
"sha256": "f67a5934ab593970aabe4bc208c593547b76ef7fe654a3521ea0b9cd1ba516c0",
"size": 10592,
"format": "webp",
"width": 256,
"height": 256,
"verifiedAt": "2026-11-14T12:45:22.148Z",
"metadataPreserved": true
},
"achievement-island-ten": {
"sourceSha256": "83cca008b31fe8e2e1b47f36224e95116889c5bcb3d01222da00632e16628c83",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/container/achievement-island-ten/582385aaca323df1/achievement-island-ten.webp",
"sha256": "582385aaca323df1b20ed0df25a5064def47b4ddb97097db6df8a07900438dac",
"size": 9698,
"format": "webp",
"width": 256,
"height": 256,
"verifiedAt": "2026-11-14T12:45:22.180Z",
"metadataPreserved": true
},
"achievement-score-100": {
"sourceSha256": "3f834e340991586e0d4ccf3b92908c088b14be2e12da68b7051f0b5603e121bc",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/container/achievement-score-100/1a536d667267f00e/achievement-score-100.webp",
"sha256": "1a536d667267f00ea614266fdd98922edd8b668ff8bec9fd42cbf2eb40888f55",
"size": 7594,
"format": "webp",
"width": 256,
"height": 256,
"verifiedAt": "2026-11-14T12:45:22.208Z",
"metadataPreserved": true
},
"achievement-score-150": {
"sourceSha256": "dde34191376692685a16dffd33e69334149c219468febf364662e213c5e5cff0",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/container/achievement-score-150/1e7df559f2e4f006/achievement-score-150.webp",
"sha256": "1e7df559f2e4f006e4696db8e7d852ad8e7e00be51672b920ab4b3d7b1aeb640",
"size": 8768,
"format": "webp",
"width": 256,
"height": 256,
"verifiedAt": "2026-11-14T12:45:22.235Z",
"metadataPreserved": true
},
"achievement-three-factories": {
"sourceSha256": "8dab494df843f8ec260dec693423ffab7f71b13abfa5211118241eb3595135a5",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/container/achievement-three-factories/f093bd44e74be16b/achievement-three-factories.webp",
"sha256": "f093bd44e74be16b1160635caf9510146d97ea3106e5c5af41e5cbed190ab985",
"size": 7428,
"format": "webp",
"width": 256,
"height": 256,
"verifiedAt": "2026-11-14T12:45:22.267Z",
"metadataPreserved": true
},
"achievement-three-warehouses": {
"sourceSha256": "84ca3b3e7ff3384271e90d12a23cb10427db76b1a9988d90a6a307b5b468cf29",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/container/achievement-three-warehouses/69fd2d83eafa7a40/achievement-three-warehouses.webp",
"sha256": "69fd2d83eafa7a40331e8454244d805c261494eebf1b2b29cdab5fb9b271abc7",
"size": 7114,
"format": "webp",
"width": 256,
"height": 256,
"verifiedAt": "2026-11-14T12:45:22.295Z",
"metadataPreserved": true
},
"achievement-warehouse-five": {
"sourceSha256": "cffc0a10d81f0b99c896b834bce85cf846c1acefd66c52489fa9e06b6655cbcd",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/container/achievement-warehouse-five/62cf1209c5f54d14/achievement-warehouse-five.webp",
"sha256": "62cf1209c5f54d1419c378cdc04ba33e26e4b870cdf277621e9109d59f724070",
"size": 7346,
"format": "webp",
"width": 256,
"height": 256,
"verifiedAt": "2026-11-14T12:45:22.324Z",
"metadataPreserved": true
},
"achievement-win": {
"sourceSha256": "744bf07b069b16d981c1e3018c38e046414445ac3fa1d2bec0745de35ebe7751",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/container/achievement-win/a1b3b8b0afea900c/achievement-win.webp",
"sha256": "a1b3b8b0afea900c1aa0481be355d680c5b95a7d31acd5fe00134d16d49e91e4",
"size": 6704,
"format": "webp",
"width": 256,
"height": 256,
"verifiedAt": "2026-11-14T12:45:22.357Z",
"metadataPreserved": true
},
"achievement-win-five-player": {
"sourceSha256": "47c7de6e78fdfa732fe3117e369d07e14189677b8158a919023092de1f470217",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/container/achievement-win-five-player/3d4acae7f1e34a3f/achievement-win-five-player.webp",
"sha256": "3d4acae7f1e34a3f51a2f6ee8333537130ce30ed59b6534fcb23047333ba0cf4",
"size": 7666,
"format": "webp",
"width": 256,
"height": 256,
"verifiedAt": "2026-11-14T12:45:22.489Z",
"metadataPreserved": true
},
"achievement-win-four-player": {
"sourceSha256": "68f1e79e5aae6a1b181f9ef1c917fb3e5cfe86abd7412ac88484255056f36ab3",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/container/achievement-win-four-player/e7fe0c89b27a0ac2/achievement-win-four-player.webp",
"sha256": "e7fe0c89b27a0ac2f4995a705a46914061bc4d6d1cad4e7f02137e55e3fb72ba",
"size": 7392,
"format": "webp",
"width": 256,
"height": 256,
"verifiedAt": "2026-11-14T12:45:22.514Z",
"metadataPreserved": true
},
"achievement-win-three-player": {
"sourceSha256": "26a4e3649c81cf05cf10bdb1332771839dda848b823af41497d4b37ebd8cbc0d",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/achievements/container/achievement-win-three-player/e721f1015d8c4927/achievement-win-three-player.webp",
"sha256": "e721f1015d8c49276d50c4fe01b8d4d8377d4f860aafa88f2bbea4e52c573416",
"size": 7336,
"format": "webp",
"width": 256,
"height": 256,
"verifiedAt": "2026-11-14T12:45:22.541Z",
"metadataPreserved": true
}
},
"preserved": {
"pictogram": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/assets/container/pictogram/bee804d124fb822a/pictogram.webp",
"sha256": "bee804d124fb822a231d3d3d12920fb7670edbe68e53a0467445c75be785c0e1",
"size": 11332,
"format": "webp",
"width": 256,
"height": 256,
"verifiedAt": "2026-11-14T12:45:22.731Z"
},
"screenshot-showcase-1": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/assets/container/screenshot-showcase-1/7d2d6bc1c731546e/screenshot-showcase-1.webp",
"sha256": "7d2d6bc1c731546e6737e356c2689ea45f684b72be0892b394d8c8102bb273e0",
"size": 99590,
"format": "webp",
"width": 1536,
"height": 898,
"verifiedAt": "2026-11-14T12:45:22.811Z"
},
"screenshot-showcase-2": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/assets/container/screenshot-showcase-2/8e79c3a32155aa22/screenshot-showcase-2.webp",
"sha256": "8e79c3a32155aa22aaf9448af2b010b3d4c6922b1fa52f7891267a8a5c43e206",
"size": 99576,
"format": "webp",
"width": 1536,
"height": 900,
"verifiedAt": "2026-11-14T12:45:22.886Z"
}
},
"planSha256": "b94282d2c6a451204f41501541c27002000557e7aa6dc6668c6337bef03947ce",
"activationReceiptSha256": "9a2f486c5019feb2dda094e35ed1f0558b39704cd772b8114834f63396966f60",
"tgzSha256": "806185b4f15dd7809132529a2cf7224793824ee3d9bc0e24e8e14d1f23c36653",
"package": {
"name": "container-engine",
"version": "2.1.10",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/engine/806185b4f15dd780/container-engine-2.1.10.tgz"
},
"hostedPackage": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/engine/806185b4f15dd780/container-engine-2.1.10.tgz",
"size": 55414,
"sha256": "806185b4f15dd7809132529a2cf7224793824ee3d9bc0e24e8e14d1f23c36653"
},
"manifest": {
"revision": 3,
"achievements": [
{
"id": "win",
"name": "Shipping Magnate",
"description": "Win a completed game of Container.",
"icon": {
"type": "asset",
"key": "achievement-win"
}
},
{
"id": "win-three-player",
"name": "Three-Company Champion",
"description": "Win a completed three-player game.",
"icon": {
"type": "asset",
"key": "achievement-win-three-player"
}
},
{
"id": "win-four-player",
"name": "Four-Company Champion",
"description": "Win a completed four-player game.",
"icon": {
"type": "asset",
"key": "achievement-win-four-player"
}
},
{
"id": "win-five-player",
"name": "Five-Company Champion",
"description": "Win a completed five-player game.",
"icon": {
"type": "asset",
"key": "achievement-win-five-player"
}
},
{
"id": "debt-free-win",
"name": "Solvent Champion",
"description": "Win a completed game with no outstanding loans.",
"icon": {
"type": "asset",
"key": "achievement-debt-free-win"
}
},
{
"id": "score-100",
"name": "Healthy Balance Sheet",
"description": "Finish with a final score of at least 100.",
"icon": {
"type": "asset",
"key": "achievement-score-100"
}
},
{
"id": "score-150",
"name": "Economic Powerhouse",
"description": "Finish with a final score of at least 150.",
"icon": {
"type": "asset",
"key": "achievement-score-150"
}
},
{
"id": "debt-free",
"name": "Books Balanced",
"description": "Finish with no outstanding loans.",
"icon": {
"type": "asset",
"key": "achievement-debt-free"
}
},
{
"id": "three-factories",
"name": "Industrial Expansion",
"description": "Finish owning at least three factories.",
"icon": {
"type": "asset",
"key": "achievement-three-factories"
}
},
{
"id": "four-factories",
"name": "Factory Network",
"description": "Finish owning four factories.",
"icon": {
"type": "asset",
"key": "achievement-four-factories"
}
},
{
"id": "three-warehouses",
"name": "Distribution Network",
"description": "Finish owning at least three warehouses.",
"icon": {
"type": "asset",
"key": "achievement-three-warehouses"
}
},
{
"id": "five-warehouses",
"name": "Warehouse Empire",
"description": "Finish owning five warehouses.",
"icon": {
"type": "asset",
"key": "achievement-five-warehouses"
}
},
{
"id": "island-fifteen",
"name": "Island Magnate",
"description": "Finish with at least fifteen containers on your island.",
"icon": {
"type": "asset",
"key": "achievement-island-fifteen"
}
},
{
"id": "island-ten",
"name": "Island Portfolio",
"description": "Finish with at least ten containers on your island.",
"icon": {
"type": "asset",
"key": "achievement-island-ten"
}
},
{
"id": "island-diversity",
"name": "A Colorful Portfolio",
"description": "Finish with all five container colors on your island.",
"icon": {
"type": "asset",
"key": "achievement-island-diversity"
}
},
{
"id": "full-ship",
"name": "Loaded Freighter",
"description": "Finish with five containers aboard your ship.",
"icon": {
"type": "asset",
"key": "achievement-full-ship"
}
},
{
"id": "warehouse-five",
"name": "Stocked for Trade",
"description": "Finish with five containers in your warehouse store.",
"icon": {
"type": "asset",
"key": "achievement-warehouse-five"
}
}
]
},
"verification": {
"publicCatalog": true,
"allAssets": true,
"unchangedMetadata": true
},
"sourceDelivery": {
"reviewer": "sub-1794658480422-eef8c1ca",
"approval": "sub-1794658480422-eef8c1ca",
"manifestSha256": "1efc0f7e05f94cd22fa8d8be90cb9edb6e22bd8211efdff279578146e521dafb",
"canonicalRemote": "git@github.com:boardgamers/container",
"branch": "master",
"publicGetVerifiedAt": "2026-11-14T13:01:47.372493+00:00",
"checks": [
"17 source artwork hashes and decoded images; unchanged evaluator",
"exact original package: revision 3, 17 refs, legal 3/4/5-player completion and replay",
"51 engine tests passed",
"public catalog manifest/package and 20 asset URLs matched; all hosted asset and package bytes SHA-256 verified"
],
"scope": "Source and sanitized receipt delivery only; no uploads, engine POST, repack, or viewer/settings/visibility changes. Existing activation receipt attests unchanged metadata."
}
}

155
docs/achievements.md Normal file
View file

@ -0,0 +1,155 @@
# Container per-game achievements
The engine wrapper exports the optional `achievementDefinitions()` and
`achievements(GameState)` hooks using the published `@boardgamers/protocol/engine`
0.11.0 types. Engine **2.2.0** includes manifest revision **4** with 19
achievements as part of the authorized Offshore Island release.
IDs are permanent; never reuse them for another condition. The original 17
definitions, conditions and stable `achievement-<id>` asset references remain
unchanged. Original SVG/PNG artwork, provenance, reproduction instructions and
contact sheets are in [achievement-art](achievement-art/README.md).
The historical revision-3 artwork manifest and release receipt are preserved,
not regenerated. The Offshore additions were reviewed and tested before release authorization.
Revision 4 adds **Offshore Magnate** (`offshore-win`) and **Two-Way Trade**
(`offshore-trader`). Both require `options.offshoreIsland === true` and the same
committed completion and human-seat eligibility checks as base achievements.
Offshore Magnate requires a sole game victory (not a draw). Two-Way Trade requires
both `player.offshoreStats.cashAuctionsWon >= 1` and
`player.offshoreStats.containerAuctionsWon >= 1` in that completed game; it does
not require winning the game. Missing/partial counters cannot prove both auctions.
Disabled or absent expansion options never earn either new award, even if counters
are present. The engine records counters on bank auction settlement and reproduces
them on replay; final holdings alone are not evidence of these auction wins.
Protocol 0.11.0 supports text badges, not emoji: the new icons use built-in `OI`
and `BANK` badges and require no nonexistent artwork or upload.
## 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-fifteen` | At least fifteen 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-five` | Five containers in the warehouse store at completion |
| `offshore-win` | Sole winner of a completed Offshore Island expansion game |
| `offshore-trader` | Win a cash bank auction and a container bank auction in the same completed expansion game |
## Revision 2 change (historical)
Engine 2.1.9 replaces `island-five` / **Island Investor** (at least five island
containers) with the new ID `island-fifteen` / **Island Magnate** (at least fifteen).
The manifest still contains 17 definitions. `island-ten` and `warehouse-five`
are unchanged. Tests cover fourteen failing and fifteen qualifying, plus a legal
completed game reaching exactly fifteen and reproducing the award on replay.
No existing award migration, deletion, or backfill is performed. The old ID is
retired, never reused; any existing platform records are left untouched.
This change subsequently shipped with the revision-3 artwork in engine 2.1.10.
The historical activation receipt remains unchanged.
## Threshold attainability audit
`warehouse-six` was an invalid review-candidate ID and is retired, not repurposed.
Its replacement is `warehouse-five`, included in revision 1 for engine 2.1.8.
| Feats | Legal limits checked |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Three/four factories | `BuyFactory` requires fewer than four factories and a new color; four is the cap, with five colors available. |
| Three/five warehouses | `BuyWarehouse` requires fewer than five; setup supplies five warehouse pieces per seat. |
| Warehouse stock five | `BuyFromFactory` requires stock below warehouse count: one container per warehouse, hence five total. |
| Full ship | `BuyFromWarehouse` requires fewer than five cargo containers. |
| Island fifteen/ten/diversity | No island holding cap; auctions transfer cargo to the island. Setup supplies 12/16/20 containers of each of five colors for 3/4/5 seats. Fifteen holdings across colors fit even the smallest supply of 60. A legal five-player completion/replay fixture finishes with exactly fifteen on one island. |
| Score 100/150 | Settled score, not cash; no score ceiling. Accepted bids add matching bank subsidies, and island holdings contribute to scoring. These thresholds are not constrained by a fixed cash supply. |
| Debt-free feats | Zero outstanding loans is legal; borrowing is optional and loans can be repaid. |
| Wins/player counts | Supported 3/4/5-seat games; no solo threshold or solo victory inferred. |
The legal attainability regression starts from setup, buys warehouses and stock
using available moves, and completes a seeded game with five warehouse containers.
It checks capacities throughout and replays the serialized completed game to the
same awards. It does not inject final holdings or alter money/supply/phase.
The expansion regression starts from seeded Offshore Island setup, makes legal
bank calls from seat zero (first bidding a stored container for cash, then bidding
cash for bank containers), and otherwise uses legal AI moves through completion.
The serialized finished game earns Two-Way Trade and awards Offshore Magnate to
the sole winner; replay reproduces all awards without injecting counters or state.
## 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.
The existing wrapper assigns sequential rankings even for exact ties; that
separate ranking bug is intentionally not changed by these achievement hooks.
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. Base achievements have no
historical shipping, auction, production or borrowing feats; only the expansion
trading feat reads the explicit bank-auction counters. 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 calls the hook with authoritative completed serialized state and maps
zero-based seats to accounts. In the reviewed platform code, capture excludes
`game.cancelled`, `game.winClaim`, and `game.soloEditedAt`, requires ended status,
and skips already-ended games/existing evidence. Bot, dropped and quit seats
are mapped to null and discarded; other human seats can still earn feats.
See `apps/game-server/app/services/game-achievements.ts` (capture/extraction).
Admin edit-data and replay routes set `soloEditedAt` even for multiplayer games.
Container itself has no cancellation flag or account IDs; the hook additionally
filters its `isAI` and `isDropped` flags.
- **No blanket practice exclusion is established.** Capture does not consult
`soloRanked` or test custom seeds, `platformRewoundAt`, `soloAnalysisAt`, unlisted
games, or a generic tutorial/practice marker. Solo ranking policy is separate
(`packages/models/solo-ranking.ts`), and does not establish Container eligibility.
Platform analysis uses separate analysis records; Container tutorials run the
engine locally in the viewer. Neither fact is a general capture-time exclusion.
Container's `GameState` contains optional `analysisCash` (created by
`createAnalysisScenario`), but `createAnalysis` has no durable provenance flag;
the achievement hook does not classify practice from these states. No
multiplayer Container exposure through those paths has been demonstrated.
Broader practice exclusion, if required, remains a coordinator/platform policy
prerequisite rather than a guarantee of this implementation.
- Install published protocol **0.11.0** using the committed lockfile. No local
unpublished protocol dependency is used.
- Engine 2.1.8 carries the reviewed revision-1 manifest (17 achievements).
Release authorization follows independent approval of commit `6ae62e0`.
Publication must follow `AGENTS.md`: deliver source, dependencies, lockfile
and version changes to canonical `master` alongside the BGS engine upload.
Activation must verify the installed manifest and public album, without
creating fake production games.
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.

129
docs/offshore-island.md Normal file
View file

@ -0,0 +1,129 @@
# Offshore Island expansion
This optional expansion adds the **Off-Shore Bank** to Container. The platform
expansion ID is `offshore-island`; standalone engine setup uses
`{ offshoreIsland: true }`. The setting is persisted in game options so replay
uses the same rules. Missing/false means the existing classic implementation.
Existing games are not opted in automatically.
## Rules reference and scope
Reference: [Container rulebook](https://bghub.org/r/container.pdf), especially
pages 2, 11–14, and 16–18. A second public copy is the
[retailer-hosted v8 rulebook](https://gamers-hq.de/media/pdf/a6/62/28/Container_Rulebook_v8_compressed.pdf).
The requested board is shown in the
[Offshore Island discussion](https://boardgamers.space/discussions/offshore-island-expansion-avhRTKevB006WhXy).
This is an expansion to the existing online rules, not a wholesale migration to
the newer edition. Existing supply counts, base-game scoring/tiebreaking, and
classic-mode behavior are not silently replaced by the newer edition's rules.
No physical-edition artwork is copied into the viewer.
### Bank economy
- Three cash lots start at $1/$2/$3. Three container lots start with 2/1/0
containers drawn from three distinct colors, removed from the supply.
- Call Bank is one action, at most once per turn. Bid cash for a container lot,
or factory/warehouse containers for a cash lot. Bank bids are public, unlike
delivery-auction bids.
- Three/four players share one active bank auction. Five players may have two,
but at most one of each type.
- The highest bidder wins at the start of their next turn, **after** paying loan
interest/default. Auction winnings cannot fund that turn's interest.
- Cash committed to a bid is unavailable for other payments. Containers
committed to a bid remain reserved against their original district's capacity.
Outbid containers return to their original district, with owner repricing.
- Bank payments start at lot I, cycling through the three lots and skipping
frozen lots with active auctions. A container payer chooses the color order.
If only one color remains, the engine places those containers automatically;
the payment prompt appears only when different colors remain to choose from.
- Interest, delivery self-buyouts, and seized containers replenish the bank.
Building costs and loan repayments still go to the ordinary supply.
- Won containers go into the winner's bank holding area, not directly onto their
ship or scoring island. Sailing to the bank allows loading one's holding-area
containers up to the ship's capacity of five.
- No Call Bank on a turn when winning a bank auction or triggering game end.
Pending auctions settle at game end. Bank holding-area containers score $3 each.
## Rules interpretations requiring playtest review
The implementation uses a minimum opening bank bid of **$1 or one container**.
The reference explicitly sets a +1 minimum for raises, but does not specify a
numeric opening minimum. This positive minimum is an interpretation, not a
verified publisher clarification. The explicit permission for $0 delivery bids
does not establish permission for $0 bank bids.
Bank pickup is available on arrival only. The reference provides no stationary
bank-loading action, unlike the explicit ordinary purchase action at a player's
harbor. To collect newly won cargo while already at the bank, sail to sea and
return. A publisher clarification could warrant changing this behavior later.
If two bank auctions remain at game end, they resolve in their persisted auction
order, completing each payment, collection, and cleanup before the next. Thus a
later payment may replenish a lot whose earlier auction has already settled.
The rulebook does not explicitly specify an ordering or simultaneous frozen-lot
snapshot; this deterministic interpretation also needs publisher/playtest review.
The old 10th Anniversary Investment Bank differs from the requested newer
Off-Shore Bank (for example its single auction and subsidy wording). It is not
used to override the newer bank rules.
## Viewer
The bank is part of the SVG board, using the same cargo pieces, outlined spaces,
player colors, buttons and bid calculator as the base game. The Offshore board
adds a lower bank area without shifting the classic board coordinates. On mobile,
the **Bank** navigation button brings that area into view.
Each lot separates its reward from the current bidder's token and bid. Click a
lot to offer cash or select stored cargo, then confirm the offer. Selected draft
cargo moves visually from its store to the bidding area; click it there to remove
it from the draft and return it to the original store. Cancelling returns all draft
cargo. These previews do not change the engine state until the offer is confirmed.
During payment, click a container below the lots; a connecting line and highlighted
lot show its fixed destination. For outbid cargo, select a container in the framed
**Returned containers** tray above the bank and choose a highlighted price space
in its original store. Default choices appear
beside the bank. Bank transfers and draft selection use brief container animations,
with reduced-motion preferences respected.
Each player's open-water berth has solid player-colored piers; shared piers split
evenly between adjacent colors. Won containers wait directly in the berth, without
a separate holding box or harbor token, until clicked to load on arrival. Cargo
moves beside a docked ship within the same unpartitioned berth.
Empty harbor rows stay visible, and large cargo lists are paginated. There is no
separate expansion banner or collapsible card panel.
## Developer testing
Run the existing local viewer with `pnpm --dir viewer serve`, then add
`?offshoreIsland=1` to its URL to opt into the expansion. Without that query
parameter the demo remains classic. BGS uses the expansion ID instead of the
local-demo query parameter.
The engine has focused bank rules tests, serializes between decisions to catch
persistence bugs, and plays complete seeded expansion games with bots for all
three player counts. Classic compatibility tests compare full serialized setup,
completed games, and replay against hashes captured from pre-expansion commit
`93194c8`, rather than merely checking that old games still finish.
New achievements are `offshore-win` (win an expansion game) and `offshore-trader`
(win both bank-auction types in one completed expansion game). They use manifest
revision 4; all 17 existing achievement IDs and artwork references are retained.
## Release boundary
Engine support alone does not expose a selectable expansion in BGS. A release
must include the engine and viewer together, register `offshore-island` in the
BGS game's expansion metadata, and verify a new expansion game through the
platform. Fetch `GET /api/admin/gameinfo/container/3`, preserve existing expansion
entries, and append `{ "name": "offshore-island", "label": "Offshore Island" }`
to the version-level `expansions` array via the corresponding PUT endpoint.
The platform filters unknown expansion IDs, so registration must follow a verified
compatible engine/viewer deployment; the old engine ignores expansion IDs. Do not opt an existing saved game into the expansion by editing its
options: its setup, supply, and history were created under different rules.
Before publication, run engine tests/build, viewer checks/unit/browser tests,
locale checks, and full-game/replay tests with the expansion both on and off.
Verify cash/container conservation, escrow spending and capacity, interrupted
turns, spectators' hidden-information views, and dropped-player/bot completion.

View file

@ -0,0 +1,291 @@
{
"game": "container",
"gameVersion": 3,
"sourceCommit": "e224cf7c784d8910a74725f97a0849a025761999",
"engineVersion": "2.2.0",
"viewerVersion": "2.1.1",
"engine": {
"engine": {
"package": {
"name": "container-engine",
"version": "2.2.0",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/engine/d91a59b7ef3ef416/container-engine-2.2.0.tgz"
},
"entryPoint": "dist/wrapper.js"
},
"sha256": "d91a59b7ef3ef416a955e841f8053be11558490f7377d5fedf06193e19f229ec"
},
"activeEngine": {
"engine": {
"package": {
"name": "container-engine",
"version": "2.2.0",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/engine/d91a59b7ef3ef416/container-engine-2.2.0.tgz"
},
"entryPoint": "dist/wrapper.js"
},
"key": "container_3_container-engine_2.2.0_9b9e20ab8243dc3c",
"revision": 4,
"achievementCount": 19
},
"viewer": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-24af9650be1f04927492/container-viewer.umd.min.js",
"scriptBytes": 510949,
"files": [
{
"name": "container-viewer.css",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-24af9650be1f04927492/container-viewer.css",
"sha256": "a10b80b2537ef892f3e555fc52e32055dd3c6716ca3cec80f2a7c81810de3a24"
},
{
"name": "container-viewer.umd.min.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-24af9650be1f04927492/container-viewer.umd.min.js",
"sha256": "7b2c30e1c7b734c4c60897e0fffa9ae42960d37d7692f5545514c48b6e18faef"
},
{
"name": "container-viewer.umd.min.locale-da.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-24af9650be1f04927492/container-viewer.umd.min.locale-da.js",
"sha256": "b0da04cd067d1f58940b3cd8633c41bef7c379e9017a57b8b0a31c2ad8c049f8"
},
{
"name": "container-viewer.umd.min.locale-de.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-24af9650be1f04927492/container-viewer.umd.min.locale-de.js",
"sha256": "12474684e57409b9eb832c606c2854d71ad633dc74f92681ff3262c8ebbacb87"
},
{
"name": "container-viewer.umd.min.locale-el.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-24af9650be1f04927492/container-viewer.umd.min.locale-el.js",
"sha256": "c4a1f83fbbdfc9a70392391260101bafcf7b33b359f5f92c50acd24a27cbc6bb"
},
{
"name": "container-viewer.umd.min.locale-fa.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-24af9650be1f04927492/container-viewer.umd.min.locale-fa.js",
"sha256": "3d8a81f83ecb106af47ff83eec878716e983b16055a5eb7e1da39df61430a061"
},
{
"name": "container-viewer.umd.min.locale-fr.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-24af9650be1f04927492/container-viewer.umd.min.locale-fr.js",
"sha256": "f5a011db4b6404ba9ad0615f41758e6e0d20157c3be5da60b6e58fbaa86691d5"
},
{
"name": "container-viewer.umd.min.locale-hi.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-24af9650be1f04927492/container-viewer.umd.min.locale-hi.js",
"sha256": "2c2badf7211974cd91d0b6510995202a390491c9352080729ced9a0112aade87"
},
{
"name": "container-viewer.umd.min.locale-it.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-24af9650be1f04927492/container-viewer.umd.min.locale-it.js",
"sha256": "b8297a6fe8b4bd352d7b72ec9b0847430f84714ebe65934ccde0b86cd9451a5f"
},
{
"name": "container-viewer.umd.min.locale-ko.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-24af9650be1f04927492/container-viewer.umd.min.locale-ko.js",
"sha256": "26730b7b5d2b6fbe53c038e310a74c6b96199a7a0005052623097ea4ae075398"
},
{
"name": "container-viewer.umd.min.locale-nl.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-24af9650be1f04927492/container-viewer.umd.min.locale-nl.js",
"sha256": "78193cae6443adc1d9b5b541c5e5cf60a7a4097812da6ce7a0e92917feca8a36"
},
{
"name": "container-viewer.umd.min.locale-pl.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-24af9650be1f04927492/container-viewer.umd.min.locale-pl.js",
"sha256": "c4a8bd275efaa4011317a5b541c64164d1f70fbb09b064b4d17e18d62ff0c424"
},
{
"name": "container-viewer.umd.min.locale-pt-BR.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-24af9650be1f04927492/container-viewer.umd.min.locale-pt-BR.js",
"sha256": "ae5c7018d997eb6d5486e7c51804005cc8546b872806ff22d2296553d3b72c4f"
},
{
"name": "container-viewer.umd.min.locale-ro.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-24af9650be1f04927492/container-viewer.umd.min.locale-ro.js",
"sha256": "c309cc9669135dd3b1c08de1b3746c94c6ac3d3caa9daca19dcc0e9a6f9f9d42"
},
{
"name": "container-viewer.umd.min.locale-ru.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-24af9650be1f04927492/container-viewer.umd.min.locale-ru.js",
"sha256": "103be3cf90662254bb179a61b7e4c5c84777de9d920f8fa3365f2e93c7b6397a"
},
{
"name": "container-viewer.umd.min.locale-vi.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-24af9650be1f04927492/container-viewer.umd.min.locale-vi.js",
"sha256": "f811925e78460be0e687ecf1c209bb319447cbb20d1cbeaa2df3637af5e9695e"
},
{
"name": "container-viewer.umd.min.locale-zh-CN.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-24af9650be1f04927492/container-viewer.umd.min.locale-zh-CN.js",
"sha256": "13078220dea6d72244acb19abb9b49dab787ad39fdf6fea979208e75e565d476"
},
{
"name": "container-viewer.umd.min.locale-zh-TW.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-24af9650be1f04927492/container-viewer.umd.min.locale-zh-TW.js",
"sha256": "cd202e360d6fae03aae679efc4422a255b893338fbb36d2dde7c05a330507308"
}
]
},
"expansions": [
{
"name": "offshore-island",
"label": "Offshore Island"
}
],
"tutorialChapters": [
{
"id": "supply-chain",
"title": "From factory to ship",
"description": "Produce, set prices, trade with another player and load a ship.",
"version": 1
},
{
"id": "buildings",
"title": "Factories and warehouses",
"description": "Distinguish buildings from sale spaces, then expand production and storage.",
"version": 1
},
{
"id": "selling",
"title": "Sail and sell your cargo",
"description": "Start an auction, reveal the sealed bids and collect the bank subsidy.",
"version": 1
},
{
"id": "bidding",
"title": "Bid, raise and break a tie",
"description": "Make a sealed offer, add a tie-break bid and see who pays.",
"version": 1
},
{
"id": "keep-cargo",
"title": "Keep the cargo yourself",
"description": "Decline the bids, pay the bank and compare the cost with selling.",
"version": 3
},
{
"id": "scoring",
"title": "What actually scores?",
"description": "Discard your most numerous colour, value a full set and count the final money.",
"version": 1
},
{
"id": "offshore-cargo",
"title": "Bank cargo and your ship",
"description": "Bid cash publicly, wait for settlement, then sail and load your safe holding.",
"version": 1
},
{
"id": "offshore-cash",
"title": "Stored cargo for bank cash",
"description": "Select real stored cargo, review one offer, then choose payment colour order.",
"version": 1
},
{
"id": "offshore-outbid",
"title": "Outbid and recover cargo",
"description": "See a public leader change, reprice returned stock, and wait for the new leader.",
"version": 1
}
],
"verification": {
"engineTests": 84,
"viewerUnitTests": 65,
"tutorialTests": 16,
"locales": 17,
"messagesPerLocale": 788,
"allNineTutorialsDesktopAndMobile": true,
"crossOriginTutorialRegression": true,
"publicCdn": [
{
"locale": "da",
"publicAssets": true,
"bankBid": true
},
{
"locale": "de",
"publicAssets": true,
"bankBid": true
},
{
"locale": "el",
"publicAssets": true,
"bankBid": true
},
{
"locale": "en",
"publicAssets": true,
"bankBid": true
},
{
"locale": "fa",
"publicAssets": true,
"bankBid": true
},
{
"locale": "fr",
"publicAssets": true,
"bankBid": true,
"languageChange": "fr→de"
},
{
"locale": "hi",
"publicAssets": true,
"bankBid": true
},
{
"locale": "it",
"publicAssets": true,
"bankBid": true
},
{
"locale": "ko",
"publicAssets": true,
"bankBid": true
},
{
"locale": "nl",
"publicAssets": true,
"bankBid": true
},
{
"locale": "pl",
"publicAssets": true,
"bankBid": true
},
{
"locale": "pt-BR",
"publicAssets": true,
"bankBid": true
},
{
"locale": "ro",
"publicAssets": true,
"bankBid": true
},
{
"locale": "ru",
"publicAssets": true,
"bankBid": true
},
{
"locale": "vi",
"publicAssets": true,
"bankBid": true
},
{
"locale": "zh-CN",
"publicAssets": true,
"bankBid": true
},
{
"locale": "zh-TW",
"publicAssets": true,
"bankBid": true
}
],
"installedProductionEngineSmoke": "Classic and Offshore initialization plus public cash bidding for 3/4/5 players; no persisted games created",
"unrelatedSettingsPreserved": true,
"allUploadedBytesHashVerified": true,
"releaseBranch": "master",
"additionalMirrorRequired": false
}
}

View file

@ -0,0 +1,266 @@
{
"game": "container",
"gameVersion": 3,
"viewerVersion": "2.1.2",
"sourceCommit": "0d5ad24c229398bd1b1197138b1f37c0bd9da175",
"activated": true,
"bundle": "split-167518d4e44d1bca8783",
"previousViewer": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-24af9650be1f04927492/container-viewer.umd.min.js",
"topLevelVariable": "container",
"fullScreen": true,
"replayable": false,
"dependencies": {
"scripts": ["https://cdn.jsdelivr.net/npm/vue@^2/dist/vue.min.js"],
"stylesheets": [
"https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-24af9650be1f04927492/container-viewer.css"
]
},
"chat": true,
"thumbnail": true,
"scriptBytes": 510949
},
"viewer": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-167518d4e44d1bca8783/container-viewer.umd.min.js",
"topLevelVariable": "container",
"fullScreen": true,
"replayable": false,
"dependencies": {
"scripts": ["https://cdn.jsdelivr.net/npm/vue@^2/dist/vue.min.js"],
"stylesheets": [
"https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-167518d4e44d1bca8783/container-viewer.css"
]
},
"chat": true,
"thumbnail": true,
"scriptBytes": 515389
},
"files": [
{
"name": "container-viewer.css",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-167518d4e44d1bca8783/container-viewer.css",
"bytes": 16007,
"storedBytes": 4172,
"sha256": "c63e8f19879ec61ccf04950a3022dd37b3c6c5ac37fa33f1a69f073e193b672d"
},
{
"name": "container-viewer.umd.min.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-167518d4e44d1bca8783/container-viewer.umd.min.js",
"bytes": 515389,
"storedBytes": 152588,
"sha256": "39a0614c4f244196c11d115968c53593335f64be64663fce0d1947ab2bb77bb0"
},
{
"name": "container-viewer.umd.min.locale-da.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-167518d4e44d1bca8783/container-viewer.umd.min.locale-da.js",
"bytes": 62259,
"storedBytes": 19265,
"sha256": "5a32e842ca40fe6f0491282d85d66a9812ac5143955701f92e03af31adf08091"
},
{
"name": "container-viewer.umd.min.locale-de.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-167518d4e44d1bca8783/container-viewer.umd.min.locale-de.js",
"bytes": 65663,
"storedBytes": 20310,
"sha256": "53945a725bdad65f87565334147ec7fe639f94d0e5eebe486d304bf581878ff3"
},
{
"name": "container-viewer.umd.min.locale-el.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-167518d4e44d1bca8783/container-viewer.umd.min.locale-el.js",
"bytes": 93670,
"storedBytes": 23517,
"sha256": "a927c7b09a0c3bc2cb33a768383c141a005397ea831f24bc982d8e7b82413a46"
},
{
"name": "container-viewer.umd.min.locale-fa.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-167518d4e44d1bca8783/container-viewer.umd.min.locale-fa.js",
"bytes": 83241,
"storedBytes": 21291,
"sha256": "1ea561ba38c41ac9ad474bfc267ab5837d51ee12ae979985916acf5fcf97f897"
},
{
"name": "container-viewer.umd.min.locale-fr.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-167518d4e44d1bca8783/container-viewer.umd.min.locale-fr.js",
"bytes": 66750,
"storedBytes": 19868,
"sha256": "900b84f10ea312888168b750c69596abcbecb91c77e1d8b6c138df5cf95487f1"
},
{
"name": "container-viewer.umd.min.locale-hi.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-167518d4e44d1bca8783/container-viewer.umd.min.locale-hi.js",
"bytes": 102168,
"storedBytes": 22575,
"sha256": "39f4b3bbd3b865f7ba350e4d56ee54d59f9ab2555ac401639706e2670fb582ae"
},
{
"name": "container-viewer.umd.min.locale-it.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-167518d4e44d1bca8783/container-viewer.umd.min.locale-it.js",
"bytes": 65880,
"storedBytes": 19608,
"sha256": "3e9878212833edbc4c7a424a7772b67ba7711d013e6771a12d43d5462ee4124c"
},
{
"name": "container-viewer.umd.min.locale-ko.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-167518d4e44d1bca8783/container-viewer.umd.min.locale-ko.js",
"bytes": 69099,
"storedBytes": 20551,
"sha256": "6905b51c4e4b9d4f9b13508f943fff2001de55e15734d4a7c011152afe802ad3"
},
{
"name": "container-viewer.umd.min.locale-nl.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-167518d4e44d1bca8783/container-viewer.umd.min.locale-nl.js",
"bytes": 63937,
"storedBytes": 19499,
"sha256": "66822778f3bb9c9fe497503d11aab70650b77826cd2bb2035dc1f68f173fa2fe"
},
{
"name": "container-viewer.umd.min.locale-pl.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-167518d4e44d1bca8783/container-viewer.umd.min.locale-pl.js",
"bytes": 64995,
"storedBytes": 20546,
"sha256": "0807321c80808f5677ea75bcec9f15365df8d240b985882a55fdbb57687fd209"
},
{
"name": "container-viewer.umd.min.locale-pt-BR.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-167518d4e44d1bca8783/container-viewer.umd.min.locale-pt-BR.js",
"bytes": 64919,
"storedBytes": 19402,
"sha256": "5e75329a509d022574cb8a63c9ed85ef6736d262b4ec7d48fbf88e89be924437"
},
{
"name": "container-viewer.umd.min.locale-ro.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-167518d4e44d1bca8783/container-viewer.umd.min.locale-ro.js",
"bytes": 66591,
"storedBytes": 20026,
"sha256": "011465c93b31d6a46423de1ec6cefb7378de1c62435b7113a13356fe93013a85"
},
{
"name": "container-viewer.umd.min.locale-ru.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-167518d4e44d1bca8783/container-viewer.umd.min.locale-ru.js",
"bytes": 85833,
"storedBytes": 23151,
"sha256": "9b340bc35aac030020fd07eae45a008b910aac30fe9d37c17998299bf8b3ed46"
},
{
"name": "container-viewer.umd.min.locale-vi.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-167518d4e44d1bca8783/container-viewer.umd.min.locale-vi.js",
"bytes": 71025,
"storedBytes": 20083,
"sha256": "fd8165c58b4136fafb52e1f53ed834d89a22eb820e7eb9fadde984e15e295650"
},
{
"name": "container-viewer.umd.min.locale-zh-CN.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-167518d4e44d1bca8783/container-viewer.umd.min.locale-zh-CN.js",
"bytes": 59905,
"storedBytes": 19763,
"sha256": "19c1c8af7f9be91fe4647790de044b66285b40739461290133ca1b9ab78da1ed"
},
{
"name": "container-viewer.umd.min.locale-zh-TW.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-167518d4e44d1bca8783/container-viewer.umd.min.locale-zh-TW.js",
"bytes": 60615,
"storedBytes": 20138,
"sha256": "f9fa2add34a3bdcc16ca38ea0a541c3ec71903288398c332cee3b115c4087ed7"
}
],
"tutorial": {
"sections": [
{
"id": "base-game",
"title": "Base game",
"description": "Learn production, trading, shipping and scoring."
},
{
"id": "offshore-island",
"title": "Offshore Island",
"description": "Learn the public bank auctions and cargo handling."
}
],
"chapters": [
{
"id": "supply-chain",
"title": "From factory to ship",
"description": "Produce, set prices, trade with another player and load a ship.",
"version": 1,
"section": "base-game"
},
{
"id": "buildings",
"title": "Factories and warehouses",
"description": "Distinguish buildings from sale spaces, then expand production and storage.",
"version": 1,
"section": "base-game"
},
{
"id": "selling",
"title": "Sail and sell your cargo",
"description": "Start an auction, reveal the sealed bids and collect the bank subsidy.",
"version": 1,
"section": "base-game"
},
{
"id": "bidding",
"title": "Bid, raise and break a tie",
"description": "Make a sealed offer, add a tie-break bid and see who pays.",
"version": 1,
"section": "base-game"
},
{
"id": "keep-cargo",
"title": "Keep the cargo yourself",
"description": "Decline the bids, pay the bank and compare the cost with selling.",
"version": 3,
"section": "base-game"
},
{
"id": "scoring",
"title": "What actually scores?",
"description": "Discard your most numerous colour, value a full set and count the final money.",
"version": 1,
"section": "base-game"
},
{
"id": "offshore-cargo",
"title": "Bank cargo and your ship",
"description": "Bid cash publicly, wait for settlement, then sail and load your safe holding.",
"version": 2,
"section": "offshore-island"
},
{
"id": "offshore-cash",
"title": "Stored cargo for bank cash",
"description": "Select real stored cargo, review one offer, then choose payment colour order.",
"version": 1,
"section": "offshore-island"
},
{
"id": "offshore-outbid",
"title": "Outbid and recover cargo",
"description": "See a public leader change, reprice returned stock, and wait for the new leader.",
"version": 1,
"section": "offshore-island"
}
]
},
"unchangedEngine": {
"package": {
"name": "container-engine",
"version": "2.2.0",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/engine/d91a59b7ef3ef416/container-engine-2.2.0.tgz"
},
"entryPoint": "dist/wrapper.js"
},
"unchangedAchievementRevision": 4,
"verification": {
"viewerUnitTests": 75,
"tutorialTests": 18,
"locales": 17,
"typeCheck": true,
"libraryBuild": true,
"offshoreBrowserWidths": [390, 1400],
"allTutorialBrowserWidths": [390, 1400],
"liveGroupedCatalog": true,
"liveCargoLessonCompleted": true,
"liveFrenchLocale": true
}
}

View file

@ -0,0 +1,174 @@
{
"game": "container",
"gameVersion": 3,
"viewerVersion": "2.1.3",
"sourceCommit": "13bbb63b65bb976f19e520888a5e47a354b55a3b",
"activated": true,
"bundle": "split-fe17891069e8f5c5f8a7",
"previousViewer": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-167518d4e44d1bca8783/container-viewer.umd.min.js",
"topLevelVariable": "container",
"fullScreen": true,
"replayable": false,
"dependencies": {
"scripts": ["https://cdn.jsdelivr.net/npm/vue@^2/dist/vue.min.js"],
"stylesheets": [
"https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-167518d4e44d1bca8783/container-viewer.css"
]
},
"chat": true,
"thumbnail": true,
"scriptBytes": 515389
},
"viewer": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-fe17891069e8f5c5f8a7/container-viewer.umd.min.js",
"topLevelVariable": "container",
"fullScreen": true,
"replayable": false,
"dependencies": {
"scripts": ["https://cdn.jsdelivr.net/npm/vue@^2/dist/vue.min.js"],
"stylesheets": [
"https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-fe17891069e8f5c5f8a7/container-viewer.css"
]
},
"chat": true,
"thumbnail": true,
"scriptBytes": 515446
},
"files": [
{
"name": "container-viewer.css",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-fe17891069e8f5c5f8a7/container-viewer.css",
"bytes": 16007,
"storedBytes": 4172,
"sha256": "c63e8f19879ec61ccf04950a3022dd37b3c6c5ac37fa33f1a69f073e193b672d"
},
{
"name": "container-viewer.umd.min.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-fe17891069e8f5c5f8a7/container-viewer.umd.min.js",
"bytes": 515446,
"storedBytes": 152611,
"sha256": "8a2828f67bdde16af9282733ca6c8a11b087cf20afffd0f3392fc9249cd9580a"
},
{
"name": "container-viewer.umd.min.locale-da.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-fe17891069e8f5c5f8a7/container-viewer.umd.min.locale-da.js",
"bytes": 62259,
"storedBytes": 19265,
"sha256": "5a32e842ca40fe6f0491282d85d66a9812ac5143955701f92e03af31adf08091"
},
{
"name": "container-viewer.umd.min.locale-de.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-fe17891069e8f5c5f8a7/container-viewer.umd.min.locale-de.js",
"bytes": 65663,
"storedBytes": 20310,
"sha256": "53945a725bdad65f87565334147ec7fe639f94d0e5eebe486d304bf581878ff3"
},
{
"name": "container-viewer.umd.min.locale-el.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-fe17891069e8f5c5f8a7/container-viewer.umd.min.locale-el.js",
"bytes": 93670,
"storedBytes": 23517,
"sha256": "a927c7b09a0c3bc2cb33a768383c141a005397ea831f24bc982d8e7b82413a46"
},
{
"name": "container-viewer.umd.min.locale-fa.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-fe17891069e8f5c5f8a7/container-viewer.umd.min.locale-fa.js",
"bytes": 83241,
"storedBytes": 21291,
"sha256": "1ea561ba38c41ac9ad474bfc267ab5837d51ee12ae979985916acf5fcf97f897"
},
{
"name": "container-viewer.umd.min.locale-fr.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-fe17891069e8f5c5f8a7/container-viewer.umd.min.locale-fr.js",
"bytes": 66750,
"storedBytes": 19868,
"sha256": "900b84f10ea312888168b750c69596abcbecb91c77e1d8b6c138df5cf95487f1"
},
{
"name": "container-viewer.umd.min.locale-hi.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-fe17891069e8f5c5f8a7/container-viewer.umd.min.locale-hi.js",
"bytes": 102168,
"storedBytes": 22575,
"sha256": "39f4b3bbd3b865f7ba350e4d56ee54d59f9ab2555ac401639706e2670fb582ae"
},
{
"name": "container-viewer.umd.min.locale-it.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-fe17891069e8f5c5f8a7/container-viewer.umd.min.locale-it.js",
"bytes": 65880,
"storedBytes": 19608,
"sha256": "3e9878212833edbc4c7a424a7772b67ba7711d013e6771a12d43d5462ee4124c"
},
{
"name": "container-viewer.umd.min.locale-ko.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-fe17891069e8f5c5f8a7/container-viewer.umd.min.locale-ko.js",
"bytes": 69099,
"storedBytes": 20551,
"sha256": "6905b51c4e4b9d4f9b13508f943fff2001de55e15734d4a7c011152afe802ad3"
},
{
"name": "container-viewer.umd.min.locale-nl.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-fe17891069e8f5c5f8a7/container-viewer.umd.min.locale-nl.js",
"bytes": 63937,
"storedBytes": 19499,
"sha256": "66822778f3bb9c9fe497503d11aab70650b77826cd2bb2035dc1f68f173fa2fe"
},
{
"name": "container-viewer.umd.min.locale-pl.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-fe17891069e8f5c5f8a7/container-viewer.umd.min.locale-pl.js",
"bytes": 64995,
"storedBytes": 20546,
"sha256": "0807321c80808f5677ea75bcec9f15365df8d240b985882a55fdbb57687fd209"
},
{
"name": "container-viewer.umd.min.locale-pt-BR.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-fe17891069e8f5c5f8a7/container-viewer.umd.min.locale-pt-BR.js",
"bytes": 64919,
"storedBytes": 19402,
"sha256": "5e75329a509d022574cb8a63c9ed85ef6736d262b4ec7d48fbf88e89be924437"
},
{
"name": "container-viewer.umd.min.locale-ro.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-fe17891069e8f5c5f8a7/container-viewer.umd.min.locale-ro.js",
"bytes": 66591,
"storedBytes": 20026,
"sha256": "011465c93b31d6a46423de1ec6cefb7378de1c62435b7113a13356fe93013a85"
},
{
"name": "container-viewer.umd.min.locale-ru.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-fe17891069e8f5c5f8a7/container-viewer.umd.min.locale-ru.js",
"bytes": 85833,
"storedBytes": 23151,
"sha256": "9b340bc35aac030020fd07eae45a008b910aac30fe9d37c17998299bf8b3ed46"
},
{
"name": "container-viewer.umd.min.locale-vi.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-fe17891069e8f5c5f8a7/container-viewer.umd.min.locale-vi.js",
"bytes": 71025,
"storedBytes": 20083,
"sha256": "fd8165c58b4136fafb52e1f53ed834d89a22eb820e7eb9fadde984e15e295650"
},
{
"name": "container-viewer.umd.min.locale-zh-CN.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-fe17891069e8f5c5f8a7/container-viewer.umd.min.locale-zh-CN.js",
"bytes": 59905,
"storedBytes": 19763,
"sha256": "19c1c8af7f9be91fe4647790de044b66285b40739461290133ca1b9ab78da1ed"
},
{
"name": "container-viewer.umd.min.locale-zh-TW.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-fe17891069e8f5c5f8a7/container-viewer.umd.min.locale-zh-TW.js",
"bytes": 60615,
"storedBytes": 20138,
"sha256": "f9fa2add34a3bdcc16ca38ea0a541c3ec71903288398c332cee3b115c4087ed7"
}
],
"verification": {
"viewerUnitTests": 77,
"tutorialTests": 18,
"typeCheck": true,
"libraryBuild": true,
"offshoreBrowserWidths": [390, 1400],
"liveBankLotToHoldingAnimations": 2
}
}

View file

@ -0,0 +1,178 @@
{
"game": "container",
"gameVersion": 3,
"viewerVersion": "2.1.4",
"sourceCommit": "5403d544794571cdc0645e2375b1990ca74b64b3",
"activated": true,
"bundle": "split-a3d6f2c5391655e4548e",
"previousViewer": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-fe17891069e8f5c5f8a7/container-viewer.umd.min.js",
"topLevelVariable": "container",
"fullScreen": true,
"replayable": false,
"dependencies": {
"scripts": ["https://cdn.jsdelivr.net/npm/vue@^2/dist/vue.min.js"],
"stylesheets": [
"https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-fe17891069e8f5c5f8a7/container-viewer.css"
]
},
"chat": true,
"thumbnail": true,
"scriptBytes": 515446
},
"viewer": {
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-a3d6f2c5391655e4548e/container-viewer.umd.min.js",
"topLevelVariable": "container",
"fullScreen": true,
"replayable": false,
"dependencies": {
"scripts": ["https://cdn.jsdelivr.net/npm/vue@^2/dist/vue.min.js"],
"stylesheets": [
"https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-a3d6f2c5391655e4548e/container-viewer.css"
]
},
"chat": true,
"thumbnail": true,
"scriptBytes": 517085
},
"files": [
{
"name": "container-viewer.css",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-a3d6f2c5391655e4548e/container-viewer.css",
"bytes": 16106,
"storedBytes": 4195,
"sha256": "9146649477b06888b915de2a91f4e41deaf71f7f0b70296219968174536ed84c"
},
{
"name": "container-viewer.umd.min.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-a3d6f2c5391655e4548e/container-viewer.umd.min.js",
"bytes": 517085,
"storedBytes": 153097,
"sha256": "97e0a71931492d7cb8f1b656ee42b495cd2ca4335019acb9959dbf04e40687db"
},
{
"name": "container-viewer.umd.min.locale-da.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-a3d6f2c5391655e4548e/container-viewer.umd.min.locale-da.js",
"bytes": 62352,
"storedBytes": 19294,
"sha256": "b387435e308b034220a24185b85409d31f2ea26a7ff6f782485cfbce72fb635b"
},
{
"name": "container-viewer.umd.min.locale-de.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-a3d6f2c5391655e4548e/container-viewer.umd.min.locale-de.js",
"bytes": 65765,
"storedBytes": 20340,
"sha256": "1198df009ba519cbf556a35106b3029ca94516a19f9461bf2cf2eb70244f14a5"
},
{
"name": "container-viewer.umd.min.locale-el.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-a3d6f2c5391655e4548e/container-viewer.umd.min.locale-el.js",
"bytes": 93818,
"storedBytes": 23552,
"sha256": "99ca375b1b484e36866bdfe11757091576cee36da4bc1a40fec9018319af7f6a"
},
{
"name": "container-viewer.umd.min.locale-fa.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-a3d6f2c5391655e4548e/container-viewer.umd.min.locale-fa.js",
"bytes": 83375,
"storedBytes": 21316,
"sha256": "92451e8d071b1626eeda7e44f8605034bc58bebc6d60cd07b1c8de5133e93a03"
},
{
"name": "container-viewer.umd.min.locale-fr.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-a3d6f2c5391655e4548e/container-viewer.umd.min.locale-fr.js",
"bytes": 66852,
"storedBytes": 19898,
"sha256": "cd403133ee7dba341bc321939cbf58e3da5a6a880173edafb37f8b4dda659d62"
},
{
"name": "container-viewer.umd.min.locale-hi.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-a3d6f2c5391655e4548e/container-viewer.umd.min.locale-hi.js",
"bytes": 102309,
"storedBytes": 22609,
"sha256": "0391f587f0f87994e067d3a22c657a608514672703d09adeee6c844a235059a7"
},
{
"name": "container-viewer.umd.min.locale-it.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-a3d6f2c5391655e4548e/container-viewer.umd.min.locale-it.js",
"bytes": 65980,
"storedBytes": 19638,
"sha256": "7bb554ed448ee7d2c0584f6cd89d6afe5243718b17bacd30afd61adbcfa71600"
},
{
"name": "container-viewer.umd.min.locale-ko.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-a3d6f2c5391655e4548e/container-viewer.umd.min.locale-ko.js",
"bytes": 69198,
"storedBytes": 20577,
"sha256": "a79a5e933d00c59a1381aa78c6b5d3fa8f43e2f669810aaf6b57903846e36526"
},
{
"name": "container-viewer.umd.min.locale-nl.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-a3d6f2c5391655e4548e/container-viewer.umd.min.locale-nl.js",
"bytes": 64037,
"storedBytes": 19532,
"sha256": "902a3b4af84e669f7e8c8a16b64163b372f7110827dbd8bc9c1b1596635f8882"
},
{
"name": "container-viewer.umd.min.locale-pl.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-a3d6f2c5391655e4548e/container-viewer.umd.min.locale-pl.js",
"bytes": 65086,
"storedBytes": 20573,
"sha256": "2f8b0f5fa60238c4a393c692956e4f4afc6d3f6533a69e7bf7dde7cd47d5b8b5"
},
{
"name": "container-viewer.umd.min.locale-pt-BR.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-a3d6f2c5391655e4548e/container-viewer.umd.min.locale-pt-BR.js",
"bytes": 65016,
"storedBytes": 19429,
"sha256": "fb5eb376e8b2bb9340fb2983c2813c831b4982295da5258842743351b0c602fc"
},
{
"name": "container-viewer.umd.min.locale-ro.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-a3d6f2c5391655e4548e/container-viewer.umd.min.locale-ro.js",
"bytes": 66689,
"storedBytes": 20055,
"sha256": "c85bdc5a62c4277267c6d2baf8f79a76e4cac56613742b9f6036107241020304"
},
{
"name": "container-viewer.umd.min.locale-ru.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-a3d6f2c5391655e4548e/container-viewer.umd.min.locale-ru.js",
"bytes": 85966,
"storedBytes": 23182,
"sha256": "2ca0103f534cba669380ae0f18a4deb535427113516670173f664d27f0f9636c"
},
{
"name": "container-viewer.umd.min.locale-vi.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-a3d6f2c5391655e4548e/container-viewer.umd.min.locale-vi.js",
"bytes": 71138,
"storedBytes": 20108,
"sha256": "6da4d40962ec0c9632c1526b335369599fe26a4e0527caa8e6ad9da6c642c051"
},
{
"name": "container-viewer.umd.min.locale-zh-CN.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-a3d6f2c5391655e4548e/container-viewer.umd.min.locale-zh-CN.js",
"bytes": 60002,
"storedBytes": 19792,
"sha256": "24d326f2561a108547ebceda2e72ed163e1d343a233df73c54ad34d269c1d0fc"
},
{
"name": "container-viewer.umd.min.locale-zh-TW.js",
"url": "https://s3.fr-par.scw.cloud/bgs-assets/games/container/3/viewer/split-a3d6f2c5391655e4548e/container-viewer.umd.min.locale-zh-TW.js",
"bytes": 60709,
"storedBytes": 20162,
"sha256": "c2bafaa14114b6cb1ca36f9040f9336d7d6c1774823e228aa1424b76b65d4e27"
}
],
"checks": {
"unitTests": 83,
"tutorialTests": 18,
"locales": 17,
"typecheck": true,
"build": true,
"offshoreBrowserWidths": [390, 1400],
"allTutorialBrowserWidths": [390, 1400],
"liveTutorial": "Verified unique bid draft cargo, removal and reselection, active return tray, neutral tray after selection, and original-store return destination.",
"uploadedAssets": "Public downloaded bytes verified by publisher",
"unchanged": ["engine", "achievementManifest", "tutorial"]
}
}

13
docs/viewer-publishing.md Normal file
View file

@ -0,0 +1,13 @@
# Publishing the viewer
Upload `container-viewer.umd.min.js`, `container-viewer.css` and all `container-viewer.umd.min.locale-*.js` files from `viewer/dist`. The other UMD/CommonJS variants are not needed.
All files in a release must share one BGS `bundle` directory, with their relative paths preserved. Upload everything before saving the new entry URL. A main-JS-only upload will break language or asset loading. Keep engines and test data out of the viewer upload.
BGS compresses JS, CSS, JSON and WASM automatically during upload. Send the original bytes; do not create `.gz` files. Keep sourcemaps local unless you deliberately want to publish them. Set `viewer.scriptBytes` to the original entry size so BGS can show download progress.
The BGS admin's **Upload folder** control handles multi-file builds. For scripted releases, use BGS's `scripts/publish-viewer.mjs` with `--dir`, `--entry` and `--style`; it verifies every uploaded file, records the previous viewer, and activates only with `--apply --activate`. The full command and API contract are in the [BGS viewer documentation](https://docs.boardgamers.space/guide/viewer-api#publishing-a-viewer-with-multiple-files).
English needs no language download; other languages load when selected. Test a cold load and a language change after publishing. Also check the browser Network panel for missing relative assets.
The UMD build captures its script URL during evaluation and resolves locale imports to absolute URLs. This is required for cross-origin classic scripts: browsers can otherwise give `import()` an `about:blank` base. The tutorial browser suite exercises all 17 languages with HTML and viewer assets on different origins, without requiring the host to set a `crossorigin` attribute.

View file

@ -0,0 +1,26 @@
# Offshore engine/viewer contract
Opt-in `GameOptions.offshoreIsland?: boolean`; wrapper expansion ID `offshore-island`.
`G.offshoreBank` exists only when enabled. `cashLots: number[3]`, `containerLots: ContainerPiece[3][]`, `auctions: BankAuction[]`, `called`, `won`. Auction `type: 'cash' | 'containers'` describes **prize**, `lot: 0|1|2`, `bidder`, `cash` (public escrow), `containers: {container: ContainerOnStore, district: 'factory'|'warehouse'}[]` (public escrow/reserves). Money is already net of escrow. Players have optional `bankHolding: ContainerPiece[]`, `offshoreStats: {cashAuctionsWon:number;containerAuctionsWon:number}` including end-game settlements.
`ShipPosition.OffshoreBank = 'offshoreBank'`. Only free pickup immediately on arrival (or successive pickup); no stationary later-turn pickup.
Move enum names/values:
- `CallBank = 'callBank'`: data `{type:'cash'|'containers',lot:number}`, extraData `{cash?:number,containers?:string[]}`. For container prize send cash; for cash prize send container IDs from own factory/warehouse. Minimum opening bid 1 (explicit interpretation of ambiguous rules), raise by at least1. Available data enumerates lot choices, not combinations.
- `ReturnBankContainer = 'returnBankContainer'`: data ContainerPiece, extraData `{price:number}`. Price 1–4 factory, 2–6 warehouse. Only returned containers reprice, owner chooses one at a time.
- `DistributeBankContainer = 'distributeBankContainer'`: data ContainerPiece, no extraData. Chooses next container to pay into deterministic next unfrozen lot, starting I; repeated until payment exhausted.
- `SeizeBankContainer = 'seizeBankContainer'`: data ContainerPiece, no extraData. Right-hand player chooses among highest-priority source; repeat then choose distribution.
- `LoadBankContainer = 'loadBankContainer'`: data ContainerPiece, no extraData, free repeat until capacity5. Other normal moves end arrival pickup window.
`Phase.BankDecision = 'bankDecision'`, `G.currentPlayers` is sole decision owner. `offshoreBank.decision` describes `kind:'return'|'distribute'|'seize'`, `player`, `resumePlayer`, returned `containers`, ordered-to-be-chosen `payment`, distribution `cursor`, optional `debtor`, `remaining`, `settlement`, `ending`. Use availableMoves keys to display controls. Each decision commits independently; resumePlayer's interrupted regular turn resumes after final choice. Discretionary choices are logged explicit moves. After each engine move, distribution automatically drains when all remaining payment pieces have the same color (including a single piece), in persisted payment order into cyclic unfrozen destinations. These forced effects are not synthetic moves or viewer emissions; collection and any following settlement finish before legal moves are published. Multiple colors still require explicit choices. Return pricing, seizure and loading remain explicit. Legacy saved single-piece distribution decisions still accept their advertised move. Fake previews normalize distribution but never score secret point cards.
Score breakdown remains same length: ship line includes bankHolding at $3 each. Other base scoring unchanged.
## Interpretations / unresolved physical-rule detail
By user-selected rule, empty container reward lots and $0 cash reward lots cannot receive opening bids or raises; replenished lots become eligible again, subject to normal auction restrictions. This resolves the PDF’s “any lot” ambiguity for this implementation, not as a publisher-confirmed ruling. Existing saved auctions on empty lots still settle normally (positive opening bids remain required).
For two auctions pending at game end, p18 says to resolve each, but does not specify a simultaneous-payment snapshot or which resolves first. This implementation resolves the persisted `auctions` array in order, with each payment before collection/cleanup as p14 directs. Only currently active tokens freeze lots; a cleaned-up lot can receive later payments. This is deterministic but end-resolution ordering is an explicit rules ambiguity requiring publisher clarification, not a claimed mandated tie-break. Normal turn-start resolution follows the same pay/collect/clean sequence.
`initialContainerLots` is an additional public immutable setup snapshot used to reconstruct observed cash from a stripped state with an unrelated analysis seed. It contains only the publicly seeded bank pieces, never secret cash or scoring cards.

View file

@ -1,6 +1,19 @@
export { availableMoves, AvailableMoves } from './src/available-moves';
export { currentPlayers, ended, move, reconstructState, setup, stripSecret } from './src/engine';
export { Phase } from './src/gamestate';
export type { GameState, Player, PointCard } from './src/gamestate';
export { GameEventName, LogItem } from './src/log';
export { Move, MoveName, Moves } from './src/move';
export { availableMoves } from './src/available-moves';
export type { AvailableMoves } from './src/available-moves';
export * from './src/choice-revisions';
export { currentPlayers, ended, move, moveAI, setup, stripSecret } from './src/engine';
export { Phase, ShipPosition } from './src/gamestate';
export type {
BankAuction,
BankAuctionType,
BankEscrowContainer,
GameOptions,
GameState,
OffshoreBank,
Player,
PointCard,
} from './src/gamestate';
export { GameEventName } from './src/log';
export type { LogItem } from './src/log';
export { isLoanReversal, MoveName } from './src/move';
export type { Move, Moves } from './src/move';

View file

@ -1,11 +1,15 @@
{
"name": "container-engine",
"version": "1.0.8",
"version": "2.2.0",
"description": "An engine for Container",
"main": "dist/index.js",
"types": "index.ts",
"source": "index.ts",
"repository": "git@github.com:LucasAMello/container-engine.git",
"repository": {
"type": "git",
"url": "git+https://github.com/boardgamers/container.git",
"directory": "engine"
},
"publishConfig": {
"access": "public"
},
@ -19,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",

2361
engine/pnpm-lock.yaml generated

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,355 @@
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 { move, moveAI, setup } from './engine';
import { containerColors, GameState, Phase } from './gamestate';
import { MoveName } from './move';
// Compile against the published optional hooks, not a local protocol imitation.
const hooks: Pick<Engine<GameState>, 'achievementDefinitions' | 'achievements'> = wrapper;
function complete(players: number, seed = `achievements-${players}`): GameState {
const random = Math.random;
Math.random = seedrandom(seed);
try {
let G = setup(players, {}, seed);
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-four manifest', () => {
expect(hooks.achievementDefinitions).to.be.a('function');
const manifest = wrapper.achievementDefinitions();
expect(manifest.revision).to.equal(4);
expect(manifest.achievements.map((d) => d.id)).not.to.include('island-five');
expect(manifest.achievements.find((d) => d.id === 'island-fifteen')).to.deep.equal({
id: 'island-fifteen',
name: 'Island Magnate',
description: 'Finish with at least fifteen containers on your island.',
icon: { type: 'asset', key: 'achievement-island-fifteen' },
});
expect(manifest.achievements).to.have.length(19);
expect(new Set(manifest.achievements.map((d) => d.id)).size).to.equal(19);
for (const definition of manifest.achievements) {
expect(definition.icon).to.deep.equal(
definition.id.startsWith('offshore-')
? { type: 'text', text: definition.id === 'offshore-win' ? 'OI' : 'BANK' }
: { type: 'asset', key: `achievement-${definition.id}` }
);
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('earns island-fifteen in a legal completed game and replay', () => {
const G = complete(5, 'island-fifteen-11');
expect(G.players[4].containersOnIsland).to.have.length(15);
const result = wrapper.achievements(freeze(G));
expect(result[4].earned).to.include('island-fifteen');
expect(result[4].earned).to.include('island-ten');
expect(result.every((row) => !row.earned.includes('island-five'))).to.equal(true);
expect(wrapper.achievements(wrapper.replay(G))).to.deep.equal(result);
});
it('earns warehouse-five through legal purchases and completion, including replay', () => {
const random = Math.random;
Math.random = seedrandom('warehouse-1');
let G = setup(3, {}, 'warehouse-1');
let reachedCapacity = false;
try {
// The ordinary AI stops expanding at three warehouses. This legal policy
// invests surplus cash in warehouses and fills them from offered stock.
// No money, pieces, phase or available moves are injected into the state.
for (let i = 0; i < 20000 && !wrapper.ended(G); i++) {
const seat = G.currentPlayers[0];
const p = G.players[seat];
const available = p.availableMoves!;
if (available[MoveName.BuyWarehouse] && p.money >= p.warehouses.length + 13) {
G = move(G, { name: MoveName.BuyWarehouse, data: true, extraData: G.warehousesLeft[0] }, seat);
} else if (available[MoveName.BuyFromFactory] && p.warehouses.length === 5 && p.money > 10) {
G = move(
G,
{
name: MoveName.BuyFromFactory,
data: available[MoveName.BuyFromFactory]![0],
extraData: { price: 6 },
},
seat
);
} else {
G = moveAI(G, seat);
}
for (const player of G.players) {
expect(player.factories.length).to.be.at.most(4);
expect(player.warehouses.length).to.be.at.most(5);
expect(player.ship.containers.length).to.be.at.most(5);
expect(player.containersOnWarehouseStore.length).to.be.at.most(player.warehouses.length);
if (player.containersOnWarehouseStore.length === 5) {
reachedCapacity = true;
expect(player.availableMoves?.[MoveName.BuyFromFactory]).to.equal(undefined);
expect(player.availableMoves?.[MoveName.BuyWarehouse]).to.equal(undefined);
}
}
}
} finally {
Math.random = random;
}
expect(reachedCapacity).to.equal(true);
expect(wrapper.ended(G)).to.equal(true);
const saved: GameState = JSON.parse(JSON.stringify(G));
expect(saved.players[2].warehouses).to.have.length(5);
expect(saved.players[2].containersOnWarehouseStore).to.have.length(5);
const result = wrapper.achievements(freeze(saved));
expect(result[2].earned).to.include('warehouse-five');
expect(result[2].earned).to.include('five-warehouses');
expect(wrapper.achievements(wrapper.replay(saved))).to.deep.equal(result);
expect(wrapper.achievementDefinitions().achievements.map((d) => d.id)).not.to.include('warehouse-six');
expect(result.every((row) => !row.earned.includes('warehouse-six'))).to.equal(true);
});
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('earns both expansion awards through legal completion and serialized replay', () => {
const random = Math.random;
Math.random = seedrandom('offshore-achievements');
let G = setup(3, { offshoreIsland: true }, 'offshore-achievements');
try {
for (let i = 0; i < 20000 && !wrapper.ended(G); i++) {
const seat = G.currentPlayers[0];
const p = G.players[seat];
// Seat zero pursues both auction types while opponents use the bank too.
// First sell stored containers, then buy bank stock with cash.
const offer =
seat === 0 &&
p.availableMoves?.[MoveName.CallBank]?.find(
(offer) => offer.type === (p.offshoreStats!.cashAuctionsWon ? 'containers' : 'cash')
);
if (offer && !p.offshoreStats!.containerAuctionsWon) {
const active = G.offshoreBank!.auctions.find((a) => a.type === offer.type);
G = move(
G,
{
name: MoveName.CallBank,
data: offer,
extraData:
offer.type === 'cash'
? {
containers: [...p.containersOnFactoryStore, ...p.containersOnWarehouseStore]
.slice(0, (active?.containers.length || 0) + 1)
.map((c) => c.piece.id),
}
: { cash: (active?.cash || 0) + 1 },
},
seat
);
} else {
G = moveAI(G, seat);
}
}
} finally {
Math.random = random;
}
expect(wrapper.ended(G), 'legal expansion policy finishes').to.equal(true);
const saved: GameState = JSON.parse(JSON.stringify(G));
const before = JSON.stringify(saved);
const result = wrapper.achievements(freeze(saved));
expect(result[0].earned).to.include('offshore-trader');
expect(result.some((row) => row.earned.includes('offshore-win'))).to.equal(true);
expect(wrapper.achievements(wrapper.replay(saved))).to.deep.equal(result);
expect(JSON.stringify(saved)).to.equal(before);
});
it('gates expansion awards on the option, both counters, completion and seat eligibility', () => {
const G = cloneDeep(completed[0]);
G.players.forEach((p, seat) => {
p.money = 100 - seat;
p.containersOnIsland = [];
p.offshoreStats = { cashAuctionsWon: 1, containerAuctionsWon: 1 };
});
const earned = (seat = 0) => wrapper.achievements(G).find((row) => row.seat === seat)!.earned;
for (const option of [undefined, false]) {
G.options.offshoreIsland = option;
expect(earned()).not.to.include('offshore-win');
expect(earned()).not.to.include('offshore-trader');
}
G.options.offshoreIsland = true;
expect(earned()).to.include('offshore-win');
expect(earned()).to.include('offshore-trader');
expect(earned(1)).not.to.include('offshore-win');
expect(earned(1)).to.include('offshore-trader');
for (const stats of [
undefined,
{},
{ cashAuctionsWon: 1 },
{ containerAuctionsWon: 1 },
{ cashAuctionsWon: 0, containerAuctionsWon: 1 },
{ cashAuctionsWon: 1, containerAuctionsWon: 0 },
]) {
// Partial counters model old or incomplete serialized evidence.
G.players[0].offshoreStats = stats as GameState['players'][number]['offshoreStats'];
expect(earned()).not.to.include('offshore-trader');
expect(earned()).to.include('offshore-win');
}
G.players[0].offshoreStats = { cashAuctionsWon: 2, containerAuctionsWon: 3 };
expect(earned()).to.include('offshore-trader');
G.players[1].money = G.players[0].money;
expect(earned()).not.to.include('offshore-win');
expect(earned()).to.include('offshore-trader');
G.players[0].isAI = true;
G.players[1].isDropped = true;
expect(wrapper.achievements(G).map((row) => row.seat)).to.deep.equal([2]);
G.newTurn = false;
expect(wrapper.achievements(G)).to.deep.equal([]);
G.newTurn = true;
G.phase = Phase.Move;
expect(wrapper.achievements(G)).to.deep.equal([]);
expect(wrapper.achievements(setup(3, { offshoreIsland: true }, 'offshore-ongoing'))).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-fifteen', 15, (n) => (p.containersOnIsland = containers(n)));
expect(earned()).not.to.include('island-five');
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-five',
5,
(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,99 @@
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-fifteen', 'Island Magnate', 'Finish with at least fifteen 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-five', 'Stocked for Trade', 'Finish with five containers in your warehouse store.'],
];
export function achievementDefinitions(): AchievementManifest {
return {
revision: 4,
achievements: [
...definitions.map(([id, name, description]) => ({
id,
name,
description,
icon: { type: 'asset' as const, key: `achievement-${id}` },
})),
{
id: 'offshore-win',
name: 'Offshore Magnate',
description: 'Win a completed game with the Offshore Island expansion.',
icon: { type: 'text', text: 'OI' },
},
{
id: 'offshore-trader',
name: 'Two-Way Trade',
description:
'Win at least one cash auction and one container auction at the bank in the same completed Offshore Island game.',
icon: { type: 'text', text: 'BANK' },
},
],
};
}
/** 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. Platform cancellation/account eligibility must be checked by BGS;
// this state cannot establish general practice or analysis provenance.
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-fifteen', p.containersOnIsland.length >= 15],
['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-five', p.containersOnWarehouseStore.length === 5],
['offshore-win', G.options.offshoreIsland === true && win],
[
'offshore-trader',
G.options.offshoreIsland === true &&
(p.offshoreStats?.cashAuctionsWon ?? 0) >= 1 &&
(p.offshoreStats?.containerAuctionsWon ?? 0) >= 1,
],
] 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

@ -0,0 +1,66 @@
import { expect } from 'chai';
import { cloneDeep } from 'lodash';
import * as wrapper from '../wrapper';
import { setup } from './engine';
import { Phase } from './gamestate';
describe('safe ongoing analysis', () => {
it('depends only on observation and the simulation seed', () => {
const original = setup(3, {}, 'source-secret');
const before = cloneDeep(original);
const other = cloneDeep(original);
other.seed = 'different';
other.hiddenLog = [{ type: 'move', player: 1, move: { name: 'secret' } } as any];
other.players.slice(1).forEach((p) => {
p.money = 99999;
p.pointCard = null;
p.bid = 987;
p.additionalBid = 654;
p.lastMove = { name: 'secret' } as any;
});
const a = wrapper.createAnalysisScenario(original, { player: 0, seed: 'simulation' });
expect(a).to.deep.equal(wrapper.createAnalysisScenario(other, { player: 0, seed: 'simulation' }));
expect(original).to.deep.equal(before);
expect(a.players[0].pointCard).to.deep.equal(original.players[0].pointCard);
expect(a.players[0].money).to.equal(original.players[0].money);
expect(JSON.stringify(a)).not.to.contain('source-secret');
expect(a).not.to.deep.equal(wrapper.createAnalysisScenario(original, { player: 0, seed: 'another' }));
for (let i = 0; i < 50 && !wrapper.ended(a); i++) wrapper.moveAI(a, a.currentPlayers[0]);
expect(a.round).to.be.greaterThan(1);
});
});
describe('observer and pending auctions', () => {
it('does not use hidden bids, cash, objectives, or logs', () => {
const original = setup(3, {}, 'private');
original.phase = Phase.Bid;
original.auctioningPlayer = 0;
original.currentPlayers = [2];
original.players[1].bid = 10;
const other = cloneDeep(original);
other.players.forEach((p) => {
p.pointCard = null;
p.money = 999;
p.bid = 999;
p.additionalBid = 999;
});
const a = wrapper.createAnalysisScenario(original, { seed: 'same' });
expect(a).to.deep.equal(wrapper.createAnalysisScenario(other, { seed: 'same' }));
expect(a.players.every((p) => p.money >= p.bid + p.additionalBid)).to.equal(true);
const b = wrapper.createAnalysisScenario(a, { seed: 'new' });
expect(b.analysisCash).to.deep.equal(a.analysisCash);
wrapper.moveAI(b, 2);
expect(b.currentPlayers.length).to.be.greaterThan(0);
});
});
describe('public cash reconstruction failures', () => {
it('fails closed when the public ledger cannot reproduce the position', () => {
const source = setup(3, {}, 'source');
source.players[0].containersOnFactoryStore[0].price = 4;
expect(wrapper.canLaunchAnalysisMode(source)).to.equal(false);
expect(() => wrapper.createAnalysisScenario(source, { seed: 'fake' })).to.throw(
'Cannot reconstruct public cash'
);
});
});

View file

@ -0,0 +1,80 @@
import { expect } from 'chai';
import { cloneDeep } from 'lodash';
import * as wrapper from '../wrapper';
import { availableMoves } from './available-moves';
import { setup } from './engine';
import { Phase, ShipPosition } from './gamestate';
import { LogMove } from './log';
import { MoveName } from './move';
function auction(bid = 7, additionalBid = 3) {
const state = setup(3, {}, 'auction-messages');
state.phase = Phase.AcceptDecline;
state.currentPlayers = [0];
state.auctioningPlayer = 0;
state.highestBidders = [1];
state.players[0].name = 'slim_shagen';
state.players[1].name = 'coyotte508';
state.players[0].ship.shipPosition = ShipPosition.Island;
state.players[0].ship.containers = [state.containersLeft.pop()!];
state.players[1].bid = bid;
state.players[1].additionalBid = additionalBid;
state.players.forEach((player) => (player.availableMoves = availableMoves(state, player)));
return state;
}
describe('Auction results in journal and chat', () => {
for (const [bid, additionalBid] of [
[7, 3],
[7, 0],
[0, 0],
]) {
it(`reports the accepted total ${bid + additionalBid} before clearing bids`, async () => {
const state = await wrapper.move(auction(bid, additionalBid), { name: MoveName.Accept, data: 1 }, 0);
const entry = state.log[state.log.length - 1] as LogMove;
expect(entry.simple).to.equal(
`slim_shagen accepts coyotte508's bid of $${bid + additionalBid} and receives $${
2 * (bid + additionalBid)
}`
);
expect(entry.pretty).to.contain(`bid of $${bid + additionalBid}`);
expect(state.players[1].bid).to.equal(0);
expect(state.players[1].additionalBid).to.equal(0);
const result = wrapper.messages(state);
expect(result.messages).to.deep.equal([entry.simple]);
expect(wrapper.messages(result.data).messages).to.deep.equal([]);
expect(state.pendingMessages).to.deep.equal([entry.simple]);
});
}
it('announces a self-purchase and its cost', async () => {
const state = await wrapper.move(auction(), { name: MoveName.Decline, data: true }, 0);
expect(wrapper.messages(state).messages).to.deep.equal([
'slim_shagen declines all bids and buys the cargo for $10',
]);
});
it('does not backfill old auctions or expose an unresolved bid', () => {
const state = auction();
expect(wrapper.messages(state).messages).to.deep.equal([]);
state.log.push({
type: 'move',
player: 0,
move: { name: MoveName.Accept, data: 1 },
simple: 'Old auction',
pretty: 'Old auction',
});
expect(wrapper.messages(state).messages).to.deep.equal([]);
state.pendingMessages = ['Pending'];
state.newTurn = false;
expect(wrapper.messages(state)).to.deep.equal({ messages: [], data: state });
});
it('does not manufacture announcements when replaying history', () => {
const state = setup(3, {}, 'auction-replay');
state.pendingMessages = ['Still pending'];
expect(wrapper.replay(cloneDeep(state)).pendingMessages).to.deep.equal(['Still pending']);
const acknowledged = wrapper.messages(state).data;
expect(wrapper.messages(wrapper.replay(acknowledged)).messages).to.deep.equal([]);
});
});

View file

@ -1,8 +1,14 @@
import { remove } from 'lodash';
import { ContainerColor, ContainerOnStore, ContainerPiece, GameState, Phase, Player, ShipPosition } from './gamestate';
import { MoveName } from './move';
import { bankMoves, bankProductionAllowed, reserved } from './offshore';
export interface AvailableMoves {
[MoveName.CallBank]?: { type: 'cash' | 'containers'; lot: number }[];
[MoveName.ReturnBankContainer]?: ContainerPiece[];
[MoveName.DistributeBankContainer]?: ContainerPiece[];
[MoveName.SeizeBankContainer]?: ContainerPiece[];
[MoveName.LoadBankContainer]?: ContainerPiece[];
[MoveName.DomesticSale]?: ContainerPiece[];
[MoveName.BuyFromFactory]?: Array<{
player: number;
@ -24,10 +30,10 @@ export interface AvailableMoves {
[MoveName.Accept]?: number[];
[MoveName.Decline]?: boolean[];
[MoveName.Pass]?: boolean[];
[MoveName.Undo]?: boolean[];
}
export function availableMoves(G: GameState, player: Player): AvailableMoves {
if (G.offshoreBank && G.phase === Phase.BankDecision) return bankMoves(G, player);
switch (G.phase) {
case Phase.Bid: {
const moves = {
@ -36,10 +42,6 @@ export function availableMoves(G: GameState, player: Player): AvailableMoves {
if (player.loans.length < 2) moves[MoveName.GetLoan] = [true];
// Undo
const lastLog = G.log[G.log.length - 1];
if (lastLog.type == 'move' && G.currentPlayers.includes(lastLog.player)) moves[MoveName.Undo] = [true];
return moves;
}
@ -53,10 +55,6 @@ export function availableMoves(G: GameState, player: Player): AvailableMoves {
const highestBidder = G.players[G.highestBidders[0]];
if (player.money >= highestBidder.bid + highestBidder.additionalBid) moves[MoveName.Decline] = [true];
// Undo
const lastLog = G.log[G.log.length - 1];
if (lastLog.type == 'move' && G.currentPlayers.includes(lastLog.player)) moves[MoveName.Undo] = [true];
return moves;
}
@ -74,7 +72,10 @@ export function availableMoves(G: GameState, player: Player): AvailableMoves {
// BuyFromFactory
if (player.actions > 0 || player.lastMove?.name === MoveName.BuyFromFactory) {
if (player.containersOnWarehouseStore.length < player.warehouses.length) {
if (
player.containersOnWarehouseStore.length + reserved(G, player, 'warehouse') <
player.warehouses.length
) {
const containersAvailable: {
player: number;
container: ContainerOnStore;
@ -110,6 +111,7 @@ export function availableMoves(G: GameState, player: Player): AvailableMoves {
player.lastMove?.name === MoveName.BuyFromWarehouse
) {
if (
player.ship.shipPosition !== ShipPosition.OffshoreBank &&
player.ship.shipPosition !== ShipPosition.Island &&
player.ship.shipPosition !== ShipPosition.OpenSea &&
player.ship.containers.length < 5
@ -251,6 +253,7 @@ export function availableMoves(G: GameState, player: Player): AvailableMoves {
remove(positions, (pos) => G.players.map((p) => p.ship.shipPosition).indexOf(pos) != -1);
if (G.offshoreBank) positions.push(ShipPosition.OffshoreBank);
if (player.ship.containers.length > 0) {
positions.push(ShipPosition.Island);
}
@ -275,7 +278,8 @@ export function availableMoves(G: GameState, player: Player): AvailableMoves {
player.lastMove?.name === MoveName.Produce
) {
if (
player.containersOnFactoryStore.length < player.factories.length * 2 &&
player.containersOnFactoryStore.length + reserved(G, player, 'factory') <
player.factories.length * 2 &&
player.produced.length < player.factories.length
) {
const canProduce: ContainerColor[] = [];
@ -289,7 +293,7 @@ export function availableMoves(G: GameState, player: Player): AvailableMoves {
).length;
if (totalFactories > producedContainers && containersLeft.indexOf(factory.color) !== -1)
canProduce.push(factory.color);
if (bankProductionAllowed(G, player, factory.color)) canProduce.push(factory.color);
}
});
@ -301,10 +305,8 @@ export function availableMoves(G: GameState, player: Player): AvailableMoves {
}
}
// Undo
const lastLog = G.log[G.log.length - 1];
if (lastLog.type == 'move' && G.currentPlayers.includes(lastLog.player)) moves[MoveName.Undo] = [true];
if (G.offshoreBank && !(player.lastMove?.name === MoveName.Produce && moves[MoveName.Produce]))
Object.assign(moves, bankMoves(G, player));
return moves;
}

View file

@ -0,0 +1,25 @@
import type { GameState } from './gamestate';
import { Phase } from './gamestate';
import { Move, MoveName } from './move';
export function bidRevision(G: GameState, seat: number): string | undefined {
const p = G.players[seat];
if (
!p ||
p.isDropped ||
G.phase !== Phase.Bid ||
G.currentPlayers.length === 0 ||
G.currentPlayers.includes(seat) ||
seat === G.auctioningPlayer ||
(G.highestBidders.length > 0 && !G.highestBidders.includes(seat))
)
return undefined;
return `${G.round}:${G.log.length}:${G.auctioningPlayer}:${G.highestBidders.length ? 'extra' : 'initial'}`;
}
export function canReviseBid(G: GameState, payload: unknown, seat: number): boolean {
const moves = Array.isArray(payload) ? payload : [payload];
if (moves.length !== 1) return false;
const move = moves[0] as Move;
const key = bidRevision(G, seat);
return !!key && !!move && move.name === MoveName.Bid && move.revision === key;
}

View file

@ -0,0 +1,52 @@
import { expect } from 'chai';
import { createHash } from 'crypto';
import seedrandom from 'seedrandom';
import * as wrapper from '../wrapper';
// Captured by running unmodified commit 93194c8 in isolation, before this expansion.
// Hash the complete serialized state, including logs and deterministic piece IDs.
const baselines = [
[
3,
102,
'1a0a53979c32085df8942e94dce769464772f8653050920f58b8a031360ad890',
'd6e2d9344f775d813ffd33ba3a9ed0f6e781c37aa7f7153da5912cfee89d95ed',
],
[
4,
187,
'e958f1b8bdbe051a77a8440ae8c34384cf640ecf5c6c07ef1e398269acab6ef8',
'bc2afe3eafcf6c38e433c5ee24abb9417b0c1bf56ac5110759c50f6ddc3451ca',
],
[
5,
293,
'5f74b35334a567ace31e59eaf988b01c374b4a74de244a631ef4d9afae91d44c',
'b46c3c6e18635c10b5c68f5d7af1373bebab7f0de415f0d85a0995aa02e19cc5',
],
] as const;
const digest = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
describe('classic compatibility with pre-expansion release', () => {
for (const [players, expectedTurns, initialHash, finalHash] of baselines) {
it(`preserves the full seeded ${players}-player setup, game and replay`, async () => {
const seed = `achievements-${players}`;
const random = Math.random;
Math.random = seedrandom(seed);
try {
let state = await wrapper.init(players, [], {}, seed);
expect(digest(state)).to.equal(initialHash);
let turns = 0;
while (!wrapper.ended(state) && turns++ < 20000) {
state = wrapper.moveAI(state, state.currentPlayers[0]);
}
expect(wrapper.ended(state)).to.equal(true);
expect(turns).to.equal(expectedTurns);
expect(digest(state)).to.equal(finalHash);
expect(digest(wrapper.replay(JSON.parse(JSON.stringify(state))))).to.equal(finalHash);
} finally {
Math.random = random;
}
});
}
});

View file

@ -1,7 +1,10 @@
import { expect } from 'chai';
import { cloneDeep, range } from 'lodash';
import { ended, move, setup } from './engine';
import AbstractJudge from './fixtures/Abstract-judge-7215.json';
import { GameEventName } from './log';
import type { Move } from './move';
import { MoveName } from './move';
describe('Engine', () => {
it('should setup a game correctly', () => {
@ -28,4 +31,29 @@ describe('Engine', () => {
expect(G.currentPlayers).to.deep.equal([0]);
expect(ended(G)).to.be.false;
});
it('should seize upkeep containers deterministically from the game seed', () => {
const base = setup(2, {}, 'upkeep-seed-test');
const A = base.currentPlayers[0];
const B = 1 - A;
// Force B into upkeep debt: two loans, no money, and a pile of island
// containers for the bank to pick from
base.players[B].loans = base.loansLeft.splice(0, 2);
base.players[B].money = 0;
base.players[B].containersOnIsland = base.containersLeft.splice(0, 12);
// A's pass hands the turn to B and runs B's upkeep, seizing two random
// containers. Same seed + same history ⇒ the same containers, every time.
const results = range(5).map(() => move(cloneDeep(base), { name: MoveName.Pass, data: true }, A));
expect(results[0].players[B].containersOnIsland).to.have.length(10);
expect(
results[0].log.filter((item) => item.type === 'event' && item.event.name === GameEventName.Upkeep)
).to.have.length(2);
for (const result of results.slice(1)) {
expect(JSON.parse(JSON.stringify(result))).to.deep.equal(JSON.parse(JSON.stringify(results[0])));
}
});
});

View file

@ -1,8 +1,9 @@
import assert from 'assert';
import { chunk, cloneDeep, groupBy, isEqual, range, zip } from 'lodash';
import { chunk, groupBy, isEqual, range, zip } from 'lodash';
import seedrandom from 'seedrandom';
import { availableMoves } from './available-moves';
import pointCards from './cards';
import { canReviseBid } from './choice-revisions';
import {
ContainerColor,
containerColors,
@ -14,13 +15,14 @@ import {
Player,
ShipPosition,
} from './gamestate';
import { GameEventName, LogItem } from './log';
import { GameEventName, LogItem, LogMove } from './log';
import { Move, MoveName, Moves } from './move';
import { applyBankMove, bankUpkeep, normalizeBankDistribution, payBankCash, settleBank } from './offshore';
import { asserts, shuffle } from './utils';
const playerColors = ['dodgerblue', 'red', 'yellow', 'limegreen', 'mediumorchid'];
export const playerColors = ['dodgerblue', 'red', 'yellow', 'limegreen', 'mediumorchid'];
export function setup(numPlayers: number, { beginner = true }: GameOptions, seed?: string): GameState {
export function setup(numPlayers: number, { beginner = true, offshoreIsland }: GameOptions, seed?: string): GameState {
seed = seed ?? Math.random().toString();
const rng = seedrandom(seed);
@ -85,6 +87,7 @@ export function setup(numPlayers: number, { beginner = true }: GameOptions, seed
hiddenLog: [],
seed,
round: 1,
newTurn: true,
} as GameState;
const colors = shuffle(containerColors, rng() + '');
@ -102,6 +105,28 @@ export function setup(numPlayers: number, { beginner = true }: GameOptions, seed
player.warehouses.push(G.warehousesLeft.pop()!);
});
if (offshoreIsland) {
G.options.offshoreIsland = true;
G.offshoreBank = {
initialContainerLots: [],
cashLots: [1, 2, 3],
containerLots: [[], [], []],
auctions: [],
called: false,
won: false,
};
const bankColors = shuffle(containerColors, rng() + '');
for (let i = 0; i < 3; i++) {
const index = G.containersLeft.findIndex((c) => c.color === bankColors[i]);
G.offshoreBank.containerLots[i < 2 ? 0 : 1].push(G.containersLeft.splice(index, 1)[0]);
}
G.offshoreBank.initialContainerLots = G.offshoreBank.containerLots.map((lot) => lot.slice());
G.players.forEach((p) => {
p.bankHolding = [];
p.offshoreStats = { cashAuctionsWon: 0, containerAuctionsWon: 0 };
});
}
G.log.push({ type: 'event', event: { name: GameEventName.GameStart } });
G.players[startingPlayer].actions = 2;
@ -126,6 +151,9 @@ export function stripSecret(G: GameState, player?: number): GameState {
money: ended(G) ? pl.money : 0,
bid: pl.showBid ? pl.bid : 0,
additionalBid: pl.showAdditionalBid ? pl.additionalBid : 0,
// Bid moves contain sealed prices (including tie-breaks). Public results
// are exposed through the reveal-controlled fields and log, not lastMove.
lastMove: pl.lastMove?.name === MoveName.Bid ? null : pl.lastMove,
};
}
}),
@ -139,20 +167,64 @@ export function currentPlayers(G: GameState): number[] {
export function move(G: GameState, move: Move, playerNumber: number, fake?: boolean): GameState {
const player = G.players[playerNumber];
const available = player.availableMoves?.[move.name];
const revision = move.revision !== undefined;
assert(!revision || canReviseBid(G, move, playerNumber), 'This bid can no longer be changed');
const available = revision ? availableMoves(G, player)[move.name] : player.availableMoves?.[move.name];
assert(G.currentPlayers.includes(playerNumber), 'It is not your turn!');
assert(revision || G.currentPlayers.includes(playerNumber), 'It is not your turn!');
assert(available, 'You are not allowed to run the command ' + move.name);
assert(
available.some((x) => isEqual(x, move.data)),
'Wrong argument for the command ' + move.name
);
assert(
move.name != MoveName.Bid || move.extraData.price + player.bid <= player.money,
move.name != MoveName.Bid ||
(Number.isInteger(move.extraData?.price) &&
move.extraData.price >= 0 &&
move.extraData.price + (G.highestBidders.length ? player.bid : 0) <= player.money),
"Can't bid more money than you have!"
);
if (G.offshoreBank && move.name === MoveName.Produce) {
assert(
move.extraData?.piece?.color === move.data &&
G.containersLeft.some((c) => isEqual(c, move.extraData.piece)),
'Invalid produced container'
);
assert(
Number.isInteger(move.extraData.price) && move.extraData.price >= 1 && move.extraData.price <= 4,
'Invalid production price'
);
}
G.liveUpdate = revision;
const previousBid = revision
? G.hiddenLog
.map((e) => e.type === 'move' && e.player === playerNumber && e.move.name === MoveName.Bid)
.lastIndexOf(true)
: -1;
const bankResult = applyBankMove(G, move, player);
if (bankResult.handled) {
G.log.push({
type: 'move',
player: playerNumber,
move,
simple: `${player.name} ${move.name}`,
pretty: `${player.name} ${move.name}`,
});
if (bankResult.ending && !fake) {
G.phase = Phase.GameEnd;
G.currentPlayers = [];
calculateEndScore(G);
}
}
switch (move.name) {
// These moves were executed by applyBankMove; common bookkeeping follows below.
case MoveName.CallBank:
case MoveName.LoadBankContainer:
case MoveName.ReturnBankContainer:
case MoveName.DistributeBankContainer:
case MoveName.SeizeBankContainer:
break;
case MoveName.DomesticSale: {
asserts<Moves.MoveDomesticSale>(move);
if (player.containersOnFactoryStore.length > 0) {
@ -444,12 +516,13 @@ export function move(G: GameState, move: Move, playerNumber: number, fake?: bool
case MoveName.Bid: {
asserts<Moves.MoveBid>(move);
const { revision: ignored, ...recordedMove } = move;
if (G.highestBidders.length === 0) {
G.hiddenLog.push({
type: 'move',
player: playerNumber,
move,
move: recordedMove,
simple: `${player.name} bids $${move.extraData.price}`,
pretty: `${playerNameHTML(player)} bids $${move.extraData.price}`,
});
@ -459,7 +532,7 @@ export function move(G: GameState, move: Move, playerNumber: number, fake?: bool
G.hiddenLog.push({
type: 'move',
player: playerNumber,
move,
move: recordedMove,
simple: `${player.name} bids additional $${move.extraData.price}`,
pretty: `${playerNameHTML(player)} bids additional $${move.extraData.price}`,
});
@ -467,6 +540,9 @@ export function move(G: GameState, move: Move, playerNumber: number, fake?: bool
G.currentPlayers = G.currentPlayers.filter((id) => id !== player.id);
}
if (revision && previousBid >= 0) {
G.hiddenLog[previousBid] = G.hiddenLog.pop()!;
}
if (G.currentPlayers.length === 0) {
if (G.highestBidders.length === 0) {
G.players
@ -474,10 +550,11 @@ export function move(G: GameState, move: Move, playerNumber: number, fake?: bool
.forEach((p) => {
p.showBid = true;
});
const highestBid = Math.max(...G.players.map((p) => p.bid));
const highestBidders = G.players
.filter((p) => p.id != G.auctioningPlayer && !p.isDropped && p.bid === highestBid)
.map((p) => p.id);
// Only players still in the game can win the auction, so a dropped
// player's bid must not enter the maximum either.
const eligible = G.players.filter((p) => p.id != G.auctioningPlayer && !p.isDropped);
const highestBid = Math.max(...eligible.map((p) => p.bid));
const highestBidders = eligible.filter((p) => p.bid === highestBid).map((p) => p.id);
G.highestBidders = highestBidders;
if (highestBidders.length > 1) {
G.currentPlayers = highestBidders;
@ -486,11 +563,10 @@ export function move(G: GameState, move: Move, playerNumber: number, fake?: bool
G.phase = Phase.AcceptDecline;
}
} else {
const highestBid = Math.max(...G.players.map((p) => p.bid + p.additionalBid));
const highestBidders = G.players
.filter(
(p) => p.id != G.auctioningPlayer && !p.isDropped && p.bid + p.additionalBid === highestBid
)
const eligible = G.players.filter((p) => p.id != G.auctioningPlayer && !p.isDropped);
const highestBid = Math.max(...eligible.map((p) => p.bid + p.additionalBid));
const highestBidders = eligible
.filter((p) => p.bid + p.additionalBid === highestBid)
.map((p) => p.id);
G.highestBidders = highestBidders;
G.players.forEach((p) => {
@ -511,10 +587,11 @@ export function move(G: GameState, move: Move, playerNumber: number, fake?: bool
case MoveName.Accept: {
const otherPlayer = G.players[move.data];
const bid = otherPlayer.bid + otherPlayer.additionalBid;
otherPlayer.containersOnIsland.push(...player.ship.containers);
player.ship.containers = [];
otherPlayer.money -= otherPlayer.bid + otherPlayer.additionalBid;
player.money += (otherPlayer.bid + otherPlayer.additionalBid) * 2;
otherPlayer.money -= bid;
player.money += bid * 2;
G.players.forEach((p) => {
p.bid = p.additionalBid = 0;
});
@ -530,9 +607,11 @@ export function move(G: GameState, move: Move, playerNumber: number, fake?: bool
if ([...new Set(G.containersLeft.map((c) => c.color))].length >= 4) {
doUpkeep(G);
} else {
G.phase = Phase.GameEnd;
G.currentPlayers = [];
calculateEndScore(G);
if (!G.offshoreBank || !settleBank(G, true)) {
G.phase = Phase.GameEnd;
G.currentPlayers = [];
calculateEndScore(G);
}
}
}
@ -540,9 +619,15 @@ export function move(G: GameState, move: Move, playerNumber: number, fake?: bool
type: 'move',
player: playerNumber,
move,
simple: `${player.name} accepts ${otherPlayer.name}'s bid`,
pretty: `${playerNameHTML(player)} accepts ${playerNameHTML(otherPlayer)}'s bid`,
simple: `${player.name} accepts ${otherPlayer.name}'s bid of $${bid} and receives $${bid * 2}`,
pretty: `${playerNameHTML(player)} accepts ${playerNameHTML(
otherPlayer
)}'s bid of $${bid} and receives $${bid * 2}`,
});
if (!fake) {
const entry = G.log[G.log.length - 1] as LogMove;
(G.pendingMessages ||= []).push(entry.simple);
}
break;
}
@ -552,6 +637,7 @@ export function move(G: GameState, move: Move, playerNumber: number, fake?: bool
player.ship.containers = [];
const bid = G.players[G.highestBidders[0]].bid + G.players[G.highestBidders[0]].additionalBid;
player.money -= bid;
payBankCash(G, bid);
G.players.forEach((p) => {
p.bid = p.additionalBid = 0;
});
@ -567,9 +653,11 @@ export function move(G: GameState, move: Move, playerNumber: number, fake?: bool
if ([...new Set(G.containersLeft.map((c) => c.color))].length >= 4) {
doUpkeep(G);
} else {
G.phase = Phase.GameEnd;
G.currentPlayers = [];
calculateEndScore(G);
if (!G.offshoreBank || !settleBank(G, true)) {
G.phase = Phase.GameEnd;
G.currentPlayers = [];
calculateEndScore(G);
}
}
}
@ -577,9 +665,13 @@ export function move(G: GameState, move: Move, playerNumber: number, fake?: bool
type: 'move',
player: playerNumber,
move,
simple: `${player.name} declines all bids`,
pretty: `${playerNameHTML(player)} declines all bids`,
simple: `${player.name} declines all bids and buys the cargo for $${bid}`,
pretty: `${playerNameHTML(player)} declines all bids and buys the cargo for $${bid}`,
});
if (!fake) {
const entry = G.log[G.log.length - 1] as LogMove;
(G.pendingMessages ||= []).push(entry.simple);
}
break;
}
@ -600,39 +692,135 @@ export function move(G: GameState, move: Move, playerNumber: number, fake?: bool
if ([...new Set(G.containersLeft.map((c) => c.color))].length >= 4) {
doUpkeep(G);
} else {
G.phase = Phase.GameEnd;
G.currentPlayers = [];
calculateEndScore(G);
if (!G.offshoreBank || !settleBank(G, true)) {
G.phase = Phase.GameEnd;
G.currentPlayers = [];
calculateEndScore(G);
}
}
}
break;
}
}
case MoveName.Undo: {
asserts<Moves.MoveUndo>(move);
const lastLog = G.log[G.log.length - 1];
if (lastLog.type == 'move' && G.currentPlayers.includes(lastLog.player) && !fake) {
G.log.pop();
G = reconstructState(getBaseState(G), G.log);
}
return G;
}
// Normalize after every transition that can create a payment decision, before
// publishing legal moves. Forced placements are effects, not synthetic player moves.
const forcedBankResult = normalizeBankDistribution(G);
if (forcedBankResult.ending && !fake) {
G.phase = Phase.GameEnd;
G.currentPlayers = [];
calculateEndScore(G);
}
player.availableMoves = null;
if (move.name != MoveName.GetLoan && move.name != MoveName.PayLoan) player.lastMove = move;
if (move.name != MoveName.GetLoan && move.name != MoveName.PayLoan) {
const { revision: ignoredRevision, ...recordedMove } = move;
player.lastMove = recordedMove;
}
G.currentPlayers.forEach((p) => (G.players[p].availableMoves = availableMoves(G, G.players[p])));
// Tentative-turn bookkeeping: the state is committed (`newTurn`) once the mover can
// no longer undo. This mirrors the old undo-availability rule — undo was offered
// whenever the last visible log entry was a move by a player still in
// `currentPlayers` — with turn-boundary moves committing unconditionally:
// - Pass / Accept / Decline end the turn (even in the edge case where the same
// player is up again because everyone else is dropped);
// - Bid (and loans taken during the bid phase) go to the hidden log and were never
// undoable: bids are single-move committed turns.
const lastLog = G.log[G.log.length - 1];
const turnBoundary =
move.name === MoveName.Pass ||
move.name === MoveName.Accept ||
move.name === MoveName.Decline ||
move.name === MoveName.Bid;
G.newTurn =
(bankResult.handled && move.name !== MoveName.LoadBankContainer && move.name !== MoveName.CallBank) ||
(bankResult.handled && G.phase === Phase.BankDecision) ||
turnBoundary ||
!(lastLog?.type === 'move' && G.currentPlayers.includes(lastLog.player));
while (G.offshoreBank && G.phase === Phase.BankDecision && G.players[G.currentPlayers[0]].isDropped) {
G = moveAI(G, G.currentPlayers[0]);
}
return G;
}
export function moveAI(G: GameState, playerNumber: number): GameState {
const player = G.players[playerNumber];
if (G.offshoreBank && G.phase === Phase.BankDecision) {
const name = Object.keys(player.availableMoves!)[0] as MoveName;
const data = player.availableMoves![name]![0];
const c = G.offshoreBank.decision?.containers.find((c) => c.container.piece.id === (data as ContainerPiece).id);
return move(
G,
{
name,
data,
...(name === MoveName.ReturnBankContainer ? { extraData: { price: c!.container.price } } : {}),
} as Move,
playerNumber
);
}
// Keep expansion decisions deterministic and entirely outside the classic random stream.
if (G.offshoreBank && G.phase === Phase.Move) {
const moves = player.availableMoves!;
const load = moves[MoveName.LoadBankContainer];
if (load?.length) return move(G, { name: MoveName.LoadBankContainer, data: load[0] }, playerNumber);
// Collect paid-for cargo before shopping for more. Do not detour a full ship.
if (player.bankHolding!.length && player.ship.containers.length < 5) {
const destination = moves[MoveName.Sail]?.includes(ShipPosition.OffshoreBank)
? ShipPosition.OffshoreBank
: player.ship.shipPosition !== ShipPosition.OpenSea &&
player.ship.shipPosition !== ShipPosition.OffshoreBank &&
moves[MoveName.Sail]?.includes(ShipPosition.OpenSea)
? ShipPosition.OpenSea
: undefined;
if (destination) return move(G, { name: MoveName.Sail, data: destination }, playerNumber);
}
let offer: Move | undefined;
let bestProfit = 0;
for (const data of moves[MoveName.CallBank] || []) {
const active = G.offshoreBank.auctions.find((a) => a.type === data.type);
if (data.type === 'containers') {
const count = G.offshoreBank.containerLots[data.lot].length;
const cash = (active?.cash || 0) + 1;
// Value cargo conservatively, cap the backlog, and reserve working cash plus interest.
const profit = count * 2 - cash;
if (
count &&
count + player.bankHolding!.length <= 5 &&
cash <= player.money - player.loans.length - 5 &&
profit > bestProfit
) {
offer = { name: MoveName.CallBank, data, extraData: { cash } };
bestProfit = profit;
}
} else {
const count = (active?.containers.length || 0) + 1;
const stock = [
...player.containersOnFactoryStore.map((c) => ({ c, value: Math.max(2, c.price) })),
...player.containersOnWarehouseStore.map((c) => ({ c, value: Math.max(3, c.price) })),
].sort((a, b) => a.value - b.value);
const payment = stock.slice(0, count);
const profit = G.offshoreBank.cashLots[data.lot] - payment.reduce((sum, c) => sum + c.value, 0);
// Stored cargo is productive inventory: only exchange it for a clear cash gain.
if (payment.length === count && profit >= 2 && profit > bestProfit) {
offer = {
name: MoveName.CallBank,
data,
extraData: { containers: payment.map((c) => c.c.piece.id) },
};
bestProfit = profit;
}
}
}
if (offer) return move(G, offer, playerNumber);
}
let moveName, data;
let retry = 0;
do {
@ -653,7 +841,7 @@ export function moveAI(G: GameState, playerNumber: number): GameState {
moveName = MoveName.Sail;
data = player.ship.shipPosition == ShipPosition.OpenSea ? ShipPosition.Island : ShipPosition.OpenSea;
} else {
const moves = Object.keys(player.availableMoves!);
const moves = Object.keys(player.availableMoves!).filter((n) => n !== MoveName.CallBank);
if (
player.lastMove?.name == MoveName.Sail &&
@ -682,11 +870,13 @@ export function moveAI(G: GameState, playerNumber: number): GameState {
data = dataArr[Math.floor(Math.random() * dataArr.length)];
if (moveName == MoveName.Undo || moveName == MoveName.GetLoan || moveName == MoveName.PayLoan) {
if (moveName == MoveName.GetLoan || moveName == MoveName.PayLoan) {
moveName = null;
} else if (moveName == MoveName.Sail) {
if (data == ShipPosition.Island) {
if (player.ship.containers.length == 0) moveName = null;
} else if (G.offshoreBank && data === ShipPosition.OffshoreBank) {
if (!player.bankHolding!.length || player.ship.containers.length === 5) moveName = null;
} else if (data.startsWith('playerHarbor0')) {
if (G.players[0].containersOnWarehouseStore.length == 0) moveName = null;
} else if (data.startsWith('playerHarbor1')) {
@ -866,8 +1056,8 @@ function calculateEndScore(G: GameState) {
player.finalScoreBreakdown.push('$' + player.containersOnWarehouseStore.length * 2);
player.money += player.containersOnWarehouseStore.length * 2;
player.finalScoreBreakdown.push('$' + player.ship.containers.length * 3);
player.money += player.ship.containers.length * 3;
player.finalScoreBreakdown.push('$' + (player.ship.containers.length + (player.bankHolding?.length || 0)) * 3);
player.money += (player.ship.containers.length + (player.bankHolding?.length || 0)) * 3;
player.finalScoreBreakdown.push('-$' + player.loans.length * 11);
player.money += player.loans.length * -11;
});
@ -877,29 +1067,6 @@ export function scores(G: GameState): number[] {
return ended(G) ? G.players.map((p) => p.money) : G.players.map((_) => 0);
}
export function reconstructState(initialState: GameState, log: LogItem[]): GameState {
const G = cloneDeep(initialState);
for (const item of log) {
switch (item.type) {
case 'event': {
break;
}
case 'phase': {
break;
}
case 'move': {
move(G, item.move, item.player);
break;
}
}
}
return G;
}
function playerBefore(player: Player, G: GameState) {
return player.id === 0 ? G.players[G.players.length - 1] : G.players[player.id - 1];
}
@ -911,15 +1078,21 @@ export function nextPlayer(G: GameState) {
}
function doUpkeep(G: GameState) {
// Container seizures must be reproducible: the platform guarantees that the same
// seed yields the same game, and `wrapper.replay` re-runs upkeep from the log. The
// seed comes from the persisted state, and the visible log length uniquely
// identifies this upkeep within the game (each upkeep immediately follows its own
// Pass/Accept/Decline log entry), so together they pin a per-upkeep random stream.
const rng = seedrandom(`${G.seed}:upkeep:${G.log.length}`);
const player = G.players[G.currentPlayers[0]];
const loanCount = player.loans.length;
const loanCount = G.offshoreBank ? 0 : player.loans.length;
const interest: string[] = [];
for (let i = 0; i < loanCount; i++) {
if (player.money > 0) {
player.money--;
interest.push('money');
} else if (player.containersOnIsland.length > 0) {
const container = removeRandom(player.containersOnIsland);
const container = removeRandom(player.containersOnIsland, rng);
G.log.push({
type: 'event',
event: {
@ -931,32 +1104,32 @@ function doUpkeep(G: GameState) {
});
} else if (player.containersOnWarehouseStore.length + player.containersOnFactoryStore.length > 0) {
if (player.containersOnWarehouseStore.length >= 2) {
const c1 = removeRandom(player.containersOnWarehouseStore);
const c2 = removeRandom(player.containersOnWarehouseStore);
const c1 = removeRandom(player.containersOnWarehouseStore, rng);
const c2 = removeRandom(player.containersOnWarehouseStore, rng);
G.log.push({
type: 'event',
event: {
name: GameEventName.Upkeep,
interest: `The bank seizes a ${containerColorHTML(
c1.color
)} container and a ${containerColorHTML(c2.color)} container from ${playerNameHTML(
c1.piece.color
)} container and a ${containerColorHTML(c2.piece.color)} container from ${playerNameHTML(
player
)}'s warehouses`,
},
});
} else if (player.containersOnWarehouseStore.length == 1) {
const c1 = removeRandom(player.containersOnWarehouseStore);
const c1 = removeRandom(player.containersOnWarehouseStore, rng);
if (player.containersOnFactoryStore.length >= 1) {
const c2 = removeRandom(player.containersOnFactoryStore);
const c2 = removeRandom(player.containersOnFactoryStore, rng);
G.log.push({
type: 'event',
event: {
name: GameEventName.Upkeep,
interest: `The bank seizes a ${containerColorHTML(
c1.color
)} container from ${playerNameHTML(player)}'s warehouses and a ${
c2.color
} container from ${playerNameHTML(player)}'s factory`,
c1.piece.color
)} container from ${playerNameHTML(player)}'s warehouses and a ${containerColorHTML(
c2.piece.color
)} container from ${playerNameHTML(player)}'s factory`,
},
});
} else {
@ -965,22 +1138,22 @@ function doUpkeep(G: GameState) {
event: {
name: GameEventName.Upkeep,
interest: `The bank seizes a ${containerColorHTML(
c1.color
c1.piece.color
)} container from ${playerNameHTML(player)}'s warehouses`,
},
});
}
} else {
const c1 = removeRandom(player.containersOnFactoryStore);
const c1 = removeRandom(player.containersOnFactoryStore, rng);
if (player.containersOnFactoryStore.length >= 1) {
const c2 = removeRandom(player.containersOnFactoryStore);
const c2 = removeRandom(player.containersOnFactoryStore, rng);
G.log.push({
type: 'event',
event: {
name: GameEventName.Upkeep,
interest: `The bank seizes a ${containerColorHTML(
c1.color
)} container and a ${containerColorHTML(c2.color)} container from ${playerNameHTML(
c1.piece.color
)} container and a ${containerColorHTML(c2.piece.color)} container from ${playerNameHTML(
player
)}'s factory`,
},
@ -991,7 +1164,7 @@ function doUpkeep(G: GameState) {
event: {
name: GameEventName.Upkeep,
interest: `The bank seizes a ${containerColorHTML(
c1.color
c1.piece.color
)} container from ${playerNameHTML(player)}'s factory`,
},
});
@ -1032,6 +1205,7 @@ function doUpkeep(G: GameState) {
if (currentPlayer == G.startingPlayer) {
G.round++;
}
if (G.offshoreBank) bankUpkeep(G);
}
function remove(array, value) {
@ -1039,22 +1213,14 @@ function remove(array, value) {
return array.splice(array.indexOf(aux), 1);
}
function removeRandom(array) {
return array.splice(Math.floor(Math.random() * array.length), 1)[0];
}
function getBaseState(G: GameState): GameState {
const baseState = setup(G.players.length, G.options, G.seed);
baseState.players.forEach((player, i) => {
player.name = G.players[i].name;
player.isAI = G.players[i].isAI;
});
return baseState;
function removeRandom<T>(array: T[], rng: () => number): T {
return array.splice(Math.floor(rng() * array.length), 1)[0];
}
function prettyShipPosition(G: GameState, data: ShipPosition, simple = false): string {
switch (data) {
case ShipPosition.OffshoreBank:
return 'the Off-Shore Bank';
case ShipPosition.Island:
return 'the island harbor';
case ShipPosition.OpenSea:
@ -1078,8 +1244,10 @@ function containerColorHTML(containerColor: ContainerColor) {
case ContainerColor.Orange:
case ContainerColor.Tan:
case ContainerColor.White:
return `<span style="background-color: ${containerColor}; font-weight: bold; border: 1px solid black; padding: 0 3px;">${containerColor}</span>`;
return `<span style="background-color: ${containerColor}; color: ${
containerColor === ContainerColor.Brown ? '#fff' : '#111'
}; font-weight: bold; border: 1px solid black; padding: 0 3px;">${containerColor}</span>`;
case ContainerColor.Black:
return '<span style="background-color: #2F4F4F; font-weight: bold; border: 1px solid black; padding: 0 3px;">darkslategray</span>';
return '<span style="background-color: #2F4F4F; color: #fff; font-weight: bold; border: 1px solid black; padding: 0 3px;">darkslategray</span>';
}
}

View file

@ -4,6 +4,7 @@ import { Move } from './move';
export interface GameOptions {
beginner?: boolean;
offshoreIsland?: boolean;
}
export enum ContainerColor {
@ -33,6 +34,7 @@ export interface ContainerOnStore {
}
export enum ShipPosition {
OffshoreBank = 'offshoreBank',
OpenSea = 'sea',
PlayerHarbor01 = 'playerHarbor01',
PlayerHarbor02 = 'playerHarbor02',
@ -64,6 +66,8 @@ export interface Ship {
}
export interface Player {
bankHolding?: ContainerPiece[];
offshoreStats?: { cashAuctionsWon: number; containerAuctionsWon: number };
id: number;
pointCard: PointCard | null;
factories: FactoryPiece[];
@ -90,6 +94,7 @@ export interface Player {
}
export enum Phase {
BankDecision = 'bankDecision',
Move = 'move',
Bid = 'bid',
AcceptDecline = 'acceptDecline',
@ -119,7 +124,43 @@ export interface ShipPiece {
id: `S${number}`;
}
export type BankAuctionType = 'cash' | 'containers';
export interface BankEscrowContainer {
container: ContainerOnStore;
district: 'factory' | 'warehouse';
}
export interface BankAuction {
type: BankAuctionType;
lot: number;
bidder: number;
cash: number;
containers: BankEscrowContainer[];
}
export interface OffshoreBank {
initialContainerLots: ContainerPiece[][];
cashLots: number[];
containerLots: ContainerPiece[][];
auctions: BankAuction[];
called: boolean;
won: boolean;
decision?: {
kind: 'return' | 'distribute' | 'seize';
player: number;
resumePlayer: number;
containers: BankEscrowContainer[];
payment: ContainerPiece[];
cursor: number;
debtor?: number;
remaining?: number;
settlement?: BankAuction;
ending?: boolean;
};
}
export interface GameState {
offshoreBank?: OffshoreBank;
liveUpdate?: boolean;
analysisCash?: number[];
pendingMessages?: string[];
players: Player[];
startingPlayer: number;
currentPlayers: number[];
@ -135,4 +176,11 @@ export interface GameState {
hiddenLog: LogItem[];
seed: string;
round: number;
/**
* Tentative-turn marker. `true` (or `undefined`, for robustness) when the state is
* committed: the last mover can no longer undo and the state can be persisted.
* `false` while a player's turn is still in progress (mid-turn moves can be undone
* by the viewer by replaying a shortened turn buffer from the last committed state).
*/
newTurn?: boolean;
}

View file

@ -1,6 +1,21 @@
import { ContainerColor, ContainerPiece, FactoryPiece, ShipPosition, WarehousePiece } from './gamestate';
export declare namespace Moves {
export interface MoveCallBank {
name: MoveName.CallBank;
data: { type: 'cash' | 'containers'; lot: number };
extraData: { cash?: number; containers?: string[] };
}
export interface MoveBankContainer {
name:
| MoveName.ReturnBankContainer
| MoveName.DistributeBankContainer
| MoveName.SeizeBankContainer
| MoveName.LoadBankContainer;
data: ContainerPiece;
extraData?: { price: number };
}
export interface MoveBuyFromFactory {
name: MoveName.BuyFromFactory;
data: {
@ -88,14 +103,11 @@ export declare namespace Moves {
name: MoveName.Pass;
data: boolean;
}
export interface MoveUndo {
name: MoveName.Undo;
data: boolean;
}
}
export type Move =
export type Move = (
| Moves.MoveCallBank
| Moves.MoveBankContainer
| Moves.MoveBuyFromFactory
| Moves.MoveBuyFromWarehouse
| Moves.MoveBuyFactory
@ -110,10 +122,15 @@ export type Move =
| Moves.MoveAccept
| Moves.MoveDecline
| Moves.MovePass
| Moves.MoveUndo
| Moves.MoveDomesticSale;
| Moves.MoveDomesticSale
) & { revision?: string };
export enum MoveName {
CallBank = 'callBank',
ReturnBankContainer = 'returnBankContainer',
DistributeBankContainer = 'distributeBankContainer',
SeizeBankContainer = 'seizeBankContainer',
LoadBankContainer = 'loadBankContainer',
DomesticSale = 'domesticSale',
BuyWarehouse = 'buyWarehouse',
BuyFactory = 'buyFactory',
@ -129,5 +146,13 @@ export enum MoveName {
Accept = 'accept',
Decline = 'decline',
Pass = 'pass',
Undo = 'undo',
}
export function isLoanReversal(previous: Move | undefined, next: Move): boolean {
return (
previous?.data === true &&
next.data === true &&
((previous.name === MoveName.GetLoan && next.name === MoveName.PayLoan) ||
(previous.name === MoveName.PayLoan && next.name === MoveName.GetLoan))
);
}

View file

@ -0,0 +1,46 @@
import { expect } from 'chai';
import seedrandom from 'seedrandom';
import * as wrapper from '../wrapper';
import { MoveName } from './move';
const json = (value: unknown) => JSON.parse(JSON.stringify(value));
describe('Off-Shore Bank bots', () => {
for (const seats of [3, 4, 5]) {
it(`completes and replays a serialized ${seats}-seat game with bank participation`, async function () {
this.timeout(30000);
const random = Math.random;
const seed = `offshore-ai-${seats}`;
Math.random = seedrandom(seed);
try {
let state = await wrapper.init(seats, [], { offshoreIsland: true }, seed);
let turns = 0;
while (!wrapper.ended(state) && turns++ < 3000) {
state = wrapper.moveAI(state, state.currentPlayers[0]);
const saved = wrapper.toSave(state);
expect(saved, 'every bot turn commits').not.equal(undefined);
state = json(saved);
}
expect(wrapper.ended(state), `finished after ${turns} turns`).equal(true);
const calls = state.log.filter((l) => l.type === 'move' && l.move.name === MoveName.CallBank);
expect(calls.length, 'bots start and compete in auctions').greaterThan(2);
expect(
state.log.some((l) => l.type === 'move' && l.move.name === MoveName.LoadBankContainer),
'collect won cargo'
).equal(true);
expect(state.players.reduce((sum, p) => sum + p.offshoreStats!.containerAuctionsWon, 0)).greaterThan(0);
expect(state.players.reduce((sum, p) => sum + p.offshoreStats!.cashAuctionsWon, 0)).greaterThan(0);
expect(
state.log.some(
(l) =>
l.type === 'move' && l.move.name === MoveName.CallBank && (l.move.extraData.cash || 0) > 1
),
'raises a public cash bid'
).equal(true);
expect(json(wrapper.replay(json(state)))).deep.equal(state);
} finally {
Math.random = random;
}
});
}
});

522
engine/src/offshore.spec.ts Normal file
View file

@ -0,0 +1,522 @@
import { expect } from 'chai';
import { cloneDeep } from 'lodash';
import * as wrapper from '../wrapper';
import { availableMoves } from './available-moves';
import { move, setup, stripSecret } from './engine';
import { GameState, Phase, ShipPosition } from './gamestate';
import { Move, MoveName } from './move';
import {
applyBankMove,
bankProductionAllowed,
normalizeBankDistribution,
payBankCash,
reserved,
settleBank,
} from './offshore';
function game(n = 3) {
const g = setup(n, { offshoreIsland: true }, 'bank-tests');
g.players.forEach((p) => (p.name = `Player ${p.id}`));
return g;
}
function act(g: GameState, m: Move) {
return move(g, m, g.currentPlayers[0]);
}
function pass(g: GameState) {
return act(g, { name: MoveName.Pass, data: true });
}
function refresh(g: GameState) {
for (const p of g.players) p.availableMoves = g.currentPlayers.includes(p.id) ? availableMoves(g, p) : null;
}
function cashBid(g: GameState, cash = 1, lot = 0) {
return act(g, { name: MoveName.CallBank, data: { type: 'containers', lot }, extraData: { cash } });
}
function containerBid(g: GameState, ids: string[], lot = 2) {
return act(g, { name: MoveName.CallBank, data: { type: 'cash', lot }, extraData: { containers: ids } });
}
function decisions(g: GameState) {
while (g.phase === Phase.BankDecision) {
const p = g.players[g.currentPlayers[0]];
const name = Object.keys(p.availableMoves!)[0] as MoveName;
const data = p.availableMoves![name]![0];
act(g, { name, data, extraData: { price: 2 } } as Move);
}
}
describe('optional Off-Shore Bank', () => {
it('does not change absent/false expansion setup or ordinary seeded player setup', () => {
const base = setup(3, {}, 'bank-tests');
expect(setup(3, { offshoreIsland: false }, 'bank-tests')).deep.equal(base);
const g = game();
expect(g.players.map((p) => p.factories)).deep.equal(base.players.map((p) => p.factories));
expect(g.offshoreBank!.cashLots).deep.equal([1, 2, 3]);
expect(g.offshoreBank!.containerLots.map((l) => l.length)).deep.equal([2, 1, 0]);
const seeded = g.offshoreBank!.containerLots.reduce((a, l) => a.concat(l), [] as typeof g.containersLeft);
expect(new Set(seeded.map((c) => c.color)).size).equal(3);
expect(g.containersLeft.length).equal(base.containersLeft.length - 3);
expect(game()).deep.equal(g);
});
for (const type of ['cash', 'containers'] as const) {
it(`rejects empty ${type} rewards without mutation and enables replenished lots`, () => {
const g = game();
const p = g.players[g.currentPlayers[0]];
const b = g.offshoreBank!;
b.cashLots[2] = 0;
const bid: Move = {
name: MoveName.CallBank,
data: { type, lot: 2 },
extraData: type === 'cash' ? { containers: [p.containersOnFactoryStore[0].piece.id] } : { cash: 1 },
};
refresh(g);
expect(p.availableMoves!.callBank).not.to.deep.include(bid.data);
const before = cloneDeep(g);
expect(() => act(g, bid)).throw();
expect(g).deep.equal(before);
expect(() => applyBankMove(g, bid, p)).throw('Bank reward lot is empty or invalid');
expect(g).deep.equal(before);
for (const lot of [-1, 3, 0.5, NaN]) {
expect(() => applyBankMove(g, { ...bid, data: { type, lot } }, p)).throw(
'Bank reward lot is empty or invalid'
);
expect(g).deep.equal(before);
}
if (type === 'cash') payBankCash(g, 3);
else b.containerLots[2].push(g.containersLeft.pop()!);
refresh(g);
expect(p.availableMoves!.callBank).to.deep.include(bid.data);
act(g, bid);
expect(b.auctions[0].lot).equal(2);
expect(p.actions).equal(1);
});
it(`blocks raises on legacy empty ${type} rewards but still settles them`, () => {
const g = game();
const b = g.offshoreBank!;
const owner = g.players[g.currentPlayers[0]];
b.cashLots[2] = 0;
const payment = type === 'cash' ? owner.containersOnFactoryStore.splice(0, 1) : [];
if (type === 'containers') owner.money--;
b.auctions.push({
type,
lot: 2,
bidder: owner.id,
cash: type === 'containers' ? 1 : 0,
containers: payment.map((container) => ({ container, district: 'factory' as const })),
});
const challenger = g.players[(owner.id + 1) % g.players.length];
challenger.containersOnFactoryStore.push({ piece: g.containersLeft.pop()!, price: 2, moved: false });
g.currentPlayers = [challenger.id];
refresh(g);
expect(challenger.availableMoves!.callBank).equal(undefined);
const before = cloneDeep(g);
expect(() =>
applyBankMove(
g,
{
name: MoveName.CallBank,
data: { type, lot: 2 },
extraData:
type === 'cash'
? { containers: challenger.containersOnFactoryStore.map((c) => c.piece.id) }
: { cash: 2 },
},
challenger
)
).throw();
expect(g).deep.equal(before);
g.currentPlayers = [owner.id];
settleBank(g);
normalizeBankDistribution(g);
expect(b.auctions).deep.equal([]);
expect(b.decision).equal(undefined);
expect(owner.offshoreStats![type === 'cash' ? 'cashAuctionsWon' : 'containerAuctionsWon']).equal(1);
});
}
it('enables via expansion ID and persists the option', async () => {
expect((await wrapper.init(3, ['offshore-island'], {}, 'seed')).options.offshoreIsland).equal(true);
expect((await wrapper.init(3, [], {}, 'seed')).offshoreBank).equal(undefined);
});
it('escrows cash, limits one call per turn, settles at next own start, and replays', () => {
const g = game();
const id = g.currentPlayers[0];
cashBid(g, 4);
expect(g.players[id].money).equal(16);
expect(g.players[id].actions).equal(1);
expect(g.players[id].availableMoves!.callBank).equal(undefined);
const publicG = stripSecret(g, (id + 1) % 3);
expect(publicG.players[id].money).equal(0);
expect(publicG.offshoreBank!.auctions[0].cash).equal(4);
pass(g);
pass(g);
pass(g);
expect(g.players[id].bankHolding!.length).equal(2);
expect(g.players[id].offshoreStats!.containerAuctionsWon).equal(1);
expect(g.offshoreBank!.cashLots).deep.equal([3, 3, 4]);
expect(g.players[id].availableMoves!.callBank).equal(undefined);
expect(wrapper.replay(g)).deep.equal(g);
});
it('returns outbid cash and rejects malformed or unaffordable bids without mutating escrow', () => {
const g = game();
const id = g.currentPlayers[0];
cashBid(g, 2);
pass(g);
const before = cloneDeep(g.offshoreBank);
expect(() => cashBid(g, 1)).throw();
expect(() => cashBid(g, 1.5)).throw();
expect(() => cashBid(g, 100)).throw();
expect(g.offshoreBank).deep.equal(before);
cashBid(g, 3);
expect(g.players[id].money).equal(20);
});
it('reserves original districts and interrupts for owner-only returned-container repricing', () => {
const g = game();
const id = g.currentPlayers[0];
const p = g.players[id];
const piece = p.containersOnFactoryStore[0].piece;
containerBid(g, [piece.id]);
expect(p.containersOnFactoryStore.length).equal(0);
expect(reserved(g, p, 'factory')).equal(1);
pass(g);
const bidder = g.players[g.currentPlayers[0]];
bidder.containersOnFactoryStore.push({ piece: g.containersLeft.pop()!, price: 3, moved: false });
refresh(g);
const resume = bidder.id;
containerBid(
g,
bidder.containersOnFactoryStore.map((c) => c.piece.id)
);
expect(g.phase).equal(Phase.BankDecision);
expect(g.currentPlayers).deep.equal([id]);
expect(p.availableMoves!.returnBankContainer).deep.equal([piece]);
expect(() => act(g, { name: MoveName.ReturnBankContainer, data: piece, extraData: { price: 5 } })).throw();
act(g, { name: MoveName.ReturnBankContainer, data: piece, extraData: { price: 1 } });
expect(p.containersOnFactoryStore[0].price).equal(1);
expect(g.currentPlayers).deep.equal([resume]);
expect(g.newTurn).equal(true);
});
it('automatically distributes a single payment and skips frozen lots', () => {
const g = game(5);
const first = g.players[g.currentPlayers[0]];
const piece = first.containersOnFactoryStore[0].piece;
containerBid(g, [piece.id]);
pass(g);
cashBid(g, 2, 0);
payBankCash(g, 3);
expect(g.offshoreBank!.cashLots).deep.equal([3, 3, 3]);
pass(g);
pass(g);
pass(g);
pass(g);
expect(g.phase).equal(Phase.Move);
expect(g.offshoreBank!.decision).equal(undefined);
expect(g.offshoreBank!.containerLots[1].some((c) => c.id === piece.id)).equal(true);
expect(first.offshoreStats!.cashAuctionsWon).equal(1);
expect(first.money).equal(23);
});
it('pays interest before bank settlement using spendable cash only; right chooses default priority', () => {
const g = game();
const p = g.players[g.currentPlayers[0]];
p.loans.push(g.loansLeft.pop()!, g.loansLeft.pop()!);
p.ship.containers.push(g.containersLeft.pop()!);
cashBid(g, 20);
pass(g);
pass(g);
pass(g);
expect(g.phase).equal(Phase.BankDecision);
expect(g.currentPlayers[0]).equal((p.id + 2) % 3);
expect(g.players[g.currentPlayers[0]].availableMoves!.seizeBankContainer).deep.equal(p.ship.containers);
expect(p.bankHolding!.length).equal(0);
decisions(g);
expect(p.ship.containers.length).equal(0);
expect(p.containersOnFactoryStore.length).equal(0);
expect(p.bankHolding!.length).equal(2);
expect(p.loans.length).equal(2);
});
it('automatically drains same-color payments in persisted order and conserves cash and pieces', () => {
const g = game();
const p = g.players[g.currentPlayers[0]];
const color = p.containersOnFactoryStore[0].piece.color;
for (let n = 0; n < 4; n++) {
const i = g.containersLeft.findIndex((c) => c.color === color);
p.containersOnFactoryStore.push({ piece: g.containersLeft.splice(i, 1)[0], price: 2, moved: false });
}
const payment = p.containersOnFactoryStore.map((c) => c.piece);
const inventory = () =>
[
...g.containersLeft,
...g.offshoreBank!.containerLots.reduce((all, lot) => all.concat(lot), [] as typeof g.containersLeft),
...g.players.reduce(
(all, p) =>
all.concat([
...p.bankHolding!,
...p.ship.containers,
...p.containersOnIsland,
...p.containersOnFactoryStore.map((c) => c.piece),
...p.containersOnWarehouseStore.map((c) => c.piece),
]),
[] as typeof g.containersLeft
),
]
.map((c) => c.id)
.sort();
const before = inventory();
const cash = () =>
g.players.reduce((n, p) => n + p.money, 0) + g.offshoreBank!.cashLots.reduce((a, b) => a + b, 0);
const money = cash();
refresh(g);
containerBid(
g,
payment.map((c) => c.id)
);
pass(g);
pass(g);
pass(g);
expect(g.phase).equal(Phase.Move);
expect(g.offshoreBank!.decision).equal(undefined);
payment.forEach((piece, i) => expect(g.offshoreBank!.containerLots[i % 3]).deep.include(piece));
expect(inventory()).deep.equal(before);
expect(new Set(inventory()).size).equal(before.length);
expect(cash()).equal(money);
expect(g.log.some((e) => e.type === 'move' && e.move.name === MoveName.DistributeBankContainer)).equal(false);
});
it('pauses for multiple colors, then automatically drains the final color after an explicit choice', () => {
let g = game();
const p = g.players[g.currentPlayers[0]];
const first = p.containersOnFactoryStore[0].piece;
const color = g.containersLeft.find((c) => c.color !== first.color)!.color;
for (let n = 0; n < 3; n++) {
const i = g.containersLeft.findIndex((c) => c.color === color);
p.containersOnFactoryStore.push({ piece: g.containersLeft.splice(i, 1)[0], price: 2, moved: false });
}
refresh(g);
containerBid(
g,
p.containersOnFactoryStore.map((c) => c.piece.id)
);
pass(g);
pass(g);
pass(g);
expect(g.phase).equal(Phase.BankDecision);
expect(g.offshoreBank!.decision!.payment.length).equal(4);
g = JSON.parse(JSON.stringify(g));
act(g, { name: MoveName.DistributeBankContainer, data: first });
expect(g.phase).equal(Phase.Move);
expect(g.offshoreBank!.decision).equal(undefined);
expect(g.players[p.id].offshoreStats!.cashAuctionsWon).equal(1);
expect(g.currentPlayers).deep.equal([p.id]);
});
it('keeps seizure explicit but automatically distributes its final single payment', () => {
const g = game();
const debtor = g.players[g.currentPlayers[0]];
const piece = debtor.containersOnFactoryStore[0].piece;
debtor.money = 0;
debtor.loans.push(g.loansLeft.pop()!, g.loansLeft.pop()!);
pass(g);
pass(g);
pass(g);
expect(g.offshoreBank!.decision!.kind).equal('seize');
act(g, { name: MoveName.SeizeBankContainer, data: piece });
expect(g.offshoreBank!.decision).equal(undefined);
expect(g.offshoreBank!.containerLots[0]).deep.include(piece);
expect(g.phase).equal(Phase.Move);
expect(g.currentPlayers).deep.equal([debtor.id]);
expect(debtor.containersOnFactoryStore).deep.equal([]);
});
it('accepts a legacy saved single-payment decision and resumes its interrupted player', () => {
let g = game();
const id = g.currentPlayers[0];
const piece = g.containersLeft.pop()!;
g.offshoreBank!.decision = {
kind: 'distribute',
player: id,
resumePlayer: (id + 1) % 3,
payment: [piece],
containers: [],
cursor: 2,
};
g.phase = Phase.BankDecision;
refresh(g);
g = JSON.parse(JSON.stringify(g));
act(g, { name: MoveName.DistributeBankContainer, data: piece });
expect(g.offshoreBank!.containerLots[2]).deep.include(piece);
expect(g.phase).equal(Phase.Move);
expect(g.currentPlayers).deep.equal([(id + 1) % 3]);
});
it('loads only on arrival for free, obeys capacity and requires leaving/reentering next turn', () => {
const g = game();
const p = g.players[g.currentPlayers[0]];
p.bankHolding!.push(...g.containersLeft.splice(0, 6));
refresh(g);
act(g, { name: MoveName.Sail, data: ShipPosition.OffshoreBank });
for (let i = 0; i < 5; i++) act(g, { name: MoveName.LoadBankContainer, data: p.bankHolding![0] });
expect(p.actions).equal(1);
expect(p.ship.containers.length).equal(5);
expect(p.availableMoves!.loadBankContainer).equal(undefined);
p.ship.containers = [];
pass(g);
pass(g);
pass(g);
expect(p.availableMoves!.loadBankContainer).equal(undefined);
});
it('forbids a mandatory production run that would end the game after Call Bank', () => {
const g = game();
const p = g.players[g.currentPlayers[0]];
const second = g.factoriesLeft.find((f) => f.color !== p.factories[0].color)!;
p.factories.push(second);
const colors = p.factories.map((f) => f.color);
g.containersLeft = g.containersLeft.filter(
(c, i, all) => !colors.includes(c.color) || i === all.findIndex((x) => x.color === c.color)
);
cashBid(g);
expect(bankProductionAllowed(g, p, colors[0])).equal(false);
expect(p.availableMoves!.produce).equal(undefined);
});
it('resolves end-game pending auctions with payer decisions and scores holdings at $3', () => {
const g = game();
const winner = g.players[g.currentPlayers[0]];
containerBid(g, [winner.containersOnFactoryStore[0].piece.id]);
pass(g);
g.containersLeft = g.containersLeft.filter((c) =>
[g.containersLeft[0].color, g.containersLeft[15].color].includes(c.color)
);
refresh(g);
pass(g);
expect(g.phase).equal(Phase.GameEnd);
expect(winner.offshoreStats!.cashAuctionsWon).equal(1);
expect(g.offshoreBank!.auctions.length).equal(0);
expect(winner.finalScoreBreakdown!.length).equal(10);
});
it('reconstructs public analysis cash and holdings with an unrelated scenario seed', () => {
const g = game();
cashBid(g, 4);
pass(g);
pass(g);
pass(g);
const analysis = wrapper.createAnalysisScenario(stripSecret(g, g.currentPlayers[0]), {
player: g.currentPlayers[0],
seed: 'different',
});
expect(analysis.players.map((p) => p.money)).deep.equal(g.players.map((p) => p.money));
expect(analysis.offshoreBank).deep.equal(g.offshoreBank);
});
it('replays automatic payments from JSON without synthetic distribution moves', async () => {
const g = game();
const p = g.players[g.currentPlayers[0]];
containerBid(g, [p.containersOnFactoryStore[0].piece.id]);
pass(g);
pass(g);
pass(g);
expect(g.phase).equal(Phase.Move);
expect(wrapper.replay(JSON.parse(JSON.stringify(g)))).deep.equal(g);
const copy = cloneDeep(g);
await wrapper.dropPlayer(copy, p.id);
expect(copy.phase).equal(Phase.Move);
decisions(g);
expect(wrapper.replay(g)).deep.equal(g);
});
it('sends delivery self-buyout cash to bank, not supply', () => {
const g = game();
const p = g.players[g.currentPlayers[0]];
p.ship.containers.push(g.containersLeft.pop()!);
refresh(g);
act(g, { name: MoveName.Sail, data: ShipPosition.Island });
for (const bidder of g.currentPlayers.slice())
move(
g,
{ name: MoveName.Bid, data: true, extraData: { price: bidder === g.currentPlayers[0] ? 3 : 1 } },
bidder
);
while (g.phase === Phase.Bid)
move(g, { name: MoveName.Bid, data: true, extraData: { price: 0 } }, g.currentPlayers[0]);
const amount = g.players[g.highestBidders[0]].bid + g.players[g.highestBidders[0]].additionalBid;
const before = g.offshoreBank!.cashLots.reduce((a, b) => a + b, 0);
act(g, { name: MoveName.Decline, data: true });
expect(g.offshoreBank!.cashLots.reduce((a, b) => a + b, 0)).equal(before + amount);
});
it('settles pending cash bids at game end and values holding containers in existing ship row', () => {
const g = game();
const p = g.players[g.currentPlayers[0]];
cashBid(g, 1);
pass(g);
g.containersLeft = g.containersLeft.filter((c) => c.color === g.containersLeft[0].color);
refresh(g);
pass(g);
expect(g.phase).equal(Phase.GameEnd);
expect(p.bankHolding!.length).equal(2);
expect(p.finalScoreBreakdown![8]).equal('$6');
expect(p.money).equal(25);
});
it('keeps returned-container reserve capacity unavailable to warehouse purchases and production', () => {
const g = game();
const p = g.players[g.currentPlayers[0]];
const extra = g.containersLeft.pop()!;
p.containersOnFactoryStore.push({ piece: extra, price: 2, moved: false });
p.containersOnWarehouseStore.push({ piece: g.containersLeft.pop()!, price: 2, moved: false });
refresh(g);
containerBid(g, [extra.id, p.containersOnWarehouseStore[0].piece.id]);
expect(reserved(g, p, 'factory')).equal(1);
expect(reserved(g, p, 'warehouse')).equal(1);
expect(p.availableMoves!.produce).equal(undefined);
expect(p.availableMoves!.buyFromFactory).equal(undefined);
expect(
g.players
.filter((x) => x.id !== p.id)
.every((x) => !x.containersOnFactoryStore.some((c) => c.piece.id === extra.id))
).equal(true);
});
it('settles two end-game auctions exactly once across JSON persistence at every decision', () => {
let g = game(5);
const first = g.players[g.currentPlayers[0]];
first.containersOnFactoryStore.push({ piece: g.containersLeft.pop()!, price: 2, moved: false });
refresh(g);
containerBid(
g,
first.containersOnFactoryStore.map((c) => c.piece.id)
);
pass(g);
const second = g.players[g.currentPlayers[0]];
cashBid(g, 2);
pass(g);
g.containersLeft = g.containersLeft.filter((c) => c.color === g.containersLeft[0].color);
refresh(g);
pass(g);
expect(g.offshoreBank!.auctions.length).equal(2);
let count = 0;
while (g.phase === Phase.BankDecision && count++ < 10) {
g = JSON.parse(JSON.stringify(g));
const piece = g.offshoreBank!.decision!.payment[0];
act(g, { name: MoveName.DistributeBankContainer, data: piece });
}
expect(count).equal(1);
expect(g.phase).equal(Phase.GameEnd);
expect(g.offshoreBank!.auctions).deep.equal([]);
expect(g.players[first.id].offshoreStats!.cashAuctionsWon).equal(1);
expect(g.players[second.id].offshoreStats!.containerAuctionsWon).equal(1);
expect(g.players[second.id].bankHolding!.length).equal(2);
});
it('optimistically completes final bank decisions without scoring secret point cards', () => {
const g = game();
const p = g.players[g.currentPlayers[0]];
const i = g.containersLeft.findIndex((c) => c.color !== p.containersOnFactoryStore[0].piece.color);
p.containersOnFactoryStore.push({ piece: g.containersLeft.splice(i, 1)[0], price: 2, moved: false });
refresh(g);
containerBid(
g,
p.containersOnFactoryStore.map((c) => c.piece.id)
);
pass(g);
g.players[g.currentPlayers[0]].containersOnIsland.push(g.containersLeft.pop()!);
g.containersLeft = g.containersLeft.filter((c) => c.color === g.containersLeft[0].color);
refresh(g);
pass(g);
const stripped = cloneDeep(stripSecret(g, p.id));
expect(() =>
move(
stripped,
{ name: MoveName.DistributeBankContainer, data: stripped.offshoreBank!.decision!.payment[0] },
p.id,
true
)
).not.throw();
expect(stripped.players.some((p) => p.finalScoreBreakdown !== undefined)).equal(false);
});
});

313
engine/src/offshore.ts Normal file
View file

@ -0,0 +1,313 @@
import assert from 'assert';
import { AvailableMoves } from './available-moves';
import { BankAuction, ContainerPiece, GameState, Phase, Player, ShipPosition } from './gamestate';
import { GameEventName } from './log';
import { Move, MoveName } from './move';
export function payBankCash(G: GameState, amount: number) {
const b = G.offshoreBank;
if (!b) return;
const lots = [0, 1, 2].filter((i) => !b.auctions.some((a) => a.type === 'cash' && a.lot === i));
for (let i = 0; i < amount; i++) b.cashLots[lots[i % lots.length]]++;
}
export function reserved(G: GameState, player: Player, district: 'factory' | 'warehouse') {
return (
G.offshoreBank?.auctions
.filter((a) => a.bidder === player.id)
.reduce((n, a) => n + a.containers.filter((c) => c.district === district).length, 0) || 0
);
}
export function seizureChoices(G: GameState, player: Player): ContainerPiece[] {
return (
[
player.containersOnIsland,
player.ship.containers,
player.bankHolding || [],
player.containersOnWarehouseStore.map((c) => c.piece),
player.containersOnFactoryStore.map((c) => c.piece),
].find((a) => a.length > 0) || []
);
}
function hasBankPrize(G: GameState, type: 'cash' | 'containers', lot: number): boolean {
if (!Number.isInteger(lot) || lot < 0 || lot >= 3) return false;
const b = G.offshoreBank!;
return type === 'cash' ? b.cashLots[lot] > 0 : type === 'containers' && b.containerLots[lot].length > 0;
}
export function bankMoves(G: GameState, player: Player): AvailableMoves {
const b = G.offshoreBank!;
const d = b.decision;
if (d) {
if (d.kind === 'return') return { [MoveName.ReturnBankContainer]: d.containers.map((c) => c.container.piece) };
if (d.kind === 'seize') return { [MoveName.SeizeBankContainer]: seizureChoices(G, G.players[d.debtor!]) };
return { [MoveName.DistributeBankContainer]: d.payment };
}
const moves: AvailableMoves = {};
if (
player.ship.shipPosition === ShipPosition.OffshoreBank &&
player.ship.containers.length < 5 &&
(player.lastMove?.name === MoveName.Sail || player.lastMove?.name === MoveName.LoadBankContainer) &&
player.bankHolding!.length
) {
moves[MoveName.LoadBankContainer] = player.bankHolding!.slice();
}
if (player.actions <= 0 || b.called || b.won || new Set(G.containersLeft.map((c) => c.color)).size < 4)
return moves;
const offers: { type: 'cash' | 'containers'; lot: number }[] = [];
for (const type of ['cash', 'containers'] as const) {
const active = b.auctions.find((a) => a.type === type);
if (active?.bidder === player.id) continue;
if (!active && b.auctions.length >= (G.players.length === 5 ? 2 : 1)) continue;
const canBid =
type === 'containers'
? player.money > (active?.cash || 0)
: player.containersOnFactoryStore.length + player.containersOnWarehouseStore.length >
(active?.containers.length || 0);
if (!canBid) continue;
for (let lot = 0; lot < 3; lot++) {
if ((!active || active.lot === lot) && hasBankPrize(G, type, lot)) offers.push({ type, lot });
}
}
if (offers.length) moves[MoveName.CallBank] = offers;
return moves;
}
function collect(G: GameState, a: BankAuction) {
const b = G.offshoreBank!;
const p = G.players[a.bidder];
if (a.type === 'cash') {
p.money += b.cashLots[a.lot];
b.cashLots[a.lot] = 0;
p.offshoreStats!.cashAuctionsWon++;
} else {
p.bankHolding!.push(...b.containerLots[a.lot]);
b.containerLots[a.lot] = [];
p.offshoreStats!.containerAuctionsWon++;
}
G.log.push({
type: 'event',
event: { name: GameEventName.Upkeep, interest: `${p.name} wins bank ${a.type} lot ${a.lot + 1}` },
});
const index = b.auctions.findIndex(
(active) => active.type === a.type && active.lot === a.lot && active.bidder === a.bidder
);
assert(index >= 0, 'Bank settlement no longer matches an active auction');
b.auctions.splice(index, 1);
b.won = true;
}
/** Returns true while a player decision is pending. */
export function settleBank(G: GameState, ending = false): boolean {
const b = G.offshoreBank!;
const player = G.currentPlayers[0];
for (const a of b.auctions.slice()) {
if (!ending && a.bidder !== player) continue;
if (a.type === 'containers') {
payBankCash(G, a.cash);
collect(G, a);
} else {
b.decision = {
kind: 'distribute',
player: a.bidder,
resumePlayer: player,
containers: [],
payment: a.containers.map((c) => c.container.piece),
cursor: 0,
settlement: a,
ending,
};
G.phase = Phase.BankDecision;
G.currentPlayers = [a.bidder];
return true;
}
}
return false;
}
export function bankUpkeep(G: GameState) {
const b = G.offshoreBank!;
const p = G.players[G.currentPlayers[0]];
b.called = b.won = false;
const interest = p.loans.length;
if (p.money < interest && p.loans.length < 2 && G.loansLeft.length) {
p.loans.push(G.loansLeft.pop()!);
p.money += 10;
}
const paid = Math.min(p.money, interest);
p.money -= paid;
payBankCash(G, paid);
if (interest)
G.log.push({
type: 'event',
event: { name: GameEventName.Upkeep, interest: `${p.name} pays $${paid} interest to the Off-Shore Bank` },
});
const remaining = interest - paid;
if (remaining && seizureChoices(G, p).length) {
const chooser = (p.id + G.players.length - 1) % G.players.length;
b.decision = {
kind: 'seize',
player: chooser,
resumePlayer: p.id,
debtor: p.id,
remaining,
containers: [],
payment: [],
cursor: 0,
};
G.phase = Phase.BankDecision;
G.currentPlayers = [chooser];
} else settleBank(G);
}
export function applyBankMove(G: GameState, move: Move, p: Player): { handled: boolean; ending?: boolean } {
const b = G.offshoreBank;
if (!b) return { handled: false };
if (move.name === MoveName.CallBank) {
assert(move.data && hasBankPrize(G, move.data.type, move.data.lot), 'Bank reward lot is empty or invalid');
assert(
move.extraData &&
typeof move.extraData === 'object' &&
Object.keys(move.extraData).every((k) => k === (move.data.type === 'cash' ? 'containers' : 'cash')),
'Invalid bank bid fields'
);
const old = b.auctions.find((a) => a.type === move.data.type);
const a: BankAuction = { ...move.data, bidder: p.id, cash: 0, containers: [] };
if (a.type === 'containers') {
const cash = move.extraData?.cash;
assert(Number.isSafeInteger(cash) && cash! > (old?.cash || 0) && cash! <= p.money, 'Invalid bank cash bid');
assert(!move.extraData.containers?.length, 'Unexpected containers');
a.cash = cash!;
} else {
const ids = move.extraData?.containers;
assert(
Array.isArray(ids) && ids.length > (old?.containers.length || 0) && new Set(ids).size === ids.length,
'Invalid bank container bid'
);
assert(!move.extraData.cash, 'Unexpected cash');
for (const id of ids!) {
const factory = p.containersOnFactoryStore.find((c) => c.piece.id === id);
const container = factory || p.containersOnWarehouseStore.find((c) => c.piece.id === id);
assert(container, 'Only stored containers can be bid');
a.containers.push({ container: container!, district: factory ? 'factory' : 'warehouse' });
}
}
p.money -= a.cash;
for (const c of a.containers) {
const store = c.district === 'factory' ? p.containersOnFactoryStore : p.containersOnWarehouseStore;
store.splice(store.indexOf(c.container), 1);
}
if (old) {
b.auctions.splice(b.auctions.indexOf(old), 1);
G.players[old.bidder].money += old.cash;
if (old.containers.length) {
b.decision = {
kind: 'return',
player: old.bidder,
resumePlayer: p.id,
containers: old.containers,
payment: [],
cursor: 0,
};
G.phase = Phase.BankDecision;
G.currentPlayers = [old.bidder];
}
}
b.auctions.push(a);
b.called = true;
p.actions--;
} else if (move.name === MoveName.LoadBankContainer) {
const i = p.bankHolding!.findIndex((c) => c.id === move.data.id);
p.ship.containers.push(p.bankHolding!.splice(i, 1)[0]);
} else if (
[MoveName.ReturnBankContainer, MoveName.DistributeBankContainer, MoveName.SeizeBankContainer].includes(
move.name
)
) {
const d = b.decision!;
const piece = (move as { data: ContainerPiece }).data;
if (move.name === MoveName.ReturnBankContainer) {
const i = d.containers.findIndex((c) => c.container.piece.id === piece.id);
const c = d.containers[i];
assert(move.extraData && Object.keys(move.extraData).every((k) => k === 'price'), 'Invalid return fields');
const price = (move as { extraData?: { price: number } }).extraData?.price;
assert(
Number.isInteger(price) &&
price! >= (c.district === 'factory' ? 1 : 2) &&
price! <= (c.district === 'factory' ? 4 : 6),
'Invalid return price'
);
c.container.price = price!;
(c.district === 'factory' ? p.containersOnFactoryStore : p.containersOnWarehouseStore).push(c.container);
d.containers.splice(i, 1);
if (d.containers.length) return { handled: true };
} else if (move.name === MoveName.SeizeBankContainer) {
const debtor = G.players[d.debtor!];
for (const arr of [debtor.containersOnIsland, debtor.ship.containers, debtor.bankHolding!]) {
const i = arr.findIndex((c) => c.id === piece.id);
if (i >= 0) arr.splice(i, 1);
}
for (const arr of [debtor.containersOnFactoryStore, debtor.containersOnWarehouseStore]) {
const i = arr.findIndex((c) => c.piece.id === piece.id);
if (i >= 0) arr.splice(i, 1);
}
d.payment.push(piece);
d.remaining!--;
if (d.remaining! > 0 && seizureChoices(G, debtor).length) return { handled: true };
d.kind = 'distribute';
return { handled: true };
} else {
const lots = [0, 1, 2].filter((i) => !b.auctions.some((a) => a.type === 'containers' && a.lot === i));
b.containerLots[lots[d.cursor++ % lots.length]].push(piece);
d.payment.splice(
d.payment.findIndex((c) => c.id === piece.id),
1
);
if (d.payment.length) return { handled: true };
if (d.settlement) collect(G, d.settlement);
}
delete b.decision;
G.phase = Phase.Move;
G.currentPlayers = [d.resumePlayer];
if (d.kind !== 'return' && settleBank(G, d.ending)) return { handled: true };
return { handled: true, ending: d.ending };
} else return { handled: false };
return { handled: true };
}
/** Drain only color-equivalent payment choices, in persisted payment order.
* IDs distinguish physical pieces, not value; price/district no longer apply in bank lots.
* Reuse the normal transition so collection, default resumption and final settlements
* behave identically to an explicit choice (including legacy saved decisions).
*/
export function normalizeBankDistribution(G: GameState): { ending?: boolean } {
let ending: boolean | undefined;
while (G.phase === Phase.BankDecision) {
const d = G.offshoreBank?.decision;
if (!d || d.kind !== 'distribute' || !d.payment.length || d.payment.some((c) => c.color !== d.payment[0].color))
break;
const result = applyBankMove(
G,
{ name: MoveName.DistributeBankContainer, data: d.payment[0] },
G.players[d.player]
);
ending = result.ending || ending;
}
return { ending };
}
/** Mandatory production must be finishable without triggering game end after Call Bank. */
export function bankProductionAllowed(G: GameState, p: Player, first: ContainerPiece['color']): boolean {
if (!G.offshoreBank?.called) return true;
const colors = p.factories
.map((f) => f.color)
.filter((c) => !p.produced.includes(c) && G.containersLeft.some((x) => x.color === c));
const slots = p.factories.length * 2 - p.containersOnFactoryStore.length - reserved(G, p, 'factory');
const required = Math.min(slots, colors.length);
for (let mask = 0; mask < 1 << colors.length; mask++) {
const selected = colors.filter((_, i) => mask & (1 << i));
if (selected.length !== required || !selected.includes(first)) continue;
const remaining = G.containersLeft.slice();
for (const color of selected)
remaining.splice(
remaining.findIndex((c) => c.color === color),
1
);
if (new Set(remaining.map((c) => c.color)).size >= 4) return true;
}
return false;
}

208
engine/src/replay.spec.ts Normal file
View file

@ -0,0 +1,208 @@
import { expect } from 'chai';
import { cloneDeep } from 'lodash';
import seedrandom from 'seedrandom';
import * as wrapper from '../wrapper';
import { bidRevision } from './choice-revisions';
import { setup } from './engine';
import { GameState, Phase } from './gamestate';
import { Move, MoveName } from './move';
const json = (value: unknown) => JSON.parse(JSON.stringify(value));
const bid = (price: number): Move => ({ name: MoveName.Bid, data: true, extraData: { price } });
const getLoan: Move = { name: MoveName.GetLoan, data: true };
/** Run `play` with a seeded Math.random, so that the AI's choices are reproducible. */
function seeded<T>(seed: string, play: () => T): T {
const random = Math.random;
Math.random = seedrandom(seed);
try {
return play();
} finally {
Math.random = random;
}
}
/**
* A game against bots, saved like BGS saves it: committed states only, as JSON, with their
* announcements posted. Each saved move of the human records an undo point (the log length
* before it). `positions` keeps the first saved state reaching each visible log length with
* no sealed bid pending: the state that this much of the log describes.
*/
class BotGame {
saved!: GameState;
positions = new Map<number, GameState>();
undoPoints: number[] = [];
constructor(players: number, seed: string, readonly human = 0) {
const G = setup(players, {}, seed);
G.players.forEach((player) => (player.name = player.id === human ? 'Human' : `Bot ${player.id}`));
this.save(G);
}
save(state: GameState | undefined) {
expect(state, 'a committed state').to.not.equal(undefined);
this.saved = json(wrapper.messages(state!).data);
const length = wrapper.logLength(this.saved);
if (this.saved.hiddenLog.length === 0 && !this.positions.has(length)) this.positions.set(length, this.saved);
}
/** A saved move of the human. */
async play(moves: Move | Move[]) {
const before = wrapper.logLength(this.saved);
this.save(wrapper.toSave(await wrapper.move(cloneDeep(this.saved), moves, this.human)));
this.undoPoints.push(before);
}
/** One saved move, by the AI: for the human when they are due, else for a bot. */
step() {
const seat = this.saved.currentPlayers.includes(this.human) ? this.human : this.saved.currentPlayers[0];
const before = wrapper.logLength(this.saved);
this.save(wrapper.toSave(wrapper.moveAI(cloneDeep(this.saved), seat)));
if (seat === this.human) this.undoPoints.push(before);
}
/** A bot plays until it is no longer due, e.g. until it has placed its sealed bid. */
bot(seat: number) {
expect(seat).to.not.equal(this.human);
for (let i = 0; i < 10 && this.saved.currentPlayers.includes(seat); i++) {
this.save(wrapper.toSave(wrapper.moveAI(cloneDeep(this.saved), seat)));
}
expect(this.saved.currentPlayers).to.not.include(seat);
}
/** Play on until an auction opens in which the human bids along with two bots. */
untilAuction() {
for (let i = 0; i < 2000; i++) {
const G = this.saved;
if (G.phase === Phase.Bid && !G.hiddenLog.length && G.currentPlayers.includes(this.human)) {
expect(G.currentPlayers).to.have.length(3);
return G.currentPlayers.filter((seat) => seat !== this.human);
}
expect(wrapper.ended(G), 'an auction comes up first').to.equal(false);
this.step();
}
throw new Error('No auction came up');
}
/** BGS's undo route: back to the last undo point, saved as a regular turn. */
undo() {
const to = this.undoPoints.pop()!;
const state = wrapper.replay(this.saved, { to });
expect(wrapper.logLength(state)).to.equal(to);
expect(wrapper.isLiveUpdate(state), 'a turn: BGS then lets the bots due play').to.equal(false);
this.save(wrapper.toSave(state));
this.undoPoints = this.undoPoints.filter((point) => point < to);
return this.saved;
}
}
describe('replay to an earlier position (undo against bots)', () => {
it('rebuilds each saved position, `to` entries long, without touching the game', () => {
const game = seeded('replay-positions', () => {
const game = new BotGame(4, 'replay-positions');
for (let i = 0; i < 400 && !wrapper.ended(game.saved); i++) game.step();
return game;
});
const saved = [...game.positions.values()];
expect(saved.length).to.be.greaterThan(80);
expect(saved.some((G) => G.phase === Phase.Bid)).to.equal(true, 'auction openings');
expect(saved.some((G) => G.phase === Phase.AcceptDecline)).to.equal(true, 'bids revealed');
expect(saved.some((G) => G.round > 5)).to.equal(true, 'later rounds');
const final = game.saved;
const before = json(final);
for (const [to, position] of game.positions) {
const replayed = wrapper.replay(final, { to });
expect(wrapper.logLength(replayed)).to.equal(to);
expect(json(replayed), `position ${to}`).to.deep.equal(position);
}
expect(json(final)).to.deep.equal(before);
const replayed = wrapper.replay(final, { to: final.log.length });
for (const entry of replayed.log) if (entry.type === 'move') entry.move.name = 'changed' as never;
expect(json(final), 'the result shares nothing with the input').to.deep.equal(before);
});
it('reopens a running auction without its sealed bids and bid-phase loans, playable by all', async () => {
const game = new BotGame(4, 'replay-auction');
const [first, second] = seeded('replay-auction', () => game.untilAuction());
const opening = game.saved;
const length = wrapper.logLength(opening);
const human = opening.players[game.human];
seeded('replay-auction-bot', () => game.bot(first));
expect(game.saved.players[game.human].availableMoves).to.have.property(MoveName.GetLoan);
await game.play(getLoan);
await game.play(bid(3));
expect(game.saved.phase).to.equal(Phase.Bid);
expect(game.saved.currentPlayers).to.deep.equal([second]);
expect(game.saved.hiddenLog.length).to.be.at.least(3);
expect(wrapper.logLength(game.saved), 'sealed bids stay out of the visible log').to.equal(length);
const undoPoints = game.undoPoints.slice();
const reopened = game.undo();
expect(reopened).to.deep.equal(opening);
expect(reopened.hiddenLog).to.deep.equal([]);
expect(reopened.currentPlayers).to.have.members([game.human, first, second]);
expect(reopened.players.map((p) => [p.bid, p.additionalBid, p.showBid])).to.deep.equal(
reopened.players.map(() => [0, 0, false])
);
expect(reopened.players[game.human].loans).to.deep.equal(human.loans);
expect(reopened.players[game.human].money).to.equal(human.money);
expect(game.undoPoints, 'the loan is taken back with the bid').to.deep.equal(undoPoints.slice(0, -2));
// The human bids again, the bots bid again and the auctioneer decides: play goes on.
expect(reopened.players[game.human].availableMoves).to.have.property(MoveName.Bid);
await game.play(bid(2));
seeded('replay-auction-after', () => {
for (const seat of [first, second]) game.bot(seat);
for (let i = 0; i < 60 && !wrapper.ended(game.saved); i++) game.step();
});
const settled = game.saved.log
.slice(length)
.filter((entry) => entry.type === 'move' && [MoveName.Accept, MoveName.Decline].includes(entry.move.name));
expect(settled.length, 'the reopened auction and later ones are settled').to.be.at.least(2);
expect(wrapper.logLength(game.saved)).to.be.greaterThan(length + 20);
});
it('takes back a replaced sealed bid as a regular turn', async () => {
const game = new BotGame(4, 'replay-revision');
const [first, second] = seeded('replay-revision', () => game.untilAuction());
await game.play(bid(3));
await game.play({ ...bid(1), revision: bidRevision(game.saved, game.human) });
expect(wrapper.isLiveUpdate(game.saved)).to.equal(true);
expect(wrapper.replay(game.saved).liveUpdate, 'a full replay keeps the live update').to.equal(true);
const reopened = game.undo();
expect(reopened.players[game.human].bid).to.equal(0);
expect(reopened.currentPlayers).to.have.members([game.human, first, second]);
expect(game.undoPoints.every((point) => point < wrapper.logLength(reopened))).to.equal(true);
});
it('rejects positions outside the visible log', () => {
const G = setup(3, {}, 'replay-bounds');
expect(G.log).to.have.length(1);
for (const to of [-1, 2, 0.5, NaN, Infinity]) {
expect(() => wrapper.replay(G, { to }), String(to)).to.throw('Invalid history position');
}
// The initial position: its log already holds the game start.
expect(json(wrapper.replay(G, { to: 0 }))).to.deep.equal(json(G));
expect(json(wrapper.replay(G, { to: 1 }))).to.deep.equal(json(G));
});
it('keeps the full replay, sealed bids, live update and announcements included, without `to`', async () => {
const game = new BotGame(4, 'replay-full');
seeded('replay-full', () => game.untilAuction());
await game.play(bid(3));
await game.play({ ...bid(2), revision: bidRevision(game.saved, game.human) });
const G = { ...game.saved, pendingMessages: ['Bot 1 accepts Bot 2’s bid of $4 and receives $8'] };
expect(json(wrapper.replay(G))).to.deep.equal(json(G));
for (const options of [undefined, {}, { to: undefined }]) {
expect(json(wrapper.replay(G, options))).to.deep.equal(json(wrapper.replay(G)));
}
// An earlier position, even at the same visible length, has neither of them.
const earlier = wrapper.replay(G, { to: wrapper.logLength(G) });
expect(earlier).to.not.have.property('pendingMessages');
expect(earlier.liveUpdate).to.equal(false);
});
});

View file

@ -0,0 +1,81 @@
import { expect } from 'chai';
import { cloneDeep } from 'lodash';
import { logSlice } from '../wrapper';
import { availableMoves } from './available-moves';
import { bidRevision } from './choice-revisions';
import { move, setup, stripSecret } from './engine';
import { GameState, Phase } from './gamestate';
import { Move, MoveName } from './move';
const bid = (price: number, revision?: string): Move => ({
name: MoveName.Bid,
data: true,
extraData: { price },
...(revision ? { revision } : {}),
});
function auction() {
const state = setup(3, {}, 'strip-secret');
state.phase = Phase.Bid;
state.auctioningPlayer = 0;
state.currentPlayers = [1, 2];
state.players.forEach((player) => (player.availableMoves = availableMoves(state, player)));
return state;
}
function assertSealed(state: GameState, price: number, additional: boolean) {
const before = cloneDeep(state);
// Auctioneer, competing bidder, and spectator; also exercise serialized log responses.
for (const viewer of [0, 2, undefined]) {
for (const view of [stripSecret(state, viewer), logSlice(state, { player: viewer }).state]) {
const serialized = JSON.parse(JSON.stringify(view)) as GameState;
expect(serialized.players[1].lastMove).to.equal(null);
expect(serialized.players[1][additional ? 'additionalBid' : 'bid']).to.equal(0);
expect(serialized.hiddenLog).to.deep.equal([]);
expect(serialized.log.some((entry) => entry.type === 'move' && entry.move.name === MoveName.Bid)).to.equal(
false
);
if (additional) expect(serialized.players[1].bid).to.equal(7);
}
}
expect(stripSecret(state, 1).players[1].lastMove).to.deep.equal(bid(price));
expect(stripSecret(state, 1).players[1][additional ? 'additionalBid' : 'bid']).to.equal(price);
expect(state).to.deep.equal(before);
}
describe('stripSecret sealed bids', () => {
it('hides initial and revised bids from opponents and spectators', () => {
const state = auction();
move(state, bid(6), 1);
assertSealed(state, 6, false);
move(state, bid(7, bidRevision(state, 1)), 1);
assertSealed(state, 7, false);
});
it('hides additional and revised tie-break bids even after initial bids are public', () => {
const state = auction();
move(state, bid(7), 1);
move(state, bid(7), 2);
expect(state.players[1].showBid).to.equal(true);
move(state, bid(3), 1);
assertSealed(state, 3, true);
move(state, bid(4, bidRevision(state, 1)), 1);
assertSealed(state, 4, true);
move(state, bid(2), 2);
for (const viewer of [0, 2, undefined]) {
const view = stripSecret(state, viewer);
expect(view.players[1].bid).to.equal(7);
expect(view.players[1].additionalBid).to.equal(4);
expect(view.log).to.deep.equal(state.log);
expect(
view.log.filter((entry) => entry.type === 'move' && entry.move.name === MoveName.Bid)
).to.have.length(4);
}
});
it('preserves non-bid last moves', () => {
const state = setup(3, {}, 'strip-secret-public');
state.players[1].lastMove = { name: MoveName.Pass, data: true };
expect(stripSecret(state).players[1].lastMove).to.deep.equal(state.players[1].lastMove);
});
});

643
engine/src/wrapper.spec.ts Normal file
View file

@ -0,0 +1,643 @@
import { expect } from 'chai';
import { cloneDeep } from 'lodash';
import * as wrapper from '../wrapper';
import { bidRevision } from './choice-revisions';
import { move as atomicMove, setup } from './engine';
import { GameState, Phase, ShipPosition } from './gamestate';
import { Move, MoveName } from './move';
const getLoan: Move = { name: MoveName.GetLoan, data: true };
const payLoan: Move = { name: MoveName.PayLoan, data: true };
const pass: Move = { name: MoveName.Pass, data: true };
describe('wrapper (tentative turns)', () => {
/**
* Simulates the platform: `saved` only ever advances when `toSave` returns the
* state (committed); tentative states are discarded, like the game server does.
*/
class Platform {
saved: GameState;
logLengths: number[] = [];
constructor(players = 2, seed = 'wrapper-test') {
this.saved = setup(players, {}, seed);
this.logLengths.push(wrapper.logLength(this.saved));
}
/** Replay a turn buffer from the saved state, persist only if committed. */
async send(moves: Move | Move[], player: number): Promise<{ result: GameState; saved: boolean }> {
const result = await wrapper.move(cloneDeep(this.saved), moves, player);
const toSave = wrapper.toSave(result);
if (toSave) {
this.saved = toSave;
this.logLengths.push(wrapper.logLength(this.saved));
}
return { result, saved: !!toSave };
}
}
it('should keep mid-turn states tentative and commit when the turn completes', async () => {
const platform = new Platform();
const A = platform.saved.currentPlayers[0];
// Mid-turn move: still undoable, must not be saved
const mid = await platform.send([getLoan], A);
expect(mid.saved).to.be.false;
expect(mid.result.newTurn).to.be.false;
expect(wrapper.toSave(mid.result)).to.be.undefined;
// ...but the tentative state did apply the move for the player's preview
expect(mid.result.players[A].loans).to.have.length(1);
// The tentative state was NOT persisted
expect(platform.saved.players[A].loans).to.have.length(0);
// Completed turn: the full buffer replays from the saved state and commits
const full = await platform.send([getLoan, pass], A);
expect(full.saved).to.be.true;
expect(full.result.newTurn).to.be.true;
expect(platform.saved.players[A].loans).to.have.length(1);
expect(platform.saved.currentPlayers).to.not.include(A);
});
it('should accept a bare move object as a one-element buffer', async () => {
const base = setup(2, {}, 'wrapper-test');
const A = base.currentPlayers[0];
const fromObject = await wrapper.move(cloneDeep(base), pass, A);
const fromArray = await wrapper.move(cloneDeep(base), [pass], A);
expect(JSON.parse(JSON.stringify(fromObject))).to.deep.equal(JSON.parse(JSON.stringify(fromArray)));
expect(wrapper.toSave(fromObject)).to.not.be.undefined;
});
it('should not save an empty buffer and not grant it any progress', async () => {
const base = setup(2, {}, 'wrapper-test');
const A = base.currentPlayers[0];
const result = await wrapper.move(cloneDeep(base), [], A);
expect(wrapper.toSave(result)).to.be.undefined;
expect(wrapper.logLength(result)).to.equal(wrapper.logLength(base));
});
it('should cancel repeated loan reversals without growing the log or committing a turn', async () => {
const base = setup(3, {}, 'loan-reversal');
const A = base.currentPlayers[0];
const moves: Move[] = [];
for (let i = 0; i < 100; i++) moves.push(getLoan, payLoan);
const result = await wrapper.move(cloneDeep(base), moves, A);
expect(result).to.deep.equal({ ...base, newTurn: false });
expect(wrapper.toSave(result)).to.be.undefined;
const committed = await wrapper.move(cloneDeep(base), [...moves, pass], A);
expect(committed).to.deep.equal(await wrapper.move(cloneDeep(base), pass, A));
});
it('should cancel a repayment followed by a loan without erasing the older loan history', async () => {
const platform = new Platform(2, 'repay-reversal');
const A = platform.saved.currentPlayers[0];
await platform.send([getLoan, pass], A);
await platform.send(pass, platform.saved.currentPlayers[0]);
const base = cloneDeep(platform.saved);
const result = await wrapper.move(cloneDeep(base), [payLoan, getLoan], A);
expect(result).to.deep.equal({ ...base, newTurn: false });
expect(result.players[A].loans).to.have.length(1);
expect(wrapper.toSave(result)).to.be.undefined;
});
it('should unwind two loans one at a time', async () => {
const base = setup(3, {}, 'nested-loans');
const A = base.currentPlayers[0];
const one = await wrapper.move(cloneDeep(base), [getLoan, getLoan, payLoan], A);
expect(one).to.deep.equal(await wrapper.move(cloneDeep(base), getLoan, A));
const none = await wrapper.move(cloneDeep(base), [getLoan, getLoan, payLoan, payLoan], A);
expect(none).to.deep.equal({ ...base, newTurn: false });
});
it('should keep loans separated by another action', async () => {
const base = setup(3, {}, 'use-loan');
const A = base.currentPlayers[0];
const purchase: Move = { name: MoveName.BuyWarehouse, data: true, extraData: base.warehousesLeft[0] };
const moves = [getLoan, purchase, payLoan];
const result = await wrapper.move(cloneDeep(base), moves, A);
let expected = cloneDeep(base);
for (const action of moves) expected = atomicMove(expected, action, A);
expect(result).to.deep.equal(expected);
expect(result.log.length).to.equal(base.log.length + 3);
});
it('should validate cancelled moves and still reject crossing a turn boundary', async () => {
const base = setup(3, {}, 'invalid-reversal');
const A = base.currentPlayers[0];
for (const actions of [
[payLoan, getLoan],
[getLoan, getLoan, getLoan, payLoan, payLoan, payLoan],
[pass, getLoan, payLoan],
]) {
let error: Error | undefined;
try {
await wrapper.move(cloneDeep(base), actions, A);
} catch (e) {
error = e as Error;
}
expect(error, 'invalid moves cannot disappear through cancellation').to.be.instanceOf(Error);
}
});
it('should preserve loan reversals when replaying already committed history', () => {
let state = setup(3, {}, 'legacy-loan-log');
state.players.forEach((player) => (player.name = `Player ${player.id}`));
const A = state.currentPlayers[0];
for (const action of [getLoan, payLoan, pass]) state = atomicMove(state, action, A);
expect(wrapper.replay(state)).to.deep.equal(state);
});
it('should make undo-by-truncation equivalent to never having made the popped move', async () => {
const base = setup(2, {}, 'wrapper-test');
const A = base.currentPlayers[0];
// Replaying a shortened buffer from the committed base...
const shortened = await wrapper.move(cloneDeep(base), [getLoan], A);
// ...equals never having made the popped move at all
const straight = await wrapper.move(cloneDeep(base), [getLoan], A);
expect(JSON.parse(JSON.stringify(shortened))).to.deep.equal(JSON.parse(JSON.stringify(straight)));
// Popping the whole buffer needs no server call at all: the saved state is the
// turn start. Taking a loan, undoing it (nothing sent), then passing yields the
// exact same committed state as passing right away.
const passedAfterUndo = await wrapper.move(cloneDeep(base), [pass], A);
const passedDirectly = await wrapper.move(cloneDeep(base), [pass], A);
expect(JSON.parse(JSON.stringify(wrapper.toSave(passedAfterUndo)))).to.deep.equal(
JSON.parse(JSON.stringify(wrapper.toSave(passedDirectly)))
);
// And the tentative detour left no trace to pop: a longer buffer, truncated,
// reproduces the shorter buffer's state exactly.
const detour = await wrapper.move(cloneDeep(base), [getLoan, payLoan], A);
expect(wrapper.toSave(detour)).to.be.undefined;
const truncated = await wrapper.move(cloneDeep(base), [getLoan], A);
expect(JSON.parse(JSON.stringify(truncated))).to.deep.equal(JSON.parse(JSON.stringify(shortened)));
});
/**
* Scripted 3-player opening: plays committed turns until the starting player A has
* sailed to the island with one container, starting an auction where B and C (the
* next players in turn order) are the simultaneous bidders.
*/
async function playToBidPhase(platform: Platform): Promise<{ A: number; B: number; C: number }> {
const A = platform.saved.currentPlayers[0];
const B = (A + 1) % 3;
const C = (A + 2) % 3;
// A buys from B's factory; B buys from A's factory (so B's warehouse store
// holds a container A can later pick up); C just passes.
await platform.send(
[
{
name: MoveName.BuyFromFactory,
data: { player: B, piece: platform.saved.players[B].containersOnFactoryStore[0].piece },
extraData: { price: 2 },
},
pass,
],
A
);
await platform.send(
[
{
name: MoveName.BuyFromFactory,
data: { player: A, piece: platform.saved.players[A].containersOnFactoryStore[0].piece },
extraData: { price: 2 },
},
pass,
],
B
);
await platform.send([pass], C);
// A picks up a container from B's warehouse...
await platform.send(
[
{ name: MoveName.Sail, data: `playerHarbor${B}1` as ShipPosition },
{
name: MoveName.BuyFromWarehouse,
data: { player: B, piece: platform.saved.players[B].containersOnWarehouseStore[0].piece },
},
pass,
],
A
);
await platform.send([pass], B);
await platform.send([pass], C);
// ...and sails to the island, starting the auction
await platform.send(
[
{ name: MoveName.Sail, data: ShipPosition.OpenSea },
{ name: MoveName.Sail, data: ShipPosition.Island },
],
A
);
expect(platform.saved.phase).to.equal(Phase.Bid);
expect(platform.saved.currentPlayers).to.have.members([B, C]);
return { A, B, C };
}
it('allows replacing sealed bids in each round without reopening the clock or exposing earlier bids', async () => {
const platform = new Platform(3, 'wrapper-test-revisions');
const { A, B, C } = await playToBidPhase(platform);
const bid = (price: number, revision?: string): Move => ({
name: MoveName.Bid,
data: true,
extraData: { price },
...(revision ? { revision } : {}),
});
await platform.send(bid(5), B);
const key = bidRevision(platform.saved, B)!;
const replacement = bid(3, key);
expect(wrapper.canMoveOutOfTurn(platform.saved, replacement, B)).to.equal(true);
expect(wrapper.canMoveOutOfTurn(platform.saved, replacement, A)).to.equal(false);
expect(wrapper.canMoveOutOfTurn(platform.saved, [replacement, getLoan], B)).to.equal(false);
await platform.send(replacement, B);
expect(wrapper.isLiveUpdate(platform.saved)).to.equal(true);
expect(platform.saved.currentPlayers).to.deep.equal([C]);
expect(platform.saved.hiddenLog).to.have.length(1);
expect(platform.saved.players[B].bid).to.equal(3);
expect(wrapper.stripSecret(platform.saved, C).players[B].bid).not.to.equal(3);
expect(wrapper.replay(platform.saved).players[B].bid).to.equal(3);
await platform.send(bid(3), C);
expect(wrapper.isLiveUpdate(platform.saved)).to.equal(false);
await platform.send(bid(2), B);
const extraKey = bidRevision(platform.saved, B)!;
expect(extraKey).not.to.equal(key);
expect(wrapper.canMoveOutOfTurn(platform.saved, replacement, B)).to.equal(false);
await platform.send(bid(0, extraKey), B);
expect(platform.saved.players[B].additionalBid).to.equal(0);
expect(platform.saved.hiddenLog).to.have.length(3);
expect(wrapper.replay(platform.saved).players[B].additionalBid).to.equal(0);
await platform.send(bid(1), C);
expect(platform.saved.phase).to.equal(Phase.AcceptDecline);
expect(platform.saved.highestBidders).to.deep.equal([C]);
expect(wrapper.canMoveOutOfTurn(platform.saved, bid(0, extraKey), B)).to.equal(false);
let rejected = false;
try {
await platform.send(bid(0, extraKey), B);
} catch {
rejected = true;
}
expect(rejected).to.equal(true);
});
it('should play a 3-player auction with a bid tie and an additional-bid round', async () => {
const platform = new Platform(3, 'wrapper-test-3p');
const { A, B, C } = await playToBidPhase(platform);
// Each bid is a single-move committed turn (bids live in the hidden log)
const bidB = await platform.send([{ name: MoveName.Bid, data: true, extraData: { price: 3 } }], B);
expect(bidB.saved).to.be.true;
expect(platform.saved.phase).to.equal(Phase.Bid);
expect(platform.saved.currentPlayers).to.deep.equal([C]);
// C matches B's bid: tie → additional-bid round between the tied bidders
const bidC = await platform.send([{ name: MoveName.Bid, data: true, extraData: { price: 3 } }], C);
expect(bidC.saved).to.be.true;
expect(platform.saved.phase).to.equal(Phase.Bid);
expect(platform.saved.highestBidders).to.have.members([B, C]);
expect(platform.saved.currentPlayers).to.have.members([B, C]);
// The bids are still hidden: nothing was flushed to the visible log yet
expect(platform.saved.hiddenLog).to.have.length(2);
// Additional bids, again one committed turn each; B outbids C
const addB = await platform.send([{ name: MoveName.Bid, data: true, extraData: { price: 2 } }], B);
expect(addB.saved).to.be.true;
expect(platform.saved.phase).to.equal(Phase.Bid);
expect(platform.saved.currentPlayers).to.deep.equal([C]);
const addC = await platform.send([{ name: MoveName.Bid, data: true, extraData: { price: 0 } }], C);
expect(addC.saved).to.be.true;
// The additional-bid round resolved the tie: the auctioneer decides, and the
// hidden bid moves surfaced in the visible log
expect(platform.saved.phase).to.equal(Phase.AcceptDecline);
expect(platform.saved.currentPlayers).to.deep.equal([A]);
expect(platform.saved.highestBidders).to.deep.equal([B]);
expect(platform.saved.hiddenLog).to.have.length(0);
const moneyA = platform.saved.players[A].money;
const moneyB = platform.saved.players[B].money;
const accept = await platform.send([{ name: MoveName.Accept, data: B }], A);
expect(accept.saved).to.be.true;
expect(platform.saved.phase).to.equal(Phase.Move);
expect(platform.saved.players[B].containersOnIsland).to.have.length(1);
expect(platform.saved.players[B].money).to.equal(moneyB - 5);
expect(platform.saved.players[A].money).to.equal(moneyA + 10);
});
it('should reject a malformed buffer without leaking anything half-applied', async () => {
const platform = new Platform();
const A = platform.saved.currentPlayers[0];
const before = JSON.parse(JSON.stringify(platform.saved));
// A third loan is illegal (two loans per player at most): the buffer must be
// rejected even though its first two moves are legal.
let error: Error | null = null;
try {
await platform.send([getLoan, getLoan, getLoan], A);
} catch (err) {
error = err as Error;
}
expect(error, 'an illegal move mid-buffer must reject the whole buffer').to.not.be.null;
// Nothing half-applied leaked into the platform's saved state...
expect(JSON.parse(JSON.stringify(platform.saved))).to.deep.equal(before);
// ...and a valid buffer from that same state still works
const ok = await platform.send([getLoan, payLoan, pass], A);
expect(ok.saved).to.be.true;
});
it('should reject a buffer that keeps playing past a turn boundary', async () => {
// Degenerate case: the only other player is dropped, so the same player is up
// again right after passing — [Pass, Pass] is a sequence of individually legal
// moves that spans TWO turns. It must not commit both for one time increment.
const platform = new Platform();
const A = platform.saved.currentPlayers[0];
const B = 1 - A;
platform.saved = await wrapper.dropPlayer(platform.saved, B);
const before = JSON.parse(JSON.stringify(platform.saved));
let error: Error | null = null;
try {
await platform.send([pass, pass], A);
} catch (err) {
error = err as Error;
}
expect(error).to.not.be.null;
expect(error!.message).to.match(/turn boundary/);
expect(JSON.parse(JSON.stringify(platform.saved))).to.deep.equal(before);
// A buffer ending exactly on the turn boundary is still fine
const ok = await platform.send([getLoan, pass], A);
expect(ok.saved).to.be.true;
expect(platform.saved.currentPlayers).to.deep.equal([A]);
});
it('should play a full auction with the right commit points and a never-shrinking log', async () => {
const platform = new Platform();
const A = platform.saved.currentPlayers[0];
const B = 1 - A;
const buyFromB: Move = {
name: MoveName.BuyFromFactory,
data: { player: B, piece: platform.saved.players[B].containersOnFactoryStore[0].piece },
extraData: { price: 2 },
};
// A: buy a container from B's factory (tentative), then pass (commits)
expect((await platform.send([buyFromB], A)).saved).to.be.false;
expect((await platform.send([buyFromB, pass], A)).saved).to.be.true;
// B: buy a container from A's factory into B's warehouse, then pass
const buyFromA: Move = {
name: MoveName.BuyFromFactory,
data: { player: A, piece: platform.saved.players[A].containersOnFactoryStore[0].piece },
extraData: { price: 2 },
};
expect((await platform.send([buyFromA, pass], B)).saved).to.be.true;
// A: sail to B's harbor, buy from B's warehouse onto the ship, pass.
// Growing buffer resent on every action, tentative until the pass.
const sailToB: Move = {
name: MoveName.Sail,
data: `playerHarbor${B}1` as ShipPosition,
};
const buyWarehouse: Move = {
name: MoveName.BuyFromWarehouse,
data: { player: B, piece: platform.saved.players[B].containersOnWarehouseStore[0].piece },
};
expect((await platform.send([sailToB], A)).saved).to.be.false;
expect((await platform.send([sailToB, buyWarehouse], A)).saved).to.be.false;
expect((await platform.send([sailToB, buyWarehouse, pass], A)).saved).to.be.true;
expect(platform.saved.players[A].ship.containers).to.have.length(1);
// B: pass
expect((await platform.send([pass], B)).saved).to.be.true;
// A: sail back to the open sea (tentative), then to the island — which starts
// the auction and commits immediately (the mover leaves currentPlayers; there
// is nothing to undo for the bidders)
const sailSea: Move = { name: MoveName.Sail, data: ShipPosition.OpenSea };
expect((await platform.send([sailSea], A)).saved).to.be.false;
const sailIsland = await platform.send([sailSea, { name: MoveName.Sail, data: ShipPosition.Island }], A);
expect(sailIsland.saved).to.be.true;
expect(platform.saved.phase).to.equal(Phase.Bid);
expect(platform.saved.currentPlayers).to.deep.equal([B]);
// B: bid — a single-move committed turn (bids live in the hidden log and were
// never undoable)
const bid = await platform.send([{ name: MoveName.Bid, data: true, extraData: { price: 3 } }], B);
expect(bid.saved).to.be.true;
expect(platform.saved.phase).to.equal(Phase.AcceptDecline);
expect(platform.saved.currentPlayers).to.deep.equal([A]);
// A (auctioneer): a loan during accept/decline is still undoable...
const loanFirst = await platform.send([getLoan], A);
expect(loanFirst.saved).to.be.false;
expect(platform.saved.players[A].loans).to.have.length(0);
// ...and accepting commits the whole turn
const moneyBefore = platform.saved.players[A].money;
const accept = await platform.send([getLoan, { name: MoveName.Accept, data: B }], A);
expect(accept.saved).to.be.true;
expect(platform.saved.phase).to.equal(Phase.Move);
expect(platform.saved.players[B].containersOnIsland).to.have.length(1);
// +10 for the loan, + twice the bid of 3 for the accepted auction
expect(platform.saved.players[A].money).to.equal(moneyBefore + 10 + 6);
// Control passed on: the accept itself can no longer be undone
expect(platform.saved.currentPlayers).to.deep.equal([B]);
expect(platform.saved.newTurn).to.be.true;
const announced = wrapper.messages(platform.saved);
expect(announced.messages).to.have.length(1);
expect(announced.messages[0]).to.contain('bid of $3 and receives $6');
expect(wrapper.messages(wrapper.replay(cloneDeep(announced.data))).messages).to.deep.equal([]);
// The saved log never shrank across committed states
for (let i = 1; i < platform.logLengths.length; i++) {
expect(platform.logLengths[i]).to.be.at.least(platform.logLengths[i - 1]);
}
});
it('should let the auctioneer decline as a committed turn', async () => {
// Same script as above up to the auction, then decline instead of accept
const platform = new Platform();
const A = platform.saved.currentPlayers[0];
const B = 1 - A;
await platform.send(
[
{
name: MoveName.BuyFromFactory,
data: { player: B, piece: platform.saved.players[B].containersOnFactoryStore[0].piece },
extraData: { price: 2 },
},
pass,
],
A
);
await platform.send(
[
{
name: MoveName.BuyFromFactory,
data: { player: A, piece: platform.saved.players[A].containersOnFactoryStore[0].piece },
extraData: { price: 2 },
},
pass,
],
B
);
await platform.send(
[
{ name: MoveName.Sail, data: `playerHarbor${B}1` as ShipPosition },
{
name: MoveName.BuyFromWarehouse,
data: { player: B, piece: platform.saved.players[B].containersOnWarehouseStore[0].piece },
},
pass,
],
A
);
await platform.send([pass], B);
await platform.send(
[
{ name: MoveName.Sail, data: ShipPosition.OpenSea },
{ name: MoveName.Sail, data: ShipPosition.Island },
],
A
);
await platform.send([{ name: MoveName.Bid, data: true, extraData: { price: 3 } }], B);
const moneyBefore = platform.saved.players[A].money;
const decline = await platform.send([{ name: MoveName.Decline, data: true }], A);
expect(decline.saved).to.be.true;
expect(platform.saved.phase).to.equal(Phase.Move);
// Declining: A pays the highest bid and keeps the containers on their island
expect(platform.saved.players[A].money).to.equal(moneyBefore - 3);
expect(platform.saved.players[A].containersOnIsland).to.have.length(1);
expect(platform.saved.currentPlayers).to.deep.equal([B]);
});
it('should replay a state saved mid-bid-phase without dropping hidden log moves', async () => {
const platform = new Platform(3, 'wrapper-test-replay');
const { B, C } = await playToBidPhase(platform);
// One bid placed, plus a bid-phase loan: both live in the hidden log of the
// saved state (they are only flushed once the accept/decline phase starts)
await platform.send([{ name: MoveName.Bid, data: true, extraData: { price: 3 } }], B);
await platform.send([getLoan], C);
expect(platform.saved.hiddenLog).to.have.length(2);
expect(platform.saved.phase).to.equal(Phase.Bid);
// An admin full-replay of that save must reproduce it exactly, hidden bids included
const replayed = wrapper.replay(cloneDeep(platform.saved));
expect(JSON.parse(JSON.stringify(replayed))).to.deep.equal(JSON.parse(JSON.stringify(platform.saved)));
expect(replayed.players[B].bid).to.equal(3);
expect(replayed.players[C].loans).to.have.length(1);
});
it('should always produce committed states from moveAI', async () => {
let G = setup(2, {}, 'wrapper-test-ai');
G.players.forEach((player, i) => {
player.name = `AI ${i}`;
player.isAI = true;
});
for (let turn = 0; turn < 25 && !wrapper.ended(G) && G.currentPlayers.length > 0; turn++) {
const logLengthBefore = wrapper.logLength(G);
G = wrapper.moveAI(G, G.currentPlayers[0]);
expect(wrapper.toSave(G), `moveAI result of turn ${turn} must be saveable`).to.not.be.undefined;
expect(wrapper.logLength(G)).to.be.at.least(logLengthBefore);
}
});
it('should always produce committed states from dropPlayer', async () => {
const G = setup(3, {}, 'wrapper-test-drop');
const dropped = G.currentPlayers[0];
const result = await wrapper.dropPlayer(G, dropped);
expect(wrapper.toSave(result)).to.not.be.undefined;
expect(result.players[dropped].isDropped).to.be.true;
expect(result.currentPlayers).to.not.include(dropped);
// The drop played the pending turn through the regular path: the next player
// got their upkeep (actions, available moves) and can actually play
expect(result.players[result.currentPlayers[0]].availableMoves).to.not.be.null;
expect(result.players[result.currentPlayers[0]].actions).to.equal(2);
});
it('should only auto-play the dropped bidder and keep the other bidders current', async () => {
const platform = new Platform(3, 'wrapper-test-drop-bid');
const { A, B, C } = await playToBidPhase(platform);
// Both B and C are deciding on their bids; dropping C must auto-play only C's
// pending bid and leave B's turn untouched
platform.saved = await wrapper.dropPlayer(platform.saved, C);
expect(wrapper.toSave(platform.saved)).to.not.be.undefined;
expect(platform.saved.phase).to.equal(Phase.Bid);
expect(platform.saved.currentPlayers).to.deep.equal([B]);
expect(platform.saved.players[B].availableMoves).to.not.be.null;
// B's bid then resolves the auction normally, with the dropped bidder excluded
const bid = await platform.send([{ name: MoveName.Bid, data: true, extraData: { price: 3 } }], B);
expect(bid.saved).to.be.true;
expect(platform.saved.phase).to.equal(Phase.AcceptDecline);
expect(platform.saved.currentPlayers).to.deep.equal([A]);
expect(platform.saved.highestBidders).to.deep.equal([B]);
});
it('should not advance the turn when dropping a player who is not up', async () => {
const platform = new Platform(3, 'wrapper-test-drop-idle');
const { A, B, C } = await playToBidPhase(platform);
// B has already bid; C is still deciding
await platform.send([{ name: MoveName.Bid, data: true, extraData: { price: 3 } }], B);
expect(platform.saved.currentPlayers).to.deep.equal([C]);
// Dropping B (not a current player) must not touch C's pending turn
platform.saved = await wrapper.dropPlayer(platform.saved, B);
expect(platform.saved.currentPlayers).to.deep.equal([C]);
expect(platform.saved.players[C].availableMoves).to.not.be.null;
// C's lower bid wins because dropped players are excluded from the auction
await platform.send([{ name: MoveName.Bid, data: true, extraData: { price: 2 } }], C);
expect(platform.saved.phase).to.equal(Phase.AcceptDecline);
expect(platform.saved.highestBidders).to.deep.equal([C]);
expect(platform.saved.currentPlayers).to.deep.equal([A]);
});
});
describe('saved analyses', () => {
it('reconstructs historical cash rather than final scores', () => {
const source = setup(3, {}, 'analysis-cash');
source.players[0].money = 999;
const copy = wrapper.createAnalysis(source, { to: 0, sourceEnded: true });
expect(copy.players.map((p) => p.money)).to.deep.equal([20, 20, 20]);
expect(source.players[0].money).to.equal(999);
const view = wrapper.analysisView(copy, { player: 0 });
expect(view.state.players[1].money).to.equal(20);
expect(view.state.players[1].pointCard).not.to.equal(null);
});
it('can continue a historical position using each current player and the real costs', async () => {
let copy = wrapper.createAnalysis(setup(3, {}, 'analysis-turns'), { to: 0, sourceEnded: true });
const actor = copy.currentPlayers[0];
copy = await wrapper.move(copy, pass, actor);
expect(copy.currentPlayers[0]).not.to.equal(actor);
const next = copy.currentPlayers[0];
copy = await wrapper.move(copy, pass, next);
expect(copy.currentPlayers[0]).not.to.equal(next);
});
});

View file

@ -1,12 +1,21 @@
import { cloneDeep } from 'lodash';
import { cloneDeep, isEqual } from 'lodash';
import seedrandom from 'seedrandom';
import type { GameState } from './index';
import { availableMoves } from './src/available-moves';
import pointCards from './src/cards';
import { canReviseBid } from './src/choice-revisions';
import * as engine from './src/engine';
import { Phase } from './src/gamestate';
import type { LogMove } from './src/log';
import { Move } from './src/move';
import { isLoanReversal, Move, MoveName } from './src/move';
import { asserts } from './src/utils';
export async function init(nbPlayers: number, expansions: string[], options: {}, seed?: string): Promise<GameState> {
return engine.setup(nbPlayers, options, seed);
return engine.setup(
nbPlayers,
expansions.includes('offshore-island') ? { ...options, offshoreIsland: true } : options,
seed
);
}
export function setPlayerMetaData(G: GameState, player: number, metaData: { name: string }) {
@ -15,14 +24,104 @@ export function setPlayerMetaData(G: GameState, player: number, metaData: { name
return G;
}
export async function move(G: GameState, move: Move, player: number) {
G = engine.move(G, move, player);
/**
* Execute the current turn of `player` so far.
*
* The payload is the **whole turn buffer**: an array of atomic moves accumulated by the
* viewer since the last committed state. `G` is always a committed state (tentative
* states are never persisted by the platform), so the buffer is replayed from it in
* order. A bare move object is also accepted and treated as a one-element buffer.
*
* While the resulting state is still tentative (the mover could undo, i.e.
* `G.newTurn === false`), `toSave` returns `undefined`: the platform then sends the
* tentative state back to the acting player without persisting it or granting a time
* increment. Undo is implemented by the viewer replaying a shortened buffer — or, when
* the buffer empties, by doing nothing at all, since the saved state *is* the turn start.
*/
export async function move(
G: GameState,
payload: Move | Move[] | null | undefined,
player: number
): Promise<GameState> {
const moves: Move[] = payload == null ? [] : Array.isArray(payload) ? payload : [payload];
if (moves.length === 0) {
// Nothing to apply — flag the result as tentative so nothing gets persisted
// and no time increment is granted.
return { ...G, newTurn: false };
}
const compacted: Move[] = [];
for (const action of moves) {
if (isLoanReversal(compacted[compacted.length - 1], action)) compacted.pop();
else compacted.push(action);
}
const before = compacted.length < moves.length ? cloneDeep(G) : undefined;
// Validate every requested move and the turn boundary before cancelling any pair.
// Historical replay deliberately keeps the original atomic engine semantics.
for (let i = 0; i < moves.length; i++) {
G = engine.move(G, moves[i], player);
// The buffer must describe at most ONE turn: committing is what grants the
// mover their per-turn time increment. Without this guard a buffer like
// `[..., Pass, ...more]` — legal in the degenerate case where the same player
// is up again because everyone else dropped — would replay across the turn
// boundary and commit several turns for a single increment.
if (G.newTurn !== false && i < moves.length - 1) {
throw new Error('The turn buffer continues past a turn boundary: only one turn may be played per call');
}
}
return before ? move(before, compacted, player) : G;
}
/**
* Only committed states are persisted. Tentative states (mid-turn, still undoable)
* return `undefined` so the platform neither saves them nor grants a time increment.
*/
export function toSave(G: GameState): GameState | undefined {
return G.newTurn === false ? undefined : G;
}
export const canMoveOutOfTurn = canReviseBid;
export const isLiveUpdate = (G: GameState): boolean => G.liveUpdate === true;
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';
/**
* Play a full turn for `player`. The engine's own `moveAI` plays one atomic move at a
* time, which can leave the state tentative (`toSave` would refuse to persist it); the
* platform's bot driver and `dropPlayer` auto-play both require committed states, so we
* keep playing until the turn commits.
*/
export function moveAI(G: GameState, player: number): GameState {
for (let i = 0; i < 500 && !engine.ended(G) && G.currentPlayers.includes(player); i++) {
G = engine.moveAI(G, player);
if (G.newTurn !== false) {
return G;
}
}
// Safety net — should be unreachable (Pass is always available in the move phase
// and commits the turn). The state is consistent (every atomic move was legal and
// logged), it just did not reach a turn boundary; persisting it keeps the game
// going instead of wedging it. Shout so a would-be livelock is visible in the
// server logs instead of being silently masked.
console.error(
`moveAI: force-committing after 500 moves without reaching a turn boundary (player ${player}, phase ${G.phase}, round ${G.round})`
);
G.newTurn = true;
return G;
}
export { ended, scores, stripSecret } from './src/engine';
export function rankings(G: GameState) {
const sortedPlayers = cloneDeep(G.players)
.sort((p1, p2) => {
@ -38,7 +137,33 @@ export function rankings(G: GameState) {
return G.players.map((pl) => sortedPlayers.indexOf(pl.id) + 1);
}
export function replay(G: GameState) {
/**
* Rebuild the state from its seed and logged moves.
*
* With `to`, rebuild the earlier position after the first `to` visible log entries instead,
* as BGS does to take back moves (undo against bots, admin replays); its undo checks that
* `logLength` is then `to`. Hidden-log moves (sealed bids, bid-phase loans) all come after
* the whole visible log, so they are left out: replaying to the visible length of a
* running auction reopens it with no bids. `to` 0 gives the initial position, whose log
* already holds the game start.
*/
export function replay(G: GameState, options?: { to?: number }): GameState {
if (options?.to !== undefined) {
const { to } = options;
if (!Number.isInteger(to) || to < 0 || to > G.log.length) throw new Error('Invalid history position');
const copy = cloneDeep(G);
const log = copy.log.slice(0, to);
return replay({
...copy,
log,
hiddenLog: [],
// As saved back then: reached by a regular move (sealed-bid replacements, the only
// live updates, never reach the visible log), its announcements already made.
liveUpdate: log.some((entry) => entry.type === 'move') ? false : undefined,
pendingMessages: undefined,
});
}
const oldPlayers = G.players;
const oldG = G;
@ -49,12 +174,22 @@ export function replay(G: GameState) {
G.players[i].name = oldPlayers[i].name;
}
for (const move of oldG.log.filter((event) => event.type === 'move')) {
// The visible log freezes during the bid phase: bids and bid-phase loans go to
// `G.hiddenLog` and are only flushed to `G.log` when the accept/decline phase
// starts. A state saved mid-bid therefore keeps its newest moves in `hiddenLog`,
// and whenever `hiddenLog` is non-empty it holds exactly the moves made after the
// last visible entry, in order — so replaying the visible log followed by the
// hidden log reproduces the state faithfully.
for (const move of [...oldG.log, ...(oldG.hiddenLog ?? [])].filter((event) => event.type === 'move')) {
asserts<LogMove>(move);
G = engine.move(G, move.move, move.player);
}
G.liveUpdate = oldG.liveUpdate;
// Reconstructing history must not announce old auctions again.
if (oldG.pendingMessages) G.pendingMessages = [...oldG.pendingMessages];
else delete G.pendingMessages;
return G;
}
@ -63,9 +198,42 @@ export function round(G: GameState) {
}
export async function dropPlayer(G: GameState, player: number) {
G.liveUpdate = false;
G.players[player].isDropped = true;
engine.nextPlayer(G);
// Auto-play only the dropped player's own pending decision, if any. Everything
// else — in particular the other simultaneous bidders' turns during an auction —
// stays untouched: from here on the engine itself skips dropped players
// (`nextPlayer` recursion, the `!isDropped` filters in the auction logic).
if (G.currentPlayers.includes(player)) {
switch (G.phase) {
case Phase.BankDecision:
while (G.phase === Phase.BankDecision && G.currentPlayers.includes(player))
G = engine.moveAI(G, player);
break;
case Phase.Bid:
// A dropped bidder bids nothing (also covers the additional-bid round)
G = engine.move(G, { name: MoveName.Bid, data: true, extraData: { price: 0 } }, player);
break;
case Phase.AcceptDecline:
// A dropped auctioneer accepts the highest bid (Accept is always
// available; Decline requires enough money to pay the bid)
G = engine.move(G, { name: MoveName.Accept, data: G.highestBidders[0] }, player);
break;
default:
// Move phase: the dropped player simply passes, which advances the
// turn through the regular path (upkeep, next player's actions, ...)
G = engine.move(G, { name: MoveName.Pass, data: true }, player);
break;
}
}
// Dropping a player always yields a committed state: tentative states are never
// persisted, so `G` was committed to begin with, and the auto-played moves above
// (Bid / Accept / Pass) are all turn-boundary moves.
G.newTurn = true;
return G;
}
@ -75,10 +243,10 @@ export function currentPlayer(G: GameState) {
}
export function messages(G: GameState) {
return {
messages: [],
data: G,
};
if (G.newTurn === false || !G.pendingMessages?.length) return { messages: [], data: G };
const data = { ...G };
delete data.pendingMessages;
return { messages: [...G.pendingMessages], data };
}
export function logLength(G: GameState, _player?: number) {
@ -88,12 +256,159 @@ export function logLength(G: GameState, _player?: number) {
export function logSlice(G: GameState, options?: { player?: number; start?: number; end?: number }) {
const stripped = engine.stripSecret(G, options?.player);
return {
// The full (stripped) state. This is how the acting player's viewer receives
// tentative states: they are never persisted or broadcast, only returned in the
// move response's log slice.
state: stripped,
log: stripped.log.slice(options?.start, options?.end),
availableMoves:
options?.end === undefined
? stripped.players.map((pl) => pl.availableMoves)
: engine
.stripSecret(replay({ ...G, log: G.log.slice(0, options!.end) }), options!.player)
// Replaying a *truncated* log reconstructs a historical state, so
// the hidden log (whose moves all come after the full visible log)
// must not be appended to it.
.stripSecret(replay({ ...G, log: G.log.slice(0, options!.end), hiddenLog: [] }), options!.player)
.players.map((pl) => pl.availableMoves),
};
}
export function createAnalysis(G: GameState, options: { to: number; sourceEnded: boolean }): GameState {
if (options.to < 0 || options.to > G.log.length) throw new Error('Invalid history position');
const copy = replay({ ...cloneDeep(G), log: G.log.slice(0, options.to), hiddenLog: [] });
for (const player of copy.players) {
player.isAI = false;
player.isDropped = false;
}
copy.newTurn = true;
return copy;
}
export function analysisView(G: GameState, options: { player: number; start?: number; end?: number }) {
const state = cloneDeep(G);
return {
state,
log: {
state,
log: state.log.slice(options.start, options.end),
availableMoves: state.players.map((p) => p.availableMoves),
},
};
}
function observedCash(G: GameState, seed: string): number[] | undefined {
if (G.analysisCash) return G.analysisCash;
try {
let replayed = engine.setup(G.players.length, G.options, seed);
const factories = [
...replayed.factoriesLeft,
...replayed.players.reduce((all, p) => all.concat(p.factories), [] as typeof replayed.factoriesLeft),
];
const containers = [
...replayed.containersLeft,
...(replayed.offshoreBank?.containerLots.reduce(
(all, lot) => all.concat(lot),
[] as typeof replayed.containersLeft
) || []),
...replayed.players.reduce(
(all, p) => all.concat(p.containersOnFactoryStore.map((c) => c.piece)),
[] as typeof replayed.containersLeft
),
];
for (const p of replayed.players) {
const color = G.players[p.id].factories[0].color;
const factory = factories.find((f) => f.color === color && f.id === G.players[p.id].factories[0].id)!;
factories.splice(factories.indexOf(factory), 1);
const container = containers
.filter((c) => c.color === color)
.sort((a, b) => Number(a.id.slice(1)) - Number(b.id.slice(1)))[0];
containers.splice(containers.indexOf(container), 1);
p.factories = [factory];
p.containersOnFactoryStore = [{ piece: container, price: 2, moved: false }];
p.actions = p.id === G.startingPlayer ? 2 : 0;
}
if (replayed.offshoreBank) {
replayed.offshoreBank.initialContainerLots = cloneDeep(G.offshoreBank!.initialContainerLots);
replayed.offshoreBank.containerLots = cloneDeep(G.offshoreBank!.initialContainerLots);
for (const piece of replayed.offshoreBank.containerLots.reduce(
(all, lot) => all.concat(lot),
[] as typeof replayed.containersLeft
)) {
const i = containers.findIndex((c) => c.id === piece.id);
if (i < 0) return undefined;
containers.splice(i, 1);
}
}
replayed.factoriesLeft = factories;
replayed.containersLeft = containers;
replayed.startingPlayer = G.startingPlayer;
replayed.currentPlayers = [G.startingPlayer];
for (const p of replayed.players)
p.availableMoves = replayed.currentPlayers.includes(p.id) ? availableMoves(replayed, p) : null;
for (const entry of G.log) {
if (entry.type === 'move') replayed = engine.move(replayed, entry.move, entry.player);
}
for (const p of replayed.players) {
const actual = G.players[p.id];
for (const key of [
'factories',
'warehouses',
'ship',
'containersOnFactoryStore',
'containersOnWarehouseStore',
'containersOnIsland',
'bankHolding',
'offshoreStats',
] as const) {
if (!isEqual(p[key], actual[key])) return undefined;
}
}
if (G.offshoreBank && !isEqual(G.offshoreBank, replayed.offshoreBank)) return undefined;
return replayed.players.map((p, i) => p.money + (G.players[i].loans.length - p.loans.length) * 10);
} catch {
return undefined;
}
}
export function createAnalysisScenario(G: GameState, { player, seed }: { player?: number; seed: string }): GameState {
if (G.newTurn === false) throw new Error('Analysis requires a committed turn');
const copy = cloneDeep(engine.stripSecret(G, player));
const rng = seedrandom(seed);
const cash = observedCash(G, seed);
if (!cash || cash.some((amount) => !Number.isFinite(amount) || amount < 0))
throw new Error('Cannot reconstruct public cash balances safely');
copy.analysisCash = cash;
const cards = cloneDeep(pointCards).filter((card) => !isEqual(card, copy.players[player!]?.pointCard));
copy.seed = seed;
copy.hiddenLog = [];
copy.log = [];
copy.newTurn = true;
for (const p of copy.players) {
p.isAI = false;
p.isDropped = false;
delete p.finalScoreBreakdown;
if (p.id !== player) {
p.pointCard = cards.splice(Math.floor(rng() * cards.length), 1)[0];
if (cash[p.id] < p.bid + p.additionalBid) throw new Error('Public bids contradict reconstructed cash');
p.money = cash[p.id];
p.lastMove = null;
if (!p.showBid)
p.bid =
G.phase === Phase.Bid && !copy.currentPlayers.includes(p.id) && p.id !== copy.auctioningPlayer
? Math.floor(rng() * (p.money + 1))
: 0;
if (!p.showAdditionalBid)
p.additionalBid =
G.phase === Phase.Bid && copy.highestBidders.includes(p.id) && !copy.currentPlayers.includes(p.id)
? Math.floor(rng() * (p.money - p.bid + 1))
: 0;
}
}
for (const p of copy.players)
p.availableMoves = copy.currentPlayers.includes(p.id) ? availableMoves(copy, p) : null;
return copy;
}
export function canLaunchAnalysisMode(G: GameState): boolean {
return G.newTurn !== false && observedCash(G, 'analysis-eligibility') !== undefined;
}

View file

@ -4,13 +4,14 @@
"lint-staged": "lint-staged",
"postinstall": "husky install",
"prettier": "prettier --plugin-search-dir=. --write .",
"prettier-check": "prettier --plugin-search-dir=. --check ."
"prettier-check": "prettier --plugin-search-dir=. --check .",
"test:locales": "node scripts/check-locales.mjs viewer/src/localization && node --test scripts/localization.test.mjs"
},
"devDependencies": {
"husky": "^5.0.9",
"lint-staged": "^10.5.4",
"prettier": "^2.2.1",
"prettier-plugin-organize-imports": "^1.1.1",
"prettier-plugin-organize-imports": "^3.2.4",
"typescript": "^4.1.5"
},
"lint-staged": {

7719
pnpm-lock.yaml generated

File diff suppressed because it is too large Load diff

View file

@ -1,3 +1,19 @@
packages:
- 'viewer'
- 'engine'
# esbuild installs and validates the platform binary used by Vite. Other listed
# dependency lifecycle scripts are unnecessary for this workspace.
allowBuilds:
esbuild: true
'@parcel/watcher': false
core-js: false
ejs: false
fsevents: false
nodent-runtime: false
yorkie: false
# Keep peer dependencies explicit and frozen installs reproducible.
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 || 0.11.0'

38
scripts/check-locales.mjs Normal file
View file

@ -0,0 +1,38 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
const directory = process.argv[2];
if (!directory) {
throw Error('Usage: node check-locales.mjs <localization directory>');
}
const source = JSON.parse(await readFile(join(directory, 'en.json'), 'utf8'));
const placeholders = (text) => [...text.matchAll(/\{\w+\}/g)].map((match) => match[0]).sort();
const locales = [
'en',
'de',
'fr',
'pl',
'ro',
'el',
'hi',
'ru',
'da',
'pt-BR',
'ko',
'zh-TW',
'zh-CN',
'vi',
'it',
'nl',
'fa',
];
for (const locale of locales) {
const catalog = JSON.parse(await readFile(join(directory, `${locale}.json`), 'utf8'));
assert.deepEqual(Object.keys(catalog).sort(), Object.keys(source).sort(), `${locale}: missing or extra strings`);
for (const [key, text] of Object.entries(catalog)) {
assert.equal(typeof text, 'string', `${locale}: ${key}`);
assert.ok(text.trim(), `${locale}: empty translation of ${key}`);
assert.deepEqual(placeholders(text), placeholders(source[key]), `${locale}: changed placeholders in ${key}`);
}
}
console.log(`${locales.length} languages × ${Object.keys(source).length} messages validated`);

View file

@ -0,0 +1,178 @@
#!/usr/bin/env python3
"""Original Container industrial geometry. Python 3.12, CairoSVG 2.8.2, Pillow 11.3.0.
Run from any directory; SVGs are the editable sources, PNGs the upload inputs.
No network inputs, fonts, randomness, or third-party artwork.
"""
import hashlib
import io
import json
import math
import re
from pathlib import Path
import cairosvg
from PIL import Image, ImageDraw
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / 'docs/achievement-art'
INK, PAPER, GOLD, TEAL = '#132e3b', '#f5e8ce', '#f4b34a', '#58bab4'
COLORS = ['#e98437', '#976444', '#f5e8ce', '#31414a', '#c7a16c']
def path(d, fill=INK, stroke=None, width=3):
return f'<path d="{d}" fill="{fill}"' + (f' stroke="{stroke}" stroke-width="{width}" stroke-linejoin="round" stroke-linecap="round"' if stroke else '') + '/>'
def rect(x, y, w, h, fill, stroke=INK, width=2):
return f'<rect x="{x}" y="{y}" width="{w}" height="{h}" fill="{fill}" stroke="{stroke}" stroke-width="{width}"/>'
def group(content, x=0, y=0, scale=1):
return f'<g transform="translate({x} {y}) scale({scale})">{content}</g>'
def cargo(x, y, color=0, w=15, h=13, pattern=False):
s = rect(x, y, w, h, COLORS[color], PAPER if color == 3 else INK, 1.5)
if pattern:
# Distinct redundant patterns for the five actual game colors.
d = [f'M{x+3} {y+h-3} L{x+w-3} {y+3}', f'M{x+3} {y+3} L{x+w-3} {y+h-3}', f'M{x+w/2} {y+2} V{y+h-2}', f'M{x+3} {y+h/2} H{x+w-3}', f'M{x+3} {y+3} L{x+w/2} {y+h-3} L{x+w-3} {y+3}'][color]
s += path(d, 'none', PAPER if color in (1, 3) else INK, 2)
else:
s += path(f'M{x+w/3} {y+3} V{y+h-3} M{x+2*w/3} {y+3} V{y+h-3}', 'none', PAPER if color == 3 else INK, 1)
return s
def flag(x, y):
return path(f'M{x} {y+25} V{y}', 'none', PAPER, 3) + path(f'M{x+2} {y} H{x+24} L{x+17} {y+7} L{x+24} {y+14} H{x+2} Z', GOLD)
def ship(full=False):
s = path('M20 75 H109 L96 91 H34 Z', PAPER, INK, 2)
s += rect(24, 52, 15, 22, TEAL) + rect(27, 46, 6, 6, PAPER)
s += rect(27, 57, 8, 6, INK, INK, 0)
if full:
s += ''.join(cargo(41+i*13, 60, i, 12, 14) for i in range(5))
else:
s += cargo(43, 59, 0, 22, 15) + cargo(67, 59, 4, 22, 15)
return s + path('M28 99 H48 L54 95 H75 L81 99 H101', 'none', TEAL, 3)
def factory(x, y, scale=1):
s = rect(3, 0, 6, 23, GOLD) + path('M0 17 L12 9 V17 L24 9 V33 H0 Z', PAPER, INK, 2)
s += rect(5, 23, 5, 10, TEAL) + rect(15, 23, 5, 10, TEAL)
return group(s, x, y, scale)
def warehouse(x, y, scale=1):
return group(path('M0 12 L14 0 L28 12 V34 H0 Z', PAPER, INK, 2) + rect(6, 16, 16, 18, TEAL) + path('M9 22 H19 M9 27 H19', 'none', INK, 2), x, y, scale)
def check(x, y, scale=1):
return group(path('M0 10 L8 18 L25 0', 'none', TEAL, 6), x, y, scale)
def ledger():
return rect(35, 28, 58, 70, PAPER, GOLD, 3) + path('M45 43 H81 M45 53 H74 M45 63 H68', 'none', INK, 4) + check(53, 73)
def number(n, x, y, scale=1):
# Hand-drawn geometric digits; never dependent on installed fonts.
digits = {'0': 'M0 0 H8 V14 H0 Z', '1': 'M1 3 L5 0 V14 M1 14 H9', '5': 'M9 0 H0 V7 H8 V14 H0'}
return group(''.join(group(path(digits[c], 'none', PAPER, 2.5), i*14) for i, c in enumerate(str(n))), x, y, scale)
def composition(id):
if id == 'win':
return flag(57, 23) + ship()
if id.startswith('win-'):
n = {'win-three-player': 3, 'win-four-player': 4, 'win-five-player': 5}[id]
s = ''
# Separate company quay-and-office units; exactly n, not cargo counters.
for i in range(n):
a = -math.pi/2 + i*2*math.pi/n
x, y = 64+39*math.cos(a), 62+37*math.sin(a)
s += group(rect(-10, -9, 20, 18, PAPER) + rect(-6, -5, 4, 5, INK) + rect(2, -5, 4, 5, INK) + rect(-8, 9, 16, 8, GOLD), round(x, 2), round(y, 2))
return s + group(ship(), 29, 16, .55) + group(flag(0, 0), 76, 35, .65)
if id == 'debt-free-win':
return group(ledger(), 49, 0, .68) + flag(27, 28) + group(ship(), 0, 23, .90)
if id == 'debt-free':
return ledger() + path('M26 37 H20 V103 H81 V107', 'none', TEAL, 3)
if id.startswith('score-'):
high = id == 'score-150'
s = ''
if high:
s += factory(28, 20, .8) + factory(53, 14, .9) + factory(82, 24, .7)
else:
s += cargo(40, 26, 0, 22, 17) + rect(70, 26, 20, 17, GOLD) + path('M75 34 H85', 'none', INK)
s += path('M22 52 L61 47 L64 52 L67 47 L106 52 V88 L67 83 L64 88 L61 83 L22 88 Z', PAPER, INK, 3)
s += path('M64 54 V81 M30 61 H52 M30 71 H52 M76 61 H97 M76 71 H97', 'none', TEAL, 4)
if high:
s += rect(22, 87, 17, 7, GOLD) + rect(89, 87, 17, 7, GOLD)
return s + number(150 if high else 100, 45, 96, .95)
if id.endswith('factories'):
n = 3 if id.startswith('three') else 4
if n == 3:
return path('M39 73 L64 40 L90 73 Z', 'none', TEAL, 5) + factory(52, 21) + factory(22, 69) + factory(82, 69)
return path('M41 43 H86 V87 H41 Z', 'none', TEAL, 5) + ''.join(factory(x, y, .95) for x, y in [(26, 22), (78, 22), (26, 73), (78, 73)])
if id.endswith('warehouses'):
if id.startswith('three'):
return path('M23 94 H106', 'none', GOLD, 5) + ''.join(warehouse(x, 48) for x in (20, 50, 80))
return path('M39 41 H88 V90 H39 Z', 'none', GOLD, 5) + ''.join(warehouse(x, y, .75) for x, y in [(28, 26), (53, 21), (78, 26), (29, 76), (78, 76)])
if id.startswith('island-'):
s = path('M17 70 L27 40 L63 29 L101 44 L111 76 L95 96 L37 99 Z', TEAL, PAPER, 3)
s += path('M21 104 H43 M85 104 H104', 'none', TEAL, 3)
if id == 'island-diversity':
for i, (x,y) in enumerate([(36,43), (67,43), (24,68), (54,68), (84,68)]):
s += cargo(x,y,i,21,19,True)
else:
n = 15 if id == 'island-fifteen' else 10
for i in range(n):
s += cargo(27+(i%5)*15, 43+(i//5)*17, i%5, 13, 14)
s += rect(47, 96, 35, 20, INK, INK, 0) + number(n, 51, 98)
return s
if id == 'full-ship':
return ship(True) + path('M43 47 H104 M43 43 V51 M104 43 V51', 'none', GOLD, 3)
if id == 'warehouse-five':
s = path('M17 49 L64 24 L111 49 V99 H17 Z', PAPER, INK, 3)
s += path('M25 49 H103 M24 93 H104', 'none', TEAL, 4)
s += ''.join(cargo(24+i*16, 67, i, 15, 21) for i in range(5))
return s
raise ValueError(id)
def main():
OUT.mkdir(parents=True, exist_ok=True)
source = (ROOT / 'engine/src/achievements.ts').read_text()
ids = re.findall(r"^ \['([^']+)',", source, re.M)
assert len(ids) == 17 and len(set(ids)) == 17
entries = []
for id in ids:
key = f'achievement-{id}'
svg = '<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 128 128">'
svg += '<circle cx="64" cy="64" r="62" fill="'+INK+'" stroke="'+GOLD+'" stroke-width="3"/>'
svg += composition(id) + '</svg>\n'
(OUT / f'{key}.svg').write_text(svg)
png = cairosvg.svg2png(bytestring=svg.encode(), output_width=256, output_height=256)
(OUT / f'{key}.png').write_bytes(png)
entries.append({'id': id, 'key': key, 'svg': f'{key}.svg', 'png': f'{key}.png', 'svgSha256': hashlib.sha256(svg.encode()).hexdigest(), 'pngSha256': hashlib.sha256(png).hexdigest()})
manifest = {'game': 'container', 'engineVersion': '2.1.10', 'revision': 3, 'baseline': '99e60d5e8f4111f0435d9ea911e2431ec8ef2f7f', 'issue': 'https://codeberg.org/boardgamers/boardgamers/issues/595', 'license': 'MIT', 'provenance': 'Original programmatic geometric compositions; no external artwork or fonts. Palette follows the five ContainerColor identities in engine/src/gamestate.ts, not commercial artwork.', 'generator': 'scripts/generate-achievement-art.py', 'generatorSha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), 'assets': entries}
(OUT / 'manifest.json').write_text(json.dumps(manifest, indent=4)+'\n')
for size in (32, 48, 64):
row_h = max(58, size+12)
sheet = Image.new('RGB', (880, row_h*len(entries)+34), '#c8cdd0')
draw = ImageDraw.Draw(sheet)
draw.text((12, 10), f'CONTAINER / {size}px actual size / light + dark circular badges', fill=INK)
for i, entry in enumerate(entries):
y = 34+i*row_h
draw.rectangle((0,y,439,y+row_h), fill='#faf7ee')
draw.rectangle((440,y,879,y+row_h), fill='#111a22')
icon = Image.open(OUT/entry['png']).convert('RGBA').resize((size,size), Image.Resampling.LANCZOS)
for x, textcolor in [(12,INK), (452,'#f5e8ce')]:
sheet.paste(icon, (x,y+6), icon)
draw.text((x+size+16,y+size//2), entry['id'], fill=textcolor)
sheet.save(OUT / f'contact-sheet-{size}.png')
print(f'Generated {len(entries)} original SVG + PNG pairs and 32/48/64px sheets in {OUT}')
if __name__ == '__main__':
main()

View file

@ -0,0 +1,73 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import test from 'node:test';
const source = await readFile(new URL('../viewer/src/localization/runtime.js', import.meta.url), 'utf8');
const { createTranslator, resolveLocale } = await import(
'data:text/javascript;base64,' + Buffer.from(source).toString('base64')
);
const catalogs = {
nl: {
Draw: 'Tekenen',
'Your cash: $': 'Je geld: $',
Ore: 'Erts',
east: 'oost',
'{p0} · ◈ {p1}': '{p0} · ◈ {p1}',
Round: 'Ronde',
'Build {p0} for {p1}': 'Bouw voor {p1}: {p0}',
'{p0} buys {p1}': '{p0} koopt {p1}',
'Make money by trading': 'Verdien geld door te handelen',
'Gain {p0} points{p1}': 'Krijg {p0} punten{p1}',
},
fr: { Round: 'Manche' },
};
test('regional language preferences select supported catalogues', () => {
assert.equal(resolveLocale('nl-BE'), 'nl');
assert.equal(resolveLocale('fa-IR'), 'fa');
assert.equal(resolveLocale('pt-PT'), 'pt-BR');
assert.equal(resolveLocale('zh-Hant-TW'), 'zh-TW');
assert.equal(resolveLocale('zh-CN'), 'zh-CN');
assert.equal(resolveLocale(undefined), 'en');
});
test('dynamic values are reordered while player names stay unchanged', () => {
const t = createTranslator(catalogs, 'nl');
t.setNames(['Draw']);
assert.equal(t.translate('Draw buys 3'), 'Draw koopt 3');
assert.equal(t.translate('Build 2 for 10'), 'Bouw voor 10: 2');
assert.equal(t.translate('Draw'), 'Draw');
assert.equal(t.translate('Gain 2 points'), 'Krijg 2 punten');
});
test('tutorial numbering and whitespace survive translation', () => {
const t = createTranslator(catalogs, 'nl');
assert.equal(t.translate(' 1/5 · Make money by trading\n'), ' 1/5 · Verdien geld door te handelen\n');
assert.equal(t.translate('Round 2'), 'Ronde 2');
assert.equal(t.translate('Unknown sentence'), 'Unknown sentence');
});
test('language changes clear caches and preserve the English fallback', () => {
const t = createTranslator(catalogs, 'nl');
assert.equal(t.translate('Round'), 'Ronde');
t.setLocale('fr');
assert.equal(t.translate('Round'), 'Manche');
t.setLocale('en');
assert.equal(t.translate('Round'), 'Round');
});
test('icon-separated values and uppercase labels are localized', () => {
const t = createTranslator(catalogs, 'nl');
assert.equal(t.translate('Ore · ◈ 10'), 'Erts · ◈ 10');
assert.equal(t.translate('EAST'), 'OOST');
});
test('decorative arrows and attached currency values keep their meaning', () => {
const t = createTranslator(catalogs, 'nl');
assert.equal(t.translate('Draw →'), 'Tekenen →');
assert.equal(t.translate('Your cash: $20'), 'Je geld: $20');
});
test('Simplified Chinese aliases preserve Traditional Chinese preferences', () => {
for (const tag of ['zh', 'zh-CN', 'zh_CN', 'zh-SG', 'zh-Hans', 'zh-Hans-CN']) {
assert.equal(resolveLocale(tag), 'zh-CN');
}
for (const tag of ['zh-TW', 'zh-HK', 'zh-MO', 'zh-Hant', 'zh-Hant-CN']) {
assert.equal(resolveLocale(tag), 'zh-TW');
}
});

View file

@ -0,0 +1,46 @@
#!/usr/bin/env python3
"""Verify artwork bytes, dimensions, coverage, and unchanged authoritative rules."""
import hashlib
import json
import re
import subprocess
from pathlib import Path
from PIL import Image
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / 'docs/achievement-art'
manifest = json.loads((OUT / 'manifest.json').read_text())
source = (ROOT / 'engine/src/achievements.ts').read_text()
baseline = subprocess.check_output(['git', 'show', manifest['baseline']+':engine/src/achievements.ts'], cwd=ROOT, text=True)
# Historical definitions stay byte-for-byte; strip only the two additive expansion rules
# before comparing the full historical evaluator. Artwork provenance remains revision 3.
assert source.split('export function achievementDefinitions')[0] == baseline.split('export function achievementDefinitions')[0]
historical_evaluator = re.sub(
r" \['offshore-win',.*?\n \],\n",
'', source.split('/** Money is already')[1], flags=re.S)
assert historical_evaluator == baseline.split('/** Money is already')[1]
ids = re.findall(r"^ \['([^']+)',", source, re.M)
assert [a['id'] for a in manifest['assets']] == ids
assert len(ids) == len(set(ids)) == 17
assert 'island-fifteen' in ids and not {'island-five', 'warehouse-six'} & set(ids)
assert manifest['revision'] == 3 and manifest['engineVersion'] == '2.1.10'
# This manifest attests the historical artwork release, not the current engine version.
assert hashlib.sha256((ROOT/manifest['generator']).read_bytes()).hexdigest() == manifest['generatorSha256']
hashes = set()
for a in manifest['assets']:
assert a['key'] == 'achievement-'+a['id']
for ext in ('svg', 'png'):
file = OUT / a[ext]
assert file.name == a['key']+'.'+ext
assert hashlib.sha256(file.read_bytes()).hexdigest() == a[ext+'Sha256']
with Image.open(OUT/a['png']) as im:
im.load()
assert im.size == (256, 256) and im.mode == 'RGBA'
assert im.getpixel((0,0))[3] == 0
hashes.add(hashlib.sha256(im.tobytes()).hexdigest())
assert len(hashes) == 17
for size in (32,48,64):
with Image.open(OUT/f'contact-sheet-{size}.png') as im:
im.load()
assert im.width == 880
print('PASS: 17 historical IDs and base evaluator unchanged; refs, source hashes, unique decoded 256px assets, 32/48/64px sheets')

View file

@ -0,0 +1,58 @@
// Usage: node scripts/test-packed-achievement-art.cjs /absolute/path/to/extracted/package
// The extracted package needs its installed runtime dependencies resolvable.
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const root = path.resolve(__dirname, '..');
const packed = path.resolve(process.argv[2]);
const hooks = require(path.join(packed, 'dist/wrapper.js'));
const { setup } = require(path.join(packed, 'dist/index.js'));
const manifest = require(path.join(root, 'docs/achievement-art/manifest.json'));
assert.equal(
require(path.join(packed, 'package.json')).version,
require(path.join(root, 'engine/package.json')).version
);
const definitions = hooks.achievementDefinitions();
assert.equal(definitions.revision, 4);
const historical = definitions.achievements.filter((a) => !a.id.startsWith('offshore-'));
const expansion = definitions.achievements.filter((a) => a.id.startsWith('offshore-'));
assert.deepEqual(
expansion.map((a) => [a.id, a.icon]),
[
['offshore-win', { type: 'text', text: 'OI' }],
['offshore-trader', { type: 'text', text: 'BANK' }],
]
);
assert.deepEqual(
historical.map((a) => a.id),
manifest.assets.map((a) => a.id)
);
for (const a of historical) {
assert.deepEqual(a.icon, { type: 'asset', key: `achievement-${a.id}` });
assert.ok(fs.existsSync(path.join(root, 'docs/achievement-art', `${a.icon.key}.png`)));
}
const seedrandom = require(path.join(root, 'engine/node_modules/seedrandom'));
for (const n of [3, 4, 5]) {
const previous = Math.random;
Math.random = seedrandom(`art-packed-${n}`);
try {
let game = setup(n, {}, `art-packed-${n}`);
for (let i = 0; i < 20000 && !hooks.ended(game); i++) {
game = hooks.moveAI(game, game.currentPlayers[0]);
}
assert.ok(hooks.ended(game));
const serialized = JSON.stringify(game);
const awards = hooks.achievements(JSON.parse(serialized));
assert.equal(awards.length, n);
assert.deepEqual(hooks.achievements(hooks.replay(game)), awards);
assert.equal(JSON.stringify(game), serialized);
for (const row of awards) {
for (const id of row.earned) assert.ok(manifest.assets.some((a) => a.id === id));
}
} finally {
Math.random = previous;
}
}
console.log(
`PASS: exact extracted ${require(path.join(packed, 'package.json')).version} package, revision 4, 17 historical asset refs and 2 text badges, legal 3/4/5-player completion and replay`
);

View file

@ -1,35 +1,82 @@
# container-viewer
# Container viewer
## Project setup
Use Node.js 24 and pnpm 11. From the repository root, install with
`pnpm install --frozen-lockfile`. The workspace explicitly permits esbuild's
required platform-binary installation script.
```
yarn install
## Local development
```sh
pnpm --dir viewer serve
```
### Compiles and hot-reloads for development
Add `?offshoreIsland=1` to opt into Offshore Island in the local demo. Without that query parameter the demo remains classic. The expansion panel displays public auctions, escrow and holding areas; its bid, return-price, distribution, default and loading controls follow the engine's legal moves.
```
yarn serve
Add `?chapter=supply-chain` to open a tutorial. The other chapter IDs are
`buildings`, `selling`, `bidding`, `keep-cargo`, `scoring`,
`offshore-cargo`, `offshore-cash` and `offshore-outbid`.
The last three opt into the Offshore Island expansion; the classic lessons retain their saved progress.
Chapter cards are exported for host integration. BGS tutorial metadata must be updated separately when publishing.
Add `&locale=fr` (or another supported locale) to preview a translated lesson.
## Build and check
```sh
pnpm --dir viewer check
pnpm --dir viewer test:tutorial
pnpm --dir viewer test:unit
pnpm --dir viewer build
pnpm --dir viewer package
pnpm --dir viewer test:browser
pnpm --dir viewer test:offshore:browser
pnpm --dir viewer test:tutorial:browser
```
### Compiles and minifies for production
Browser checks use Playwright Chromium. Set `CHROMIUM_EXECUTABLE` if using an
existing installation. `pnpm --dir viewer preview:tutorial` serves the built
viewer on port 5197.
```
yarn build
```
The Vue 2 type checker needs `zod` available directly in this workspace to resolve
the protocol's schema types through pnpm's symlinks. It is a development dependency.
### Run your unit tests
## Package compatibility
```
yarn test:unit
```
The Vue 2 viewer uses Vite for development and builds; no OpenSSL legacy
provider or Vue CLI setup is needed. `build` produces the standalone demo,
while `package` produces the classic-script UMD viewer for BGS.
### Lints and fixes files
Load Vue 2 before `dist/container-viewer.umd.min.js` and include
`dist/container-viewer.css` separately; the bundle does not inject CSS. The
existing `container.launch` and `container.launchTutorial` globals are retained.
Deploy the matching `container-viewer.umd.min.locale-*.js` sidecars beside the
minified entry, keeping their filenames: non-English translations are loaded
lazily as native ES modules relative to that script URL. Serve them with a
JavaScript MIME type and allow CORS when hosting assets on another origin.
English is bundled. The readable `container-viewer.umd.js` build uses its own
`container-viewer.umd.locale-*.js` sidecars. Publish/deploy JS, CSS and matching
sidecars together (do not upload only the entry bundle).
```
yarn lint
```
## Tutorials on BGS
### Customize configuration
Upload the same JS, CSS and locale sidecars as the ordinary viewer. The `container` global exposes
both `launch` and `launchTutorial`. Complete BGS metadata is exported as `tutorialCatalog`
from `src/tutorial/lessons.ts` (`chapterSections` and `chapterCards` are also exported).
Save that payload in the BGS version's Tutorial settings, including the `sections`
array and each chapter's `section`. The six original chapters belong to **Base game**;
the three bank chapters belong to **Offshore Island**. Preserve chapter IDs and
versions when changing grouping so existing progress stays associated with its lesson.
See [Configuration Reference](https://cli.vuejs.org/config/).
Lessons run the real engine locally with deterministic opponents and private
player views. The extra lesson controls make drag actions accessible on mobile.
Chapter progress survives refresh. Playback controls return to the previous step,
replay the current step or go back to the start. No live game or chat messages are sent.
## Shared accessibility preference
The viewer follows BGS's boolean `colorBlind` preference (default `false`).
Its eye icon updates the same shared preference through `update:preference`.
Shapes identify container colours across pieces, factories, value cards, trade
controls, tutorials and the journal. Player numbers match ships, boards and
island rows. No engine state or colour identifiers are changed.
Register `{ "name": "colorBlind", "label": "Color-blind mode", "type": "checkbox", "default": false }` in the BGS viewer preferences.

View file

@ -1,3 +0,0 @@
module.exports = {
presets: ['@vue/cli-plugin-babel/preset'],
};

19
viewer/index.html Normal file
View file

@ -0,0 +1,19 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<title>Container</title>
</head>
<body>
<noscript>
<strong>Container needs JavaScript enabled to run. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<script type="module">
import process from 'process/browser';
globalThis.process = process;
import('/src/main.ts');
</script>
</body>
</html>

View file

@ -1,42 +1,61 @@
{
"name": "container-viewer",
"version": "1.1.4",
"version": "2.1.4",
"repository": {
"type": "git",
"url": "git+https://github.com/boardgamers/container.git",
"directory": "viewer"
},
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"test:unit": "vue-cli-service test:unit",
"package": "vue-cli-service build --target lib --name container-viewer src/wrapper.ts",
"prepublishOnly": "npm run package"
"serve": "vite --host 0.0.0.0",
"build": "vite build",
"test:unit": "vitest run",
"package": "vite build --mode library && vite build --mode library-readable",
"prepublishOnly": "npm run package",
"test:browser": "node scripts/protocol-smoke.mjs",
"test:offshore:browser": "node scripts/offshore-smoke.mjs",
"test:tutorial": "node --test tests/tutorial/lessons.cjs",
"check": "tsc --noEmit",
"test:tutorial:browser": "node scripts/tutorial-smoke.mjs",
"preview:tutorial": "node scripts/tutorial-preview.mjs"
},
"dependencies": {
"@boardgamers/protocol": "0.11.0",
"assert": "^2.1.0",
"container-engine": "workspace:../engine",
"core-js": "^3.6.5",
"events": "^3.3.0",
"lodash": "^4.17.19",
"process": "^0.11.10",
"regenerator-runtime": "^0.13.7",
"tslib": "^2.2.0",
"vue": "^2.6.11",
"vue": "2.7.16",
"vue-class-component": "^7.2.3",
"vue-property-decorator": "^8.4.2"
"vue-property-decorator": "^9.1.2"
},
"devDependencies": {
"@rollup/plugin-inject": "^5.0.5",
"@types/assert": "^1.4.7",
"@types/chai": "^4.2.11",
"@types/events": "^3.0.0",
"@types/lodash": "^4.14.154",
"@types/mocha": "^5.2.4",
"@types/node": "^24.0.0",
"@typescript-eslint/parser": "^4.26.1",
"@vue/cli-plugin-babel": "~4.4.0",
"@vue/cli-plugin-typescript": "~4.4.0",
"@vue/cli-plugin-unit-mocha": "~4.4.0",
"@vue/cli-service": "~4.4.0",
"@vue/test-utils": "^1.0.3",
"chai": "^4.1.2",
"@vitejs/plugin-vue2": "2.3.4",
"@vue/test-utils": "^1.3.6",
"chai": "^4.5.0",
"csstype": "^3.2.3",
"esbuild": "0.25.12",
"eslint": "^7.28.0",
"eslint-plugin-vue": "^7.11.0",
"sass": "^1.26.5",
"sass-loader": "^8.0.2",
"typescript": "^4.3.5",
"vue-template-compiler": "^2.6.11"
"jsdom": "^28.0.0",
"playwright": "1.62.1",
"sass": "^1.97.0",
"typescript": "^5.9.3",
"vite": "7.2.0",
"vitest": "^4.1.0",
"vue-template-compiler": "2.7.16",
"zod": "^4.6.2"
},
"files": [
"src",
@ -45,6 +64,7 @@
"dist/img",
"dist/media",
"tsconfig.json",
"public/audio"
"public/audio",
"dist/container-viewer.umd.min.locale-*.js"
]
}

12309
viewer/pnpm-lock.yaml generated

File diff suppressed because it is too large Load diff

View file

@ -1,20 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<!-- <link rel="icon" href="<%= BASE_URL %>favicon.ico">-->
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<noscript>
<strong
>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript
enabled. Please enable it to continue.</strong
>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>

View file

@ -0,0 +1,50 @@
import assert from 'node:assert/strict';
export async function checkAuctionMessages(page, state) {
const accepted = "slim_shagen accepts coyotte508's bid of $10 and receives $20";
const declined = 'slim_shagen declines all bids and buys the cargo for $10';
await page.evaluate(
({ state, accepted, declined }) => {
state.players[0].name = 'slim_shagen';
state.players[1].name = 'coyotte508';
state.log = [
{
type: 'move',
player: 0,
move: { name: 'accept', data: 1 },
simple: accepted,
pretty: "<b>slim_shagen</b> accepts <b>coyotte508</b>'s bid of $10 and receives $20",
},
];
host.emit('state', state);
host.emit('chat:messages', [
{ _id: '000000050000000000000001', type: 'system', text: accepted },
{ _id: '000000050000000000000002', type: 'system', text: declined },
{ _id: '000000050000000000000003', type: 'text', author: 'coyotte508', text: accepted },
]);
host.emit('preferences', { locale: 'fr' });
},
{ state, accepted, declined }
);
await page.waitForFunction(() => document.querySelector('.journal-entry')?.textContent.includes('reçoit $20'));
await page.waitForFunction(() =>
document.querySelector('.bgs-game-chat article.system')?.textContent.includes('reçoit $20')
);
assert.match(
await page.locator('.journal-entry').textContent(),
/slim_shagen accepte l’enchère de coyotte508 de \$10 et reçoit \$20/
);
assert.match(
await page.locator('.bgs-game-chat article.system').nth(1).textContent(),
/achète la cargaison pour \$10/
);
assert.ok(
(await page.locator('.bgs-game-chat article:not(.system)').textContent()).includes(accepted),
'player messages remain untouched'
);
await page.evaluate(() => host.emit('preferences', { locale: 'en' }));
await page.waitForFunction(() =>
document.querySelector('.bgs-game-chat article.system')?.textContent.includes('bid of $10 and receives $20')
);
assert.ok((await page.locator('.journal-entry').textContent()).includes(accepted));
}

View file

@ -0,0 +1,94 @@
import assert from 'node:assert/strict';
export async function checkFinalScore(browser, origin, engine) {
const state = JSON.parse(JSON.stringify(engine.setup(5, {}, 'final-score-scroll')));
state.phase = 'gameEnd';
state.players.forEach((player, index) => {
player.name = ['You', 'Spock', 'SchweddyBalls', 'Ada', 'Last player'][index];
player.finalScoreBreakdown = Array(10).fill('$10');
});
for (const [width, height] of [
[320, 568],
[390, 620],
[844, 390],
[1400, 900],
]) {
const mobile = width < 1000;
const page = await browser.newPage({ viewport: { width, height }, isMobile: mobile, hasTouch: mobile });
const errors = [];
page.on('pageerror', (error) => errors.push(error.message));
try {
page.setDefaultTimeout(5000);
await page.goto(origin);
await page.evaluate((state) => {
window.host = window.container.launch('#app');
host.emit('preferences', { sound: false });
host.emit('player', { index: 0 });
host.emit('state', state);
}, state);
await page.locator('g.button').filter({ hasText: 'Final Score' }).click();
const dialog = page.getByRole('dialog', { name: 'Final Score' });
const bounds = await dialog.boundingBox();
assert.ok(bounds.x >= 0 && bounds.y >= 0, 'dialog starts inside the viewport');
assert.ok(bounds.x + bounds.width <= width && bounds.y + bounds.height <= height, 'dialog fits viewport');
const scroller = dialog.getByRole('region');
const metrics = () =>
scroller.evaluate((el) => ({
x: el.scrollLeft,
y: el.scrollTop,
maxX: el.scrollWidth - el.clientWidth,
maxY: el.scrollHeight - el.clientHeight,
}));
assert.equal((await metrics()).x, 0, 'category column is reachable from the start');
if (mobile) {
const cdp = await page.context().newCDPSession(page);
const box = await scroller.boundingBox();
const swipe = async (dx, dy) => {
const x = box.x + box.width / 2 - dx / 2;
const y = box.y + box.height / 2 - dy / 2;
await cdp.send('Input.dispatchTouchEvent', {
type: 'touchStart',
touchPoints: [{ x, y, id: 1 }],
});
for (let step = 1; step <= 12; step++) {
await cdp.send('Input.dispatchTouchEvent', {
type: 'touchMove',
touchPoints: [{ x: x + (dx * step) / 12, y: y + (dy * step) / 12, id: 1 }],
});
await page.waitForTimeout(20);
}
await page.waitForTimeout(100);
await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
await page.waitForTimeout(100);
};
assert.ok((await metrics()).maxX > 0, 'five-player table overflows horizontally');
assert.ok((await metrics()).maxY > 0, 'short screen needs vertical scrolling');
await swipe(-160, 0);
await page.waitForFunction(() => document.querySelector('.final-score-scroll').scrollLeft > 0);
await swipe(160, 0);
await page.waitForFunction(() => document.querySelector('.final-score-scroll').scrollLeft < 2);
for (let i = 0; i < 6 && (await metrics()).x < (await metrics()).maxX - 2; i++) await swipe(-160, 0);
const horizontal = await metrics();
assert.ok(horizontal.x >= horizontal.maxX - 2, 'last player is reachable by swiping');
await swipe(0, -140);
await page.waitForFunction(() => document.querySelector('.final-score-scroll').scrollTop > 0);
for (let i = 0; i < 6 && (await metrics()).y < (await metrics()).maxY - 2; i++) await swipe(0, -140);
const vertical = await metrics();
assert.ok(vertical.y >= vertical.maxY - 2, 'final total is reachable by swiping');
const lastCell = await dialog.locator('tr').last().locator('td').last().boundingBox();
assert.ok(
lastCell.y >= box.y && lastCell.y + lastCell.height <= box.y + box.height,
'total is visible'
);
await cdp.detach();
}
await page.screenshot({ path: `/tmp/container-final-score-${width}.png` });
await dialog.getByRole('button', { name: 'Close', exact: true }).click();
assert.equal(await dialog.isVisible(), false, 'close stays reachable after scrolling');
assert.deepEqual(errors, [], 'final score has no browser errors');
console.log(`container ${width}x${height}: final-score scrolling passed`);
} finally {
await page.close();
}
}
}

View file

@ -0,0 +1,51 @@
import assert from 'node:assert/strict';
export async function checkHostPresentation(page, hostName, screenshot) {
await page.evaluate((key) => {
window.presentationEvents = [];
for (const name of ['player:hovered', 'thumbnail:ready', 'move']) {
window[key].on(name, (data) => presentationEvents.push({ name, data }));
}
}, hostName);
const name = page.locator('[data-bgs-player]:visible').first();
await name.hover();
const index = Number(await name.getAttribute('data-bgs-player'));
await page.waitForFunction(() => presentationEvents.some((e) => e.name === 'player:hovered' && e.data));
const hover = await page.evaluate(() => presentationEvents.findLast((e) => e.name === 'player:hovered').data);
assert.equal(hover.index, index);
assert.ok(hover.anchor.width > 0 && hover.anchor.height > 0);
await name.dispatchEvent('mouseout', { relatedTarget: null });
assert.equal(await page.evaluate(() => presentationEvents.findLast((e) => e.name === 'player:hovered').data), null);
const focusable = page.locator('button[data-bgs-player]:visible, [data-bgs-player][tabindex]:visible').first();
await focusable.focus();
assert.ok(await page.evaluate(() => presentationEvents.findLast((e) => e.name === 'player:hovered').data));
await focusable.blur();
assert.equal(await page.evaluate(() => presentationEvents.findLast((e) => e.name === 'player:hovered').data), null);
await page.setViewportSize({ width: 1200, height: 900 });
await page.evaluate((key) => {
window[key].emit('preferences', { sound: false, thumbnail: true });
window[key].emit('player', {});
window[key].emit('thumbnail:render', { width: 1200, height: 630 });
}, hostName);
await page.waitForFunction(() => presentationEvents.some((e) => e.name === 'thumbnail:ready'), null, {
timeout: 5000,
});
const result = await page.evaluate(() => presentationEvents.findLast((e) => e.name === 'thumbnail:ready').data);
assert.equal(result.supported, true);
assert.deepEqual(result.bounds, { x: 0, y: 0, width: 1200, height: 630 });
assert.equal(await page.locator('.bgs-board-thumbnail').count(), 1);
assert.ok(
await page.locator('.bgs-board-thumbnail').evaluate((preview) =>
[...preview.querySelectorAll('path, rect, circle, text, image, button')].some((node) => {
const bounds = node.getBoundingClientRect();
return bounds.width > 20 && bounds.height > 10;
})
),
'the preview contains visible board content'
);
await page.locator('.bgs-board-thumbnail').screenshot({ path: screenshot });
await page.evaluate((key) => window[key].emit('thumbnail:render', { width: 1200, height: 630 }), hostName);
await page.waitForFunction(() => presentationEvents.filter((e) => e.name === 'thumbnail:ready').length === 2);
assert.equal(await page.locator('.bgs-board-thumbnail').count(), 1, 'a repeated capture replaces the previous one');
assert.equal(await page.evaluate(() => presentationEvents.filter((e) => e.name === 'move').length), 0);
}

View file

@ -0,0 +1,82 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { chromium } from 'playwright';
import ts from 'typescript';
const root = new URL('../src/', import.meta.url);
const runtime = await readFile(new URL('localization/runtime.js', root), 'utf8');
const journal = await readFile(new URL('journal-pieces.ts', root), 'utf8');
const marks = await readFile(new URL('color-blind.ts', root), 'utf8');
const js = ts.transpileModule(marks.replace(/^import .*$/gm, '') + journal.replace(/^import .*$/gm, ''), {
compilerOptions: { module: ts.ModuleKind.ES2020, target: ts.ScriptTarget.ES2020 },
}).outputText;
const catalogs = Object.fromEntries(
await Promise.all(
['en', 'fr', 'hi', 'ko', 'nl', 'fa'].map(async (locale) => [
locale,
JSON.parse(await readFile(new URL(`localization/${locale}.json`, root), 'utf8')),
])
)
);
const browser = await chromium.launch({ headless: true });
try {
const page = await browser.newPage();
await page.setContent('<div id="app"></div>');
const result = await page.evaluate(
async ({ runtime, js, catalogs }) => {
const { mountLocalization } = await import(
'data:text/javascript;base64,' + btoa(unescape(encodeURIComponent(runtime)))
);
const { journalPieces } = await import(
'data:text/javascript;base64,' + btoa(unescape(encodeURIComponent(js)))
);
const node = document.getElementById('app');
const name = '<span style="background-color: blue">Build</span>';
const other = '<span style="background-color: red">Fish</span>';
const piece = '<span style="border:1px solid black">orange</span> container';
const source = `${name} buys a ${piece} from ${other} for $3, new price is $5`;
node.innerHTML = journalPieces(source, true);
const l = mountLocalization(node, catalogs, 'fr');
const results = {};
for (const lang of ['fr', 'hi', 'ko', 'nl', 'fa', 'en', 'hi']) {
l.setLocale(lang);
await new Promise((resolve) => setTimeout(resolve, 10));
results[lang] = {
text: node.textContent,
icons: node.querySelectorAll('svg[role="img"]').length,
names: [...node.querySelectorAll('[style*="background-color"]')].map((el) => el.textContent),
};
}
node.innerHTML = journalPieces(`${name} buys a warehouse for $4`);
l.setLocale('fr');
await new Promise((resolve) => setTimeout(resolve, 10));
results.warehouse = { text: node.textContent, icons: node.querySelectorAll('svg[role="img"]').length };
node.innerHTML = journalPieces(`The bank seizes a ${piece} from ${name}'s factory`);
l.setLocale('ko');
await new Promise((resolve) => setTimeout(resolve, 10));
results.seizure = { text: node.textContent, icons: node.querySelectorAll('svg[role="img"]').length };
l.destroy();
return results;
},
{ runtime, js, catalogs }
);
assert.match(result.fr.text, /achète.*à Fish pour 3 \$, puis fixe le prix à 5 \$/);
assert.match(result.hi.text, /Build ने Fish से 3 \$ में.*खरीदा; नई कीमत: 5 \$/);
assert.match(result.ko.text, /Build: Fish에게서 \$3에.*구매, 새 가격 \$5/);
assert.match(result.nl.text, /Build koopt.*van Fish voor \$3; nieuwe prijs: \$5/);
assert.match(result.fa.text, /Build.*Fish.*3.*5/s);
assert.match(result.fa.text, /[\u0600-\u06ff]/);
assert.match(result.warehouse.text, /Build achète.*pour 4 \$/);
assert.equal(result.warehouse.icons, 1);
assert.match(result.seizure.text, /은행이 Build의 공장에서.*압류/);
assert.equal(result.seizure.icons, 1);
for (const item of ['fr', 'hi', 'ko', 'nl', 'fa', 'en'].map((lang) => result[lang])) {
assert.equal(item.icons, 1);
assert.deepEqual(item.names, ['Build', 'Fish']);
assert.doesNotMatch(item.text, /⟪|\{p\d/);
}
console.log(
'Journal translations preserve pictograms and names, reorder Hindi/Korean, and survive locale switching.'
);
} finally {
await browser.close();
}

View file

@ -0,0 +1,728 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { createServer } from 'node:http';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
import { chromium } from 'playwright';
const require = createRequire(import.meta.url);
const root = new URL('../../', import.meta.url);
const engine = require(fileURLToPath(new URL('engine/dist/index.js', root)));
const copy = (value) => JSON.parse(JSON.stringify(value));
const files = {
'/bundle.js': fileURLToPath(new URL('viewer/dist/container-viewer.umd.min.js', root)),
'/bundle.css': fileURLToPath(new URL('viewer/dist/container-viewer.css', root)),
'/vue.js': require.resolve('vue/dist/vue.min.js'),
};
const server = createServer(async (req, res) => {
try {
if (req.url === '/') {
res.setHeader('Content-Type', 'text/html');
res.end(
'<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="/bundle.css"><div id="app"></div><script src="/vue.js"></script><script src="/bundle.js"></script>'
);
} else {
const locale = /^\/container-viewer\.umd\.min\.locale-[a-zA-Z-]+\.js$/.test(req.url);
const path = files[req.url] || (locale && fileURLToPath(new URL('viewer/dist' + req.url, root)));
if (!path) {
res.statusCode = 404;
res.end();
return;
}
res.setHeader('Content-Type', req.url.endsWith('.css') ? 'text/css' : 'text/javascript; charset=utf-8');
res.end(await readFile(path));
}
} catch (error) {
res.statusCode = 500;
res.end(String(error));
}
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const browser = await chromium.launch({ executablePath: process.env.CHROMIUM_EXECUTABLE });
try {
for (const width of [390, 1400]) {
const page = await browser.newPage({ viewport: { width, height: 900 } });
await page.addInitScript(() => {
window.cargoAnimations = [];
const animate = Element.prototype.animate;
Element.prototype.animate = function (frames, options) {
if (options?.duration === 320 && this.hasAttribute('data-piece-id')) {
window.cargoAnimations.push({
id: this.getAttribute('data-piece-id'),
frames,
holding: this.closest('.bank-holding')?.getAttribute('data-owner'),
copies: [...document.querySelectorAll('[data-piece-id]')].filter(
(node) => node.getAttribute('data-piece-id') === this.getAttribute('data-piece-id')
).length,
});
}
return animate.call(this, frames, options);
};
});
const checkReturnTray = async () => {
const geometry = await page.evaluate(() => {
const tray = document.querySelector('.bank-return-tray').getBoundingClientRect();
const decision = document.querySelector('.bank-decision');
const inside = [...decision.querySelectorAll('[data-piece-id], [role="button"], text')].every(
(node) => {
const r = node.getBoundingClientRect();
return (
r.left >= tray.left - 1 &&
r.right <= tray.right + 1 &&
r.top >= tray.top - 1 &&
r.bottom <= tray.bottom + 1
);
}
);
const clear = [
...document.querySelectorAll('.bank-board, .bank-piers, .point-card, .piece, .island-value'),
].every((node) => {
const r = node.getBoundingClientRect();
return r.right <= tray.left || r.left >= tray.right || r.bottom <= tray.top || r.top >= tray.bottom;
});
return {
inside,
clear,
aboveBank: tray.bottom < document.querySelector('.bank-board').getBoundingClientRect().top,
};
});
assert.deepEqual(geometry, { inside: true, clear: true, aboveBank: true });
};
const errors = [];
page.on('pageerror', (e) => errors.push(e.message));
page.on('console', (msg) => {
if (msg.type() === 'error') console.error(msg.text());
});
await page.goto(`http://127.0.0.1:${server.address().port}/`);
let state = engine.setup(3, { offshoreIsland: true }, 'offshore-browser');
state.offshoreBank.containerLots[2].push(state.containersLeft.pop());
const player = state.currentPlayers[0];
state.players[player].availableMoves = engine.availableMoves(state, state.players[player]);
state.players.forEach((p, i) => (p.name = ['Ada', 'Benoît', 'Cleo'][i]));
state.newTurn = true;
await page.evaluate(
({ state, player }) => {
window.host = container.launch('#app');
window.moves = [];
host.on('move', (value) => moves.push(value));
host.emit('preferences', { sound: false, colorBlind: true });
host.emit('player', { index: player });
host.emit('state', state);
},
{ state: engine.stripSecret(copy(state), player), player }
);
const push = async () => {
state.players[player].availableMoves = engine.availableMoves(state, state.players[player]);
await page.evaluate((state) => {
moves.length = 0;
host.emit('state', state);
}, engine.stripSecret(copy(state), player));
};
await page.waitForSelector('.offshore-bank .offshore-lot', { state: 'attached' });
assert.equal(await page.locator('.offshore-bank .offshore-lot').count(), 6);
assert.equal(await page.locator('text=OPTIONAL EXPANSION').count(), 0);
// Empty rewards remain visible, but cannot open a draft or emit a move.
const reward = state.offshoreBank.containerLots[2].pop();
state.containersLeft.push(reward);
state.offshoreBank.cashLots[1] = 0;
await push();
for (const [type, lot] of [
['containers', 2],
['cash', 1],
]) {
const node = page.locator(`.offshore-lot[data-type="${type}"][data-lot="${lot}"]`);
assert.equal(await node.getAttribute('role'), null);
assert.ok(!(await node.getAttribute('class')).split(/\s+/).includes('legal'));
assert.ok((await node.textContent()).includes('Bid'));
await node.click();
assert.equal(await page.locator('.bank-draft').count(), 0);
assert.equal(await page.evaluate(() => moves.length), 0);
}
state.offshoreBank.containerLots[2].push(state.containersLeft.pop());
state.offshoreBank.cashLots[1] = 2;
await push();
for (const [type, lot] of [
['containers', 2],
['cash', 1],
]) {
assert.equal(
await page.locator(`.offshore-lot[data-type="${type}"][data-lot="${lot}"]`).getAttribute('role'),
'button'
);
}
const lotBounds = await page.locator('.offshore-lot[data-type="containers"][data-lot="2"]').boundingBox();
const pierBounds = await page.locator('.bank-piers').boundingBox();
assert.ok(pierBounds.x >= lotBounds.x + lotBounds.width, 'harbor is beside the bank lots');
assert.ok(pierBounds.x - lotBounds.x - lotBounds.width < 12, 'harbor joins the bank, not a distant area');
assert.equal(await page.getByText('BANK HARBOR', { exact: true }).count(), 0);
await page.locator('.offshore-lot[data-type="containers"][data-lot="2"]').click();
const checkDraft = async (type, lot) => {
const selected = page.locator('.offshore-lot.selected');
assert.equal(await selected.count(), 1);
assert.equal(await selected.getAttribute('data-type'), type);
assert.equal(await selected.getAttribute('data-lot'), String(lot));
assert.equal(await selected.getAttribute('aria-pressed'), 'true');
assert.equal(await selected.evaluate((el) => getComputedStyle(el).stroke), 'rgb(0, 0, 255)');
assert.equal(await page.locator('.bank-bid-guidance').count(), 0);
const draft = page.locator(type === 'cash' ? '.bank-draft-focus' : '.bank-draft');
await draft.scrollIntoViewIfNeeded();
const bounds = await draft.boundingBox();
const svg = await draft.evaluate((el) => {
const r = el.ownerSVGElement.getBoundingClientRect();
return { x: r.x, y: r.y, right: r.right, bottom: r.bottom };
});
assert.ok(
bounds.x >= svg.x &&
bounds.y >= svg.y &&
bounds.x + bounds.width <= svg.right + 1 &&
bounds.y + bounds.height <= svg.bottom + 1,
'draft within SVG'
);
assert.ok(bounds.x >= 0 && bounds.x + bounds.width <= width + 1, 'complete draft visible horizontally');
};
// Zero cancels this bank draft only, by either mouse or keyboard.
for (const keyboard of [false, true]) {
const zeroCalculator = page.locator('[data-tutorial="bank-bid"]');
assert.equal(
await page.locator('.bank-draft').getByRole('button', { name: 'Cancel', exact: true }).count(),
0
);
if (keyboard) {
await zeroCalculator.focus();
await zeroCalculator.press('0');
await zeroCalculator.press('Enter');
} else await zeroCalculator.getByRole('button', { name: 'Bid', exact: true }).click();
assert.equal(await page.locator('.bank-draft, .offshore-lot.selected').count(), 0);
assert.equal(await page.evaluate(() => moves.length), 0);
await page.locator('.offshore-lot[data-type="containers"][data-lot="2"]').click();
}
await checkDraft('containers', 2);
const calculator = page.locator('[data-tutorial="bank-bid"]');
await calculator.focus();
await calculator.press('9');
await calculator.press('9');
await calculator.press('9');
await calculator.getByRole('button', { name: 'Bid', exact: true }).click();
assert.equal(await page.evaluate(() => moves.length), 0, 'invalid cash offer is not submitted');
await calculator.locator('rect[y="130"][x="50"]').click();
await page.screenshot({ path: `/tmp/container-offshore-draft-${width}.png`, fullPage: true });
await calculator.getByRole('button', { name: 'Bid', exact: true }).click();
const bid = await page.evaluate(() => moves.at(-1));
assert.equal(bid.at(-1).name, 'callBank');
assert.equal(bid.at(-1).data.lot, 2);
for (const action of bid) state = engine.move(state, action, player);
await push();
assert.match(await page.locator('.bank-bid-amount').textContent(), /^\$2/);
assert.equal(await page.locator('.bank-bid-amount').getAttribute('font-size'), '16');
const tokenBounds = await page.locator('.bank-bidder circle').first().boundingBox();
const amountBounds = await page.locator('.bank-bid-amount').boundingBox();
assert.ok(amountBounds.x > tokenBounds.x + tokenBounds.width, 'cash bid is beside, not below, the token');
assert.ok(
Math.abs(amountBounds.y + amountBounds.height / 2 - tokenBounds.y - tokenBounds.height / 2) < 8,
'cash bid and token are aligned'
);
assert.equal(await page.getByRole('button', { name: 'Sail to bank', exact: true }).count(), 0);
const bidder = page.locator('.bank-bidder');
assert.equal(await bidder.getAttribute('aria-label'), state.players[player].name);
assert.equal((await bidder.locator('text').textContent()).trim(), String(player + 1));
await page.evaluate(() => host.emit('preferences', { colorBlind: false }));
await page.waitForFunction(() => !document.querySelector('.bank-bidder text'));
assert.equal(await bidder.locator('text').count(), 0, 'normal mode shows only a player token');
await page.evaluate(() => host.emit('preferences', { colorBlind: true }));
await page.waitForFunction(() => !!document.querySelector('.bank-bidder text'));
// A fresh turn fixture: calling the bank twice in one turn is illegal.
state = engine.setup(3, { offshoreIsland: true }, 'offshore-browser');
state.players.forEach((p, i) => (p.name = ['Ada', 'Benoît', 'Cleo'][i]));
state.newTurn = true;
const offered = state.players[player].containersOnFactoryStore[0].piece;
const second = state.containersLeft.pop();
state.players[player].containersOnWarehouseStore.push({ piece: second, price: 3, moved: false });
await push();
await page.locator('.offshore-lot[data-type="cash"][data-lot="1"]').click();
assert.deepEqual(
await page
.locator('.bank-bid-storage-zone')
.evaluateAll((els) => els.map((el) => [el.dataset.district, el.dataset.owner])),
[
['factory', String(player)],
['warehouse', String(player)],
]
);
assert.equal(
await page
.locator(`.piece.bid-eligible[data-piece-id="${offered.id}"] > rect`)
.evaluate((el) => getComputedStyle(el).stroke),
'rgb(33, 52, 59)',
'eligible cargo retains its normal border'
);
await page.locator(`.piece.bid-eligible[data-piece-id="${offered.id}"]`).click();
await checkDraft('cash', 1);
assert.equal(await page.locator('.bank-lot-draft [data-piece-id]').count(), 1);
await page.screenshot({ path: `/tmp/container-offshore-cargo-one-${width}.png`, fullPage: true });
await page.locator(`.piece.bid-eligible[data-piece-id="${second.id}"]`).click();
assert.equal(await page.evaluate(() => moves.length), 0, 'selection never auto-submits');
assert.equal(await page.locator('.piece.canDrag, .loan.canDrag, .offshore-lot.legal').count(), 0);
assert.equal(await page.locator('.piece.bid-selected').count(), 0);
for (const id of [offered.id, second.id])
assert.equal(await page.locator(`[data-piece-id="${id}"]`).count(), 1, 'draft has no store duplicate');
assert.equal(
await page.locator('rect[stroke="blue"]').count(),
2,
'only the two eligible own storage zones have action outlines'
);
const originalStore = copy(state.players[player]);
const draftPiece = () => page.locator(`.bank-lot-draft [data-piece-id="${second.id}"]`);
await page.waitForTimeout(350);
await draftPiece().focus();
await draftPiece().press('Space');
const selectedPiece = page.locator(`.piece[data-piece-id="${second.id}"]`);
assert.equal(await selectedPiece.count(), 1);
assert.equal(await draftPiece().count(), 0);
await selectedPiece.focus();
await selectedPiece.press('Enter');
assert.equal(await selectedPiece.count(), 0);
assert.equal(await draftPiece().count(), 1);
await draftPiece().focus();
await draftPiece().press('Enter');
assert.equal(await selectedPiece.count(), 1);
await selectedPiece.click();
const draftAnimations = await page.evaluate(() => cargoAnimations);
assert.ok(draftAnimations.filter((a) => a.id === second.id).length >= 5, 'draft selection and removal animate');
assert.ok(
draftAnimations.every((a) => a.copies === 1),
'animation never introduces a duplicate'
);
assert.deepEqual(state.players[player], originalStore, 'local draft never changes engine stores or money');
const returnAnimation = draftAnimations.filter((a) => a.id === second.id)[1];
assert.notEqual(
returnAnimation.frames[0].transform,
returnAnimation.frames[1].transform,
'removal travels back to storage'
);
await page.waitForTimeout(350);
const animationsBeforeSwitch = await page.evaluate(() => cargoAnimations.length);
await page.locator('.offshore-lot[data-type="cash"][data-lot="0"]').click();
assert.equal(await page.locator('.bank-lot-draft [data-piece-id]').count(), 0);
for (const id of [offered.id, second.id]) {
assert.equal(await page.locator(`[data-piece-id="${id}"]`).count(), 1);
assert.equal(
await page.locator(`.piece[data-piece-id="${id}"]`).count(),
1,
'switch restores original store'
);
}
const returnAnimations = await page.evaluate((count) => cargoAnimations.slice(count), animationsBeforeSwitch);
assert.equal(returnAnimations.length, 2, 'switch cancels draft with both return animations');
assert.ok(returnAnimations.every((a) => a.copies === 1));
await page.locator('.offshore-lot[data-type="cash"][data-lot="1"]').click();
for (const id of [offered.id, second.id]) await page.locator(`.piece[data-piece-id="${id}"]`).click();
if (width < 600) await page.locator('.player-board-tab').nth(player).click();
await page.screenshot({ path: `/tmp/container-offshore-cargo-focus-${width}.png`, fullPage: true });
await page.locator(`.bank-lot-draft [data-piece-id="${offered.id}"]`).click();
await page.locator(`.bank-lot-draft [data-piece-id="${second.id}"]`).click();
assert.equal(await page.locator('.bank-lot-draft [data-piece-id]').count(), 0);
await page.getByRole('button', { name: 'Cancel', exact: true }).click();
assert.equal(await page.locator('.bid-eligible, .bid-selected, .bank-draft').count(), 0);
assert.equal(await page.locator('.bank-bid-storage-zone').count(), 0);
assert.ok((await page.locator('rect[stroke="blue"]').count()) > 0, 'cancel restores normal action outlines');
assert.ok((await page.locator('.piece.canDrag').count()) > 0, 'cancel restores ordinary actions');
assert.equal(await page.evaluate(() => moves.length), 0);
await page.locator('.offshore-lot[data-type="cash"][data-lot="1"]').click();
await page.locator(`.piece.bid-eligible[data-piece-id="${offered.id}"]`).click();
await page.locator(`.piece.bid-eligible[data-piece-id="${second.id}"]`).click();
if (width < 600) {
await page.getByRole('button', { name: 'Bid (2)', exact: true }).click();
assert.equal(
await page.locator('.bank-lot-draft [data-piece-id]').count(),
2,
'navigation preserves draft'
);
}
await checkDraft('cash', 1);
await page.screenshot({ path: `/tmp/container-offshore-cargo-draft-${width}.png`, fullPage: true });
assert.equal(await page.locator('.bank-draft-action').count(), 1);
assert.deepEqual(
await page
.locator('.bank-lot-draft [data-piece-id]')
.evaluateAll((els) => els.map((el) => el.dataset.pieceId)),
[offered.id, second.id]
);
await page.locator('.bank-draft-action').click();
const cargoBid = await page.evaluate(() => moves.at(-1));
assert.equal(cargoBid.at(-1).name, 'callBank');
assert.equal(cargoBid.at(-1).data.lot, 1);
assert.deepEqual(cargoBid.at(-1).extraData.containers, [offered.id, second.id]);
for (const action of cargoBid) state = engine.move(state, action, player);
await push();
assert.equal(await page.locator('.bank-lot-draft').count(), 0);
for (const id of [offered.id, second.id]) {
assert.equal(
await page.locator(`[data-piece-id="${id}"]`).count(),
1,
'confirmed escrow has no duplicates'
);
assert.equal(await page.locator(`.piece[data-piece-id="${id}"]`).count(), 0);
}
assert.deepEqual(
state.offshoreBank.auctions
.find((a) => a.type === 'cash' && a.lot === 1)
.containers.map((c) => [c.district, c.container.price]),
[
['factory', originalStore.containersOnFactoryStore[0].price],
['warehouse', 3],
]
);
await page.locator('.board-scroll').evaluate((el) => {
el.scrollLeft = 0;
});
await page.waitForTimeout(1200);
await page.screenshot({ path: `/tmp/container-offshore-bid-zones-${width}.png`, fullPage: true });
// The decision is on-board too: no HTML cards, forms, expansion eyebrow or toggle.
assert.equal(await page.locator('.bank-toggle, #offshore-title, .bank-decision form').count(), 0);
const own = state.players[player];
const returned = { piece: state.containersLeft.pop(), price: 2, moved: false };
assert.ok(returned);
state.newTurn = true;
state.phase = 'bankDecision';
state.currentPlayers = [player];
state.offshoreBank.decision = {
kind: 'return',
player,
resumePlayer: player,
containers: [{ container: returned, district: 'factory' }],
payment: [],
cursor: 0,
};
await page.evaluate((state) => {
host.emit('player', { index: undefined });
host.emit('state', state);
}, engine.stripSecret(copy(state)));
await page.waitForFunction(() =>
document.querySelector('.bank-decision')?.textContent.includes('Returned containers')
);
assert.equal(
await page.locator('.bank-decision [data-piece-id]').count(),
1,
'spectator sees pending return cargo'
);
assert.equal(
await page.locator('.bank-decision [role="button"]').count(),
0,
'spectator has no decision controls'
);
await checkReturnTray();
await page.evaluate((player) => host.emit('player', { index: player }), player);
await push();
await checkReturnTray();
await page.screenshot({ path: `/tmp/container-offshore-return-tray-${width}.png`, fullPage: true });
await page.locator('.bank-choice [data-piece-id]').click();
await page.getByRole('button', { name: 'Return to factory store at $3', exact: true }).click();
const repricing = await page.evaluate(() => moves.at(-1));
assert.equal(repricing.length, 1, 'interruption is not appended to the previous bid buffer');
state = engine.move(state, repricing[0], player);
assert.equal(state.newTurn, true);
await push();
assert.equal(await page.locator('.bank-decision').count(), 0);
assert.equal(
state.players[player].containersOnFactoryStore.find((c) => c.piece.id === returned.piece.id).price,
3
);
// Public bank entries use the same badges and SVG/CB pieces as ordinary logs,
// even after the escrow has been outbid and returned to a store.
const cashEntries = page.locator('.journal-entry').filter({ hasText: 'calls bank for cash lot' });
assert.ok(await cashEntries.count());
assert.ok(await cashEntries.first().locator('svg[role="img"]').count());
assert.ok(await cashEntries.first().locator('.color-mark').count());
const journalBadge = cashEntries.first().locator('[data-localized-journal] > span').first();
assert.equal(await journalBadge.textContent(), state.players[player].name);
assert.notEqual(await journalBadge.evaluate((el) => el.style.backgroundColor), '');
// A temporary, legal ordinary loan gives a side-by-side styling reference.
const reference = engine.setup(3, {}, 'ordinary-journal');
reference.players[player].name = state.players[player].name;
const loan = engine.move(reference, { name: engine.MoveName.GetLoan, data: true }, player).log.at(-1);
const comparison = copy(state);
comparison.log.push(loan);
await page.evaluate((state) => host.emit('state', state), engine.stripSecret(comparison, player));
await page.locator('.journal-entry').filter({ hasText: 'takes a loan' }).waitFor({ state: 'attached' });
const ordinaryBadge = page
.locator('.journal-entry')
.filter({ hasText: 'takes a loan' })
.locator('[data-localized-journal] > span')
.first();
assert.equal(
await ordinaryBadge.evaluate((el) => el.style.backgroundColor),
await journalBadge.evaluate((el) => el.style.backgroundColor)
);
await page.locator('.inline-game-log').screenshot({ path: `/tmp/container-offshore-journal-${width}.png` });
await push();
// Existing journal localization works without a separate web-style panel.
await page.evaluate(() => host.emit('preferences', { locale: 'fr' }));
await page.waitForFunction(() =>
document.querySelector('.inline-game-log')?.textContent.includes('appelle la banque')
);
assert.match(await page.locator('.inline-game-log').innerText(), /appelle la banque/);
assert.match(await page.locator('.inline-game-log').innerText(), /remet un conteneur/);
await page.locator('.board-scroll').evaluate((el) => {
el.scrollLeft = 0;
});
await page.waitForTimeout(100);
const bounds = await page.locator('.bank-board').boundingBox();
assert.ok(bounds.x >= 0 && bounds.x + bounds.width <= width + 1, 'bank visible within board viewport');
await page.screenshot({ path: `/tmp/container-offshore-${width}.png`, fullPage: true });
await page.evaluate(() => host.emit('preferences', { locale: 'en' }));
// Sail using the normal ship selection/destination flow, without a separate button.
state.players[player].ship.shipPosition = engine.ShipPosition.OpenSea;
state.players[player].lastMove = null;
state.players[player].actions = 2;
const pickup = state.containersLeft.pop();
state.players[player].bankHolding.push(pickup, ...state.containersLeft.splice(-7));
state.players[(player + 1) % 3].bankHolding.push(state.containersLeft.pop());
state.newTurn = true;
await push();
await page
.locator('.piece')
.filter({ hasText: `${state.players[player].name}'s Ship` })
.click();
assert.equal(await page.locator('.bank-harbor').count(), 5);
assert.equal(await page.locator('.bank-harbor.showDrop').count(), 1);
assert.equal(await page.locator('.bank-harbor.canClick').getAttribute('data-berth'), String(player));
await page.locator('.bank-harbor.canClick').click();
const sailing = await page.evaluate(() => moves.at(-1));
assert.deepEqual(sailing.at(-1), { name: 'sail', data: 'offshoreBank' });
for (const action of sailing) state = engine.move(state, action, player);
assert.equal(state.players[player].ship.shipPosition, 'offshoreBank');
await push();
// Ship and waiting cargo share a player-colored berth, never the same space.
await page.waitForTimeout(1200);
const ownBerth = page.locator(`.bank-berth[data-owner="${player}"]`);
await ownBerth.scrollIntoViewIfNeeded();
const holdingBounds = await ownBerth.locator('.bank-holding').boundingBox();
const shipBounds = await page
.locator('.piece')
.filter({ hasText: `${state.players[player].name}'s Ship` })
.boundingBox();
assert.ok(shipBounds.x + shipBounds.width < holdingBounds.x, 'ship never overlaps waiting cargo');
assert.equal(await page.locator('.bank-berth').count(), 3);
assert.equal(await ownBerth.locator('[data-piece-id]').count(), 2);
await ownBerth.getByRole('button', { name: 'Next cargo page' }).click();
assert.equal(await ownBerth.locator('[data-piece-id]').count(), 2);
await ownBerth.getByRole('button', { name: 'Previous cargo page' }).click();
await page.screenshot({ path: `/tmp/container-offshore-harbor-${width}.png`, fullPage: true });
// Arrival-only pickup still uses the displayed holding cargo.
await page.locator(`.bank-holding [data-piece-id="${pickup.id}"]`).click();
const loading = await page.evaluate(() => moves.at(-1));
assert.equal(loading.at(-1).name, 'loadBankContainer');
// The emitted turn buffer includes sailing, already applied to this fixture above.
state = engine.move(state, loading.at(-1), player);
assert.ok(state.players[player].ship.containers.some((piece) => piece.id === pickup.id));
await push();
// Pick the payment color, not the destination: lot II is frozen by an auction.
const payments = ['orange', 'white', 'orange'].map((color) => {
const index = state.containersLeft.findIndex((piece) => piece.color === color);
assert.ok(index >= 0);
return state.containersLeft.splice(index, 1)[0];
});
state.offshoreBank.auctions = [
{ type: 'containers', lot: 1, bidder: (player + 1) % 3, cash: 2, containers: [] },
];
state.offshoreBank.decision = {
kind: 'distribute',
player,
resumePlayer: player,
containers: [],
payment: payments.slice(),
cursor: 0,
};
state.phase = 'bankDecision';
state.newTurn = true;
state.currentPlayers = [player];
await push();
const checkPayment = async (lot, stage) => {
assert.equal(await page.locator('.offshore-lot.destination').getAttribute('data-lot'), String(lot));
assert.equal(await page.locator('.offshore-lot[role="button"]').count(), 0);
assert.equal(await page.locator('.bank-decision > text').count(), 0);
assert.equal(await page.evaluate(() => moves.length), 0, 'color choice waits for the player');
await page.waitForTimeout(1200);
await page.screenshot({ path: `/tmp/container-offshore-payment-${stage}-${width}.png`, fullPage: true });
};
await checkPayment(0, 'choice');
// Spectators see destination and pending cargo, but cannot choose or bid.
await page.evaluate((state) => {
host.emit('player', { index: undefined });
host.emit('state', state);
}, engine.stripSecret(copy(state)));
assert.equal(await page.locator('.bank-decision [role="button"]').count(), 0);
assert.equal(await page.locator('.offshore-lot.destination').getAttribute('data-lot'), '0');
await page.evaluate((player) => host.emit('player', { index: player }), player);
await push();
for (const [index, lot] of [
[0, 0],
[1, 2],
]) {
await page.locator(`.bank-choice [data-piece-id="${payments[index].id}"]`).click();
const actions = await page.evaluate(() => moves.at(-1));
assert.equal(actions.length, 1);
assert.equal(actions[0].name, 'distributeBankContainer');
state = engine.move(state, actions[0], player);
assert.ok(state.offshoreBank.containerLots[lot].some((piece) => piece.id === payments[index].id));
await push();
if (index === 0) await checkPayment(2, 'skip');
}
// The final orange container is placed automatically, skipping the frozen lot.
assert.ok(state.offshoreBank.containerLots[0].some((piece) => piece.id === payments[2].id));
assert.equal(await page.locator('.bank-decision, .offshore-lot.destination').count(), 0);
// Final settlement: choose between colors, then finish automatically with stripped opponent cards.
const payment = state.players[player].containersOnFactoryStore.pop();
const finalOther = state.containersLeft.splice(
state.containersLeft.findIndex((piece) => piece.color !== payment.piece.color),
1
)[0];
const auction = {
type: 'cash',
lot: 0,
bidder: player,
cash: 0,
containers: [
{ container: payment, district: 'factory' },
{ container: { piece: finalOther, price: 2, moved: false }, district: 'factory' },
],
};
state.offshoreBank.auctions = [auction];
state.offshoreBank.decision = {
kind: 'distribute',
player,
resumePlayer: player,
containers: [],
payment: [payment.piece, finalOther],
cursor: 0,
settlement: copy(auction),
ending: true,
};
state.phase = 'bankDecision';
state.newTurn = true;
state.currentPlayers = [player];
await push();
assert.equal(await page.evaluate(() => moves.length), 0, 'different colors require a choice');
await page.locator('.bank-choice [data-piece-id][role="button"]').first().click();
const distribution = await page.evaluate(() => moves.at(-1));
assert.equal(distribution.length, 1);
state = engine.move(state, distribution[0], player);
assert.equal(state.phase, 'gameEnd');
await push();
await page.waitForFunction(() => document.querySelector('.statusBar')?.textContent.includes('Game ended'));
// Five fixed assignments, all docked; waiting cargo belongs to the same colored row.
state = engine.setup(5, { offshoreIsland: true }, 'offshore-five-harbors');
state.currentPlayers = [player];
state.players.forEach((p, i) => {
p.name = `Trader ${i + 1}`;
p.ship.shipPosition = engine.ShipPosition.OffshoreBank;
p.bankHolding = state.containersLeft.splice(-7);
});
await push();
await page.waitForTimeout(1200);
assert.equal(await page.locator('.bank-berth').count(), 5);
assert.equal(await page.locator('.bank-berth .player-token, .bank-berth [fill-opacity]').count(), 0);
assert.equal(await page.locator('.bank-berth-border[fill="none"][stroke-width="2"]').count(), 5);
for (let i = 0; i < 5; i++) {
const berth = page.locator(`.bank-berth[data-owner="${i}"]`);
const cargo = await berth.locator('.bank-holding').boundingBox();
const ship = await page
.locator('.piece')
.filter({ hasText: `Trader ${i + 1}'s Ship` })
.boundingBox();
const bounds = await berth.boundingBox();
assert.ok(ship.x + ship.width < cargo.x);
assert.ok(cargo.x >= bounds.x && cargo.x + cargo.width <= bounds.x + bounds.width + 1);
assert.ok(cargo.y >= bounds.y && cargo.y + cargo.height <= bounds.y + bounds.height);
assert.ok(
ship.y >= bounds.y - 2 && ship.y + ship.height <= bounds.y + bounds.height + 2,
JSON.stringify({ i, ship, bounds })
);
}
await page.locator(`.bank-berth[data-owner="${player}"]`).scrollIntoViewIfNeeded();
await page.screenshot({ path: `/tmp/container-offshore-five-harbors-${width}.png`, fullPage: true });
await page.evaluate((state) => {
host.emit('player', { index: undefined });
host.emit('state', state);
}, engine.stripSecret(copy(state)));
assert.equal(await page.locator('.bank-holding [data-piece-id][role="button"]').count(), 0);
assert.equal(await page.locator('.bank-harbor.canClick').count(), 0);
// A large pending return remains bounded with all five berths populated, including spectators.
state.phase = 'bankDecision';
state.offshoreBank.decision = {
kind: 'return',
player,
resumePlayer: player,
containers: state.containersLeft
.splice(0)
.map((piece) => ({ container: { piece, price: 2, moved: false }, district: 'factory' })),
payment: [],
cursor: 0,
};
await page.evaluate((state) => host.emit('state', state), engine.stripSecret(copy(state)));
await page.waitForSelector('.bank-return-tray');
await checkReturnTray();
await page.locator('.bank-decision [aria-label="Next cargo page"]').click();
await checkReturnTray();
await page.screenshot({ path: `/tmp/container-offshore-return-spectator-${width}.png`, fullPage: true });
await page.evaluate((player) => host.emit('player', { index: player }), player);
await push();
await checkReturnTray();
await page.locator('.bank-decision .button').click();
await checkReturnTray();
// A real pass settles a cash bid for containers and appends an upkeep event.
// Both prize pieces must visibly move from their lot into the winner's holding.
state = engine.setup(3, { offshoreIsland: true }, 'offshore-browser');
const prizeIds = state.offshoreBank.containerLots[0].map((piece) => piece.id);
state = engine.move(
state,
{ name: 'callBank', data: { type: 'containers', lot: 0 }, extraData: { cash: 1 } },
player
);
for (let i = 0; i < 2; i++) state = engine.move(state, { name: 'pass', data: true }, state.currentPlayers[0]);
await page.evaluate((player) => host.emit('player', { index: player }), player);
await push();
await page.waitForFunction(() => document.querySelectorAll('.bank-holding [data-piece-id]').length === 0);
const previousAnimations = await page.evaluate(() => window.cargoAnimations.length);
const previousLogLength = state.log.length;
state = engine.move(state, { name: 'pass', data: true }, state.currentPlayers[0]);
assert.ok(state.log.length > previousLogLength + 1, 'settlement includes event and move');
await push();
await page.waitForFunction(
({ ids, owner, start }) =>
ids.every((id) =>
window.cargoAnimations.slice(start).some((a) => a.id === id && a.holding === String(owner))
),
{ ids: prizeIds, owner: player, start: previousAnimations }
);
const cargoAnimations = await page.evaluate(() => window.cargoAnimations);
assert.ok(cargoAnimations.length >= 4, 'bank transfers animate physical cargo');
assert.ok(
cargoAnimations.every((animation) => animation.copies === 1),
'no duplicate animated cargo'
);
assert.ok(
cargoAnimations.every((animation) =>
animation.frames.every((frame) => !/NaN|Infinity/.test(frame.transform))
),
'SVG motion matrices remain finite'
);
assert.deepEqual(errors, []);
await page.close();
console.log(
`Offshore browser smoke passed: ${width}px, stripped state, bids, interruption, final settlement, French.`
);
}
} finally {
await browser.close();
await new Promise((resolve) => server.close(resolve));
}

View file

@ -0,0 +1,153 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { createServer } from 'node:http';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
import { chromium } from 'playwright';
const require = createRequire(import.meta.url);
require('../../engine/node_modules/ts-node').register({
transpileOnly: true,
compilerOptions: { module: 'CommonJS', moduleResolution: 'Node', target: 'ES2022', importHelpers: false },
});
const { lessons } = require('../src/tutorial/lessons');
const viewer = new URL('../', import.meta.url);
const files = {
'/bundle.js': fileURLToPath(new URL('dist/container-viewer.umd.min.js', viewer)),
'/bundle.css': fileURLToPath(new URL('dist/container-viewer.css', viewer)),
'/vue.js': require.resolve('vue/dist/vue.min.js'),
};
const html =
'<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><link rel="stylesheet" href="/bundle.css"><div id="app"></div><script src="/vue.js"></script><script src="/bundle.js"></script><script>container.launchTutorial("#app",{locale:"fa-IR",chapter:new URLSearchParams(location.search).get("chapter")||"supply-chain"});</script>';
const server = createServer(async (req, res) => {
const request = new URL(req.url, 'http://localhost');
const path = request.pathname;
if (request.searchParams.has('embedded')) {
res.setHeader('content-type', 'text/html');
res.end(
'<!doctype html><meta name=viewport content=width=device-width,initial-scale=1><iframe style=width:100%;height:900px sandbox="allow-scripts allow-same-origin" src="/?chapter=bidding"></iframe>'
);
return;
}
if (files[path]) {
res.setHeader('content-type', path.endsWith('.css') ? 'text/css' : 'text/javascript');
res.end(await readFile(files[path]));
} else {
res.setHeader('content-type', 'text/html');
res.end(html);
}
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const origin = `http://127.0.0.1:${server.address().port}`;
async function playOnBoard(page, move) {
if (move.name === 'pass') return page.locator('[data-tutorial="turn"]').click();
if (move.name === 'bid') {
const keys = [7, 8, 9, 4, 5, 6, 1, 2, 3, 0, 'Del', 'Bid'];
for (const digit of String(move.extraData.price))
await page
.locator('.calculator rect.button')
.nth(keys.indexOf(Number(digit)))
.click();
await page.locator('.calculator rect.button').last().click();
if (await page.locator('.modal.visible').isVisible())
await page.locator('.modal.visible').getByRole('button', { name: 'تأیید', exact: true }).click();
return;
}
if (move.name === 'accept') return page.locator('g.button').filter({ hasText: 'Accept Ada' }).click();
if (move.name === 'decline') return page.locator('g.button').filter({ hasText: 'Keep for $6' }).click();
const id = move.name === 'produce' ? move.extraData.piece.id : move.data?.piece?.id ?? move.extraData?.id;
const pieces = page.locator('.piece.canDrag');
const index = await pieces.evaluateAll(
(els, { id, sail, factory }) =>
els.findLastIndex((el) =>
sail
? el.__vue__.pieceType === 'ship' && el.__vue__.owner === 0
: factory
? el.__vue__.pieceType === 'factory' && el.__vue__.color === factory
: el.__vue__.pieceId === id
),
{ id, sail: move.name === 'sail', factory: move.name === 'buyFactory' ? move.data : undefined }
);
assert.ok(index >= 0, 'piece available for ' + move.name);
await pieces.nth(index).click();
const zones = page.locator('.placeholder.canClick');
const type = {
produce: 'factoryStore',
buyFromFactory: 'warehouseStore',
buyFactory: 'factory',
buyWarehouse: 'warehouse',
sail: move.data === 'sea' ? 'openSea' : 'islandHarbor',
}[move.name];
const zone = await zones.evaluateAll(
(els, { type, price }) =>
els.findIndex(
(el) => el.__vue__.data.type === type && (price === undefined || el.__vue__.data.price === price)
),
{ type, price: move.extraData?.price }
);
assert.ok(zone >= 0, 'destination available for ' + move.name + ' ' + type);
const bounds = await zones.nth(zone).boundingBox();
await zones.nth(zone).click({
position: {
x: bounds.width * (type === 'factory' || type === 'warehouse' ? 0.4 : 0.15),
y: bounds.height * 0.4,
},
});
if (await page.locator('.modal.visible').isVisible())
await page.locator('.modal.visible').getByRole('button', { name: 'تأیید', exact: true }).click();
}
const browser = await chromium.launch();
try {
for (const width of [1440, 390]) {
const context = await browser.newContext({ viewport: { width, height: 950 }, reducedMotion: 'reduce' });
const page = await context.newPage();
const errors = [];
page.on('pageerror', (error) => errors.push(error.message));
for (const lesson of lessons) {
await page.goto(`${origin}/?chapter=${lesson.id}`);
const guide = page.locator('.bgs-tutorial-guide');
await guide.waitFor();
await page.waitForFunction(() =>
/[\u0600-\u06ff]/.test(document.querySelector('.bgs-tutorial-body')?.textContent ?? '')
);
assert.equal(await guide.evaluate((el) => getComputedStyle(el).direction), 'rtl');
assert.equal(
await page.locator('.container-tutorial').evaluate((el) => getComputedStyle(el).direction),
'ltr'
);
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth + 1), false);
}
const lesson = lessons.find((l) => l.id === 'supply-chain');
await page.goto(`${origin}/?chapter=${lesson.id}`);
const guide = page.locator('.bgs-tutorial-guide');
await guide.waitFor();
let state = lesson.initialState();
for (let step = 0; step < 24; step++) {
const heading = await guide.locator('.bgs-tutorial-heading strong').innerText();
if (heading === 'فصل تمام شد') break;
const next = guide.getByRole('button', { name: 'ادامه', exact: true });
if (await next.isEnabled()) await next.click();
else {
const stepId = await page.locator('.container-tutorial').getAttribute('data-step');
const action = lesson.choices(state, stepId)[0]?.action;
assert.ok(action, `action for ${stepId}`);
if (action.kind === 'move') await playOnBoard(page, action.move);
else await page.locator('.tutorial-actions button').first().click();
state = lesson.move(state, action);
}
await page.waitForFunction(
(previous) => document.querySelector('.bgs-tutorial-heading strong')?.textContent !== previous,
heading
);
}
assert.equal(await guide.locator('.bgs-tutorial-heading strong').innerText(), 'فصل تمام شد');
await page.screenshot({ path: `/tmp/container-fa-${width}.png`, fullPage: true });
assert.deepEqual(errors, []);
await context.close();
console.log(`Persian chapters and supply-chain actions passed at ${width}px`);
}
} finally {
await browser.close();
await new Promise((resolve) => server.close(resolve));
}

View file

@ -0,0 +1,427 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { createServer } from 'node:http';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
import { chromium } from 'playwright';
import { checkAuctionMessages } from './auction-messages-smoke.mjs';
import { checkFinalScore } from './final-score-smoke.mjs';
import { checkHostPresentation } from './host-presentation-smoke.mjs';
import { checkUndoMove } from './undo-move-smoke.mjs';
const game = 'container';
const require = createRequire(import.meta.url);
const repo = new URL('../../', import.meta.url);
const engine = require(fileURLToPath(new URL('engine/dist/index.js', repo)));
const journalEntry = (text) => ({ type: 'move', move: { name: 'pass' }, pretty: text, simple: text });
const html =
'<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><link rel="stylesheet" href="/bundle.css"><div id="app"></div><script src="/vue.js"></script>' +
'<script src="/bundle.js"></script>';
const server = createServer(async (req, res) => {
try {
const bundle = `viewer/dist/${game}-viewer.umd.min.js`;
const css = `viewer/dist/${game}-viewer.css`;
const files = {
'/bundle.js': fileURLToPath(new URL(bundle, repo)),
'/bundle.css': fileURLToPath(new URL(css, repo)),
'/vue.js': require.resolve('vue/dist/vue.min.js'),
};
if (req.url === '/') {
res.setHeader('Content-Type', 'text/html');
res.end(html);
} else if (/^\/container-viewer\.umd\.min\.locale-[a-zA-Z-]+\.js$/.test(req.url)) {
res.setHeader('Content-Type', 'text/javascript; charset=utf-8');
res.end(await readFile(fileURLToPath(new URL('viewer/dist' + req.url, repo))));
} else if (files[req.url]) {
res.setHeader('Content-Type', req.url.endsWith('.css') ? 'text/css' : 'text/javascript; charset=utf-8');
res.end(await readFile(files[req.url]));
} else {
res.statusCode = 404;
res.end();
}
} catch (error) {
res.statusCode = 500;
res.end(String(error));
}
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const browser = await chromium.launch({ executablePath: process.env.CHROMIUM_EXECUTABLE });
try {
for (const width of [390, 1400]) {
const page = await browser.newPage({ viewport: { width, height: 900 } });
const errors = [];
page.on('pageerror', (error) => errors.push(error.message));
await page.goto(`http://127.0.0.1:${server.address().port}/`);
assert.deepEqual(errors, [], 'bundle loads without browser errors');
let state = engine.setup(3, {}, '17');
state = JSON.parse(JSON.stringify(state));
state.newTurn = true;
state.players.forEach((player, index) => {
player.name = ['You', 'Ada Lovelace', 'Bob'][index];
});
state.log = Array.from({ length: 50 }, (_, index) =>
journalEntry(`Journal entry ${index + 1}: Ada buys containers from Bob's warehouse.`)
);
state.log.unshift(journalEntry('<span style="border:1px solid black">orange</span> container'));
const id = (value) => value.toString(16).padStart(24, '0');
const messages = Array.from({ length: 35 }, (_, i) => ({
_id: id(i + 1),
type: 'text',
author: 'Bob',
playerIndex: 2,
text: `Earlier message ${i + 1}`,
createdAt: '2026-09-13T12:00:00Z',
}));
// BGS can load the viewer before revealing its iframe.
await page.locator('#app').evaluate((el) => (el.style.display = 'none'));
await page.evaluate(
({ game, state, messages }) => {
window.globalName = game;
window.readyCount = 0;
window.receipts = [];
window.sent = [];
window.playerClicks = [];
window.fetches = 0;
window.host = window[window.globalName].launch('#app');
host.on('ready', () => readyCount++);
host.on('fetchState', () => fetches++);
host.on('chat:read', (payload) => receipts.push(payload));
host.on('chat:send', (payload) => sent.push(payload));
host.on('player:clicked', (payload) => playerClicks.push(payload));
host.emit('preferences', { sound: false });
host.emit('player', { index: 0 });
host.emit('state', state);
host.emit('chat:state', {
canSend: true,
mentions: [
{ id: 'self', name: 'You', playerIndex: 0 },
{ id: 'ada', name: 'Ada Lovelace', playerIndex: 1 },
{ id: 'bob', name: 'Bob', playerIndex: 2 },
],
});
host.emit('chat:messages', messages);
},
{ game, state, messages }
);
await page.waitForFunction(() => readyCount === 1);
await page.locator('#app').evaluate((el) => (el.style.display = ''));
assert.equal(await page.locator('.color-mark').count(), 0, 'colour symbols are off by default');
await page.evaluate(() => {
window.preferenceChanges = [];
host.on('update:preference', (value) => preferenceChanges.push(value));
host.emit('preferences', { colorBlind: true });
});
await page.waitForFunction(() => document.querySelectorAll('.color-mark').length > 20);
assert.equal(await page.locator('.point-card .color-mark').count(), 5, 'value card matches cargo symbols');
assert.equal(
await page.locator('.inline-game-log .color-mark').count(),
1,
'journal uses the same colour symbols'
);
assert.equal(await page.locator('.player-number').count(), 6, 'ships and island rows identify all players');
await page.evaluate(() =>
host.emit('preferences', {
colorBlind: true,
bgs: { players: [], playerColors: [], playerSymbols: ['star', 'hexagon', 'cross'] },
})
);
await page.waitForFunction(() => document.querySelector('.player-number')?.textContent.includes('★'));
assert.equal(
await page.locator('.point-card .color-mark').count(),
5,
'resource symbols keep their own meaning'
);
await page.evaluate(() =>
host.emit('preferences', {
colorBlind: true,
bgs: { players: [], playerColors: [], playerSymbols: ['diamond', 'hexagon', 'cross'] },
})
);
await page.waitForFunction(() => document.querySelector('.player-number')?.textContent.includes('◆'));
await page.screenshot({ path: `/tmp/container-color-blind-${width}.png`, fullPage: true });
await page.locator('.color-blind-toggle').scrollIntoViewIfNeeded();
await page.locator('.color-blind-toggle').click();
await page.waitForFunction(() => document.querySelectorAll('.color-mark').length === 0);
assert.deepEqual(await page.evaluate(() => preferenceChanges), [{ name: 'colorBlind', value: false }]);
const panel = page.locator('.bgs-game-chat');
const input = panel.locator('input');
const list = panel.locator('.chat-messages');
const journal = page.locator('.journal-feed');
const assertJournalAtEnd = () =>
page.waitForFunction(
() => {
const el = document.querySelector('.journal-feed');
return el && el.clientHeight > 0 && Math.abs(el.scrollHeight - el.scrollTop - el.clientHeight) < 3;
},
null,
{ timeout: 3000 }
);
await assertJournalAtEnd();
const journalHeight = await page
.locator('.inline-game-log')
.evaluate((el) => el.getBoundingClientRect().height);
const chatHeight = await panel.evaluate((el) => el.getBoundingClientRect().height);
if (width >= 1000) {
assert.ok(Math.abs(journalHeight - chatHeight) < 2, 'journal and chat have the same height');
} else {
assert.equal(chatHeight, 0, 'mobile starts on the journal tab');
assert.ok(journalHeight > 0, 'journal is visible');
}
await journal.evaluate((el) => {
el.scrollTop = 0;
el.dispatchEvent(new Event('scroll'));
});
state.log.push(journalEntry('New entry while reading older moves.'));
await page.evaluate((state) => host.emit('state', state), state);
await journal.locator('.journal-entry').last().getByText('New entry while reading older moves.').waitFor();
assert.equal(await journal.evaluate((el) => el.scrollTop), 0, 'new moves preserve the reading position');
await journal.evaluate((el) => {
el.scrollTop = el.scrollHeight;
el.dispatchEvent(new Event('scroll'));
});
state.log.push(journalEntry('New entry while following the journal.'));
await page.evaluate((state) => host.emit('state', state), state);
await journal.locator('.journal-entry').last().getByText('New entry while following the journal.').waitFor();
await assertJournalAtEnd();
if (width < 1000) await page.getByRole('tab', { name: /^Chat/ }).click();
await panel.scrollIntoViewIfNeeded();
await page.waitForFunction(() => {
const el = document.querySelector('.chat-messages');
return el && Math.abs(el.scrollHeight - el.scrollTop - el.clientHeight) < 3;
});
if (width < 1000) {
await page.setViewportSize({ width, height: 600 });
await panel.evaluate((el) => window.scrollTo(0, window.scrollY + el.getBoundingClientRect().top - 400));
await list.evaluate((el) => {
el.scrollTop = el.scrollHeight;
});
const point = await list.evaluate((el) => {
const rect = el.getBoundingClientRect();
return { x: rect.left + 50, y: rect.top + 50 };
});
await page.mouse.move(point.x, point.y);
await page.mouse.wheel(0, 500);
await page.waitForFunction(
() => {
const composer = document.querySelector('.chat-composer').getBoundingClientRect();
return composer.bottom <= window.innerHeight + 1;
},
null,
{ timeout: 3000 }
);
await page.setViewportSize({ width, height: 900 });
}
assert.equal(await panel.locator('summary').textContent(), 'Chat', 'old history is not unread');
await input.fill('@');
assert.deepEqual(await panel.locator('.chat-suggestions button').allTextContents(), ['@Ada Lovelace', '@Bob']);
await input.press('Enter');
assert.equal(await input.inputValue(), '@"Ada Lovelace" ');
assert.equal(await page.evaluate(() => sent.length), 0, 'selecting a mention does not send');
await input.fill('@"Ada Lovelace" hello');
await input.press('Enter');
assert.equal(await page.evaluate(() => sent.length), 1);
await input.fill('next draft');
await page.evaluate(() => host.emit('chat:result', { requestId: sent[0].requestId, ok: true }));
assert.equal(await input.inputValue(), 'next draft', 'ack preserves a newer draft');
await input.press('Enter');
await page.evaluate(() =>
host.emit('chat:result', { requestId: sent[1].requestId, ok: false, error: 'Try again' })
);
assert.equal(await input.inputValue(), 'next draft');
assert.match(await panel.locator('.chat-status').textContent(), /Try again/);
await panel.evaluate((el) => {
el.open = false;
});
await page.evaluate(() => window.scrollTo(0, 0));
await page.waitForFunction(() => document.querySelector('.chat-shortcut').hidden);
const incoming = {
_id: id(40),
type: 'text',
author: 'Ada Lovelace',
playerIndex: 1,
text: '@You see https://example.com',
segments: [
{ kind: 'mention', name: 'You', id: 'self' },
{ kind: 'text', text: ' see ' },
{ kind: 'link', text: 'example', url: 'https://example.com' },
],
};
await page.evaluate((incoming) => {
host.emit('chat:appended', [incoming]);
host.emit('chat:appended', [incoming]);
}, incoming);
assert.match(await panel.locator('summary').textContent(), /1 unread/);
// Visibility follows the chat panel's animation-frame measurement.
await page.locator('.chat-shortcut').waitFor({ state: 'visible' });
assert.equal(await page.locator('.chat-shortcut').isVisible(), true, 'unread messages show the shortcut');
await page.evaluate(() => host.emit('preferences', { sound: false, chatNotifications: false }));
await page.locator('.chat-shortcut').waitFor({ state: 'hidden' });
assert.match(await panel.locator('summary').textContent(), /1 unread/);
await page.evaluate(() => host.emit('preferences', { sound: false, chatNotifications: true }));
await page.locator('.chat-shortcut').waitFor({ state: 'visible' });
assert.equal(await list.locator('article').count(), 36, 'duplicate append is ignored');
await page.evaluate((messages) => host.emit('chat:messages', messages), [...messages, incoming]);
assert.match(
await panel.locator('summary').textContent(),
/1 unread/,
'history refresh preserves known unread'
);
const link = list.locator('a');
assert.equal(await link.getAttribute('href'), 'https://example.com');
assert.match(await link.getAttribute('rel'), /noopener/);
await page.evaluate(
(incoming) =>
host.emit('chat:updated', [{ ...incoming, text: '<img src=x onerror=alert(1)>', segments: undefined }]),
incoming
);
assert.equal(await list.locator('article').last().locator('img').count(), 0);
assert.match(await list.locator('article').last().textContent(), /<img/);
await page.evaluate((incoming) => host.emit('chat:updated', [incoming]), incoming);
await panel.evaluate((el) => {
el.open = true;
});
if (width < 1000) await page.getByRole('tab', { name: /^Chat/ }).click();
await panel.scrollIntoViewIfNeeded();
await list.evaluate((el) => {
el.scrollTop = el.scrollHeight;
el.dispatchEvent(new Event('scroll'));
});
await list.locator('.chat-mention').click();
assert.deepEqual(await page.evaluate(() => playerClicks), [{ index: 0 }]);
await page.waitForFunction(() => receipts.some((r) => r.messageId === '000000000000000000000028'));
await page.waitForFunction(() => document.querySelector('.chat-shortcut').hidden);
const receiptCount = await page.evaluate(() => receipts.length);
await list.evaluate((el) => {
el.scrollTop = 0;
el.dispatchEvent(new Event('scroll'));
el.scrollTop = el.scrollHeight;
el.dispatchEvent(new Event('scroll'));
});
await page.waitForTimeout(650);
assert.equal(await page.evaluate(() => receipts.length), receiptCount, 'scrolling does not repeat read events');
await page.evaluate(() => host.emit('chat:deleted', ['000000000000000000000028']));
assert.equal(await list.locator('article').count(), 35);
await page.evaluate((state) => {
host.emit('state', state);
host.emit('state:updated');
}, state);
await page.waitForFunction(() => fetches > 0);
assert.equal(await page.evaluate(() => readyCount), 1, 'ready fires once');
await page.evaluate(
(state) => host.emit('gamelog', { start: 0, data: { state: { ...state, newTurn: false } } }),
state
);
await page.waitForTimeout(100);
assert.equal(
await page.evaluate(() => fetches),
1,
'tentative move state is rendered without fetching a committed state'
);
await page.evaluate(() => {
window.translationsRequested = [];
host.on('chat:translate', (request) => {
translationsRequested.push(request);
host.emit('chat:translation', { ...request, ok: true, text: 'Bonjour <img src=x>', language: 'en' });
});
host.emit('chat:state', {
canSend: true,
translationTarget: 'fr',
translationLabels: {
translate: 'Traduire',
translating: 'Traduction…',
translated: 'Traduit',
original: 'Voir l’original',
error: 'Indisponible',
retry: 'Réessayer',
},
});
host.emit('chat:messages', [
{ _id: '000000000000000000000070', type: 'text', text: 'Hello', language: 'en' },
]);
});
await page.locator('.chat-translate').click();
await page.getByRole('button', { name: 'Traduit · Voir l’original', exact: true }).waitFor();
assert.equal(await page.evaluate(() => translationsRequested.length), 1);
assert.equal(await page.locator('[data-message-id="000000000000000000000070"] img').count(), 0);
assert.match(
await page.locator('[data-message-id="000000000000000000000070"]').textContent(),
/Bonjour <img src=x>/
);
await page.locator('.chat-translate').click();
assert.match(await page.locator('[data-message-id="000000000000000000000070"]').textContent(), /Hello/);
assert.equal(
await page.evaluate(() => translationsRequested.length),
1,
'showing original needs no new request'
);
await page.evaluate(() => host.emit('preferences', { sound: false, analysis: true }));
await page.waitForFunction(() => !document.querySelector('.chat-translate')?.getBoundingClientRect().height);
await page.screenshot({ path: '/tmp/container-analysis-' + width + '.png', fullPage: true });
await page.evaluate(() => host.emit('preferences', { sound: false, analysis: false }));
await page.screenshot({ path: `/tmp/${game}-protocol-${width}.png`, fullPage: true });
await page.evaluate(
({ state, incoming }) => {
const old = host;
host = window[globalName].launch('#app');
host.emit('preferences', { sound: false });
host.emit('player', { index: 0 });
host.emit('state', state);
host.emit('chat:state', { canSend: true });
old.emit('chat:appended', [incoming]);
},
{ state, incoming }
);
assert.equal(await page.locator('.bgs-game-chat').count(), 1);
assert.equal(await page.locator('.chat-messages article').count(), 0, 'relaunch detaches old chat');
await assertJournalAtEnd();
await page.reload();
await page.evaluate((state) => {
window.host = window.container.launch('#app');
host.emit('preferences', { sound: false });
host.emit('state', state);
}, state);
await assertJournalAtEnd();
assert.deepEqual(errors, [], 'no browser errors');
// Reloaded history uses BGS's saved watermark, not just live append events.
await page.locator('.bgs-game-chat').evaluate((el) => {
el.open = false;
});
await page.evaluate(() => {
window.restoredReceipts = [];
host.on('chat:read', (payload) => restoredReceipts.push(payload));
host.emit('chat:state', { canSend: true, readState: { userId: 'self', lastReadAt: 1000 } });
host.emit('chat:messages', [
{ _id: '000000010000000000000001', type: 'text', authorId: 'bob', text: 'Already read' },
{ _id: '000000020000000000000001', type: 'text', authorId: 'bob', text: 'Unread after reload' },
{ _id: '000000030000000000000001', type: 'text', authorId: 'self', text: 'My own message' },
{ _id: '000000040000000000000001', type: 'system', text: 'Game started' },
]);
});
await page.waitForFunction(() => /1 unread/.test(document.querySelector('.bgs-game-chat summary').textContent));
await page.waitForTimeout(650);
assert.equal(
await page.evaluate(() => restoredReceipts.length),
0,
'hidden chat does not mark restored history read'
);
await page.locator('.chat-shortcut').click();
await page.waitForFunction(() => restoredReceipts.length > 0);
assert.doesNotMatch(
await page.locator('.bgs-game-chat summary').textContent(),
/unread/,
'opening chat clears restored unread'
);
await checkHostPresentation(page, 'host', `/tmp/container-board-thumbnail-${width}.png`);
await checkAuctionMessages(page, state);
await checkUndoMove(page, engine);
assert.deepEqual(errors, []);
await page.close();
console.log(`${game} ${width}px: protocol/chat smoke passed`);
}
await checkFinalScore(browser, `http://127.0.0.1:${server.address().port}/`, engine);
} finally {
await browser.close();
await new Promise((resolve) => server.close(resolve));
}

Some files were not shown because too many files have changed in this diff Show more