Initialize project with Outpost engine and viewer foundations
This commit is contained in:
commit
b2c3100d45
57 changed files with 6386 additions and 0 deletions
39
.github/workflows/ci.yml
vendored
Normal file
39
.github/workflows/ci.yml
vendored
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 11.11.0
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
cache: pnpm
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Format check (oxfmt)
|
||||
run: pnpm fmt:check
|
||||
|
||||
- name: Lint (oxlint)
|
||||
run: pnpm lint
|
||||
|
||||
- name: Typecheck (engine tsc + viewer svelte-check)
|
||||
run: pnpm tsc
|
||||
|
||||
- name: Test (engine)
|
||||
run: pnpm test
|
||||
|
||||
- name: Build (engine + viewer)
|
||||
run: pnpm build
|
||||
8
.gitignore
vendored
Normal file
8
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
node_modules
|
||||
dist
|
||||
.DS_Store
|
||||
*.local
|
||||
.vite
|
||||
dist-test
|
||||
.pnpm-store
|
||||
.playwright-mcp
|
||||
1
.nvmrc
Normal file
1
.nvmrc
Normal file
|
|
@ -0,0 +1 @@
|
|||
24
|
||||
10
.oxfmtrc.json
Normal file
10
.oxfmtrc.json
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
{
|
||||
"printWidth": 120,
|
||||
"tabWidth": 2,
|
||||
"useTabs": true,
|
||||
"semi": true,
|
||||
"singleQuote": false,
|
||||
"trailingComma": "es5",
|
||||
"svelte": true,
|
||||
"ignorePatterns": ["**/dist/**", "**/dist-test/**", "**/node_modules/**", "pnpm-lock.yaml"]
|
||||
}
|
||||
7
.oxlintrc.json
Normal file
7
.oxlintrc.json
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
"$schema": "https://raw.githubusercontent.com/oxc-project/oxc/main/npm/oxlint/configuration_schema.json",
|
||||
"rules": {
|
||||
"curly": ["error", "all"]
|
||||
},
|
||||
"ignorePatterns": ["**/dist/**", "**/dist-test/**", "**/node_modules/**"]
|
||||
}
|
||||
93
AGENTS.md
Normal file
93
AGENTS.md
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
# AGENTS.md
|
||||
|
||||
Guidance for AI agents and contributors working in this repository.
|
||||
|
||||
## What this is
|
||||
|
||||
Unofficial open-source implementation of the board game Outpost (1991, James Hlavaty) for
|
||||
boardgamers.space (BGS). Two packages: `packages/engine` (`outpost-engine`, rules + BGS
|
||||
wrapper) and `packages/viewer` (`outpost-viewer`, Svelte 5 browser UI). See README.md for
|
||||
the full picture, including the rules set implemented (Expert Rules v1.32) and the known
|
||||
data deviations (some production deck distributions are inferred, not confirmed).
|
||||
|
||||
## Conventions
|
||||
|
||||
- **ESM everywhere**: `"type": "module"` in every package. TS imports use explicit `.js`
|
||||
extensions in the engine (`moduleResolution: nodenext`) and no extension in the viewer
|
||||
(`moduleResolution: bundler`) — follow the local pattern of each package.
|
||||
- **Node >= 24** (`engines` field, `.nvmrc`), **pnpm 11** workspaces (`pnpm-workspace.yaml`).
|
||||
- **TypeScript strict**, including `noUncheckedIndexedAccess`. Code must pass `pnpm tsc`
|
||||
(engine `tsc --noEmit`, viewer `svelte-check`) with zero errors.
|
||||
- **No comments by default** — write self-explanatory code; comment only the non-obvious "why"
|
||||
(e.g. a BGS contract quirk, a rules edge case). No emojis in code or docs.
|
||||
- **Formatting**: oxfmt (`.oxfmtrc.json`) — **tabs** for indentation (tabWidth 2),
|
||||
120-column lines, Svelte formatting enabled. Run `pnpm fmt` to format, `pnpm fmt:check`
|
||||
in CI. Linting: oxlint (`.oxlintrc.json`) with `curly: all` — always brace `if`/`for`/
|
||||
`while` bodies. Run `pnpm lint`.
|
||||
- **Tests**: colocated `*.spec.ts` next to engine sources, run with `node --test` against
|
||||
compiled output (`pnpm --filter outpost-engine test` compiles to `dist-test/` first).
|
||||
Use `node:assert/strict`.
|
||||
- **Dependencies**: pin exact versions; verify a version exists (`npm view <pkg> version`)
|
||||
before adding it. Keep the dependency list minimal.
|
||||
|
||||
## Engine specifics
|
||||
|
||||
- **In-place state mutation is intentional.** `applyMove` / `dropPlayer` mutate the passed
|
||||
`GameState` and return it, matching BGS/take6 engine semantics (the game-server
|
||||
JSON-serializes the state between calls). Illegal moves must throw **before any
|
||||
mutation** — validation runs first. Never mutate-then-throw.
|
||||
- The game state must stay JSON-serializable at all times (no functions, no class
|
||||
instances, no Map/Set) because BGS round-trips it through `JSON.parse(JSON.stringify(...))`.
|
||||
- All randomness goes through the seeded PRNG (`src/prng.ts`); the seed arrives via `init`.
|
||||
Never use `Math.random` in the engine — replay determinism depends on it. Randomness is
|
||||
drawn as `seedrandom(seed:counter)` with the counter stored in the state, so nothing
|
||||
needs to persist PRNG internals.
|
||||
- **The wrapper boundary deep-validates untrusted input.** `wrapper.move` receives raw
|
||||
network JSON; `applyMove` runs `sanitizeMove` (`src/sanitize.ts`) which rebuilds the move
|
||||
as a fresh literal with only whitelisted fields, strict type checks and bounded arrays —
|
||||
this protects both interpretation and the log (moves are stored verbatim in `state.log`).
|
||||
- **Hidden information**: `stripSecret` hides the seed (it derives all deck orders), deck
|
||||
values, other players' hand values (v = -1), and produced card values in round log
|
||||
entries. `logSlice` applies the same treatment. When writing features, never leak deck
|
||||
contents or opponents' card values into what a client can see.
|
||||
- **Replay** (`src/replay.ts`) rebuilds state from the log without consuming randomness:
|
||||
"round" log entries carry purchase order, market, supply and production draws, and a
|
||||
`replayMode` flag (`src/moves.ts`) makes round transitions and affordability checks
|
||||
inert so a _stripped_ log replays into a stripped state.
|
||||
- `packages/engine/wrapper.ts` is the BGS Engine API contract: keep the exported names and
|
||||
signatures in sync with the platform's `app/types/engine.ts`. `dist/wrapper.js` must
|
||||
exist after build (it is the registered `entryPoint`).
|
||||
- Production deck data (`src/data.ts`) reproduces the published card counts; treat it as
|
||||
rules data, not creative content. See README.md "Data notes / deviations" before changing
|
||||
distributions.
|
||||
|
||||
## Viewer specifics
|
||||
|
||||
- **Svelte 5 runes mode only**: `$state`, `$derived`, `$props`, `$effect`. No legacy
|
||||
`export let`, no `$:` reactive statements.
|
||||
- The viewer must keep working both inside the BGS iframe (postMessage bridge in
|
||||
`src/lib/bgs.svelte.ts`) and standalone (dev harness: `packages/viewer/index.html` +
|
||||
`src/dev.ts`). Uplink events are emitted on the emitter returned by `launch()` as well as
|
||||
posted to `window.parent`, so a local backend can subscribe the same way BGS does.
|
||||
- Keep everything asset-free: cards and tokens are pure CSS. Theme tokens live in
|
||||
`src/lib/theme.css`.
|
||||
- The BGS host measures `body.scrollHeight` — normal top-down document flow, no vertical
|
||||
centering tricks.
|
||||
- `wrapper.currentPlayer` returns an **array** of seats during the simultaneous discard
|
||||
phase; the dev backend (and any future integration) must handle both shapes.
|
||||
|
||||
## Workflow
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm dev # viewer dev server + mock backend harness
|
||||
pnpm fmt # oxfmt format (tabs, 120 cols)
|
||||
pnpm lint # oxlint (curly rule)
|
||||
pnpm tsc # engine tsc + viewer svelte-check
|
||||
pnpm test # engine tests
|
||||
pnpm build # engine dist/ + viewer dist/ (iife + css)
|
||||
pnpm check # fmt:check + lint + tsc + test + build
|
||||
```
|
||||
|
||||
Run `pnpm check` before committing. Commit with clear messages; do not create PRs
|
||||
(this repo has no remote).
|
||||
67
README.md
Normal file
67
README.md
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
# Outpost
|
||||
|
||||
Unofficial open-source implementation of the board game **Outpost** (James Hlavaty, 1991)
|
||||
for [boardgamers.space](https://boardgamers.space) (BGS). Not affiliated with TimJim or
|
||||
Stronghold Games.
|
||||
|
||||
Two packages:
|
||||
|
||||
- **`packages/engine`** (`outpost-engine`) — pure TypeScript rules engine plus the BGS
|
||||
wrapper contract (`wrapper.ts`). Dependency-light (only `seedrandom`), deterministic via
|
||||
a seeded PRNG, state stays JSON-serializable at all times.
|
||||
- **`packages/viewer`** (`outpost-viewer`) — Svelte 5 browser UI, built as a self-contained
|
||||
IIFE bundle for the BGS iframe (`window.outpost.launch(selector)`).
|
||||
|
||||
## Rules set
|
||||
|
||||
The engine implements the **20th Anniversary / Expert Rules v1.32** set, which is the
|
||||
version Stronghold Games adopted as the base rules:
|
||||
|
||||
- Hand capacity 10 (research & microbiotics cards don't count against it)
|
||||
- Research factories cost 30 and require a Laboratory; buying a New Chemicals factory
|
||||
requires spending a research card
|
||||
- Over-capacity players discard **before** actions (after production)
|
||||
- Robots don't count against the population limit; robot ownership is capped at
|
||||
(Robots upgrades × population)
|
||||
- Victory: 75 VP (manned factories + upgrades); ties on VP in purchase order are broken
|
||||
by total credits spent
|
||||
- Market refill via d4 / d10 / d12+1 depending on the leading VP, per the v1.32 setup chart
|
||||
|
||||
### Data notes / deviations
|
||||
|
||||
Production card distributions and averages follow the official reference sheet v1.32 and
|
||||
owner-verified card counts (BGG thread 2801038). Water, titanium, new chemicals and orbital
|
||||
medicine decks are confirmed card-by-card; the remaining decks (ore, research, microbiotics,
|
||||
ring ore, moon ore) use symmetric bell distributions matching the confirmed deck sizes and
|
||||
official average values, since exact value splits were not available. The original edition's
|
||||
physical decks differ in a few counts (e.g. only two "4" water cards).
|
||||
|
||||
- In-game randomness (deck shuffles, die rolls, tie-breaks) is fully deterministic from the
|
||||
game seed; BGS supplies the seed, so replays and save/load are exact.
|
||||
- Random VP tie-breaks in purchase order are resolved by seat order (never relevant online).
|
||||
- Auction winners receive no change when overpaying, per the rules.
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm dev # viewer dev server + mock backend harness (human + bots)
|
||||
pnpm check # fmt:check + lint + tsc + test + build
|
||||
```
|
||||
|
||||
Dev harness URL params: `?players=4&seed=xyz&delay=700&auto=1`.
|
||||
|
||||
Node >= 24, pnpm 11 (see `packageManager`). All dependencies pinned.
|
||||
|
||||
## Deploying to BGS
|
||||
|
||||
- Engine: `npm pack` the built `outpost-engine` (or publish) and register it as the game
|
||||
engine in the BGS admin panel; entry point `dist/wrapper.js`.
|
||||
- Viewer: upload `packages/viewer/dist/outpost-viewer.iife.js` + `outpost-viewer.css`
|
||||
(and the `.map` with a shared bundle id if you want devtools sourcemaps).
|
||||
|
||||
See <https://docs.boardgamers.space/guide/adding-a-game>.
|
||||
|
||||
## License
|
||||
|
||||
AGPL-3.0.
|
||||
27
package.json
Normal file
27
package.json
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
{
|
||||
"name": "outpost",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"description": "Unofficial open-source implementation of the board game Outpost for boardgamers.space (engine + viewer)",
|
||||
"license": "AGPL-3.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "pnpm --filter outpost-viewer dev",
|
||||
"build": "pnpm --filter outpost-engine build && pnpm --filter outpost-viewer build",
|
||||
"test": "pnpm --filter outpost-engine test",
|
||||
"tsc": "pnpm --filter outpost-engine tsc && pnpm --filter outpost-viewer tsc",
|
||||
"fmt": "oxfmt",
|
||||
"fmt:check": "oxfmt --check",
|
||||
"lint": "oxlint",
|
||||
"check": "pnpm fmt:check && pnpm lint && pnpm tsc && pnpm test && pnpm build"
|
||||
},
|
||||
"devDependencies": {
|
||||
"oxfmt": "0.61.0",
|
||||
"oxlint": "1.76.0",
|
||||
"svelte": "5.56.8"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=24"
|
||||
},
|
||||
"packageManager": "pnpm@11.11.0"
|
||||
}
|
||||
12
packages/engine/index.ts
Normal file
12
packages/engine/index.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
export * from "./src/types.js";
|
||||
export * from "./src/data.js";
|
||||
export * from "./src/prng.js";
|
||||
export * from "./src/sanitize.js";
|
||||
export * from "./src/state.js";
|
||||
export * from "./src/market.js";
|
||||
export * from "./src/production.js";
|
||||
export * from "./src/moves.js";
|
||||
export * from "./src/rankings.js";
|
||||
export * from "./src/describe.js";
|
||||
export * from "./src/replay.js";
|
||||
export * from "./src/ai.js";
|
||||
45
packages/engine/package.json
Normal file
45
packages/engine/package.json
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
{
|
||||
"name": "outpost-engine",
|
||||
"version": "0.1.0",
|
||||
"description": "Unofficial Outpost rules engine for boardgamers.space",
|
||||
"license": "AGPL-3.0",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./wrapper": {
|
||||
"types": "./dist/wrapper.d.ts",
|
||||
"default": "./dist/wrapper.js"
|
||||
},
|
||||
"./wrapper.js": {
|
||||
"types": "./dist/wrapper.d.ts",
|
||||
"default": "./dist/wrapper.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.build.json",
|
||||
"prepack": "pnpm build",
|
||||
"prepublishOnly": "pnpm build",
|
||||
"tsc": "tsc --noEmit",
|
||||
"test": "tsc -p tsconfig.test.json && node --test \"dist-test/src/*.spec.js\""
|
||||
},
|
||||
"dependencies": {
|
||||
"seedrandom": "3.0.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "24.10.1",
|
||||
"@types/seedrandom": "3.0.8",
|
||||
"typescript": "5.9.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=24"
|
||||
}
|
||||
}
|
||||
42
packages/engine/src/ai.spec.ts
Normal file
42
packages/engine/src/ai.spec.ts
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { chooseMove, moveAI } from "./ai.js";
|
||||
import { initGame } from "./moves.js";
|
||||
import { scores } from "./state.js";
|
||||
import { currentPlayer } from "../wrapper.js";
|
||||
import type { GameState } from "./types.js";
|
||||
|
||||
function playOut(state: GameState, maxMoves = 100000): GameState {
|
||||
for (let i = 0; i < maxMoves && !state.ended; i++) {
|
||||
const current = currentPlayer(state);
|
||||
const seat = Array.isArray(current) ? current[0] : current;
|
||||
assert.notEqual(seat, undefined, `no current player in phase ${state.phase}`);
|
||||
moveAI(state, seat as number);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
test("AI plays a full 4-player game to completion", () => {
|
||||
const state = playOut(initGame(4, {}, "ai-4p"));
|
||||
assert.ok(state.ended);
|
||||
assert.ok(state.round <= 200);
|
||||
assert.ok(Math.max(...scores(state)) > 3, "somebody scored beyond the starting VP");
|
||||
});
|
||||
|
||||
test("AI plays a full 2-player game to completion", () => {
|
||||
const state = playOut(initGame(2, {}, "ai-2p"));
|
||||
assert.ok(state.ended);
|
||||
});
|
||||
|
||||
test("AI always proposes legal moves from any solicited state", () => {
|
||||
const state = initGame(5, {}, "ai-legal");
|
||||
for (let i = 0; i < 2000 && !state.ended; i++) {
|
||||
const current = currentPlayer(state);
|
||||
const seat = Array.isArray(current) ? current[0] : current;
|
||||
assert.notEqual(seat, undefined);
|
||||
// chooseMove must not throw and applyMove must accept it.
|
||||
const move = chooseMove(state, seat as number);
|
||||
moveAI(state, seat as number);
|
||||
assert.ok(move.action.length > 0);
|
||||
}
|
||||
});
|
||||
121
packages/engine/src/ai.ts
Normal file
121
packages/engine/src/ai.ts
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
import { FACTORIES, PRODUCTION_DECKS, UPGRADE_SPECS } from "./data.js";
|
||||
import { applyMove } from "./moves.js";
|
||||
import { canBuyFactory, handCapacity, handValue, populationCost, populationMax, upgradeDiscount } from "./state.js";
|
||||
import type { GameState, Move, PlayerState, Upgrade } from "./types.js";
|
||||
|
||||
/** Pick a legal (and mildly sensible) move for the player, then apply it. */
|
||||
export function moveAI(state: GameState, seat: number): GameState {
|
||||
return applyMove(state, chooseMove(state, seat), seat);
|
||||
}
|
||||
|
||||
export function chooseMove(state: GameState, seat: number): Move {
|
||||
const player = state.players[seat];
|
||||
if (!player || player.dropped) {
|
||||
throw new Error(`no move expected from player ${seat}`);
|
||||
}
|
||||
switch (state.phase) {
|
||||
case "discard":
|
||||
return chooseDiscard(player);
|
||||
case "auction":
|
||||
return { action: "bidPass" };
|
||||
case "auctionPayment": {
|
||||
const auction = state.auction;
|
||||
if (!auction) {
|
||||
throw new Error("no auction in progress");
|
||||
}
|
||||
const due = Math.max(0, auction.highBid - upgradeDiscount(player, auction.upgrade));
|
||||
return { action: "pay", cards: choosePayment(player, due) };
|
||||
}
|
||||
case "actions":
|
||||
return chooseAction(state, player);
|
||||
default:
|
||||
throw new Error(`no move expected in phase ${state.phase}`);
|
||||
}
|
||||
}
|
||||
|
||||
function chooseDiscard(player: PlayerState): Move {
|
||||
const cap = handCapacity(player);
|
||||
const counting = player.hand
|
||||
.map((card, index) => ({ card, index }))
|
||||
.filter(({ card }) => card.t !== "research" && card.t !== "microbiotics")
|
||||
.sort((a, b) => a.card.v - b.card.v);
|
||||
const excess = Math.max(0, counting.length - cap);
|
||||
return { action: "discard", cards: counting.slice(0, excess).map((e) => e.index) };
|
||||
}
|
||||
|
||||
/** Smallest cards first until the amount is covered — burns change, keeps big cards. */
|
||||
function choosePayment(player: PlayerState, due: number, mustIncludeResearch = false): number[] {
|
||||
const picked: number[] = [];
|
||||
let total = 0;
|
||||
if (mustIncludeResearch) {
|
||||
const research = player.hand
|
||||
.map((card, index) => ({ card, index }))
|
||||
.filter(({ card }) => card.t === "research")
|
||||
.sort((a, b) => a.card.v - b.card.v)[0];
|
||||
if (research) {
|
||||
picked.push(research.index);
|
||||
total += research.card.v;
|
||||
}
|
||||
}
|
||||
const ascending = player.hand
|
||||
.map((card, index) => ({ card, index }))
|
||||
.filter(({ index }) => !picked.includes(index))
|
||||
.sort((a, b) => a.card.v - b.card.v);
|
||||
for (const { card, index } of ascending) {
|
||||
if (total >= due) {
|
||||
break;
|
||||
}
|
||||
picked.push(index);
|
||||
total += card.v;
|
||||
}
|
||||
return picked;
|
||||
}
|
||||
|
||||
function chooseAction(state: GameState, player: PlayerState): Move {
|
||||
const cash = handValue(player);
|
||||
|
||||
// 1. Auction the highest-VP upgrade we can afford at list price.
|
||||
let bestIndex = -1;
|
||||
let bestVp = -1;
|
||||
state.market.forEach((upgrade, index) => {
|
||||
const spec = UPGRADE_SPECS[upgrade];
|
||||
const due = Math.max(0, spec.price - upgradeDiscount(player, upgrade));
|
||||
if (cash >= due && spec.vp > bestVp) {
|
||||
bestVp = spec.vp;
|
||||
bestIndex = index;
|
||||
}
|
||||
});
|
||||
if (bestIndex >= 0) {
|
||||
const upgrade = state.market[bestIndex] as Upgrade;
|
||||
return { action: "auction", marketIndex: bestIndex, bid: UPGRADE_SPECS[upgrade].price };
|
||||
}
|
||||
|
||||
// 2. Recruit population while there are factories to man.
|
||||
const unmanned = player.factories.length - (player.population + player.robots);
|
||||
if (unmanned > 0 && player.population < populationMax(player) && cash >= populationCost(player)) {
|
||||
return { action: "buyPopulation", count: 1, cards: choosePayment(player, populationCost(player)) };
|
||||
}
|
||||
|
||||
// 3. Expand production while there are operators (or room) for it.
|
||||
for (const type of ["titanium", "water", "ore"] as const) {
|
||||
const cost = FACTORIES[type].cost;
|
||||
if (
|
||||
canBuyFactory(player, type) &&
|
||||
cash >= cost &&
|
||||
player.factories.length < populationMax(player) + player.robots
|
||||
) {
|
||||
if (type === "titanium" || cash >= cost + populationCost(player)) {
|
||||
return { action: "buyFactory", factory: type, cards: choosePayment(player, cost) };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Man the most valuable factories and end the turn.
|
||||
const operators = player.population + player.robots;
|
||||
const manned = player.factories
|
||||
.map((factory, index) => ({ index, value: PRODUCTION_DECKS[factory.type].average }))
|
||||
.sort((a, b) => b.value - a.value)
|
||||
.slice(0, operators)
|
||||
.map((e) => e.index);
|
||||
return { action: "endTurn", manned };
|
||||
}
|
||||
107
packages/engine/src/auction.spec.ts
Normal file
107
packages/engine/src/auction.spec.ts
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { applyMove, initGame } from "./moves.js";
|
||||
import { handValue, upgradeDiscount, victoryPoints } from "./state.js";
|
||||
import type { GameState, PlayerState, ProductionCard } from "./types.js";
|
||||
|
||||
function fixedGame(): GameState {
|
||||
const state = initGame(3, {}, "auction-spec");
|
||||
// Deterministic hands for the test: give the active player plenty of cash.
|
||||
const active = state.players[state.activeSeat] as PlayerState;
|
||||
active.hand = [
|
||||
{ t: "water", v: 10 },
|
||||
{ t: "water", v: 10 },
|
||||
{ t: "water", v: 10 },
|
||||
];
|
||||
return state;
|
||||
}
|
||||
|
||||
function seatAfter(state: GameState, seat: number): number {
|
||||
const order = state.purchaseOrder;
|
||||
return order[(order.indexOf(seat) + 1) % order.length] as number;
|
||||
}
|
||||
|
||||
test("auction: open, outbid, pass, pay", () => {
|
||||
const state = fixedGame();
|
||||
const opener = state.activeSeat;
|
||||
const upgrade = state.market[0]!;
|
||||
const rival = seatAfter(state, opener);
|
||||
(state.players[rival] as PlayerState).hand = [{ t: "water", v: 50 } as ProductionCard];
|
||||
|
||||
applyMove(state, { action: "auction", marketIndex: 0, bid: 25 }, opener);
|
||||
assert.equal(state.phase, "auction");
|
||||
assert.equal(state.auction?.activeBidder, rival);
|
||||
|
||||
applyMove(state, { action: "bid", amount: 28 }, rival);
|
||||
assert.equal(state.auction?.highBidder, rival);
|
||||
|
||||
const third = seatAfter(state, rival);
|
||||
applyMove(state, { action: "bidPass" }, third);
|
||||
// Opener declines to raise.
|
||||
applyMove(state, { action: "bidPass" }, opener);
|
||||
assert.equal(state.phase, "auctionPayment");
|
||||
assert.equal(state.auction?.highBidder, rival);
|
||||
|
||||
applyMove(state, { action: "pay", cards: [0] }, rival);
|
||||
const winner = state.players[rival] as PlayerState;
|
||||
assert.equal(winner.upgrades[upgrade], 1);
|
||||
assert.equal(winner.hand.length, 0); // no change given
|
||||
assert.equal(winner.spent, 50);
|
||||
// Action resumes with the auctioneer.
|
||||
assert.equal(state.phase, "actions");
|
||||
assert.equal(state.activeSeat, opener);
|
||||
});
|
||||
|
||||
test("auction: opening bid below list price is rejected", () => {
|
||||
const state = fixedGame();
|
||||
assert.throws(() => applyMove(state, { action: "auction", marketIndex: 0, bid: 5 }, state.activeSeat));
|
||||
assert.equal(state.phase, "actions");
|
||||
});
|
||||
|
||||
test("auction: cannot bid beyond your hand value", () => {
|
||||
const state = fixedGame();
|
||||
const opener = state.activeSeat;
|
||||
applyMove(state, { action: "auction", marketIndex: 0, bid: 25 }, opener);
|
||||
const bidder = state.auction?.activeBidder as number;
|
||||
const player = state.players[bidder] as PlayerState;
|
||||
assert.throws(() => applyMove(state, { action: "bid", amount: handValue(player) + 100 }, bidder));
|
||||
});
|
||||
|
||||
test("data library discounts scientists at payment time", () => {
|
||||
const state = initGame(3, {}, "discount-spec");
|
||||
const seat = state.activeSeat;
|
||||
const player = state.players[seat] as PlayerState;
|
||||
player.upgrades.dataLibrary = 1;
|
||||
assert.equal(upgradeDiscount(player, "scientists"), 10);
|
||||
state.market[0] = "scientists";
|
||||
player.hand = [{ t: "water", v: 30 }];
|
||||
|
||||
applyMove(state, { action: "auction", marketIndex: 0, bid: 40 }, seat);
|
||||
for (let guard = 0; guard < 5 && state.phase === "auction"; guard++) {
|
||||
applyMove(state, { action: "bidPass" }, state.auction?.activeBidder as number);
|
||||
}
|
||||
assert.equal(state.phase, "auctionPayment");
|
||||
// Due 40 - 10 = 30, payable with the single 30 card.
|
||||
applyMove(state, { action: "pay", cards: [0] }, seat);
|
||||
assert.equal(player.upgrades.scientists, 1);
|
||||
});
|
||||
|
||||
test("upgrade effects: outpost grants capacity, population max, free titanium factory and VP", () => {
|
||||
const state = initGame(3, {}, "effects-spec");
|
||||
const seat = state.activeSeat;
|
||||
const player = state.players[seat] as PlayerState;
|
||||
const before = victoryPoints(player);
|
||||
state.market[0] = "outpost";
|
||||
player.hand = [{ t: "water", v: 100 }];
|
||||
|
||||
applyMove(state, { action: "auction", marketIndex: 0, bid: 100 }, seat);
|
||||
for (let guard = 0; guard < 5 && state.phase === "auction"; guard++) {
|
||||
applyMove(state, { action: "bidPass" }, state.auction?.activeBidder as number);
|
||||
}
|
||||
applyMove(state, { action: "pay", cards: [0] }, seat);
|
||||
|
||||
assert.equal(player.upgrades.outpost, 1);
|
||||
assert.equal(player.factories.filter((f) => f.type === "titanium").length, 1);
|
||||
assert.equal(player.factories.at(-1)?.manned, false);
|
||||
assert.equal(victoryPoints(player), before + 5);
|
||||
});
|
||||
128
packages/engine/src/data.ts
Normal file
128
packages/engine/src/data.ts
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
import type { FactoryType, Resource, Upgrade } from "./types.js";
|
||||
|
||||
// Rules data for the 20th Anniversary edition (former "Expert Rules v1.32").
|
||||
// Sources: the official Outpost reference sheet v1.32 (costs, average values,
|
||||
// VPs, setup chart) and owner card counts reported on BGG (thread 2801038) for
|
||||
// the production deck distributions. Water, titanium, new chemicals and
|
||||
// orbital medicine distributions are confirmed card-by-card; the other decks
|
||||
// use symmetric bell distributions matching the confirmed deck sizes and the
|
||||
// official average values.
|
||||
|
||||
export interface DeckSpec {
|
||||
average: number;
|
||||
/** value -> number of copies */
|
||||
distribution: Record<number, number>;
|
||||
}
|
||||
|
||||
export const PRODUCTION_DECKS: Record<Resource, DeckSpec> = {
|
||||
ore: { average: 3, distribution: { 1: 3, 2: 6, 3: 8, 4: 6, 5: 3 } },
|
||||
water: { average: 7, distribution: { 4: 3, 5: 5, 6: 7, 7: 9, 8: 7, 9: 5, 10: 3 } },
|
||||
titanium: { average: 10, distribution: { 7: 5, 8: 7, 9: 9, 10: 11, 11: 9, 12: 7, 13: 5 } },
|
||||
research: { average: 13, distribution: { 9: 2, 10: 3, 11: 4, 12: 5, 13: 6, 14: 5, 15: 4, 16: 3, 17: 2 } },
|
||||
microbiotics: { average: 17, distribution: { 14: 1, 15: 2, 16: 3, 17: 4, 18: 3, 19: 2, 20: 1 } },
|
||||
newChemicals: { average: 20, distribution: { 14: 2, 16: 3, 18: 4, 20: 5, 22: 4, 24: 3, 26: 2 } },
|
||||
orbitalMedicine: { average: 30, distribution: { 20: 2, 25: 3, 30: 4, 35: 3, 40: 2 } },
|
||||
ringOre: { average: 40, distribution: { 30: 2, 35: 2, 40: 4, 45: 2, 50: 2 } },
|
||||
moonOre: { average: 50, distribution: { 40: 2, 45: 2, 50: 4, 55: 2, 60: 2 } },
|
||||
};
|
||||
|
||||
/** Resources that do not count against hand capacity. */
|
||||
export const CAP_EXEMPT: readonly Resource[] = ["research", "microbiotics"];
|
||||
|
||||
export interface FactorySpec {
|
||||
cost: number;
|
||||
vp: number;
|
||||
/** Upgrade required to be allowed to buy this factory type. */
|
||||
requires?: Upgrade;
|
||||
/** Buying requires spending at least one research production card. */
|
||||
needsResearchCard?: boolean;
|
||||
}
|
||||
|
||||
export const FACTORIES: Record<FactoryType, FactorySpec> = {
|
||||
ore: { cost: 10, vp: 1 },
|
||||
water: { cost: 20, vp: 1 },
|
||||
titanium: { cost: 30, vp: 2, requires: "heavyEquipment" },
|
||||
research: { cost: 30, vp: 2, requires: "laboratory" },
|
||||
newChemicals: { cost: 60, vp: 3, needsResearchCard: true },
|
||||
};
|
||||
|
||||
export interface UpgradeSpec {
|
||||
name: string;
|
||||
/** Minimum bid. */
|
||||
price: number;
|
||||
vp: number;
|
||||
/** Free production card(s) received each round per copy owned. */
|
||||
produces?: Resource;
|
||||
/** Free factory received on purchase (starts unmanned). */
|
||||
freeFactory?: FactoryType;
|
||||
handCapacityBonus?: number;
|
||||
populationBonus?: number;
|
||||
}
|
||||
|
||||
export const UPGRADE_SPECS: Record<Upgrade, UpgradeSpec> = {
|
||||
dataLibrary: { name: "Data Library", price: 15, vp: 1 },
|
||||
warehouse: { name: "Warehouse", price: 25, vp: 1, handCapacityBonus: 3 },
|
||||
heavyEquipment: { name: "Heavy Equipment", price: 25, vp: 1 },
|
||||
nodule: { name: "Nodule", price: 25, vp: 2, populationBonus: 3 },
|
||||
scientists: { name: "Scientists", price: 40, vp: 2, produces: "research" },
|
||||
orbitalLab: { name: "Orbital Lab", price: 50, vp: 3, produces: "microbiotics" },
|
||||
robots: { name: "Robots", price: 50, vp: 3 },
|
||||
laboratory: { name: "Laboratory", price: 100, vp: 5, freeFactory: "research" },
|
||||
ecoplants: { name: "Ecoplants", price: 50, vp: 5 },
|
||||
outpost: { name: "Outpost", price: 100, vp: 5, freeFactory: "titanium", handCapacityBonus: 5, populationBonus: 5 },
|
||||
spaceStation: { name: "Space Station", price: 120, vp: 10, produces: "orbitalMedicine" },
|
||||
planetaryCruiser: { name: "Planetary Cruiser", price: 160, vp: 15, produces: "ringOre" },
|
||||
moonBase: { name: "Moon Base", price: 200, vp: 20, produces: "moonOre" },
|
||||
};
|
||||
|
||||
/** Upgrade types rolled with the d4 / d10 / d12+1 (index = die result - 1). */
|
||||
export const UPGRADE_BY_ROLL: readonly Upgrade[] = [
|
||||
"dataLibrary",
|
||||
"warehouse",
|
||||
"heavyEquipment",
|
||||
"nodule",
|
||||
"scientists",
|
||||
"orbitalLab",
|
||||
"robots",
|
||||
"laboratory",
|
||||
"ecoplants",
|
||||
"outpost",
|
||||
"spaceStation",
|
||||
"planetaryCruiser",
|
||||
"moonBase",
|
||||
];
|
||||
|
||||
export const FIRST_TEN: readonly Upgrade[] = UPGRADE_BY_ROLL.slice(0, 10);
|
||||
export const LAST_THREE: readonly Upgrade[] = UPGRADE_BY_ROLL.slice(10);
|
||||
|
||||
export interface SetupRow {
|
||||
firstTen: number;
|
||||
lastThree: number;
|
||||
/** VP any player must reach before the d12+1 (phase 3) rolls start. */
|
||||
bigThreshold: number;
|
||||
}
|
||||
|
||||
/** Expert game setup chart (reference sheet v1.32). Player count 2 uses a die roll per type instead. */
|
||||
export const SETUP_CHART: Record<number, SetupRow> = {
|
||||
2: { firstTen: 0, lastThree: 0, bigThreshold: 40 },
|
||||
3: { firstTen: 2, lastThree: 2, bigThreshold: 35 },
|
||||
4: { firstTen: 3, lastThree: 3, bigThreshold: 40 },
|
||||
5: { firstTen: 3, lastThree: 4, bigThreshold: 30 },
|
||||
6: { firstTen: 4, lastThree: 4, bigThreshold: 35 },
|
||||
7: { firstTen: 5, lastThree: 5, bigThreshold: 40 },
|
||||
8: { firstTen: 5, lastThree: 6, bigThreshold: 30 },
|
||||
9: { firstTen: 6, lastThree: 6, bigThreshold: 35 },
|
||||
10: { firstTen: 7, lastThree: 7, bigThreshold: 40 },
|
||||
};
|
||||
|
||||
export const VICTORY_VP = 75;
|
||||
export const BASE_HAND_CAPACITY = 10;
|
||||
export const BASE_POPULATION_MAX = 5;
|
||||
export const POPULATION_COST = 10;
|
||||
export const POPULATION_COST_ECOPLANTS = 5;
|
||||
export const ROBOT_COST = 10;
|
||||
/** VP any player must reach before the d10 (phase 2) rolls start. */
|
||||
export const MID_THRESHOLD = 10;
|
||||
|
||||
export const MIN_PLAYERS = 2;
|
||||
export const MAX_PLAYERS = 10;
|
||||
54
packages/engine/src/describe.ts
Normal file
54
packages/engine/src/describe.ts
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
import { FACTORIES, UPGRADE_SPECS } from "./data.js";
|
||||
import type { GameState, LogEntry } from "./types.js";
|
||||
|
||||
function playerName(state: GameState, seat: number): string {
|
||||
return state.players[seat]?.name ?? `Player ${seat + 1}`;
|
||||
}
|
||||
|
||||
export function describeLogEntry(state: GameState, entry: LogEntry): string {
|
||||
switch (entry.type) {
|
||||
case "init":
|
||||
return `Game started with ${entry.players} players`;
|
||||
case "round": {
|
||||
const market = entry.market.map((u) => UPGRADE_SPECS[u].name).join(", ") || "empty";
|
||||
return `Round ${entry.round} — colony ship arrives: ${market}`;
|
||||
}
|
||||
case "end": {
|
||||
const scores = entry.scores.map((vp, seat) => `${playerName(state, seat)} ${vp} VP`).join(", ");
|
||||
return `Game over — ${scores}`;
|
||||
}
|
||||
case "move": {
|
||||
const name = playerName(state, entry.player);
|
||||
const move = entry.move;
|
||||
const info = entry.info;
|
||||
switch (move.action) {
|
||||
case "discard":
|
||||
return `${name} discards ${info?.discarded ?? move.cards.length} card(s)`;
|
||||
case "auction":
|
||||
return `${name} puts ${info?.upgrade ? UPGRADE_SPECS[info.upgrade].name : "an upgrade"} up for auction at ${move.bid}`;
|
||||
case "bid":
|
||||
return `${name} bids ${move.amount}`;
|
||||
case "bidPass":
|
||||
return `${name} passes on the auction`;
|
||||
case "pay":
|
||||
return `${name} buys ${info?.upgrade ? UPGRADE_SPECS[info.upgrade].name : "the upgrade"} (paid ${info?.paid ?? 0})`;
|
||||
case "buyFactory":
|
||||
return `${name} builds a ${FACTORIES[move.factory] ? move.factory : "?"} factory (paid ${info?.paid ?? 0})`;
|
||||
case "buyPopulation":
|
||||
return `${name} recruits ${move.count} colonist(s) (paid ${info?.paid ?? 0})`;
|
||||
case "buyRobots":
|
||||
return `${name} buys ${move.count} robot(s) (paid ${info?.paid ?? 0})`;
|
||||
case "endTurn":
|
||||
return `${name} ends their turn (${move.manned.length} factories manned)`;
|
||||
default:
|
||||
return `${name} moves`;
|
||||
}
|
||||
}
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
export function describeLog(state: GameState): string[] {
|
||||
return state.log.map((entry) => describeLogEntry(state, entry));
|
||||
}
|
||||
61
packages/engine/src/market.ts
Normal file
61
packages/engine/src/market.ts
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
import { MID_THRESHOLD, UPGRADE_BY_ROLL } from "./data.js";
|
||||
import { rollDie } from "./prng.js";
|
||||
import { bigThreshold, scores } from "./state.js";
|
||||
import type { GameState, Upgrade } from "./types.js";
|
||||
|
||||
/** Which die is rolled to refill the market, based on the current leader's VP. */
|
||||
export function marketDie(state: GameState): { sides: number; offset: number } {
|
||||
const best = Math.max(0, ...scores(state));
|
||||
if (best >= bigThreshold(state)) {
|
||||
return { sides: 12, offset: 1 }; // d12+1: upgrades 2-13
|
||||
}
|
||||
if (best >= MID_THRESHOLD) {
|
||||
return { sides: 10, offset: 0 }; // d10: upgrades 1-10
|
||||
}
|
||||
return { sides: 4, offset: 0 }; // d4: upgrades 1-4
|
||||
}
|
||||
|
||||
/** Max copies of one upgrade type in the market: half the players, rounded down, min 1. */
|
||||
export function marketTypeCap(state: GameState): number {
|
||||
return Math.max(1, Math.floor(state.players.length / 2));
|
||||
}
|
||||
|
||||
function marketCount(state: GameState, upgrade: Upgrade): number {
|
||||
return state.market.filter((u) => u === upgrade).length;
|
||||
}
|
||||
|
||||
function canOffer(state: GameState, upgrade: Upgrade, rollable: readonly Upgrade[]): boolean {
|
||||
return rollable.includes(upgrade) && state.supply[upgrade] > 0 && marketCount(state, upgrade) < marketTypeCap(state);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refill the market up to one card per player. Unsold cards stay. Each empty
|
||||
* slot is filled by rolling the phase die, rerolling while the rolled type is
|
||||
* exhausted or already at the market cap; if no rollable type can legally be
|
||||
* added, the slot stays empty.
|
||||
*/
|
||||
export function refillMarket(state: GameState): void {
|
||||
const { sides, offset } = marketDie(state);
|
||||
const rollable = UPGRADE_BY_ROLL.slice(offset, offset + sides);
|
||||
const slots = state.players.filter((p) => !p.dropped).length;
|
||||
|
||||
while (state.market.length < slots) {
|
||||
if (!rollable.some((u) => canOffer(state, u, rollable))) {
|
||||
return;
|
||||
}
|
||||
let upgrade: Upgrade | undefined;
|
||||
// Bounded rerolls; falls back to the first offerable type for determinism.
|
||||
for (let i = 0; i < 100 && upgrade === undefined; i++) {
|
||||
const rolled = UPGRADE_BY_ROLL[rollDie(state, sides) + offset - 1] as Upgrade;
|
||||
if (canOffer(state, rolled, rollable)) {
|
||||
upgrade = rolled;
|
||||
}
|
||||
}
|
||||
upgrade ??= rollable.find((u) => canOffer(state, u, rollable));
|
||||
if (upgrade === undefined) {
|
||||
return;
|
||||
}
|
||||
state.supply[upgrade] -= 1;
|
||||
state.market.push(upgrade);
|
||||
}
|
||||
}
|
||||
164
packages/engine/src/moves.spec.ts
Normal file
164
packages/engine/src/moves.spec.ts
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { applyMove, initGame } from "./moves.js";
|
||||
import { countingHandSize, handCapacity, populationMax, robotMax } from "./state.js";
|
||||
import type { GameState, PlayerState } from "./types.js";
|
||||
|
||||
function activePlayer(state: GameState): PlayerState {
|
||||
return state.players[state.activeSeat] as PlayerState;
|
||||
}
|
||||
|
||||
test("buy factory: water factory costs 20, joins unmanned", () => {
|
||||
const state = initGame(3, {}, "buy-spec");
|
||||
const player = activePlayer(state);
|
||||
player.hand = [
|
||||
{ t: "water", v: 10 },
|
||||
{ t: "water", v: 10 },
|
||||
];
|
||||
applyMove(state, { action: "buyFactory", factory: "water", cards: [0, 1] }, state.activeSeat);
|
||||
assert.equal(player.factories.length, 4);
|
||||
assert.equal(player.factories.at(-1)?.type, "water");
|
||||
assert.equal(player.factories.at(-1)?.manned, false);
|
||||
assert.equal(player.hand.length, 0);
|
||||
// Spent cards go to the face-up discard pile.
|
||||
assert.equal(state.discards.water.length, 2);
|
||||
});
|
||||
|
||||
test("buy factory: titanium requires heavy equipment, research requires laboratory", () => {
|
||||
const state = initGame(3, {}, "buy-spec2");
|
||||
const player = activePlayer(state);
|
||||
player.hand = [{ t: "water", v: 40 }];
|
||||
assert.throws(() => applyMove(state, { action: "buyFactory", factory: "titanium", cards: [0] }, state.activeSeat));
|
||||
assert.throws(() => applyMove(state, { action: "buyFactory", factory: "research", cards: [0] }, state.activeSeat));
|
||||
player.upgrades.heavyEquipment = 1;
|
||||
applyMove(state, { action: "buyFactory", factory: "titanium", cards: [0] }, state.activeSeat);
|
||||
assert.equal(player.factories.at(-1)?.type, "titanium");
|
||||
});
|
||||
|
||||
test("buy factory: new chemicals requires a research card in the payment", () => {
|
||||
const state = initGame(3, {}, "buy-spec3");
|
||||
const player = activePlayer(state);
|
||||
player.hand = [{ t: "water", v: 60 }];
|
||||
assert.throws(() =>
|
||||
applyMove(state, { action: "buyFactory", factory: "newChemicals", cards: [0] }, state.activeSeat)
|
||||
);
|
||||
player.hand = [
|
||||
{ t: "water", v: 50 },
|
||||
{ t: "research", v: 12 },
|
||||
];
|
||||
applyMove(state, { action: "buyFactory", factory: "newChemicals", cards: [0, 1] }, state.activeSeat);
|
||||
assert.equal(player.factories.at(-1)?.type, "newChemicals");
|
||||
});
|
||||
|
||||
test("population: costs 10 (5 with ecoplants), capped by population max", () => {
|
||||
const state = initGame(3, {}, "pop-spec");
|
||||
const player = activePlayer(state);
|
||||
player.hand = [
|
||||
{ t: "water", v: 10 },
|
||||
{ t: "water", v: 10 },
|
||||
{ t: "water", v: 10 },
|
||||
];
|
||||
applyMove(state, { action: "buyPopulation", count: 2, cards: [0, 1] }, state.activeSeat);
|
||||
assert.equal(player.population, 5);
|
||||
assert.throws(() => applyMove(state, { action: "buyPopulation", count: 1, cards: [0] }, state.activeSeat));
|
||||
assert.equal(populationMax(player), 5);
|
||||
player.upgrades.ecoplants = 1;
|
||||
player.upgrades.nodule = 1;
|
||||
assert.equal(populationMax(player), 8);
|
||||
applyMove(state, { action: "buyPopulation", count: 1, cards: [0] }, state.activeSeat); // 5 with ecoplants, 10 paid
|
||||
assert.equal(player.population, 6);
|
||||
});
|
||||
|
||||
test("robots: require the upgrade and respect the robot limit", () => {
|
||||
const state = initGame(3, {}, "robot-spec");
|
||||
const player = activePlayer(state);
|
||||
player.hand = [
|
||||
{ t: "water", v: 10 },
|
||||
{ t: "water", v: 10 },
|
||||
];
|
||||
assert.throws(() => applyMove(state, { action: "buyRobots", count: 1, cards: [0] }, state.activeSeat));
|
||||
player.upgrades.robots = 1;
|
||||
assert.equal(robotMax(player), player.population);
|
||||
applyMove(state, { action: "buyRobots", count: 1, cards: [0] }, state.activeSeat);
|
||||
assert.equal(player.robots, 1);
|
||||
});
|
||||
|
||||
test("end turn: mans the selected factories and passes the action turn on", () => {
|
||||
const state = initGame(3, {}, "turn-spec");
|
||||
const first = state.activeSeat;
|
||||
const player = activePlayer(state);
|
||||
applyMove(state, { action: "endTurn", manned: [0, 2] }, first);
|
||||
assert.equal(player.factories[0]?.manned, true);
|
||||
assert.equal(player.factories[1]?.manned, false);
|
||||
assert.equal(player.factories[2]?.manned, true);
|
||||
assert.ok(state.activeSeat !== first);
|
||||
assert.throws(() => applyMove(state, { action: "endTurn", manned: [] }, first));
|
||||
});
|
||||
|
||||
test("end turn: cannot man more factories than operators", () => {
|
||||
const state = initGame(3, {}, "turn-spec2");
|
||||
const player = activePlayer(state);
|
||||
player.factories.push({ type: "ore", manned: false });
|
||||
player.factories.push({ type: "ore", manned: false });
|
||||
assert.throws(() => applyMove(state, { action: "endTurn", manned: [0, 1, 2, 3, 4] }, state.activeSeat));
|
||||
});
|
||||
|
||||
test("discard phase: over-capacity players must discard down to the cap", () => {
|
||||
const state = initGame(3, {}, "discard-spec");
|
||||
// Complete round 1 with everyone hoarding; force a big hand on player 0.
|
||||
const hoarder = state.players[0] as PlayerState;
|
||||
hoarder.hand = Array.from({ length: 13 }, () => ({ t: "ore" as const, v: 1 }));
|
||||
hoarder.hand.push({ t: "research", v: 9 }); // exempt from the cap
|
||||
for (let guard = 0; guard < 10 && state.round === 1; guard++) {
|
||||
applyMove(state, { action: "endTurn", manned: [0, 1, 2] }, state.activeSeat);
|
||||
}
|
||||
assert.equal(state.round, 2);
|
||||
assert.equal(state.phase, "discard");
|
||||
assert.ok(hoarder.mustDiscard);
|
||||
assert.ok(countingHandSize(hoarder) > handCapacity(hoarder));
|
||||
// Not enough discards rejected.
|
||||
assert.throws(() => applyMove(state, { action: "discard", cards: [0] }, 0));
|
||||
const excess = countingHandSize(hoarder) - handCapacity(hoarder);
|
||||
applyMove(state, { action: "discard", cards: Array.from({ length: excess }, (_, i) => i) }, 0);
|
||||
assert.equal(hoarder.mustDiscard, false);
|
||||
assert.equal(state.phase, "actions");
|
||||
});
|
||||
|
||||
test("hardening: malformed moves are rejected without mutating state", () => {
|
||||
const state = initGame(3, {}, "hardening-spec");
|
||||
const snapshot = JSON.stringify(state);
|
||||
const seat = state.activeSeat;
|
||||
assert.throws(() => applyMove(state, null as never, seat));
|
||||
assert.throws(() => applyMove(state, "endTurn" as never, seat));
|
||||
assert.throws(() => applyMove(state, [] as never, seat));
|
||||
assert.throws(() => applyMove(state, { action: "unknown" } as never, seat));
|
||||
assert.throws(() => applyMove(state, { action: "buyFactory", factory: "moon", cards: [] } as never, seat));
|
||||
assert.throws(() => applyMove(state, { action: "buyPopulation", count: 1, cards: [99] } as never, seat));
|
||||
assert.throws(() => applyMove(state, { action: "buyPopulation", count: 1, cards: [0, 0] } as never, seat));
|
||||
assert.throws(() => applyMove(state, { action: "buyPopulation", count: 1.5, cards: [0] } as never, seat));
|
||||
assert.throws(() => applyMove(state, { action: "buyPopulation", count: 1, cards: [0.5] } as never, seat));
|
||||
assert.throws(() => applyMove(state, { action: "bid", amount: Infinity } as never, seat));
|
||||
assert.throws(() => applyMove(state, { action: "bid", amount: "9" } as never, seat));
|
||||
assert.throws(() => applyMove(state, { action: "endTurn", manned: "all" } as never, seat));
|
||||
assert.throws(() => applyMove(state, { action: "endTurn", manned: [0] } as never, seat + 1));
|
||||
assert.throws(() => applyMove(state, { action: "endTurn", manned: [0] } as never, "0" as never));
|
||||
assert.throws(() =>
|
||||
applyMove(state, { action: "discard", cards: Array.from({ length: 10_000 }, (_, i) => i) } as never, seat)
|
||||
);
|
||||
assert.equal(JSON.stringify(state), snapshot);
|
||||
});
|
||||
|
||||
test("hardening: extra keys and __proto__ payloads are stripped before logging", () => {
|
||||
const state = initGame(3, {}, "hardening-spec2");
|
||||
const seat = state.activeSeat;
|
||||
const malicious = JSON.parse(
|
||||
'{"action":"endTurn","manned":[0,1,2],"__proto__":{"polluted":true},"junk":"x","nested":{"a":1}}'
|
||||
) as never;
|
||||
applyMove(state, malicious, seat);
|
||||
const logged = state.log.at(-1);
|
||||
assert.ok(logged?.type === "move");
|
||||
assert.deepEqual(logged.move, { action: "endTurn", manned: [0, 1, 2] });
|
||||
assert.equal(({} as { polluted?: boolean }).polluted, undefined);
|
||||
// The logged move is a fresh literal, not the network object.
|
||||
assert.notEqual(logged.move, malicious);
|
||||
});
|
||||
521
packages/engine/src/moves.ts
Normal file
521
packages/engine/src/moves.ts
Normal file
|
|
@ -0,0 +1,521 @@
|
|||
import { FACTORIES, ROBOT_COST, UPGRADE_SPECS, VICTORY_VP } from "./data.js";
|
||||
import { refillMarket } from "./market.js";
|
||||
import { producePlayer } from "./production.js";
|
||||
import {
|
||||
canBuyFactory,
|
||||
computePurchaseOrder,
|
||||
countingHandSize,
|
||||
handCapacity,
|
||||
handValue,
|
||||
populationCost,
|
||||
populationMax,
|
||||
robotMax,
|
||||
scores,
|
||||
setup,
|
||||
upgradeDiscount,
|
||||
} from "./state.js";
|
||||
import { sanitizeMove } from "./sanitize.js";
|
||||
import type { GameState, Move, MoveInfo, PlayerState, ProductionCard, Upgrade } from "./types.js";
|
||||
|
||||
/** Safety valve: no sane game lasts anywhere near this long. */
|
||||
export const MAX_ROUNDS = 200;
|
||||
|
||||
// During replay, rounds are driven by the "round" log entries (which carry the
|
||||
// market and production draws) instead of the PRNG, so ending a round must not
|
||||
// start the next one.
|
||||
let replayMode = false;
|
||||
|
||||
export function setReplayMode(value: boolean): void {
|
||||
replayMode = value;
|
||||
}
|
||||
|
||||
export function initGame(players: number, options: Record<string, unknown>, seed: string): GameState {
|
||||
const state = setup(players, options, seed);
|
||||
beginRound(state);
|
||||
return state;
|
||||
}
|
||||
|
||||
export function beginRound(state: GameState): void {
|
||||
state.round += 1;
|
||||
state.purchaseOrder = computePurchaseOrder(state);
|
||||
refillMarket(state);
|
||||
|
||||
const produced: { player: number; cards: ProductionCard[] }[] = [];
|
||||
for (const seat of state.purchaseOrder) {
|
||||
const player = state.players[seat] as PlayerState;
|
||||
produced.push({ player: seat, cards: producePlayer(state, player) });
|
||||
}
|
||||
|
||||
state.log.push({
|
||||
type: "round",
|
||||
round: state.round,
|
||||
purchaseOrder: [...state.purchaseOrder],
|
||||
market: [...state.market],
|
||||
supply: { ...state.supply },
|
||||
produced,
|
||||
});
|
||||
|
||||
enterDiscardPhase(state);
|
||||
}
|
||||
|
||||
export function enterDiscardPhase(state: GameState): void {
|
||||
let anyDiscard = false;
|
||||
for (const player of state.players) {
|
||||
player.done = false;
|
||||
player.mustDiscard = !player.dropped && countingHandSize(player) > handCapacity(player);
|
||||
anyDiscard ||= player.mustDiscard;
|
||||
}
|
||||
if (anyDiscard) {
|
||||
state.phase = "discard";
|
||||
} else {
|
||||
startActions(state);
|
||||
}
|
||||
}
|
||||
|
||||
function startActions(state: GameState): void {
|
||||
state.phase = "actions";
|
||||
const next = state.purchaseOrder.find((seat) => {
|
||||
const p = state.players[seat];
|
||||
return p && !p.dropped && !p.done;
|
||||
});
|
||||
if (next === undefined) {
|
||||
endRound(state);
|
||||
} else {
|
||||
state.activeSeat = next;
|
||||
}
|
||||
}
|
||||
|
||||
function endRound(state: GameState): void {
|
||||
const best = Math.max(0, ...scores(state));
|
||||
if (best >= VICTORY_VP || state.round >= MAX_ROUNDS || activePlayers(state) <= 1) {
|
||||
finishGame(state);
|
||||
return;
|
||||
}
|
||||
if (replayMode) {
|
||||
return;
|
||||
}
|
||||
// A stalled economy (nobody can produce) would loop forever; call it a draw.
|
||||
if (
|
||||
state.decks.ore.length + state.discards.ore.length + state.decks.water.length + state.discards.water.length ===
|
||||
0
|
||||
) {
|
||||
finishGame(state);
|
||||
return;
|
||||
}
|
||||
beginRound(state);
|
||||
}
|
||||
|
||||
function finishGame(state: GameState): void {
|
||||
state.ended = true;
|
||||
state.phase = "ended";
|
||||
state.auction = null;
|
||||
state.log.push({ type: "end", scores: scores(state) });
|
||||
}
|
||||
|
||||
function activePlayers(state: GameState): number {
|
||||
return state.players.filter((p) => !p.dropped).length;
|
||||
}
|
||||
|
||||
function err(message: string): never {
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
function getPlayer(state: GameState, seat: number): PlayerState {
|
||||
const player = state.players[seat];
|
||||
if (!player) {
|
||||
err(`invalid player ${seat}`);
|
||||
}
|
||||
if (player.dropped) {
|
||||
err(`player ${seat} has dropped`);
|
||||
}
|
||||
return player;
|
||||
}
|
||||
|
||||
function sanitizeIndices(raw: unknown, max: number, label: string): number[] {
|
||||
if (!Array.isArray(raw)) {
|
||||
err(`${label}: expected an array of card indices`);
|
||||
}
|
||||
const indices = raw.map((i) => {
|
||||
if (typeof i !== "number" || !Number.isInteger(i) || i < 0 || i >= max) {
|
||||
err(`${label}: invalid index ${String(i)}`);
|
||||
}
|
||||
return i;
|
||||
});
|
||||
if (new Set(indices).size !== indices.length) {
|
||||
err(`${label}: duplicate indices`);
|
||||
}
|
||||
return indices;
|
||||
}
|
||||
|
||||
/** Validate then move the selected cards to the discard piles. Returns their total value. */
|
||||
function spendCards(state: GameState, player: PlayerState, indices: number[], minValue: number): number {
|
||||
const total = indices.reduce((sum, i) => sum + (player.hand[i]?.v ?? 0), 0);
|
||||
// A stripped log carries hidden card values (-1); the server already
|
||||
// validated these payments, so replay must not re-check affordability.
|
||||
if (total < minValue && !replayMode) {
|
||||
err(`payment of ${total} is less than the required ${minValue}`);
|
||||
}
|
||||
removeCards(state, player, indices);
|
||||
player.spent += total;
|
||||
return total;
|
||||
}
|
||||
|
||||
function removeCards(state: GameState, player: PlayerState, indices: number[]): void {
|
||||
const sorted = [...indices].sort((a, b) => b - a);
|
||||
for (const i of sorted) {
|
||||
const card = player.hand.splice(i, 1)[0] as ProductionCard;
|
||||
state.discards[card.t].push(card.v);
|
||||
}
|
||||
}
|
||||
|
||||
export function applyMove(state: GameState, rawMove: Move | unknown, seat: number): GameState {
|
||||
if (state.ended) {
|
||||
err("the game has ended");
|
||||
}
|
||||
// Deep-validate the untrusted payload and rebuild it with only whitelisted
|
||||
// fields before it is interpreted or logged.
|
||||
const move = sanitizeMove(rawMove);
|
||||
if (typeof seat !== "number" || !Number.isInteger(seat)) {
|
||||
err("invalid player");
|
||||
}
|
||||
const player = getPlayer(state, seat);
|
||||
let info: MoveInfo | undefined;
|
||||
|
||||
switch (move.action) {
|
||||
case "discard":
|
||||
info = moveDiscard(state, move, seat, player);
|
||||
break;
|
||||
case "auction":
|
||||
info = moveAuction(state, move, seat, player);
|
||||
break;
|
||||
case "bid":
|
||||
info = moveBid(state, move, seat, player);
|
||||
break;
|
||||
case "bidPass":
|
||||
info = moveBidPass(state, move, seat);
|
||||
break;
|
||||
case "pay":
|
||||
info = movePay(state, move, seat, player);
|
||||
break;
|
||||
case "buyFactory":
|
||||
info = moveBuyFactory(state, move, seat, player);
|
||||
break;
|
||||
case "buyPopulation":
|
||||
info = moveBuyPopulation(state, move, seat, player);
|
||||
break;
|
||||
case "buyRobots":
|
||||
info = moveBuyRobots(state, move, seat, player);
|
||||
break;
|
||||
case "endTurn":
|
||||
info = moveEndTurn(state, move, seat, player);
|
||||
break;
|
||||
default:
|
||||
err(`unknown action ${String((move as { action: string }).action)}`);
|
||||
}
|
||||
|
||||
state.moveCount += 1;
|
||||
state.log.push(info ? { type: "move", player: seat, move, info } : { type: "move", player: seat, move });
|
||||
postMove(state, move);
|
||||
return state;
|
||||
}
|
||||
|
||||
/** Phase transitions that must happen after the move is logged (may end the round/game). */
|
||||
function postMove(state: GameState, move: Move): void {
|
||||
if (state.phase === "discard" && !state.players.some((p) => p.mustDiscard)) {
|
||||
startActions(state);
|
||||
return;
|
||||
}
|
||||
if (move.action === "endTurn") {
|
||||
startActions(state);
|
||||
}
|
||||
}
|
||||
|
||||
function moveDiscard(
|
||||
state: GameState,
|
||||
move: Move & { action: "discard" },
|
||||
seat: number,
|
||||
player: PlayerState
|
||||
): MoveInfo {
|
||||
if (state.phase !== "discard" || !player.mustDiscard) {
|
||||
err("no discard expected from this player");
|
||||
}
|
||||
const indices = sanitizeIndices(move.cards, player.hand.length, "discard");
|
||||
const remaining = player.hand.filter((_, i) => !indices.includes(i));
|
||||
const counting = remaining.filter((c) => c.t !== "research" && c.t !== "microbiotics").length;
|
||||
if (counting > handCapacity(player)) {
|
||||
err(`still ${counting} cards over the hand capacity of ${handCapacity(player)}`);
|
||||
}
|
||||
removeCards(state, player, indices);
|
||||
player.mustDiscard = false;
|
||||
return { discarded: indices.length };
|
||||
}
|
||||
|
||||
function requireActionTurn(state: GameState, seat: number, player: PlayerState): void {
|
||||
if (state.phase !== "actions") {
|
||||
err("not in the action phase");
|
||||
}
|
||||
if (state.activeSeat !== seat) {
|
||||
err("not this player's action turn");
|
||||
}
|
||||
if (player.done) {
|
||||
err("this player has already ended their turn");
|
||||
}
|
||||
}
|
||||
|
||||
function moveAuction(
|
||||
state: GameState,
|
||||
move: Move & { action: "auction" },
|
||||
seat: number,
|
||||
player: PlayerState
|
||||
): MoveInfo {
|
||||
requireActionTurn(state, seat, player);
|
||||
const { marketIndex, bid } = move;
|
||||
if (!Number.isInteger(marketIndex) || marketIndex < 0 || marketIndex >= state.market.length) {
|
||||
err("invalid market index");
|
||||
}
|
||||
const upgrade = state.market[marketIndex] as Upgrade;
|
||||
if (!Number.isInteger(bid) || bid < UPGRADE_SPECS[upgrade].price) {
|
||||
err(`opening bid must be at least ${UPGRADE_SPECS[upgrade].price}`);
|
||||
}
|
||||
assertCanPayBid(player, upgrade, bid);
|
||||
state.phase = "auction";
|
||||
state.auction = {
|
||||
marketIndex,
|
||||
upgrade,
|
||||
auctioneer: seat,
|
||||
highBid: bid,
|
||||
highBidder: seat,
|
||||
passed: [],
|
||||
activeBidder: seat,
|
||||
};
|
||||
advanceBidder(state);
|
||||
return { upgrade };
|
||||
}
|
||||
|
||||
function assertCanPayBid(player: PlayerState, upgrade: Upgrade, bid: number): void {
|
||||
if (replayMode) {
|
||||
return;
|
||||
}
|
||||
const due = Math.max(0, bid - upgradeDiscount(player, upgrade));
|
||||
if (handValue(player) < due) {
|
||||
err(`cannot afford a bid of ${bid} (needs ${due}, holds ${handValue(player)})`);
|
||||
}
|
||||
}
|
||||
|
||||
function biddingOrder(state: GameState): number[] {
|
||||
const auction = state.auction;
|
||||
if (!auction) {
|
||||
err("no auction in progress");
|
||||
}
|
||||
const order = state.purchaseOrder;
|
||||
const start = order.indexOf(auction.auctioneer);
|
||||
return order.map((_, i) => order[(start + i) % order.length] as number);
|
||||
}
|
||||
|
||||
function advanceBidder(state: GameState): void {
|
||||
const auction = state.auction;
|
||||
if (!auction) {
|
||||
err("no auction in progress");
|
||||
}
|
||||
const order = biddingOrder(state);
|
||||
const from = order.indexOf(auction.activeBidder);
|
||||
for (let step = 1; step <= order.length; step++) {
|
||||
const seat = order[(from + step) % order.length] as number;
|
||||
if (seat === auction.highBidder) {
|
||||
state.phase = "auctionPayment";
|
||||
auction.activeBidder = seat;
|
||||
return;
|
||||
}
|
||||
const p = state.players[seat];
|
||||
if (p && !p.dropped && !auction.passed.includes(seat)) {
|
||||
auction.activeBidder = seat;
|
||||
return;
|
||||
}
|
||||
}
|
||||
state.phase = "auctionPayment";
|
||||
auction.activeBidder = auction.highBidder;
|
||||
}
|
||||
|
||||
function moveBid(state: GameState, move: Move & { action: "bid" }, seat: number, player: PlayerState): MoveInfo {
|
||||
const auction = state.auction;
|
||||
if (state.phase !== "auction" || !auction || auction.activeBidder !== seat) {
|
||||
err("not this player's turn to bid");
|
||||
}
|
||||
if (!Number.isInteger(move.amount) || move.amount <= auction.highBid) {
|
||||
err(`bid must be higher than ${auction.highBid}`);
|
||||
}
|
||||
assertCanPayBid(player, auction.upgrade, move.amount);
|
||||
auction.highBid = move.amount;
|
||||
auction.highBidder = seat;
|
||||
advanceBidder(state);
|
||||
return { upgrade: auction.upgrade };
|
||||
}
|
||||
|
||||
function moveBidPass(state: GameState, _move: Move & { action: "bidPass" }, seat: number): MoveInfo {
|
||||
const auction = state.auction;
|
||||
if (state.phase !== "auction" || !auction || auction.activeBidder !== seat) {
|
||||
err("not this player's turn to bid");
|
||||
}
|
||||
auction.passed.push(seat);
|
||||
advanceBidder(state);
|
||||
return { upgrade: auction.upgrade };
|
||||
}
|
||||
|
||||
function movePay(state: GameState, move: Move & { action: "pay" }, seat: number, player: PlayerState): MoveInfo {
|
||||
const auction = state.auction;
|
||||
if (state.phase !== "auctionPayment" || !auction || auction.highBidder !== seat) {
|
||||
err("no payment expected from this player");
|
||||
}
|
||||
const due = Math.max(0, auction.highBid - upgradeDiscount(player, auction.upgrade));
|
||||
const indices = sanitizeIndices(move.cards, player.hand.length, "pay");
|
||||
const paid = spendCards(state, player, indices, due);
|
||||
|
||||
const upgrade = auction.upgrade;
|
||||
state.market.splice(auction.marketIndex, 1);
|
||||
player.upgrades[upgrade] += 1;
|
||||
const freeFactory = UPGRADE_SPECS[upgrade].freeFactory;
|
||||
if (freeFactory) {
|
||||
player.factories.push({ type: freeFactory, manned: false });
|
||||
}
|
||||
|
||||
state.messages.push(`${player.name} won ${UPGRADE_SPECS[upgrade].name} for ${auction.highBid}`);
|
||||
state.phase = "actions";
|
||||
state.activeSeat = auction.auctioneer;
|
||||
state.auction = null;
|
||||
|
||||
const auctioneer = state.players[state.activeSeat];
|
||||
if (!auctioneer || auctioneer.dropped || auctioneer.done) {
|
||||
startActions(state);
|
||||
}
|
||||
return { upgrade, paid };
|
||||
}
|
||||
|
||||
function moveBuyFactory(
|
||||
state: GameState,
|
||||
move: Move & { action: "buyFactory" },
|
||||
seat: number,
|
||||
player: PlayerState
|
||||
): MoveInfo {
|
||||
requireActionTurn(state, seat, player);
|
||||
const type = move.factory;
|
||||
const spec = FACTORIES[type];
|
||||
if (!canBuyFactory(player, type)) {
|
||||
err(`cannot build ${type} factories`);
|
||||
}
|
||||
const indices = sanitizeIndices(move.cards, player.hand.length, "buyFactory");
|
||||
if (spec.needsResearchCard && !indices.some((i) => player.hand[i]?.t === "research")) {
|
||||
err("buying a New Chemicals factory requires spending a research card");
|
||||
}
|
||||
const paid = spendCards(state, player, indices, spec.cost);
|
||||
player.factories.push({ type, manned: false });
|
||||
return { paid };
|
||||
}
|
||||
|
||||
function moveBuyPopulation(
|
||||
state: GameState,
|
||||
move: Move & { action: "buyPopulation" },
|
||||
seat: number,
|
||||
player: PlayerState
|
||||
): MoveInfo {
|
||||
requireActionTurn(state, seat, player);
|
||||
const count = move.count;
|
||||
if (!Number.isInteger(count) || count < 1) {
|
||||
err("invalid population count");
|
||||
}
|
||||
if (player.population + count > populationMax(player)) {
|
||||
err(`population limit is ${populationMax(player)}`);
|
||||
}
|
||||
const indices = sanitizeIndices(move.cards, player.hand.length, "buyPopulation");
|
||||
const paid = spendCards(state, player, indices, populationCost(player) * count);
|
||||
player.population += count;
|
||||
return { paid };
|
||||
}
|
||||
|
||||
function moveBuyRobots(
|
||||
state: GameState,
|
||||
move: Move & { action: "buyRobots" },
|
||||
seat: number,
|
||||
player: PlayerState
|
||||
): MoveInfo {
|
||||
requireActionTurn(state, seat, player);
|
||||
if (player.upgrades.robots === 0) {
|
||||
err("requires the Robots upgrade");
|
||||
}
|
||||
const count = move.count;
|
||||
if (!Number.isInteger(count) || count < 1) {
|
||||
err("invalid robot count");
|
||||
}
|
||||
if (player.robots + count > robotMax(player)) {
|
||||
err(`robot limit is ${robotMax(player)}`);
|
||||
}
|
||||
const indices = sanitizeIndices(move.cards, player.hand.length, "buyRobots");
|
||||
const paid = spendCards(state, player, indices, ROBOT_COST * count);
|
||||
player.robots += count;
|
||||
return { paid };
|
||||
}
|
||||
|
||||
function moveEndTurn(
|
||||
state: GameState,
|
||||
move: Move & { action: "endTurn" },
|
||||
seat: number,
|
||||
player: PlayerState
|
||||
): MoveInfo {
|
||||
requireActionTurn(state, seat, player);
|
||||
const manned = sanitizeIndices(move.manned, player.factories.length, "endTurn");
|
||||
if (manned.length > player.population + player.robots) {
|
||||
err(`only ${player.population + player.robots} operators available`);
|
||||
}
|
||||
player.factories.forEach((factory, i) => {
|
||||
factory.manned = manned.includes(i);
|
||||
});
|
||||
player.done = true;
|
||||
return {};
|
||||
}
|
||||
|
||||
export function dropPlayer(state: GameState, seat: number): GameState {
|
||||
const player = state.players[seat];
|
||||
if (!player || player.dropped) {
|
||||
return state;
|
||||
}
|
||||
player.dropped = true;
|
||||
player.mustDiscard = false;
|
||||
player.done = true;
|
||||
for (const factory of player.factories) {
|
||||
factory.manned = false;
|
||||
}
|
||||
state.purchaseOrder = state.purchaseOrder.filter((s) => s !== seat);
|
||||
|
||||
if (state.ended) {
|
||||
return state;
|
||||
}
|
||||
if (activePlayers(state) <= 1) {
|
||||
finishGame(state);
|
||||
return state;
|
||||
}
|
||||
|
||||
const auction = state.auction;
|
||||
if (auction && (state.phase === "auction" || state.phase === "auctionPayment")) {
|
||||
if (auction.highBidder === seat) {
|
||||
// The would-be buyer is gone: cancel the auction, the card stays in the market.
|
||||
state.phase = "actions";
|
||||
state.auction = null;
|
||||
state.activeSeat = auction.auctioneer;
|
||||
const auctioneer = state.players[state.activeSeat];
|
||||
if (!auctioneer || auctioneer.dropped || auctioneer.done) {
|
||||
startActions(state);
|
||||
}
|
||||
} else if (auction.activeBidder === seat) {
|
||||
auction.passed.push(seat);
|
||||
advanceBidder(state);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
if (state.phase === "discard" && !state.players.some((p) => p.mustDiscard)) {
|
||||
startActions(state);
|
||||
return state;
|
||||
}
|
||||
if (state.phase === "actions" && state.activeSeat === seat) {
|
||||
startActions(state);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
32
packages/engine/src/prng.ts
Normal file
32
packages/engine/src/prng.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import seedrandom from "seedrandom";
|
||||
import type { GameState } from "./types.js";
|
||||
|
||||
// All in-game randomness is derived from the game seed plus a monotonically
|
||||
// increasing counter stored in the state. This keeps draws deterministic
|
||||
// across save/load and replay without persisting PRNG internals.
|
||||
|
||||
export function nextRandom(state: GameState): number {
|
||||
const rng = seedrandom(`${state.seed}:${state.rngCounter}`);
|
||||
state.rngCounter += 1;
|
||||
return rng();
|
||||
}
|
||||
|
||||
export function nextInt(state: GameState, maxExclusive: number): number {
|
||||
return Math.floor(nextRandom(state) * maxExclusive);
|
||||
}
|
||||
|
||||
/** Roll a die with faces 1..sides. */
|
||||
export function rollDie(state: GameState, sides: number): number {
|
||||
return nextInt(state, sides) + 1;
|
||||
}
|
||||
|
||||
/** Fisher-Yates shuffle in place, driven by the state PRNG. */
|
||||
export function shuffle<T>(state: GameState, items: T[]): T[] {
|
||||
for (let i = items.length - 1; i > 0; i--) {
|
||||
const j = nextInt(state, i + 1);
|
||||
const a = items[i] as T;
|
||||
items[i] = items[j] as T;
|
||||
items[j] = a;
|
||||
}
|
||||
return items;
|
||||
}
|
||||
31
packages/engine/src/production.ts
Normal file
31
packages/engine/src/production.ts
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
import { UPGRADE_SPECS } from "./data.js";
|
||||
import { drawCard } from "./state.js";
|
||||
import { UPGRADES } from "./types.js";
|
||||
import type { GameState, PlayerState, ProductionCard } from "./types.js";
|
||||
|
||||
/** Draw production for one player: one card per manned factory plus upgrade freebies. */
|
||||
export function producePlayer(state: GameState, player: PlayerState): ProductionCard[] {
|
||||
const produced: ProductionCard[] = [];
|
||||
for (const factory of player.factories) {
|
||||
if (factory.manned) {
|
||||
const value = drawCard(state, factory.type);
|
||||
if (value !== undefined) {
|
||||
produced.push({ t: factory.type, v: value });
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const u of UPGRADES) {
|
||||
const resource = UPGRADE_SPECS[u].produces;
|
||||
if (!resource) {
|
||||
continue;
|
||||
}
|
||||
for (let i = 0; i < player.upgrades[u]; i++) {
|
||||
const value = drawCard(state, resource);
|
||||
if (value !== undefined) {
|
||||
produced.push({ t: resource, v: value });
|
||||
}
|
||||
}
|
||||
}
|
||||
player.hand.push(...produced);
|
||||
return produced;
|
||||
}
|
||||
21
packages/engine/src/rankings.ts
Normal file
21
packages/engine/src/rankings.ts
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import { scores } from "./state.js";
|
||||
import type { GameState } from "./types.js";
|
||||
|
||||
/** Final rankings: 1 is best. Dropped players rank below everyone still in the game. */
|
||||
export function rankings(state: GameState): number[] {
|
||||
const finalScores = scores(state);
|
||||
const keyOf = (seat: number): number => {
|
||||
const player = state.players[seat];
|
||||
return player?.dropped ? -1 : (finalScores[seat] ?? 0);
|
||||
};
|
||||
return state.players.map((_, seat) => {
|
||||
const key = keyOf(seat);
|
||||
let rank = 1;
|
||||
for (let other = 0; other < state.players.length; other++) {
|
||||
if (other !== seat && keyOf(other) > key) {
|
||||
rank += 1;
|
||||
}
|
||||
}
|
||||
return rank;
|
||||
});
|
||||
}
|
||||
52
packages/engine/src/replay.ts
Normal file
52
packages/engine/src/replay.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
import { applyMove, enterDiscardPhase, setReplayMode } from "./moves.js";
|
||||
import { setup } from "./state.js";
|
||||
import type { GameState, LogEntry } from "./types.js";
|
||||
|
||||
/**
|
||||
* Rebuild the game state from the log, optionally stopping after `to` entries.
|
||||
* Rounds are applied from the "round" log entries (market + production draws),
|
||||
* so a secret-stripped log replays into a secret-stripped state.
|
||||
*/
|
||||
export function replay(state: GameState, options?: { to?: number }): GameState {
|
||||
const init = state.log[0];
|
||||
if (!init || init.type !== "init") {
|
||||
throw new Error("log does not start with an init entry");
|
||||
}
|
||||
const to = Math.min(options?.to ?? state.log.length, state.log.length);
|
||||
|
||||
const replayed = setup(init.players, init.options, init.seed);
|
||||
replayed.players.forEach((player, i) => {
|
||||
player.name = state.players[i]?.name ?? player.name;
|
||||
});
|
||||
|
||||
setReplayMode(true);
|
||||
try {
|
||||
for (let i = 1; i < to; i++) {
|
||||
const entry = state.log[i] as LogEntry;
|
||||
if (entry.type === "round") {
|
||||
applyRoundEntry(replayed, entry);
|
||||
} else if (entry.type === "move") {
|
||||
applyMove(replayed, entry.move, entry.player);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
setReplayMode(false);
|
||||
}
|
||||
return replayed;
|
||||
}
|
||||
|
||||
function applyRoundEntry(state: GameState, entry: LogEntry & { type: "round" }): void {
|
||||
state.round = entry.round;
|
||||
// The order was computed server-side from true spent totals; a stripped
|
||||
// state cannot recompute it (spent derives from hidden card values).
|
||||
state.purchaseOrder = [...entry.purchaseOrder];
|
||||
state.market = [...entry.market];
|
||||
state.supply = { ...entry.supply };
|
||||
for (const { player: seat, cards } of entry.produced) {
|
||||
state.players[seat]?.hand.push(...cards.map((c) => ({ ...c })));
|
||||
}
|
||||
// The round entry was already recorded by the source log; keep the replayed
|
||||
// log aligned so log indexes match between original and replay.
|
||||
state.log.push(entry);
|
||||
enterDiscardPhase(state);
|
||||
}
|
||||
76
packages/engine/src/sanitize.ts
Normal file
76
packages/engine/src/sanitize.ts
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
import { FACTORY_TYPES } from "./types.js";
|
||||
import type { FactoryType, Move } from "./types.js";
|
||||
|
||||
// Moves arrive as untrusted JSON from the network and are stored verbatim in
|
||||
// the game log. Rebuild every move as a fresh literal with exactly the
|
||||
// whitelisted fields: unknown keys (including __proto__ tricks) are dropped,
|
||||
// values are strictly type-checked, and array sizes are bounded.
|
||||
|
||||
const MAX_ARRAY = 200;
|
||||
|
||||
function fail(message: string): never {
|
||||
throw new Error(`invalid move: ${message}`);
|
||||
}
|
||||
|
||||
function record(raw: unknown): Record<string, unknown> {
|
||||
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
||||
fail("expected an object");
|
||||
}
|
||||
return raw as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function int(value: unknown, label: string, min: number, max = 1_000_000): number {
|
||||
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < min || value > max) {
|
||||
fail(`${label} must be an integer in [${min}, ${max}]`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function intArray(value: unknown, label: string): number[] {
|
||||
if (!Array.isArray(value)) {
|
||||
fail(`${label} must be an array`);
|
||||
}
|
||||
if (value.length > MAX_ARRAY) {
|
||||
fail(`${label} is too large`);
|
||||
}
|
||||
return value.map((v) => int(v, `${label} entry`, 0, 10_000));
|
||||
}
|
||||
|
||||
export function sanitizeMove(raw: unknown): Move {
|
||||
const move = record(raw);
|
||||
const action = move.action;
|
||||
if (typeof action !== "string") {
|
||||
fail("missing action");
|
||||
}
|
||||
switch (action) {
|
||||
case "discard":
|
||||
return { action, cards: intArray(move.cards, "cards") };
|
||||
case "auction":
|
||||
return {
|
||||
action,
|
||||
marketIndex: int(move.marketIndex, "marketIndex", 0),
|
||||
bid: int(move.bid, "bid", 0),
|
||||
};
|
||||
case "bid":
|
||||
return { action, amount: int(move.amount, "amount", 0) };
|
||||
case "bidPass":
|
||||
return { action };
|
||||
case "pay":
|
||||
return { action, cards: intArray(move.cards, "cards") };
|
||||
case "buyFactory": {
|
||||
const factory = move.factory;
|
||||
if (typeof factory !== "string" || !FACTORY_TYPES.includes(factory as FactoryType)) {
|
||||
fail("unknown factory type");
|
||||
}
|
||||
return { action, factory: factory as FactoryType, cards: intArray(move.cards, "cards") };
|
||||
}
|
||||
case "buyPopulation":
|
||||
return { action, count: int(move.count, "count", 1, 100), cards: intArray(move.cards, "cards") };
|
||||
case "buyRobots":
|
||||
return { action, count: int(move.count, "count", 1, 100), cards: intArray(move.cards, "cards") };
|
||||
case "endTurn":
|
||||
return { action, manned: intArray(move.manned, "manned") };
|
||||
default:
|
||||
fail(`unknown action ${action}`);
|
||||
}
|
||||
}
|
||||
76
packages/engine/src/setup.spec.ts
Normal file
76
packages/engine/src/setup.spec.ts
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { PRODUCTION_DECKS, SETUP_CHART } from "./data.js";
|
||||
import { initGame } from "./moves.js";
|
||||
import { handCapacity, populationMax, scores, setup, victoryPoints } from "./state.js";
|
||||
import { RESOURCES } from "./types.js";
|
||||
|
||||
test("setup gives each player 2 ore + 1 water, 3 population, all manned", () => {
|
||||
const state = setup(4, {}, "seed");
|
||||
for (const player of state.players) {
|
||||
assert.equal(player.factories.length, 3);
|
||||
assert.deepEqual(player.factories.map((f) => f.type).sort(), ["ore", "ore", "water"]);
|
||||
assert.ok(player.factories.every((f) => f.manned));
|
||||
assert.equal(player.population, 3);
|
||||
assert.equal(player.robots, 0);
|
||||
assert.equal(handCapacity(player), 10);
|
||||
assert.equal(populationMax(player), 5);
|
||||
assert.equal(victoryPoints(player), 3);
|
||||
}
|
||||
});
|
||||
|
||||
test("decks match the documented distributions and averages", () => {
|
||||
const state = setup(4, {}, "seed");
|
||||
for (const resource of RESOURCES) {
|
||||
const spec = PRODUCTION_DECKS[resource];
|
||||
const expectedSize = Object.values(spec.distribution).reduce((a, b) => a + b, 0);
|
||||
const deck = state.decks[resource];
|
||||
assert.equal(deck.length, expectedSize, `${resource} deck size`);
|
||||
const average = deck.reduce((a, b) => a + b, 0) / deck.length;
|
||||
assert.equal(average, spec.average, `${resource} average`);
|
||||
}
|
||||
});
|
||||
|
||||
test("supply follows the expert setup chart", () => {
|
||||
const state = setup(5, {}, "seed");
|
||||
assert.equal(state.supply.dataLibrary, SETUP_CHART[5]?.firstTen);
|
||||
assert.equal(state.supply.moonBase, SETUP_CHART[5]?.lastThree);
|
||||
});
|
||||
|
||||
test("two-player supply is randomized to 1-2 copies per type with 4-10 pairs", () => {
|
||||
const state = setup(2, {}, "seed");
|
||||
const counts = Object.values(state.supply);
|
||||
assert.ok(counts.every((c) => c === 1 || c === 2));
|
||||
const pairs = counts.filter((c) => c === 2).length;
|
||||
assert.ok(pairs >= 4 && pairs <= 10, `pairs=${pairs}`);
|
||||
});
|
||||
|
||||
test("initGame runs the first production round", () => {
|
||||
const state = initGame(3, {}, "seed");
|
||||
assert.equal(state.round, 1);
|
||||
for (const player of state.players) {
|
||||
assert.equal(player.hand.length, 3); // 2 ore + 1 water
|
||||
}
|
||||
// Round 1: nobody over cap, so straight to actions in purchase order.
|
||||
assert.equal(state.phase, "actions");
|
||||
assert.equal(state.market.length, 3);
|
||||
// Only d4 upgrades before anyone reaches 10 VP.
|
||||
for (const upgrade of state.market) {
|
||||
assert.ok(["dataLibrary", "warehouse", "heavyEquipment", "nodule"].includes(upgrade));
|
||||
}
|
||||
assert.deepEqual(scores(state), [3, 3, 3]);
|
||||
});
|
||||
|
||||
test("player count is validated", () => {
|
||||
assert.throws(() => setup(1, {}, "s"));
|
||||
assert.throws(() => setup(11, {}, "s"));
|
||||
assert.throws(() => setup(2.5, {}, "s"));
|
||||
});
|
||||
|
||||
test("setup is deterministic per seed", () => {
|
||||
const a = initGame(4, {}, "abc");
|
||||
const b = initGame(4, {}, "abc");
|
||||
assert.deepEqual(a, b);
|
||||
const c = initGame(4, {}, "xyz");
|
||||
assert.notDeepEqual(a.decks, c.decks);
|
||||
});
|
||||
267
packages/engine/src/state.ts
Normal file
267
packages/engine/src/state.ts
Normal file
|
|
@ -0,0 +1,267 @@
|
|||
import {
|
||||
BASE_HAND_CAPACITY,
|
||||
BASE_POPULATION_MAX,
|
||||
CAP_EXEMPT,
|
||||
FACTORIES,
|
||||
FIRST_TEN,
|
||||
LAST_THREE,
|
||||
MAX_PLAYERS,
|
||||
MIN_PLAYERS,
|
||||
POPULATION_COST,
|
||||
POPULATION_COST_ECOPLANTS,
|
||||
PRODUCTION_DECKS,
|
||||
SETUP_CHART,
|
||||
UPGRADE_SPECS,
|
||||
} from "./data.js";
|
||||
import { nextInt, shuffle } from "./prng.js";
|
||||
import { RESOURCES, UPGRADES } from "./types.js";
|
||||
import type { FactoryType, GameState, PlayerState, Resource, Upgrade } from "./types.js";
|
||||
|
||||
export function setup(players: number, options: Record<string, unknown>, seed: string): GameState {
|
||||
if (!Number.isInteger(players) || players < MIN_PLAYERS || players > MAX_PLAYERS) {
|
||||
throw new Error(`Outpost supports ${MIN_PLAYERS}-${MAX_PLAYERS} players`);
|
||||
}
|
||||
|
||||
const state: GameState = {
|
||||
players: Array.from({ length: players }, (_, i) => createPlayer(i)),
|
||||
round: 0,
|
||||
phase: "actions",
|
||||
purchaseOrder: [],
|
||||
activeSeat: 0,
|
||||
auction: null,
|
||||
market: [],
|
||||
supply: createSupply(players),
|
||||
decks: emptyPiles(),
|
||||
discards: emptyPiles(),
|
||||
seed,
|
||||
rngCounter: 0,
|
||||
options: options ?? {},
|
||||
log: [{ type: "init", players, seed, options: options ?? {} }],
|
||||
moveCount: 0,
|
||||
ended: false,
|
||||
messages: [],
|
||||
};
|
||||
|
||||
if (players === 2) {
|
||||
rollTwoPlayerSupply(state);
|
||||
}
|
||||
|
||||
for (const resource of RESOURCES) {
|
||||
state.decks[resource] = buildDeck(state, resource);
|
||||
}
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
function createPlayer(index: number): PlayerState {
|
||||
const upgrades = {} as Record<Upgrade, number>;
|
||||
for (const u of UPGRADES) {
|
||||
upgrades[u] = 0;
|
||||
}
|
||||
return {
|
||||
name: `Player ${index + 1}`,
|
||||
factories: [
|
||||
{ type: "ore", manned: true },
|
||||
{ type: "ore", manned: true },
|
||||
{ type: "water", manned: true },
|
||||
],
|
||||
population: 3,
|
||||
robots: 0,
|
||||
hand: [],
|
||||
upgrades,
|
||||
spent: 0,
|
||||
done: false,
|
||||
mustDiscard: false,
|
||||
dropped: false,
|
||||
};
|
||||
}
|
||||
|
||||
function emptyPiles(): Record<Resource, number[]> {
|
||||
const piles = {} as Record<Resource, number[]>;
|
||||
for (const r of RESOURCES) {
|
||||
piles[r] = [];
|
||||
}
|
||||
return piles;
|
||||
}
|
||||
|
||||
function createSupply(players: number): Record<Upgrade, number> {
|
||||
const row = SETUP_CHART[Math.min(players, 10)];
|
||||
const supply = {} as Record<Upgrade, number>;
|
||||
for (const u of FIRST_TEN) {
|
||||
supply[u] = row?.firstTen ?? 3;
|
||||
}
|
||||
for (const u of LAST_THREE) {
|
||||
supply[u] = row?.lastThree ?? 3;
|
||||
}
|
||||
return supply;
|
||||
}
|
||||
|
||||
/** 2-player setup: roll per type (even: 2 copies, odd: 1), reroll until 4-10 types have 2 copies. */
|
||||
function rollTwoPlayerSupply(state: GameState): void {
|
||||
for (let attempt = 0; attempt < 1000; attempt++) {
|
||||
const counts = UPGRADES.map(() => (nextInt(state, 2) === 0 ? 2 : 1));
|
||||
const pairs = counts.filter((c) => c === 2).length;
|
||||
if (pairs >= 4 && pairs <= 10) {
|
||||
UPGRADES.forEach((u, i) => {
|
||||
state.supply[u] = counts[i] ?? 1;
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new Error("unreachable: two-player supply roll");
|
||||
}
|
||||
|
||||
function buildDeck(state: GameState, resource: Resource): number[] {
|
||||
const deck: number[] = [];
|
||||
const spec = PRODUCTION_DECKS[resource];
|
||||
for (const [value, count] of Object.entries(spec.distribution)) {
|
||||
for (let i = 0; i < count; i++) {
|
||||
deck.push(Number(value));
|
||||
}
|
||||
}
|
||||
return shuffle(state, deck);
|
||||
}
|
||||
|
||||
export function bigThreshold(state: GameState): number {
|
||||
return SETUP_CHART[Math.min(state.players.length, 10)]?.bigThreshold ?? 40;
|
||||
}
|
||||
|
||||
export function handCapacity(player: PlayerState): number {
|
||||
let cap = BASE_HAND_CAPACITY;
|
||||
for (const u of UPGRADES) {
|
||||
cap += (UPGRADE_SPECS[u].handCapacityBonus ?? 0) * player.upgrades[u];
|
||||
}
|
||||
return cap;
|
||||
}
|
||||
|
||||
export function populationMax(player: PlayerState): number {
|
||||
let max = BASE_POPULATION_MAX;
|
||||
for (const u of UPGRADES) {
|
||||
max += (UPGRADE_SPECS[u].populationBonus ?? 0) * player.upgrades[u];
|
||||
}
|
||||
return max;
|
||||
}
|
||||
|
||||
/**
|
||||
* Robots don't count against the population limit; each Robots upgrade allows
|
||||
* robots up to the current population count (v1.32 expert-rules limit).
|
||||
*/
|
||||
export function robotMax(player: PlayerState): number {
|
||||
return player.upgrades.robots * player.population;
|
||||
}
|
||||
|
||||
export function operators(player: PlayerState): number {
|
||||
return player.population + player.robots;
|
||||
}
|
||||
|
||||
/** Number of hand cards that count against hand capacity. */
|
||||
export function countingHandSize(player: PlayerState): number {
|
||||
return player.hand.filter((c) => !CAP_EXEMPT.includes(c.t)).length;
|
||||
}
|
||||
|
||||
export function handValue(player: PlayerState): number {
|
||||
return player.hand.reduce((sum, c) => sum + c.v, 0);
|
||||
}
|
||||
|
||||
export function populationCost(player: PlayerState): number {
|
||||
return player.upgrades.ecoplants > 0 ? POPULATION_COST_ECOPLANTS : POPULATION_COST;
|
||||
}
|
||||
|
||||
/** Per-buyer discount on an upgrade's auction price. */
|
||||
export function upgradeDiscount(player: PlayerState, upgrade: Upgrade): number {
|
||||
let discount = 0;
|
||||
if (upgrade === "scientists" || upgrade === "laboratory") {
|
||||
discount += 10 * player.upgrades.dataLibrary;
|
||||
}
|
||||
if (upgrade === "warehouse" || upgrade === "nodule") {
|
||||
discount += 5 * player.upgrades.heavyEquipment;
|
||||
}
|
||||
if (upgrade === "outpost") {
|
||||
discount += 15 * player.upgrades.heavyEquipment + 10 * player.upgrades.ecoplants;
|
||||
}
|
||||
return discount;
|
||||
}
|
||||
|
||||
export function canBuyFactory(player: PlayerState, type: FactoryType): boolean {
|
||||
const spec = FACTORIES[type];
|
||||
if (spec.requires && player.upgrades[spec.requires] === 0) {
|
||||
return false;
|
||||
}
|
||||
if (spec.needsResearchCard && !player.hand.some((c) => c.t === "research")) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function victoryPoints(player: PlayerState): number {
|
||||
let vp = 0;
|
||||
for (const factory of player.factories) {
|
||||
if (factory.manned) {
|
||||
vp += FACTORIES[factory.type].vp;
|
||||
}
|
||||
}
|
||||
for (const u of UPGRADES) {
|
||||
vp += UPGRADE_SPECS[u].vp * player.upgrades[u];
|
||||
}
|
||||
return vp;
|
||||
}
|
||||
|
||||
export function scores(state: GameState): number[] {
|
||||
return state.players.map((p) => victoryPoints(p));
|
||||
}
|
||||
|
||||
/** Purchase order: VP descending, then total spent descending, then seat. */
|
||||
export function computePurchaseOrder(state: GameState): number[] {
|
||||
return state.players
|
||||
.map((p, seat) => ({ seat, vp: victoryPoints(p), spent: p.spent, dropped: p.dropped }))
|
||||
.filter((e) => !e.dropped)
|
||||
.sort((a, b) => b.vp - a.vp || b.spent - a.spent || a.seat - b.seat)
|
||||
.map((e) => e.seat);
|
||||
}
|
||||
|
||||
export function drawCard(state: GameState, resource: Resource): number | undefined {
|
||||
const deck = state.decks[resource];
|
||||
if (deck.length === 0) {
|
||||
const discard = state.discards[resource];
|
||||
if (discard.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
state.decks[resource] = shuffle(state, discard.splice(0));
|
||||
}
|
||||
return state.decks[resource].pop();
|
||||
}
|
||||
|
||||
/** Coarse list of the moves available to a player, for the BGS sidebar. */
|
||||
export function availableMoves(state: GameState, player?: number): string[] {
|
||||
if (state.ended || player === undefined) {
|
||||
return [];
|
||||
}
|
||||
const p = state.players[player];
|
||||
if (!p || p.dropped) {
|
||||
return [];
|
||||
}
|
||||
switch (state.phase) {
|
||||
case "discard":
|
||||
return p.mustDiscard ? ["discard"] : [];
|
||||
case "auction":
|
||||
return state.auction?.activeBidder === player ? ["bid", "bidPass"] : [];
|
||||
case "auctionPayment":
|
||||
return state.auction?.highBidder === player ? ["pay"] : [];
|
||||
case "actions": {
|
||||
if (state.activeSeat !== player || p.done) {
|
||||
return [];
|
||||
}
|
||||
const moves = ["endTurn"];
|
||||
if (state.market.length > 0) {
|
||||
moves.push("auction");
|
||||
}
|
||||
moves.push("buyFactory", "buyPopulation");
|
||||
if (p.upgrades.robots > 0) {
|
||||
moves.push("buyRobots");
|
||||
}
|
||||
return moves;
|
||||
}
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
137
packages/engine/src/types.ts
Normal file
137
packages/engine/src/types.ts
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
export const RESOURCES = [
|
||||
"ore",
|
||||
"water",
|
||||
"titanium",
|
||||
"research",
|
||||
"microbiotics",
|
||||
"newChemicals",
|
||||
"orbitalMedicine",
|
||||
"ringOre",
|
||||
"moonOre",
|
||||
] as const;
|
||||
|
||||
export type Resource = (typeof RESOURCES)[number];
|
||||
|
||||
export const FACTORY_TYPES = ["ore", "water", "titanium", "research", "newChemicals"] as const;
|
||||
|
||||
export type FactoryType = (typeof FACTORY_TYPES)[number];
|
||||
|
||||
export const UPGRADES = [
|
||||
"dataLibrary",
|
||||
"warehouse",
|
||||
"heavyEquipment",
|
||||
"nodule",
|
||||
"scientists",
|
||||
"orbitalLab",
|
||||
"robots",
|
||||
"laboratory",
|
||||
"ecoplants",
|
||||
"outpost",
|
||||
"spaceStation",
|
||||
"planetaryCruiser",
|
||||
"moonBase",
|
||||
] as const;
|
||||
|
||||
export type Upgrade = (typeof UPGRADES)[number];
|
||||
|
||||
export interface ProductionCard {
|
||||
/** Resource type. */
|
||||
t: Resource;
|
||||
/** Credit value. -1 when hidden by stripSecret. */
|
||||
v: number;
|
||||
}
|
||||
|
||||
export interface Factory {
|
||||
type: FactoryType;
|
||||
manned: boolean;
|
||||
}
|
||||
|
||||
export interface PlayerState {
|
||||
name: string;
|
||||
factories: Factory[];
|
||||
population: number;
|
||||
robots: number;
|
||||
hand: ProductionCard[];
|
||||
upgrades: Record<Upgrade, number>;
|
||||
/** Total credits spent over the game (purchase-order tie-break). */
|
||||
spent: number;
|
||||
/** Turn bookkeeping: has finished their action turn this round. */
|
||||
done: boolean;
|
||||
/** Must still discard down to hand capacity this round. */
|
||||
mustDiscard: boolean;
|
||||
dropped: boolean;
|
||||
}
|
||||
|
||||
export type Phase = "discard" | "actions" | "auction" | "auctionPayment" | "ended";
|
||||
|
||||
export interface AuctionState {
|
||||
/** Index into state.market of the upgrade under auction. */
|
||||
marketIndex: number;
|
||||
upgrade: Upgrade;
|
||||
/** Seat of the player who opened the auction (their action turn resumes afterwards). */
|
||||
auctioneer: number;
|
||||
highBid: number;
|
||||
highBidder: number;
|
||||
/** Seats that passed out of this auction. */
|
||||
passed: number[];
|
||||
/** Seat currently asked to bid (only meaningful in phase "auction"). */
|
||||
activeBidder: number;
|
||||
}
|
||||
|
||||
export type Move =
|
||||
| { action: "discard"; cards: number[] }
|
||||
| { action: "auction"; marketIndex: number; bid: number }
|
||||
| { action: "bid"; amount: number }
|
||||
| { action: "bidPass" }
|
||||
| { action: "pay"; cards: number[] }
|
||||
| { action: "buyFactory"; factory: FactoryType; cards: number[] }
|
||||
| { action: "buyPopulation"; count: number; cards: number[] }
|
||||
| { action: "buyRobots"; count: number; cards: number[] }
|
||||
| { action: "endTurn"; manned: number[] };
|
||||
|
||||
export type LogEntry =
|
||||
| { type: "init"; players: number; seed: string; options: Record<string, unknown> }
|
||||
| {
|
||||
type: "round";
|
||||
round: number;
|
||||
purchaseOrder: number[];
|
||||
market: Upgrade[];
|
||||
supply: Record<Upgrade, number>;
|
||||
produced: { player: number; cards: ProductionCard[] }[];
|
||||
}
|
||||
| { type: "move"; player: number; move: Move; info?: MoveInfo }
|
||||
| { type: "end"; scores: number[] };
|
||||
|
||||
/** Derived facts recorded with a move so the log can be described without replaying. */
|
||||
export interface MoveInfo {
|
||||
paid?: number;
|
||||
upgrade?: Upgrade;
|
||||
discarded?: number;
|
||||
}
|
||||
|
||||
export interface GameState {
|
||||
players: PlayerState[];
|
||||
round: number;
|
||||
phase: Phase;
|
||||
/** Seat numbers in purchase order for the current round. */
|
||||
purchaseOrder: number[];
|
||||
/** Seat whose action turn it is (phase "actions"). */
|
||||
activeSeat: number;
|
||||
auction: AuctionState | null;
|
||||
/** Upgrades currently up for auction. */
|
||||
market: Upgrade[];
|
||||
/** Remaining copies of each upgrade in the supply. */
|
||||
supply: Record<Upgrade, number>;
|
||||
/** Draw piles, face-down (top = last element). */
|
||||
decks: Record<Resource, number[]>;
|
||||
/** Spent cards, face-up. */
|
||||
discards: Record<Resource, number[]>;
|
||||
seed: string;
|
||||
/** Number of PRNG draws consumed so far (determinism across save/load). */
|
||||
rngCounter: number;
|
||||
options: Record<string, unknown>;
|
||||
log: LogEntry[];
|
||||
moveCount: number;
|
||||
ended: boolean;
|
||||
messages: string[];
|
||||
}
|
||||
106
packages/engine/src/wrapper.spec.ts
Normal file
106
packages/engine/src/wrapper.spec.ts
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { moveAI } from "./ai.js";
|
||||
import { initGame } from "./moves.js";
|
||||
import { replay } from "./replay.js";
|
||||
import * as wrapper from "../wrapper.js";
|
||||
import type { GameState } from "./types.js";
|
||||
|
||||
function play(state: GameState, moves: number): GameState {
|
||||
for (let i = 0; i < moves && !state.ended; i++) {
|
||||
const current = wrapper.currentPlayer(state);
|
||||
const seat = Array.isArray(current) ? current[0] : current;
|
||||
moveAI(state, seat as number);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
test("wrapper: init/currentPlayer/scores/logLength contract", async () => {
|
||||
const state = await wrapper.init(4, [], {}, "wrapper-spec");
|
||||
assert.equal(state.players.length, 4);
|
||||
assert.equal(typeof wrapper.currentPlayer(state), "number");
|
||||
assert.deepEqual(wrapper.scores(state), [3, 3, 3, 3]);
|
||||
assert.ok(wrapper.logLength(state) >= 2); // init + round 1
|
||||
assert.equal(wrapper.ended(state), false);
|
||||
assert.equal(wrapper.round(state), 1);
|
||||
});
|
||||
|
||||
test("stripSecret hides seed, deck values and other players' hand values", () => {
|
||||
const state = play(initGame(3, {}, "strip-spec"), 30);
|
||||
const stripped = wrapper.stripSecret(state, 0);
|
||||
assert.equal(stripped.seed, "");
|
||||
assert.ok(Object.values(stripped.decks).every((deck) => deck.every((v) => v === -1)));
|
||||
assert.deepEqual(stripped.players[0]?.hand, state.players[0]?.hand);
|
||||
for (const seat of [1, 2]) {
|
||||
assert.ok(stripped.players[seat]?.hand.every((c) => c.v === -1));
|
||||
assert.equal(stripped.players[seat]?.hand.length, state.players[seat]?.hand.length);
|
||||
}
|
||||
const initEntry = stripped.log[0];
|
||||
assert.ok(initEntry?.type === "init" && initEntry.seed === "");
|
||||
for (const entry of stripped.log) {
|
||||
if (entry.type === "round") {
|
||||
for (const { player, cards } of entry.produced) {
|
||||
if (player !== 0) {
|
||||
assert.ok(cards.every((c) => c.v === -1));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// stripSecret must not mutate the source state.
|
||||
assert.notEqual(state.seed, "");
|
||||
});
|
||||
|
||||
test("stripped state stays JSON-round-trippable", () => {
|
||||
const state = play(initGame(3, {}, "json-spec"), 50);
|
||||
const stripped = wrapper.stripSecret(state, 1);
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(stripped)), stripped);
|
||||
});
|
||||
|
||||
test("replay rebuilds the same public state from the log", () => {
|
||||
const state = play(initGame(3, {}, "replay-spec"), 200);
|
||||
const replayed = replay(state);
|
||||
assert.equal(replayed.round, state.round);
|
||||
assert.equal(replayed.moveCount, state.moveCount);
|
||||
assert.deepEqual(wrapper.scores(replayed), wrapper.scores(state));
|
||||
replayed.players.forEach((player, seat) => {
|
||||
assert.deepEqual(player.hand, state.players[seat]?.hand);
|
||||
assert.deepEqual(player.factories, state.players[seat]?.factories);
|
||||
assert.deepEqual(player.upgrades, state.players[seat]?.upgrades);
|
||||
});
|
||||
assert.deepEqual(replayed.market, state.market);
|
||||
});
|
||||
|
||||
test("replay of a stripped state yields a stripped state", () => {
|
||||
const state = play(initGame(3, {}, "replay-strip-spec"), 100);
|
||||
const stripped = wrapper.stripSecret(state, 0);
|
||||
const replayed = replay(stripped);
|
||||
assert.equal(replayed.round, stripped.round);
|
||||
assert.deepEqual(replayed.players[0]?.hand, stripped.players[0]?.hand);
|
||||
assert.ok(replayed.players[1]?.hand.every((c) => c.v === -1));
|
||||
});
|
||||
|
||||
test("replay to a mid-game point stops there", () => {
|
||||
const state = play(initGame(3, {}, "replay-to-spec"), 60);
|
||||
const partial = replay(state, { to: 10 });
|
||||
assert.ok(partial.moveCount < state.moveCount);
|
||||
});
|
||||
|
||||
test("dropPlayer removes the player from play and can end the game", async () => {
|
||||
const state = play(initGame(3, {}, "drop-spec"), 20);
|
||||
await wrapper.dropPlayer(state, state.activeSeat);
|
||||
assert.ok(!state.purchaseOrder.includes(state.players.findIndex((p) => p.dropped)));
|
||||
await wrapper.dropPlayer(
|
||||
state,
|
||||
state.players.findIndex((p) => !p.dropped)
|
||||
);
|
||||
assert.ok(state.ended);
|
||||
const ranks = wrapper.rankings(state);
|
||||
assert.equal(ranks.length, 3);
|
||||
});
|
||||
|
||||
test("messages drain once", () => {
|
||||
const state = play(initGame(4, {}, "messages-spec"), 500);
|
||||
const first = wrapper.messages(state);
|
||||
assert.deepEqual(wrapper.messages(state).messages, []);
|
||||
assert.ok(Array.isArray(first.messages));
|
||||
});
|
||||
12
packages/engine/tsconfig.build.json
Normal file
12
packages/engine/tsconfig.build.json
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "dist",
|
||||
"rootDir": ".",
|
||||
"declaration": true,
|
||||
"sourceMap": false,
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts", "wrapper.ts", "index.ts"],
|
||||
"exclude": ["src/**/*.spec.ts"]
|
||||
}
|
||||
8
packages/engine/tsconfig.json
Normal file
8
packages/engine/tsconfig.json
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"noEmit": true,
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts", "wrapper.ts", "index.ts"]
|
||||
}
|
||||
11
packages/engine/tsconfig.test.json
Normal file
11
packages/engine/tsconfig.test.json
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "dist-test",
|
||||
"rootDir": ".",
|
||||
"declaration": false,
|
||||
"sourceMap": false,
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts", "wrapper.ts", "index.ts"]
|
||||
}
|
||||
163
packages/engine/wrapper.ts
Normal file
163
packages/engine/wrapper.ts
Normal file
|
|
@ -0,0 +1,163 @@
|
|||
import { moveAI as moveAICore } from "./src/ai.js";
|
||||
import { applyMove, dropPlayer as dropPlayerCore, initGame } from "./src/moves.js";
|
||||
import { rankings as computeRankings } from "./src/rankings.js";
|
||||
import { replay as replayCore } from "./src/replay.js";
|
||||
import { availableMoves, scores as computeScores } from "./src/state.js";
|
||||
import type { GameState, LogEntry, Move, ProductionCard } from "./src/types.js";
|
||||
|
||||
export async function init(
|
||||
players: number,
|
||||
_expansions: string[],
|
||||
options: Record<string, unknown>,
|
||||
seed: string,
|
||||
_creator?: number
|
||||
): Promise<GameState> {
|
||||
return initGame(players, options ?? {}, seed);
|
||||
}
|
||||
|
||||
export async function move(data: GameState, mv: unknown, player: number): Promise<GameState> {
|
||||
// mv is untrusted JSON from the network; applyMove validates it before use.
|
||||
return applyMove(data, mv as Move, player);
|
||||
}
|
||||
|
||||
export function ended(data: GameState): boolean {
|
||||
return data.ended;
|
||||
}
|
||||
|
||||
export function scores(data: GameState): number[] {
|
||||
return computeScores(data);
|
||||
}
|
||||
|
||||
export function rankings(data: GameState): number[] {
|
||||
return computeRankings(data);
|
||||
}
|
||||
|
||||
export async function dropPlayer(data: GameState, player: number): Promise<GameState> {
|
||||
return dropPlayerCore(data, player);
|
||||
}
|
||||
|
||||
export async function moveAI(data: GameState, player: number): Promise<GameState> {
|
||||
return moveAICore(data, player);
|
||||
}
|
||||
|
||||
export function currentPlayer(data: GameState): number | number[] | undefined {
|
||||
if (data.ended) {
|
||||
return undefined;
|
||||
}
|
||||
switch (data.phase) {
|
||||
case "discard": {
|
||||
const waiting = data.players.flatMap((p, seat) => (p.mustDiscard && !p.dropped ? [seat] : []));
|
||||
return waiting.length === 1 ? waiting[0] : waiting;
|
||||
}
|
||||
case "auction":
|
||||
return data.auction?.activeBidder;
|
||||
case "auctionPayment":
|
||||
return data.auction?.highBidder;
|
||||
case "actions":
|
||||
return data.activeSeat;
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function logLength(data: GameState): number {
|
||||
return data.log.length;
|
||||
}
|
||||
|
||||
function hideProduced(entry: LogEntry, viewer?: number): LogEntry {
|
||||
if (entry.type === "init") {
|
||||
// The seed derives every deck order; it must never reach a client.
|
||||
return { ...entry, seed: "" };
|
||||
}
|
||||
if (entry.type !== "round") {
|
||||
return entry;
|
||||
}
|
||||
return {
|
||||
...entry,
|
||||
produced: entry.produced.map(({ player, cards }) => ({
|
||||
player,
|
||||
cards: player === viewer ? cards : cards.map((c): ProductionCard => ({ t: c.t, v: -1 })),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export function stripSecret(data: GameState, player?: number): GameState {
|
||||
const viewer = player !== undefined && player >= 0 ? player : undefined;
|
||||
return {
|
||||
...data,
|
||||
// The seed derives every deck order; hiding it is what keeps hands secret.
|
||||
seed: "",
|
||||
decks: Object.fromEntries(
|
||||
Object.entries(data.decks).map(([resource, deck]) => [resource, deck.map(() => -1)])
|
||||
) as GameState["decks"],
|
||||
players: data.players.map((p, i) =>
|
||||
i === viewer
|
||||
? p
|
||||
: {
|
||||
...p,
|
||||
hand: p.hand.map((c): ProductionCard => ({ t: c.t, v: -1 })),
|
||||
}
|
||||
),
|
||||
log: data.log.map((entry) => hideProduced(entry, viewer)),
|
||||
messages: [...data.messages],
|
||||
};
|
||||
}
|
||||
|
||||
export interface LogSliceOptions {
|
||||
player?: number;
|
||||
start?: number;
|
||||
end?: number;
|
||||
}
|
||||
|
||||
export interface LogSliceResult {
|
||||
log: LogEntry[];
|
||||
availableMoves?: string[];
|
||||
}
|
||||
|
||||
export function logSlice(data: GameState, options?: LogSliceOptions): LogSliceResult {
|
||||
const viewer = options?.player !== undefined && options.player >= 0 ? options.player : undefined;
|
||||
const start = Math.max(0, options?.start ?? 0);
|
||||
const end = options?.end ?? data.log.length;
|
||||
const log = data.log.slice(start, end).map((entry) => hideProduced(entry, viewer));
|
||||
const result: LogSliceResult = { log };
|
||||
if (options?.end === undefined) {
|
||||
result.availableMoves = availableMoves(data, viewer);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function setPlayerMetaData(data: GameState, player: number, metaData: { name: string }): GameState {
|
||||
const target = data.players[player];
|
||||
if (target) {
|
||||
target.name = metaData.name;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
export function toSave(data: GameState): GameState {
|
||||
return data;
|
||||
}
|
||||
|
||||
export function messages(data: GameState): { messages: string[]; data: GameState } {
|
||||
const drained = [...data.messages];
|
||||
data.messages = [];
|
||||
return { messages: drained, data };
|
||||
}
|
||||
|
||||
export function replay(data: GameState, options?: { to?: number }): GameState {
|
||||
return replayCore(data, options);
|
||||
}
|
||||
|
||||
export const stripSecretLike = stripSecret;
|
||||
|
||||
export function round(data: GameState): number {
|
||||
return data.round;
|
||||
}
|
||||
|
||||
export function cancelled(data: GameState): boolean {
|
||||
return data.ended && data.round <= 1;
|
||||
}
|
||||
|
||||
export function factions(data: GameState): string[] {
|
||||
return data.players.map((p) => p.name);
|
||||
}
|
||||
16
packages/viewer/index.html
Normal file
16
packages/viewer/index.html
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<link
|
||||
rel="icon"
|
||||
href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'><circle cx='8' cy='8' r='7' fill='%232f7fa8'/></svg>"
|
||||
/>
|
||||
<title>Outpost viewer — dev harness</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/dev.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
32
packages/viewer/package.json
Normal file
32
packages/viewer/package.json
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
{
|
||||
"name": "outpost-viewer",
|
||||
"version": "0.1.0",
|
||||
"description": "Browser viewer for the Outpost game on boardgamers.space",
|
||||
"license": "AGPL-3.0",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"type": "module",
|
||||
"main": "dist/outpost-viewer.iife.js",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"prepublishOnly": "pnpm build",
|
||||
"tsc": "svelte-check --tsconfig ./tsconfig.json",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"outpost-engine": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@sveltejs/vite-plugin-svelte": "7.2.0",
|
||||
"@types/node": "24.10.1",
|
||||
"svelte": "5.56.8",
|
||||
"svelte-check": "4.7.4",
|
||||
"typescript": "5.9.3",
|
||||
"vite": "8.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=24"
|
||||
}
|
||||
}
|
||||
137
packages/viewer/src/App.svelte
Normal file
137
packages/viewer/src/App.svelte
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
<script lang="ts">
|
||||
import type { ViewerStore } from "./lib/store.svelte";
|
||||
import HeaderStrip from "./lib/HeaderStrip.svelte";
|
||||
import MarketPanel from "./lib/MarketPanel.svelte";
|
||||
import AuctionBanner from "./lib/AuctionBanner.svelte";
|
||||
import PlayerPanel from "./lib/PlayerPanel.svelte";
|
||||
import ActionBar from "./lib/ActionBar.svelte";
|
||||
import GameEndBanner from "./lib/GameEndBanner.svelte";
|
||||
import ReplayBar from "./lib/ReplayBar.svelte";
|
||||
import LogFeed from "./lib/LogFeed.svelte";
|
||||
|
||||
interface Props {
|
||||
store: ViewerStore;
|
||||
onPlayerClick?: (index: number) => void;
|
||||
}
|
||||
|
||||
let { store, onPlayerClick }: Props = $props();
|
||||
const state = $derived(store.state);
|
||||
</script>
|
||||
|
||||
{#if state}
|
||||
<div class="board">
|
||||
<ReplayBar {store} />
|
||||
<HeaderStrip {state} />
|
||||
|
||||
<div class="page">
|
||||
<GameEndBanner {store} />
|
||||
|
||||
<div class="columns">
|
||||
<div class="main">
|
||||
<div class="players" data-count={state.players.length}>
|
||||
{#each state.players as _, i (i)}
|
||||
<PlayerPanel {state} {store} index={i} onNameClick={onPlayerClick} />
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
{#if state.auction && !state.ended}
|
||||
<AuctionBanner {state} {store} />
|
||||
{/if}
|
||||
|
||||
<MarketPanel {state} {store} />
|
||||
</div>
|
||||
|
||||
<div class="side">
|
||||
<ActionBar {store} />
|
||||
<LogFeed {store} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="loading">Waiting for game state…</div>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.board {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
padding: 16px;
|
||||
max-width: 1400px;
|
||||
/* Center the board within a wide iframe so large screens don't leave a
|
||||
one-sided empty gutter. */
|
||||
margin: 0 auto;
|
||||
width: 100%;
|
||||
}
|
||||
.page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
}
|
||||
.columns {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
}
|
||||
.main {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
min-width: 0;
|
||||
}
|
||||
.side {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
}
|
||||
.players {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(230px, 100%), 1fr));
|
||||
grid-auto-rows: min-content;
|
||||
align-content: start;
|
||||
gap: 10px;
|
||||
align-items: start;
|
||||
}
|
||||
/* Wide screens: two columns — players/market on the left, action bar + event
|
||||
feed in a fixed right sidebar. */
|
||||
@media (min-width: 1100px) {
|
||||
.page {
|
||||
width: fit-content;
|
||||
margin: 0 auto;
|
||||
align-items: stretch;
|
||||
}
|
||||
.columns {
|
||||
flex-direction: row;
|
||||
align-items: flex-start;
|
||||
justify-content: center;
|
||||
gap: 24px;
|
||||
}
|
||||
.main {
|
||||
flex: 0 1 auto;
|
||||
align-items: stretch;
|
||||
}
|
||||
.side {
|
||||
flex: 0 0 360px;
|
||||
position: sticky;
|
||||
top: 16px;
|
||||
}
|
||||
}
|
||||
.loading {
|
||||
padding: 40px;
|
||||
text-align: center;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.board {
|
||||
padding: 10px;
|
||||
gap: 10px;
|
||||
}
|
||||
.players {
|
||||
grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
|
||||
gap: 8px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
113
packages/viewer/src/dev-backend.ts
Normal file
113
packages/viewer/src/dev-backend.ts
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
import { applyMove, chooseMove, initGame, type GameState, type Move } from "outpost-engine";
|
||||
import { currentPlayer, stripSecret } from "outpost-engine/wrapper.js";
|
||||
|
||||
export interface DevOptions {
|
||||
players?: number;
|
||||
seed?: string;
|
||||
delayMs?: number;
|
||||
/* When true, the human seat also auto-plays — the whole game plays itself
|
||||
out (handy for reaching the end screen in dev). */
|
||||
auto?: boolean;
|
||||
}
|
||||
|
||||
const NAMES = [
|
||||
"You",
|
||||
"Ada (bot)",
|
||||
"Cleo (bot)",
|
||||
"Dora (bot)",
|
||||
"Ezra (bot)",
|
||||
"Faye (bot)",
|
||||
"Gus (bot)",
|
||||
"Hana (bot)",
|
||||
"Ivan (bot)",
|
||||
"Juno (bot)",
|
||||
];
|
||||
const AVATARS = [
|
||||
"",
|
||||
"https://api.dicebear.com/9.x/bottts-neutral/svg?seed=Ada&backgroundColor=ffdfbf",
|
||||
"https://api.dicebear.com/9.x/bottts-neutral/svg?seed=Cleo&backgroundColor=b6e3f4",
|
||||
"https://api.dicebear.com/9.x/bottts-neutral/svg?seed=Dora&backgroundColor=c0aede",
|
||||
"https://api.dicebear.com/9.x/bottts-neutral/svg?seed=Ezra&backgroundColor=d1d4f9",
|
||||
"https://api.dicebear.com/9.x/bottts-neutral/svg?seed=Faye&backgroundColor=ffd5dc",
|
||||
"https://api.dicebear.com/9.x/bottts-neutral/svg?seed=Gus&backgroundColor=c0f0c0",
|
||||
"https://api.dicebear.com/9.x/bottts-neutral/svg?seed=Hana&backgroundColor=ffe8b6",
|
||||
"https://api.dicebear.com/9.x/bottts-neutral/svg?seed=Ivan&backgroundColor=b6e3f4",
|
||||
"https://api.dicebear.com/9.x/bottts-neutral/svg?seed=Juno&backgroundColor=e8c0f0",
|
||||
];
|
||||
|
||||
export function startDevBackend(
|
||||
emitter: {
|
||||
emit: (event: string, payload?: unknown) => void;
|
||||
on: (event: string, fn: (payload: never) => void) => void;
|
||||
},
|
||||
options: DevOptions = {}
|
||||
): void {
|
||||
const playerCount = options.players ?? 4;
|
||||
const seed = options.seed ?? `dev-${Math.floor(Math.random() * 1e6)}`;
|
||||
const delay = options.delayMs ?? 700;
|
||||
|
||||
let state: GameState = initGame(playerCount, {}, seed);
|
||||
for (let i = 0; i < playerCount; i++) {
|
||||
state.players[i]!.name = NAMES[i] ?? `Player ${i + 1}`;
|
||||
}
|
||||
state.messages = [];
|
||||
|
||||
const human = 0;
|
||||
let ended = false;
|
||||
|
||||
function publish(): void {
|
||||
emitter.emit("state", stripSecret(state, human));
|
||||
emitter.emit("player", { index: human });
|
||||
emitter.emit("avatars", AVATARS.slice(0, playerCount));
|
||||
if (state.ended && !ended) {
|
||||
ended = true;
|
||||
return;
|
||||
}
|
||||
scheduleBots();
|
||||
}
|
||||
|
||||
function scheduleBots(): void {
|
||||
if (state.ended) {
|
||||
return;
|
||||
}
|
||||
// currentPlayer is an ARRAY of seats during the simultaneous discard
|
||||
// phase — every bot in it may move (one per delay tick), and the loop
|
||||
// must stop and wait if the human is among them.
|
||||
const current = currentPlayer(state);
|
||||
const seats = Array.isArray(current) ? current : current === undefined ? [] : [current];
|
||||
const seat = seats.find((s) => s !== human || options.auto);
|
||||
if (seat === undefined) {
|
||||
return;
|
||||
}
|
||||
window.setTimeout(() => {
|
||||
if (state.ended) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
state = applyMove(state, chooseMove(state, seat), seat);
|
||||
} catch (error) {
|
||||
console.error("[dev-backend] bot move failed", error);
|
||||
return;
|
||||
}
|
||||
publish();
|
||||
}, delay);
|
||||
}
|
||||
|
||||
emitter.on("move", ((move: Move) => {
|
||||
if (state.ended) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
state = applyMove(state, move, human);
|
||||
} catch (error) {
|
||||
console.error("[dev-backend] illegal move", error);
|
||||
publish();
|
||||
return;
|
||||
}
|
||||
publish();
|
||||
}) as never);
|
||||
|
||||
emitter.on("fetchState", (() => publish()) as never);
|
||||
|
||||
window.setTimeout(publish, 50);
|
||||
}
|
||||
51
packages/viewer/src/dev.ts
Normal file
51
packages/viewer/src/dev.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import { startDevBackend } from "./dev-backend";
|
||||
import { launch } from "./viewer";
|
||||
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const players = Math.min(10, Math.max(2, Number(params.get("players") ?? 4)));
|
||||
const seed = params.get("seed") ?? undefined;
|
||||
const auto = params.get("auto") === "1" || params.get("auto") === "true";
|
||||
const delayMs = params.get("delay") ? Number(params.get("delay")) : undefined;
|
||||
|
||||
const emitter = launch("#app");
|
||||
startDevBackend(emitter as never, { players, seed, auto, delayMs });
|
||||
|
||||
// Dev-harness theme control: default to the system theme, and add a small
|
||||
// toggle button that re-emits "theme" on the emitter exactly like the BGS shim
|
||||
// does, so the viewer's light/dark switch is exercised end to end.
|
||||
const systemDark = window.matchMedia("(prefers-color-scheme: dark)");
|
||||
let dark = params.get("theme") ? params.get("theme") === "dark" : systemDark.matches;
|
||||
|
||||
function applyTheme(): void {
|
||||
emitter.emit("theme" as never, { dark } as never);
|
||||
toggle.textContent = dark ? "Light mode" : "Dark mode";
|
||||
}
|
||||
|
||||
const toggle = document.createElement("button");
|
||||
toggle.type = "button";
|
||||
toggle.style.cssText =
|
||||
"position:fixed;bottom:12px;right:12px;z-index:1000;padding:6px 12px;border-radius:8px;border:1px solid #888;background:#fff;color:#222;font:13px system-ui;cursor:pointer;opacity:0.85";
|
||||
toggle.addEventListener("click", () => {
|
||||
dark = !dark;
|
||||
applyTheme();
|
||||
});
|
||||
document.body.appendChild(toggle);
|
||||
|
||||
applyTheme();
|
||||
systemDark.addEventListener("change", (e) => {
|
||||
dark = e.matches;
|
||||
applyTheme();
|
||||
});
|
||||
|
||||
(window as unknown as { outpostDev?: unknown }).outpostDev = {
|
||||
emitter,
|
||||
replayStart: () => emitter.emit("replay:start" as never),
|
||||
replayTo: (to: number) => emitter.emit("replay:to" as never, to as never),
|
||||
replayEnd: () => emitter.emit("replay:end" as never),
|
||||
setTheme: (d: boolean) => {
|
||||
dark = d;
|
||||
applyTheme();
|
||||
},
|
||||
};
|
||||
|
||||
console.log(`[outpost dev] hot-seat vs bots: you are player 0 of ${players}, seed=${seed ?? "random"}`);
|
||||
1
packages/viewer/src/env.d.ts
vendored
Normal file
1
packages/viewer/src/env.d.ts
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
declare const __DEV__: boolean;
|
||||
222
packages/viewer/src/lib/ActionBar.svelte
Normal file
222
packages/viewer/src/lib/ActionBar.svelte
Normal file
|
|
@ -0,0 +1,222 @@
|
|||
<script lang="ts">
|
||||
import { FACTORIES, FACTORY_TYPES, UPGRADE_SPECS } from "outpost-engine";
|
||||
import { RESOURCE_LABELS, type ViewerStore } from "./store.svelte";
|
||||
|
||||
interface Props {
|
||||
store: ViewerStore;
|
||||
}
|
||||
|
||||
let { store }: Props = $props();
|
||||
|
||||
const state = $derived(store.liveState);
|
||||
const me = $derived(store.me);
|
||||
const pending = $derived(store.pending);
|
||||
const total = $derived(store.pickTotal());
|
||||
const pickCount = $derived(store.cardPick.length);
|
||||
const needsResearch = $derived(pending?.kind === "factory" && FACTORIES[pending.factory].needsResearchCard === true);
|
||||
const hasResearch = $derived(!!me && store.cardPick.some((i) => me.hand[i]?.t === "research"));
|
||||
const waitingOn = $derived.by((): string => {
|
||||
const s = state;
|
||||
if (!s || s.ended) {
|
||||
return "";
|
||||
}
|
||||
const name = (seat: number | undefined) =>
|
||||
seat === undefined ? "…" : (s.players[seat]?.name ?? `Player ${seat + 1}`);
|
||||
switch (s.phase) {
|
||||
case "discard": {
|
||||
const seats = s.players.flatMap((p, i) => (p.mustDiscard ? [i] : []));
|
||||
return `Waiting for ${seats.map(name).join(", ")} to discard…`;
|
||||
}
|
||||
case "actions":
|
||||
return `Waiting for ${name(s.activeSeat)} to take their turn…`;
|
||||
case "auction":
|
||||
return `Auction: waiting for ${name(s.auction?.activeBidder)} to bid…`;
|
||||
case "auctionPayment":
|
||||
return `Auction: waiting for ${name(s.auction?.highBidder)} to pay…`;
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
});
|
||||
const factoryReason = $derived.by((): Partial<Record<(typeof FACTORY_TYPES)[number], string>> => {
|
||||
if (!me) {
|
||||
return {};
|
||||
}
|
||||
return {
|
||||
titanium: me.upgrades.heavyEquipment === 0 ? "requires Heavy Equipment" : undefined,
|
||||
research: me.upgrades.laboratory === 0 ? "requires Laboratory" : undefined,
|
||||
newChemicals: !me.hand.some((c) => c.t === "research") ? "needs a research card in payment" : undefined,
|
||||
};
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if state && !state.ended && !store.replay.active}
|
||||
<div class="actionbar">
|
||||
{#if store.iMustDiscard && me}
|
||||
<div class="flow">
|
||||
<span class="hint warn">
|
||||
Over hand capacity — discard {store.discardExcess} more card{store.discardExcess === 1 ? "" : "s"}
|
||||
(selected {pickCount}; research and microbiotics don't count).
|
||||
</span>
|
||||
<button class="confirm" disabled={pickCount === 0} onclick={() => store.confirmDiscard()}>
|
||||
Discard selected
|
||||
</button>
|
||||
</div>
|
||||
{:else if store.myPayment && me}
|
||||
<div class="flow">
|
||||
{#if pending?.kind === "payAuction"}
|
||||
<span class="hint">
|
||||
Paying for <strong>{UPGRADE_SPECS[state.auction?.upgrade ?? "dataLibrary"].name}</strong>: selected
|
||||
<strong>{total}</strong> / {pending.cost} credits.
|
||||
</span>
|
||||
<button class="confirm" disabled={!store.pendingValid()} onclick={() => store.confirmPending()}>
|
||||
Pay {pending.cost}
|
||||
</button>
|
||||
<button class="cancel" onclick={() => store.cancel()}>Re-pick cards</button>
|
||||
{:else}
|
||||
<span class="hint gold-hint">
|
||||
You won the auction — select hand cards worth at least {store.auctionDue()} credits, then
|
||||
</span>
|
||||
<button class="confirm" onclick={() => store.startAuctionPayment()}>Select payment…</button>
|
||||
{/if}
|
||||
</div>
|
||||
{:else if store.myActionTurn && me}
|
||||
{#if store.manning}
|
||||
<div class="flow">
|
||||
<span class="hint gold-hint">
|
||||
Assign operators: {store.manningPick.length} / {me.population + me.robots} factories manned — click the factory
|
||||
chips in your panel to toggle them.
|
||||
</span>
|
||||
<button class="confirm" onclick={() => store.confirmEndTurn()}>Confirm & end turn</button>
|
||||
<button class="cancel" onclick={() => store.cancel()}>Back</button>
|
||||
</div>
|
||||
{:else if pending && pending.kind !== "payAuction"}
|
||||
<div class="flow">
|
||||
<span class="hint">
|
||||
{#if pending.kind === "factory"}
|
||||
Building a <strong>{RESOURCE_LABELS[pending.factory]}</strong> factory:
|
||||
{:else if pending.kind === "population"}
|
||||
Recruiting <strong>{pending.count}</strong> colonist{pending.count === 1 ? "" : "s"}:
|
||||
{:else}
|
||||
Buying <strong>{pending.count}</strong> robot{pending.count === 1 ? "" : "s"}:
|
||||
{/if}
|
||||
selected <strong>{total}</strong> / {pending.cost} credits.
|
||||
{#if needsResearch && !hasResearch}
|
||||
<span class="warn">Payment must include a research card.</span>
|
||||
{/if}
|
||||
</span>
|
||||
{#if pending.kind === "population" || pending.kind === "robots"}
|
||||
<button onclick={() => store.bumpPendingCount(-1)} disabled={pending.count <= 1}>−</button>
|
||||
<button onclick={() => store.bumpPendingCount(1)}>+1</button>
|
||||
{/if}
|
||||
<button class="confirm" disabled={!store.pendingValid()} onclick={() => store.confirmPending()}>
|
||||
Confirm ({pending.cost})
|
||||
</button>
|
||||
<button class="cancel" onclick={() => store.cancel()}>Cancel</button>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="flow wrap">
|
||||
<span class="hint">Your turn — cash {store.myHandValue}:</span>
|
||||
{#each FACTORY_TYPES as type (type)}
|
||||
{@const spec = FACTORIES[type]}
|
||||
{@const reason = factoryReason[type]}
|
||||
<button
|
||||
class="buy res-{type}"
|
||||
disabled={!store.canAffordFactory(type)}
|
||||
title={reason ?? `${RESOURCE_LABELS[type]} factory — ${spec.cost} credits, ${spec.vp} VP`}
|
||||
onclick={() => store.startFactoryPayment(type)}
|
||||
>
|
||||
{RESOURCE_LABELS[type]} · {spec.cost}
|
||||
</button>
|
||||
{/each}
|
||||
<button
|
||||
class="buy"
|
||||
disabled={me.population >= store.popMaxOf(store.playerIndex ?? -1) || store.myHandValue < store.popCost}
|
||||
title="Recruit a colonist — {store.popCost} credits{me.upgrades.ecoplants > 0
|
||||
? ' (Ecoplants discount)'
|
||||
: ''}"
|
||||
onclick={() => store.startPopulationPayment()}
|
||||
>
|
||||
Colonist · {store.popCost}
|
||||
</button>
|
||||
{#if me.upgrades.robots > 0}
|
||||
<button
|
||||
class="buy"
|
||||
disabled={me.robots >= store.robotMaxOf(store.playerIndex ?? -1) || store.myHandValue < 10}
|
||||
title="Buy a robot — 10 credits"
|
||||
onclick={() => store.startRobotsPayment()}
|
||||
>
|
||||
Robot · 10
|
||||
</button>
|
||||
{/if}
|
||||
<button class="end" onclick={() => store.startManning()}>End turn…</button>
|
||||
</div>
|
||||
<div class="flow">
|
||||
<span class="hint dim">
|
||||
Click a market upgrade to auction it, or a buy button and then the hand cards to pay with.
|
||||
</span>
|
||||
</div>
|
||||
{/if}
|
||||
{:else if !store.myBidTurn}
|
||||
<div class="flow">
|
||||
<span class="hint dim">{waitingOn}</span>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.actionbar {
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
padding: 10px 14px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
.flow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.hint {
|
||||
color: var(--text);
|
||||
font-size: 13px;
|
||||
}
|
||||
.hint.dim {
|
||||
color: var(--text-dim);
|
||||
}
|
||||
.gold-hint {
|
||||
color: var(--gold);
|
||||
font-weight: 600;
|
||||
}
|
||||
.warn {
|
||||
color: var(--danger);
|
||||
font-weight: 600;
|
||||
}
|
||||
.buy {
|
||||
padding: 5px 10px;
|
||||
font-size: 12.5px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.buy.res-ore,
|
||||
.buy.res-water,
|
||||
.buy.res-titanium,
|
||||
.buy.res-research,
|
||||
.buy.res-newChemicals {
|
||||
border-color: color-mix(in srgb, var(--res) 65%, transparent);
|
||||
}
|
||||
.confirm {
|
||||
border-color: var(--gold);
|
||||
font-weight: 700;
|
||||
}
|
||||
.cancel {
|
||||
color: var(--text-dim);
|
||||
}
|
||||
.end {
|
||||
margin-left: auto;
|
||||
border-color: var(--gold);
|
||||
font-weight: 700;
|
||||
}
|
||||
</style>
|
||||
151
packages/viewer/src/lib/AuctionBanner.svelte
Normal file
151
packages/viewer/src/lib/AuctionBanner.svelte
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
<script lang="ts">
|
||||
import { UPGRADE_SPECS, type GameState } from "outpost-engine";
|
||||
import { UPGRADE_EFFECTS, type ViewerStore } from "./store.svelte";
|
||||
|
||||
interface Props {
|
||||
state: GameState;
|
||||
store: ViewerStore;
|
||||
}
|
||||
|
||||
let { state, store }: Props = $props();
|
||||
|
||||
const auction = $derived(state.auction);
|
||||
const spec = $derived(auction ? UPGRADE_SPECS[auction.upgrade] : null);
|
||||
const nameOf = (seat: number) => state.players[seat]?.name ?? `Player ${seat + 1}`;
|
||||
const meIndex = $derived(store.playerIndex);
|
||||
const discount = $derived(auction && meIndex !== undefined ? store.discountOf(meIndex, auction.upgrade) : 0);
|
||||
const due = $derived(store.auctionDue());
|
||||
const minBid = $derived((auction?.highBid ?? 0) + 1);
|
||||
const maxBid = $derived(store.maxBid);
|
||||
|
||||
$effect(() => {
|
||||
if (store.myBidTurn) {
|
||||
store.prepareBid();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if auction && spec}
|
||||
<div class="banner">
|
||||
<div class="block">
|
||||
<span class="label">On the block</span>
|
||||
<span class="uname">{spec.name}</span>
|
||||
<span class="uvp">{spec.vp} VP · list {spec.price}</span>
|
||||
<span class="ueffect">{UPGRADE_EFFECTS[auction.upgrade]}</span>
|
||||
</div>
|
||||
<div class="status">
|
||||
<div class="bid">
|
||||
High bid <strong>{auction.highBid}</strong> by <strong>{nameOf(auction.highBidder)}</strong>
|
||||
</div>
|
||||
{#if state.phase === "auction"}
|
||||
<div class="turn">
|
||||
{#if store.myBidTurn}
|
||||
Your bid — raise to at least {minBid} or pass.
|
||||
{:else}
|
||||
Waiting for {nameOf(auction.activeBidder)} to bid…
|
||||
{/if}
|
||||
</div>
|
||||
{#if store.myBidTurn}
|
||||
<div class="controls">
|
||||
<input type="number" min={minBid} max={maxBid} bind:value={store.bidAmount} />
|
||||
<button
|
||||
class="confirm"
|
||||
disabled={store.bidAmount < minBid || store.bidAmount > maxBid}
|
||||
onclick={() => store.confirmBid()}>Bid</button
|
||||
>
|
||||
<button class="pass" onclick={() => store.passBid()}>Pass</button>
|
||||
</div>
|
||||
<div class="hint">
|
||||
You hold {store.myHandValue} credits{#if discount > 0}
|
||||
and get a −{discount} discount on this upgrade{/if} — max bid {maxBid}.
|
||||
</div>
|
||||
{/if}
|
||||
{:else}
|
||||
<div class="turn">
|
||||
{#if store.myPayment}
|
||||
You won — pay {due} credits (bid {auction.highBid}{#if discount > 0}
|
||||
− {discount} discount{/if}).
|
||||
{:else}
|
||||
Waiting for {nameOf(auction.highBidder)} to pay…
|
||||
{/if}
|
||||
</div>
|
||||
{#if store.myPayment}
|
||||
<div class="hint">Select cards from your hand below, then confirm the payment in the action bar.</div>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.banner {
|
||||
display: flex;
|
||||
gap: 18px;
|
||||
align-items: flex-start;
|
||||
flex-wrap: wrap;
|
||||
background: linear-gradient(160deg, color-mix(in srgb, var(--gold) 14%, var(--bg-panel)), var(--bg-panel));
|
||||
border: 1px solid var(--gold);
|
||||
border-radius: var(--radius);
|
||||
padding: 12px 16px;
|
||||
animation: glowPulse 2.5s ease-in-out infinite;
|
||||
}
|
||||
.block {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 170px;
|
||||
}
|
||||
.label {
|
||||
font-size: 10px;
|
||||
font-weight: 800;
|
||||
letter-spacing: 0.1em;
|
||||
text-transform: uppercase;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
.uname {
|
||||
font-size: 17px;
|
||||
font-weight: 800;
|
||||
color: var(--gold);
|
||||
}
|
||||
.uvp {
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: var(--text);
|
||||
}
|
||||
.ueffect {
|
||||
font-size: 11px;
|
||||
color: var(--text-dim);
|
||||
max-width: 260px;
|
||||
}
|
||||
.status {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
flex: 1;
|
||||
min-width: 220px;
|
||||
}
|
||||
.bid {
|
||||
font-size: 14px;
|
||||
}
|
||||
.turn {
|
||||
font-size: 13px;
|
||||
color: var(--text);
|
||||
font-weight: 600;
|
||||
}
|
||||
.controls {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
}
|
||||
.confirm {
|
||||
border-color: var(--gold);
|
||||
font-weight: 700;
|
||||
}
|
||||
.pass {
|
||||
color: var(--text-dim);
|
||||
}
|
||||
.hint {
|
||||
font-size: 11.5px;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
</style>
|
||||
88
packages/viewer/src/lib/GameEndBanner.svelte
Normal file
88
packages/viewer/src/lib/GameEndBanner.svelte
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
<script lang="ts">
|
||||
import { VICTORY_VP } from "outpost-engine";
|
||||
import type { ViewerStore } from "./store.svelte";
|
||||
|
||||
interface Props {
|
||||
store: ViewerStore;
|
||||
}
|
||||
|
||||
let { store }: Props = $props();
|
||||
const state = $derived(store.state);
|
||||
const ranks = $derived(store.finalRankings);
|
||||
const scores = $derived(store.finalScores);
|
||||
const winners = $derived(state?.ended ? ranks.map((r, i) => (r === 1 ? i : -1)).filter((i) => i >= 0) : []);
|
||||
</script>
|
||||
|
||||
{#if state?.ended}
|
||||
<div class="banner">
|
||||
<h2>Game over</h2>
|
||||
<p class="result">
|
||||
{#if winners.length > 1}
|
||||
Shared victory: {winners.map((i) => state.players[i]!.name).join(" & ")}
|
||||
{:else if winners.length === 1}
|
||||
{state.players[winners[0]!]!.name} wins
|
||||
{/if}
|
||||
</p>
|
||||
<table>
|
||||
<thead>
|
||||
<tr><th>#</th><th>Player</th><th>VP</th><th>Factories</th><th>Upgrades</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{#each state.players.map((p, i) => ({ p, i })).sort((a, b) => ranks[a.i]! - ranks[b.i]!) as row (row.i)}
|
||||
<tr class:winner={ranks[row.i] === 1}>
|
||||
<td>{ranks[row.i]}</td>
|
||||
<td>{row.p.name}</td>
|
||||
<td>{scores[row.i]}</td>
|
||||
<td>{row.p.factories.length}</td>
|
||||
<td>{Object.values(row.p.upgrades).reduce((a, b) => a + b, 0)}</td>
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
<p class="target">Victory target: {VICTORY_VP} VP</p>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.banner {
|
||||
background: var(--banner-bg);
|
||||
border: 1px solid var(--gold);
|
||||
border-radius: var(--radius);
|
||||
padding: 16px 20px;
|
||||
}
|
||||
h2 {
|
||||
margin: 0 0 4px;
|
||||
color: var(--gold);
|
||||
font-size: 20px;
|
||||
}
|
||||
.result {
|
||||
margin: 0 0 12px;
|
||||
color: var(--text);
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
}
|
||||
table {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
max-width: 460px;
|
||||
}
|
||||
th,
|
||||
td {
|
||||
text-align: left;
|
||||
padding: 4px 12px 4px 0;
|
||||
font-size: 13px;
|
||||
}
|
||||
th {
|
||||
color: var(--text-dim);
|
||||
font-weight: 600;
|
||||
}
|
||||
tr.winner td {
|
||||
color: var(--gold);
|
||||
font-weight: 700;
|
||||
}
|
||||
.target {
|
||||
margin: 10px 0 0;
|
||||
color: var(--text-dim);
|
||||
font-size: 12px;
|
||||
}
|
||||
</style>
|
||||
68
packages/viewer/src/lib/HeaderStrip.svelte
Normal file
68
packages/viewer/src/lib/HeaderStrip.svelte
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
<script lang="ts">
|
||||
import { VICTORY_VP, type GameState } from "outpost-engine";
|
||||
|
||||
interface Props {
|
||||
state: GameState;
|
||||
}
|
||||
|
||||
let { state }: Props = $props();
|
||||
|
||||
const phaseLabel = $derived(
|
||||
state.ended
|
||||
? "Game over"
|
||||
: state.phase === "discard"
|
||||
? "Discard"
|
||||
: state.phase === "actions"
|
||||
? "Actions"
|
||||
: state.phase === "auction"
|
||||
? "Auction"
|
||||
: "Auction payment"
|
||||
);
|
||||
</script>
|
||||
|
||||
<div class="strip">
|
||||
<span class="brand">OUTPOST</span>
|
||||
<span class="item">Round <strong>{state.round}</strong></span>
|
||||
<span class="item phase">{phaseLabel}</span>
|
||||
<span class="item dim">First to {VICTORY_VP} VP wins</span>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.strip {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
padding: 8px 14px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.brand {
|
||||
font-weight: 800;
|
||||
letter-spacing: 0.18em;
|
||||
font-size: 13px;
|
||||
color: var(--gold);
|
||||
}
|
||||
.item {
|
||||
font-size: 13px;
|
||||
color: var(--text);
|
||||
}
|
||||
.item strong {
|
||||
font-weight: 800;
|
||||
}
|
||||
.phase {
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
font-size: 11px;
|
||||
letter-spacing: 0.08em;
|
||||
background: color-mix(in srgb, var(--gold) 18%, transparent);
|
||||
color: var(--gold);
|
||||
border-radius: 5px;
|
||||
padding: 2px 8px;
|
||||
}
|
||||
.dim {
|
||||
color: var(--text-dim);
|
||||
margin-left: auto;
|
||||
}
|
||||
</style>
|
||||
71
packages/viewer/src/lib/LogFeed.svelte
Normal file
71
packages/viewer/src/lib/LogFeed.svelte
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
<script lang="ts">
|
||||
import type { ViewerStore } from "./store.svelte";
|
||||
|
||||
interface Props {
|
||||
store: ViewerStore;
|
||||
}
|
||||
|
||||
let { store }: Props = $props();
|
||||
const lines = $derived(store.logLines);
|
||||
const recent = $derived(
|
||||
lines
|
||||
.map((line, index) => ({ line, index }))
|
||||
.slice(-10)
|
||||
.reverse()
|
||||
);
|
||||
</script>
|
||||
|
||||
<div class="side">
|
||||
<div class="caption">Recent events</div>
|
||||
<div class="feed">
|
||||
{#each recent as item (item.index)}
|
||||
<div class="entry" class:latest={item.index === lines.length - 1}>{item.line}</div>
|
||||
{/each}
|
||||
{#if recent.length === 0}
|
||||
<div class="entry dim">No events yet</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.side {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
.caption {
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
color: var(--text-dim);
|
||||
padding: 0 4px;
|
||||
}
|
||||
.feed {
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
padding: 8px 12px;
|
||||
max-height: 170px;
|
||||
overflow-y: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
}
|
||||
.entry {
|
||||
font-size: 12px;
|
||||
color: var(--text);
|
||||
border-bottom: 1px solid color-mix(in srgb, var(--line) 50%, transparent);
|
||||
padding-bottom: 3px;
|
||||
}
|
||||
.entry:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
.entry.latest {
|
||||
color: var(--gold);
|
||||
font-weight: 600;
|
||||
}
|
||||
.entry.dim {
|
||||
color: var(--text-dim);
|
||||
}
|
||||
</style>
|
||||
205
packages/viewer/src/lib/MarketPanel.svelte
Normal file
205
packages/viewer/src/lib/MarketPanel.svelte
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
<script lang="ts">
|
||||
import { UPGRADE_SPECS, UPGRADES, type GameState } from "outpost-engine";
|
||||
import { UPGRADE_EFFECTS, type ViewerStore } from "./store.svelte";
|
||||
|
||||
interface Props {
|
||||
state: GameState;
|
||||
store: ViewerStore;
|
||||
}
|
||||
|
||||
let { state, store }: Props = $props();
|
||||
|
||||
const supplyLeft = $derived(UPGRADES.map((u) => ({ u, n: state.supply[u] })).filter((x) => x.n > 0));
|
||||
const pick = $derived(store.auctionPick);
|
||||
const meIndex = $derived(store.playerIndex);
|
||||
|
||||
function myDue(upgrade: (typeof UPGRADES)[number]): number {
|
||||
if (meIndex === undefined) {
|
||||
return UPGRADE_SPECS[upgrade].price;
|
||||
}
|
||||
return Math.max(0, UPGRADE_SPECS[upgrade].price - store.discountOf(meIndex, upgrade));
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="market">
|
||||
<div class="caption">Colony upgrades for auction</div>
|
||||
{#if state.market.length === 0}
|
||||
<div class="empty">The market is empty — new upgrades arrive with the next colony ship.</div>
|
||||
{:else}
|
||||
<div class="cards">
|
||||
{#each state.market as upgrade, i (i)}
|
||||
{@const spec = UPGRADE_SPECS[upgrade]}
|
||||
{@const open = pick?.marketIndex === i}
|
||||
{@const due = myDue(upgrade)}
|
||||
<div class="slot">
|
||||
<button
|
||||
class="ucard"
|
||||
class:open
|
||||
class:clickable={store.myActionTurn}
|
||||
disabled={!store.myActionTurn}
|
||||
title={store.myActionTurn ? "Put up for auction" : spec.name}
|
||||
onclick={() => (open ? store.cancel() : store.openAuction(i))}
|
||||
>
|
||||
<span class="uname">{spec.name}</span>
|
||||
<span class="uvp">{spec.vp} VP</span>
|
||||
<span class="uprice">
|
||||
min {spec.price}{#if due < spec.price}
|
||||
· you pay {due}{/if}
|
||||
</span>
|
||||
<span class="ueffect">{UPGRADE_EFFECTS[upgrade]}</span>
|
||||
</button>
|
||||
{#if open && pick}
|
||||
<div class="bidbox">
|
||||
<div class="bidrow">
|
||||
<button onclick={() => store.bumpAuctionBid(-1)} disabled={pick.bid <= spec.price}>−</button>
|
||||
<input
|
||||
type="number"
|
||||
min={spec.price}
|
||||
value={pick.bid}
|
||||
oninput={(e) => store.setAuctionBid(Number(e.currentTarget.value))}
|
||||
/>
|
||||
<button onclick={() => store.bumpAuctionBid(1)}>+1</button>
|
||||
<button onclick={() => store.bumpAuctionBid(5)}>+5</button>
|
||||
</div>
|
||||
<div class="bidrow">
|
||||
<button class="confirm" onclick={() => store.confirmAuction()}>Auction at {pick.bid}</button>
|
||||
<button class="cancel" onclick={() => store.cancel()}>Cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
<div class="supply">
|
||||
{#each supplyLeft as x (x.u)}
|
||||
<span class="stag" title="{UPGRADE_SPECS[x.u].name} left in the supply">{UPGRADE_SPECS[x.u].name} ×{x.n}</span>
|
||||
{/each}
|
||||
{#if supplyLeft.length === 0}
|
||||
<span class="stag dim">Supply exhausted</span>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.market {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
.caption {
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
color: var(--text-dim);
|
||||
padding: 0 4px;
|
||||
}
|
||||
.empty {
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
padding: 12px 14px;
|
||||
color: var(--text-dim);
|
||||
font-size: 13px;
|
||||
}
|
||||
.cards {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.slot {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
.ucard {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 3px;
|
||||
width: 168px;
|
||||
min-height: 118px;
|
||||
padding: 10px 12px;
|
||||
text-align: left;
|
||||
background: linear-gradient(165deg, var(--bg-elevated), var(--bg-panel));
|
||||
border: 1px solid var(--line);
|
||||
border-top: 3px solid var(--gold);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.25);
|
||||
}
|
||||
.ucard.clickable:hover:not(:disabled) {
|
||||
border-color: var(--gold);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
.ucard.open {
|
||||
outline: 2px solid var(--gold);
|
||||
animation: glowPulse 2s ease-in-out infinite;
|
||||
}
|
||||
.uname {
|
||||
font-weight: 800;
|
||||
font-size: 13px;
|
||||
color: var(--text);
|
||||
}
|
||||
.uvp {
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
color: var(--gold);
|
||||
}
|
||||
.uprice {
|
||||
font-size: 11px;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
.ueffect {
|
||||
font-size: 10.5px;
|
||||
line-height: 1.3;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
.bidbox {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--gold);
|
||||
border-radius: var(--radius);
|
||||
padding: 8px;
|
||||
width: 168px;
|
||||
}
|
||||
.bidrow {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
align-items: center;
|
||||
}
|
||||
.bidrow button {
|
||||
padding: 3px 8px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.bidrow input {
|
||||
width: 62px;
|
||||
padding: 3px 6px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.confirm {
|
||||
border-color: var(--gold);
|
||||
font-weight: 700;
|
||||
}
|
||||
.cancel {
|
||||
color: var(--text-dim);
|
||||
}
|
||||
.supply {
|
||||
display: flex;
|
||||
gap: 5px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.stag {
|
||||
font-size: 10px;
|
||||
color: var(--text-dim);
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 4px;
|
||||
padding: 1px 6px;
|
||||
}
|
||||
.stag.dim {
|
||||
font-style: italic;
|
||||
}
|
||||
</style>
|
||||
337
packages/viewer/src/lib/PlayerPanel.svelte
Normal file
337
packages/viewer/src/lib/PlayerPanel.svelte
Normal file
|
|
@ -0,0 +1,337 @@
|
|||
<script lang="ts">
|
||||
import { FACTORIES, FACTORY_TYPES, UPGRADE_SPECS, UPGRADES, type GameState, type Resource } from "outpost-engine";
|
||||
import ProductionCardView from "./ProductionCardView.svelte";
|
||||
import { RESOURCE_LABELS, playerColor, type ViewerStore } from "./store.svelte";
|
||||
|
||||
interface Props {
|
||||
state: GameState;
|
||||
store: ViewerStore;
|
||||
index: number;
|
||||
onNameClick?: (index: number) => void;
|
||||
}
|
||||
|
||||
let { state, store, index, onNameClick }: Props = $props();
|
||||
|
||||
const player = $derived(state.players[index]!);
|
||||
const isMe = $derived(store.playerIndex === index);
|
||||
const avatar = $derived(store.avatars[index]);
|
||||
const initial = $derived((player.name.trim()[0] ?? "?").toUpperCase());
|
||||
const orderPos = $derived(state.purchaseOrder.indexOf(index) + 1);
|
||||
const isActive = $derived(
|
||||
!state.ended &&
|
||||
((state.phase === "actions" && state.activeSeat === index) ||
|
||||
(state.phase === "discard" && player.mustDiscard) ||
|
||||
((state.phase === "auction" || state.phase === "auctionPayment") &&
|
||||
(state.auction?.activeBidder === index ||
|
||||
(state.phase === "auctionPayment" && state.auction?.highBidder === index))))
|
||||
);
|
||||
const factories = $derived(
|
||||
FACTORY_TYPES.map((type) => ({
|
||||
type,
|
||||
items: player.factories.map((f, i) => ({ ...f, index: i })).filter((f) => f.type === type),
|
||||
})).filter((g) => g.items.length > 0)
|
||||
);
|
||||
const upgrades = $derived(UPGRADES.map((u) => ({ u, n: player.upgrades[u] })).filter((x) => x.n > 0));
|
||||
const hiddenCounts = $derived.by(() => {
|
||||
const counts = new Map<Resource, number>();
|
||||
for (const card of player.hand) {
|
||||
counts.set(card.t, (counts.get(card.t) ?? 0) + 1);
|
||||
}
|
||||
return [...counts.entries()];
|
||||
});
|
||||
const manning = $derived(store.manning && isMe);
|
||||
const operators = $derived(player.population + player.robots);
|
||||
</script>
|
||||
|
||||
<div
|
||||
class="panel"
|
||||
class:active={isActive}
|
||||
class:dropped={player.dropped}
|
||||
class:me={isMe}
|
||||
style="--pc: {playerColor(index)}"
|
||||
>
|
||||
<div class="head">
|
||||
<button class="identity" onclick={() => onNameClick?.(index)} title={player.name}>
|
||||
{#if orderPos > 0}
|
||||
<span
|
||||
class="order"
|
||||
title="purchase order — buys {orderPos}{orderPos === 1
|
||||
? 'st'
|
||||
: orderPos === 2
|
||||
? 'nd'
|
||||
: orderPos === 3
|
||||
? 'rd'
|
||||
: 'th'} this round">{orderPos}</span
|
||||
>
|
||||
{/if}
|
||||
{#if avatar}
|
||||
<img class="avatar" src={avatar} alt="" referrerpolicy="no-referrer" />
|
||||
{:else}
|
||||
<span class="avatar fallback">{initial}</span>
|
||||
{/if}
|
||||
<span class="name">{player.name}</span>
|
||||
</button>
|
||||
<span class="vp" title="victory points">{store.vpOf(index)}<span class="unit">VP</span></span>
|
||||
</div>
|
||||
|
||||
<div class="row stats">
|
||||
<span title="colonists / population limit">👤 {player.population}/{store.popMaxOf(index)}</span>
|
||||
{#if player.robots > 0 || player.upgrades.robots > 0}
|
||||
<span title="robots / robot limit">🤖 {player.robots}/{store.robotMaxOf(index)}</span>
|
||||
{/if}
|
||||
<span title="hand cards counting toward capacity / hand capacity (research and microbiotics are exempt)">
|
||||
🂠 {store.countingOf(index)}/{store.handCapOf(index)}
|
||||
</span>
|
||||
{#if player.done && !state.ended}
|
||||
<span class="done" title="has ended their turn this round">✓ done</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="row chips">
|
||||
{#each factories as group (group.type)}
|
||||
<span
|
||||
class="fgroup res-{group.type}"
|
||||
title="{RESOURCE_LABELS[group.type]} factories ({FACTORIES[group.type].vp} VP each when manned)"
|
||||
>
|
||||
{#each group.items as factory (factory.index)}
|
||||
<button
|
||||
class="chip"
|
||||
class:manned={manning ? store.manningPick.includes(factory.index) : factory.manned}
|
||||
class:toggle={manning}
|
||||
disabled={!manning}
|
||||
title={manning ? "toggle operator" : factory.manned ? "manned" : "unmanned"}
|
||||
onclick={() => store.toggleManning(factory.index)}
|
||||
></button>
|
||||
{/each}
|
||||
</span>
|
||||
{/each}
|
||||
{#if factories.length === 0}
|
||||
<span class="none">no factories</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if upgrades.length > 0}
|
||||
<div class="row tags">
|
||||
{#each upgrades as x (x.u)}
|
||||
<span class="utag" title={UPGRADE_SPECS[x.u].name}
|
||||
>{UPGRADE_SPECS[x.u].name}{#if x.n > 1}×{x.n}{/if}</span
|
||||
>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="row hand">
|
||||
{#if isMe}
|
||||
{#each player.hand as card, i (i)}
|
||||
<ProductionCardView
|
||||
{card}
|
||||
selectable={store.interactive}
|
||||
selected={store.cardPick.includes(i)}
|
||||
onclick={() => store.toggleCard(i)}
|
||||
/>
|
||||
{/each}
|
||||
{#if player.hand.length === 0}
|
||||
<span class="none">no cards</span>
|
||||
{/if}
|
||||
{:else}
|
||||
{#each hiddenCounts as [res, n] (res)}
|
||||
<span class="hcount res-{res}" title="{n} {RESOURCE_LABELS[res]} card{n === 1 ? '' : 's'}">{n}</span>
|
||||
{/each}
|
||||
{#if player.hand.length === 0}
|
||||
<span class="none">no cards</span>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.panel {
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--line);
|
||||
border-left: 4px solid var(--pc);
|
||||
border-radius: var(--radius);
|
||||
padding: 8px 12px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
min-width: 220px;
|
||||
transition:
|
||||
box-shadow 0.2s ease,
|
||||
border-color 0.2s ease;
|
||||
}
|
||||
.panel.active {
|
||||
border-color: var(--pc);
|
||||
box-shadow:
|
||||
0 0 0 1px var(--pc),
|
||||
0 0 14px color-mix(in srgb, var(--pc) 40%, transparent);
|
||||
}
|
||||
.panel.me {
|
||||
background: var(--bg-elevated);
|
||||
}
|
||||
.panel.dropped {
|
||||
opacity: 0.45;
|
||||
filter: grayscale(0.8);
|
||||
}
|
||||
.head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.identity {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
background: none;
|
||||
border: none;
|
||||
padding: 0;
|
||||
min-width: 0;
|
||||
}
|
||||
.identity:hover {
|
||||
border: none;
|
||||
}
|
||||
.identity:hover .name {
|
||||
color: var(--gold);
|
||||
}
|
||||
.avatar {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border-radius: 50%;
|
||||
object-fit: cover;
|
||||
border: 2px solid var(--pc);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.avatar.fallback {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: color-mix(in srgb, var(--pc) 30%, var(--bg-elevated));
|
||||
color: var(--text);
|
||||
font-weight: 800;
|
||||
font-size: 14px;
|
||||
}
|
||||
.name {
|
||||
font-weight: 700;
|
||||
color: var(--text);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.vp {
|
||||
font-weight: 800;
|
||||
color: var(--gold);
|
||||
font-size: 16px;
|
||||
}
|
||||
.vp .unit {
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
color: var(--text-dim);
|
||||
margin-left: 2px;
|
||||
}
|
||||
.order {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
border-radius: 50%;
|
||||
background: color-mix(in srgb, var(--pc) 25%, var(--bg-elevated));
|
||||
border: 1px solid var(--pc);
|
||||
color: var(--text);
|
||||
font-size: 10px;
|
||||
font-weight: 800;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.row {
|
||||
display: flex;
|
||||
gap: 5px;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
min-height: 18px;
|
||||
}
|
||||
.stats {
|
||||
font-size: 11.5px;
|
||||
color: var(--text-dim);
|
||||
gap: 10px;
|
||||
}
|
||||
.stats .done {
|
||||
color: var(--microbiotics);
|
||||
font-weight: 700;
|
||||
}
|
||||
.fgroup {
|
||||
display: inline-flex;
|
||||
gap: 3px;
|
||||
padding: 3px 4px;
|
||||
border-radius: 6px;
|
||||
background: color-mix(in srgb, var(--res) 16%, transparent);
|
||||
border: 1px solid color-mix(in srgb, var(--res) 45%, transparent);
|
||||
}
|
||||
.chip {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border-radius: 50%;
|
||||
border: 1.5px solid var(--res);
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
}
|
||||
.chip.manned {
|
||||
background: var(--res);
|
||||
box-shadow: 0 0 4px color-mix(in srgb, var(--res) 70%, transparent);
|
||||
}
|
||||
.chip.toggle {
|
||||
cursor: pointer;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
}
|
||||
.chip.toggle:hover {
|
||||
transform: scale(1.15);
|
||||
}
|
||||
.utag {
|
||||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
background: color-mix(in srgb, var(--gold) 14%, var(--bg-elevated));
|
||||
border: 1px solid color-mix(in srgb, var(--gold) 40%, transparent);
|
||||
border-radius: 4px;
|
||||
padding: 1px 6px;
|
||||
}
|
||||
.hand {
|
||||
gap: 4px;
|
||||
}
|
||||
.hcount {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-width: 20px;
|
||||
height: 20px;
|
||||
padding: 0 4px;
|
||||
border-radius: 5px;
|
||||
background: var(--res);
|
||||
border: 1px solid color-mix(in srgb, var(--res) 60%, #000);
|
||||
color: var(--res-text);
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
}
|
||||
.none {
|
||||
color: var(--text-dim);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.panel {
|
||||
min-width: 0;
|
||||
padding: 6px 8px;
|
||||
gap: 4px;
|
||||
}
|
||||
.avatar {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
}
|
||||
.name {
|
||||
font-size: 13px;
|
||||
}
|
||||
.vp {
|
||||
font-size: 14px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
86
packages/viewer/src/lib/ProductionCardView.svelte
Normal file
86
packages/viewer/src/lib/ProductionCardView.svelte
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
<script lang="ts">
|
||||
import type { ProductionCard } from "outpost-engine";
|
||||
import { RESOURCE_LABELS } from "./store.svelte";
|
||||
|
||||
interface Props {
|
||||
card: ProductionCard;
|
||||
selected?: boolean;
|
||||
selectable?: boolean;
|
||||
onclick?: () => void;
|
||||
}
|
||||
|
||||
let { card, selected = false, selectable = false, onclick }: Props = $props();
|
||||
const hidden = $derived(card.v < 0);
|
||||
</script>
|
||||
|
||||
<button
|
||||
class="pcard res-{card.t}"
|
||||
class:selected
|
||||
class:selectable
|
||||
class:hidden
|
||||
disabled={!selectable}
|
||||
title="{RESOURCE_LABELS[card.t]}{hidden ? '' : ` — ${card.v} credits`}"
|
||||
{onclick}
|
||||
>
|
||||
<span class="value">{hidden ? "?" : card.v}</span>
|
||||
<span class="label">{RESOURCE_LABELS[card.t]}</span>
|
||||
</button>
|
||||
|
||||
<style>
|
||||
.pcard {
|
||||
display: inline-flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 1px;
|
||||
width: var(--card-w);
|
||||
height: var(--card-h);
|
||||
padding: 2px;
|
||||
border-radius: 6px;
|
||||
border: 1px solid color-mix(in srgb, var(--res) 60%, #000);
|
||||
background: linear-gradient(
|
||||
160deg,
|
||||
color-mix(in srgb, var(--res) 88%, #fff),
|
||||
var(--res) 65%,
|
||||
color-mix(in srgb, var(--res) 78%, #000)
|
||||
);
|
||||
color: var(--res-text);
|
||||
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.35);
|
||||
user-select: none;
|
||||
transition:
|
||||
transform 0.12s ease,
|
||||
box-shadow 0.12s ease;
|
||||
}
|
||||
.value {
|
||||
font-size: 16px;
|
||||
font-weight: 800;
|
||||
line-height: 1;
|
||||
text-shadow: 0 1px 1px rgba(0, 0, 0, 0.25);
|
||||
}
|
||||
.label {
|
||||
font-size: 7.5px;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.02em;
|
||||
text-align: center;
|
||||
line-height: 1.1;
|
||||
opacity: 0.9;
|
||||
}
|
||||
.pcard.selectable {
|
||||
cursor: pointer;
|
||||
}
|
||||
.pcard.selectable:hover {
|
||||
transform: translateY(-3px);
|
||||
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.45);
|
||||
}
|
||||
.pcard.selected {
|
||||
outline: 3px solid var(--gold);
|
||||
outline-offset: 1px;
|
||||
transform: translateY(-3px);
|
||||
}
|
||||
.pcard.hidden {
|
||||
background: linear-gradient(160deg, #3a4152, #262b38 65%, #1b1f29);
|
||||
border-color: #454e63;
|
||||
color: #8f9ab0;
|
||||
}
|
||||
</style>
|
||||
105
packages/viewer/src/lib/ReplayBar.svelte
Normal file
105
packages/viewer/src/lib/ReplayBar.svelte
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
<script lang="ts">
|
||||
import type { ViewerStore } from "./store.svelte";
|
||||
|
||||
interface Props {
|
||||
store: ViewerStore;
|
||||
}
|
||||
|
||||
let { store }: Props = $props();
|
||||
const replay = $derived(store.replay);
|
||||
const lines = $derived(store.logLines);
|
||||
const marks = $derived(lines.map((_, log) => ({ log })).filter((m) => m.log > 0));
|
||||
</script>
|
||||
|
||||
{#if replay.active}
|
||||
<div class="replaybar">
|
||||
<div class="title">
|
||||
<span class="badge">REPLAY</span>
|
||||
<span class="pos">entry {replay.current} / {replay.end}</span>
|
||||
</div>
|
||||
<div class="track">
|
||||
<button class="nav" disabled={replay.current <= 1} onclick={() => store.replayToEntry(1)} title="Start">⏮</button>
|
||||
<div class="marks">
|
||||
{#each marks as mark (mark.log)}
|
||||
<button
|
||||
class="mark"
|
||||
class:done={mark.log < replay.current}
|
||||
class:current={mark.log === replay.current - 1}
|
||||
title={lines[mark.log]}
|
||||
onclick={() => store.replayToEntry(mark.log + 1)}
|
||||
></button>
|
||||
{/each}
|
||||
</div>
|
||||
<button
|
||||
class="nav"
|
||||
disabled={replay.current >= replay.end}
|
||||
onclick={() => store.replayToEntry(replay.end)}
|
||||
title="Live">⏭</button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.replaybar {
|
||||
background: linear-gradient(160deg, #1e2430, #161b25);
|
||||
border: 1px solid #4f7ba8;
|
||||
border-radius: var(--radius);
|
||||
padding: 10px 14px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
.badge {
|
||||
background: #4f7ba8;
|
||||
color: #fff;
|
||||
font-size: 10px;
|
||||
font-weight: 800;
|
||||
letter-spacing: 1px;
|
||||
padding: 2px 7px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.pos {
|
||||
color: var(--text-dim);
|
||||
font-size: 12px;
|
||||
}
|
||||
.track {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.nav {
|
||||
padding: 2px 8px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.marks {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
gap: 3px;
|
||||
align-items: center;
|
||||
overflow-x: auto;
|
||||
padding: 4px 0;
|
||||
}
|
||||
.mark {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
min-width: 10px;
|
||||
border-radius: 50%;
|
||||
border: 1px solid #3d5a78;
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
}
|
||||
.mark.done {
|
||||
background: #4f7ba8;
|
||||
}
|
||||
.mark.current {
|
||||
border-color: var(--gold);
|
||||
background: var(--gold);
|
||||
box-shadow: 0 0 6px var(--gold-soft);
|
||||
}
|
||||
</style>
|
||||
99
packages/viewer/src/lib/bgs.svelte.ts
Normal file
99
packages/viewer/src/lib/bgs.svelte.ts
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
import type { GameState, Move } from "outpost-engine";
|
||||
import { Emitter } from "./emitter";
|
||||
|
||||
// Uplink payloads can be Svelte $state proxies (e.g. the logLines array). The
|
||||
// BGS shim re-posts whatever we emit straight to the parent via postMessage,
|
||||
// whose structured clone throws "Proxy object could not be cloned" on proxies.
|
||||
// Deep-unwrap at the emit boundary so nothing downstream ever sees a proxy.
|
||||
function declone<T>(value: T): T {
|
||||
try {
|
||||
return $state.snapshot(value) as T;
|
||||
} catch {
|
||||
try {
|
||||
return value === undefined ? value : (JSON.parse(JSON.stringify(value)) as T);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export interface ViewerEvents {
|
||||
state: GameState;
|
||||
"state:updated": void;
|
||||
gamelog: { start: number; end?: number; data: unknown };
|
||||
player: { index?: number };
|
||||
avatars: string[];
|
||||
preferences: Record<string, unknown>;
|
||||
theme: { dark: boolean };
|
||||
"replay:start": void;
|
||||
"replay:to": number;
|
||||
"replay:end": void;
|
||||
}
|
||||
|
||||
export interface UplinkEvents {
|
||||
ready: void;
|
||||
// The shim relays the emitted payload verbatim as the gameMove's `move` field,
|
||||
// so it must be the move object itself — not wrapped in { move } (that would
|
||||
// double-wrap it and the engine would read move.action === undefined).
|
||||
move: Move;
|
||||
fetchState: void;
|
||||
fetchLog: { start: number; end?: number };
|
||||
addLog: string[];
|
||||
replaceLog: string[];
|
||||
"player:clicked": { index: number };
|
||||
"update:preference": { name: string; value: string | boolean | null };
|
||||
"replay:info": { start: number; current: number; end: number };
|
||||
}
|
||||
|
||||
// The BGS iframe shim (resources/game/<game>/<v>/iframe) owns the postMessage
|
||||
// protocol: it re-emits controller messages on the emitter returned by launch()
|
||||
// (downlink) and re-posts our emitted uplink events to the parent. The dev
|
||||
// harness drives the same emitter directly. So this bridge is just the typed
|
||||
// emitter surface — no window/postMessage code of our own.
|
||||
export class ViewerBridge {
|
||||
readonly events = new Emitter();
|
||||
|
||||
on<K extends keyof ViewerEvents>(event: K, listener: (payload: ViewerEvents[K]) => void): () => void {
|
||||
return this.events.on(event, listener);
|
||||
}
|
||||
|
||||
private emitUplink<K extends keyof UplinkEvents>(event: K, payload?: UplinkEvents[K]): void {
|
||||
this.events.emit(event, declone(payload));
|
||||
}
|
||||
|
||||
sendMove(move: Move): void {
|
||||
this.emitUplink("move", move);
|
||||
}
|
||||
|
||||
ready(): void {
|
||||
this.emitUplink("ready");
|
||||
}
|
||||
|
||||
replaceLog(lines: string[]): void {
|
||||
this.emitUplink("replaceLog", lines);
|
||||
}
|
||||
|
||||
fetchState(): void {
|
||||
this.emitUplink("fetchState");
|
||||
}
|
||||
|
||||
replayInfo(info: { start: number; current: number; end: number }): void {
|
||||
this.emitUplink("replay:info", info);
|
||||
}
|
||||
|
||||
playerClicked(index: number): void {
|
||||
this.emitUplink("player:clicked", { index });
|
||||
}
|
||||
|
||||
updatePreference(name: string, value: string | boolean | null): void {
|
||||
this.emitUplink("update:preference", { name, value });
|
||||
}
|
||||
|
||||
fetchLog(start: number, end?: number): void {
|
||||
this.emitUplink("fetchLog", { start, end });
|
||||
}
|
||||
}
|
||||
|
||||
export function launchBridge(): ViewerBridge {
|
||||
return new ViewerBridge();
|
||||
}
|
||||
34
packages/viewer/src/lib/emitter.ts
Normal file
34
packages/viewer/src/lib/emitter.ts
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
export type Listener<T = unknown> = (payload: T) => void;
|
||||
|
||||
export class Emitter {
|
||||
private listeners = new Map<string, Set<Listener>>();
|
||||
|
||||
on<T = unknown>(event: string, listener: Listener<T>): () => void {
|
||||
let set = this.listeners.get(event);
|
||||
if (!set) {
|
||||
set = new Set();
|
||||
this.listeners.set(event, set);
|
||||
}
|
||||
const wrapped = listener as Listener;
|
||||
set.add(wrapped);
|
||||
return () => set.delete(wrapped);
|
||||
}
|
||||
|
||||
once<T = unknown>(event: string, listener: Listener<T>): () => void {
|
||||
const off = this.on<T>(event, (payload) => {
|
||||
off();
|
||||
listener(payload);
|
||||
});
|
||||
return off;
|
||||
}
|
||||
|
||||
emit<T = unknown>(event: string, payload?: T): void {
|
||||
for (const listener of this.listeners.get(event) ?? []) {
|
||||
try {
|
||||
listener(payload);
|
||||
} catch (error) {
|
||||
console.error(`[outpost-viewer] listener for "${event}" failed`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
559
packages/viewer/src/lib/store.svelte.ts
Normal file
559
packages/viewer/src/lib/store.svelte.ts
Normal file
|
|
@ -0,0 +1,559 @@
|
|||
import {
|
||||
FACTORIES,
|
||||
UPGRADE_SPECS,
|
||||
applyMove,
|
||||
canBuyFactory,
|
||||
countingHandSize,
|
||||
describeLog,
|
||||
describeLogEntry,
|
||||
handCapacity,
|
||||
handValue,
|
||||
populationCost,
|
||||
populationMax,
|
||||
rankings,
|
||||
replay as replayEngine,
|
||||
robotMax,
|
||||
scores,
|
||||
upgradeDiscount,
|
||||
victoryPoints,
|
||||
type FactoryType,
|
||||
type GameState,
|
||||
type Move,
|
||||
type PlayerState,
|
||||
type Upgrade,
|
||||
} from "outpost-engine";
|
||||
import type { ViewerBridge } from "./bgs.svelte";
|
||||
|
||||
export interface ReplayState {
|
||||
active: boolean;
|
||||
current: number;
|
||||
end: number;
|
||||
state: GameState | null;
|
||||
}
|
||||
|
||||
export type PendingKind =
|
||||
| { kind: "factory"; factory: FactoryType; cost: number }
|
||||
| { kind: "population"; count: number; cost: number }
|
||||
| { kind: "robots"; count: number; cost: number }
|
||||
| { kind: "payAuction"; cost: number };
|
||||
|
||||
export const PLAYER_COLORS = [
|
||||
"#4f8ef7",
|
||||
"#f0716a",
|
||||
"#57c17b",
|
||||
"#f2b84b",
|
||||
"#b07fe8",
|
||||
"#4fd1c5",
|
||||
"#f28ec0",
|
||||
"#a3d65c",
|
||||
"#f79a4f",
|
||||
"#8b94f7",
|
||||
] as const;
|
||||
|
||||
export function playerColor(index: number): string {
|
||||
return PLAYER_COLORS[index % PLAYER_COLORS.length] as string;
|
||||
}
|
||||
|
||||
export const RESOURCE_LABELS: Record<string, string> = {
|
||||
ore: "Ore",
|
||||
water: "Water",
|
||||
titanium: "Titanium",
|
||||
research: "Research",
|
||||
microbiotics: "Microbiotics",
|
||||
newChemicals: "New Chemicals",
|
||||
orbitalMedicine: "Orbital Medicine",
|
||||
ringOre: "Ring Ore",
|
||||
moonOre: "Moon Ore",
|
||||
};
|
||||
|
||||
export const UPGRADE_EFFECTS: Record<Upgrade, string> = {
|
||||
dataLibrary: "−10 on Scientists and Laboratory bids (per copy).",
|
||||
warehouse: "+3 hand capacity (per copy).",
|
||||
heavyEquipment: "Allows titanium factories. −5 on Warehouse/Nodule, −15 on Outpost (per copy).",
|
||||
nodule: "+3 population limit (per copy).",
|
||||
scientists: "Produces a Research card each round (per copy).",
|
||||
orbitalLab: "Produces a Microbiotics card each round (per copy).",
|
||||
robots: "Allows buying robots — operators that ignore the population limit (per copy: up to population).",
|
||||
laboratory: "Allows research factories; comes with a free research factory.",
|
||||
ecoplants: "Colonists cost 5 instead of 10. −10 on Outpost bids (per copy).",
|
||||
outpost: "Free titanium factory, +5 hand capacity, +5 population limit.",
|
||||
spaceStation: "Produces an Orbital Medicine card each round.",
|
||||
planetaryCruiser: "Produces a Ring Ore card each round.",
|
||||
moonBase: "Produces a Moon Ore card each round.",
|
||||
};
|
||||
|
||||
export class ViewerStore {
|
||||
liveState = $state<GameState | null>(null);
|
||||
replay = $state<ReplayState>({ active: false, current: 0, end: 0, state: null });
|
||||
playerIndex = $state<number | undefined>(undefined);
|
||||
avatars = $state<string[]>([]);
|
||||
preferences = $state<Record<string, unknown>>({});
|
||||
logLines = $state<string[]>([]);
|
||||
seenLog = $state(0);
|
||||
lastMoveAt = $state<number>(0);
|
||||
|
||||
cardPick = $state<number[]>([]);
|
||||
pending = $state<PendingKind | null>(null);
|
||||
auctionPick = $state<{ marketIndex: number; bid: number } | null>(null);
|
||||
bidAmount = $state(0);
|
||||
manning = $state(false);
|
||||
manningPick = $state<number[]>([]);
|
||||
|
||||
constructor(private bridge: ViewerBridge) {
|
||||
bridge.on("state", (state) => this.setState(state));
|
||||
bridge.on("player", ({ index }) => {
|
||||
this.playerIndex = typeof index === "number" && index >= 0 ? index : undefined;
|
||||
});
|
||||
bridge.on("avatars", (list) => (this.avatars = list ?? []));
|
||||
bridge.on("preferences", (prefs) => (this.preferences = prefs ?? {}));
|
||||
bridge.on("state:updated", () => bridge.fetchState());
|
||||
bridge.on("gamelog", (payload) => this.onGamelog(payload));
|
||||
bridge.on("replay:start", () => this.startReplay());
|
||||
bridge.on("replay:to", (to) => this.replayTo(to));
|
||||
bridge.on("replay:end", () => this.endReplay());
|
||||
}
|
||||
|
||||
get state(): GameState | null {
|
||||
return this.replay.active ? this.replay.state : this.liveState;
|
||||
}
|
||||
|
||||
private setState(state: GameState): void {
|
||||
this.liveState = state;
|
||||
this.seenLog = state.log.length;
|
||||
this.logLines = describeLog(state);
|
||||
if (!this.replay.active) {
|
||||
this.cancel();
|
||||
this.lastMoveAt = Date.now();
|
||||
}
|
||||
this.bridge.replaceLog(this.logLines);
|
||||
}
|
||||
|
||||
private onGamelog(payload: { start: number; end?: number; data: unknown }): void {
|
||||
const data = payload?.data as { log?: unknown[] } | undefined;
|
||||
const entries = Array.isArray(data?.log) ? (data.log as GameState["log"]) : [];
|
||||
const base = this.liveState;
|
||||
if (!base || entries.length === 0) {
|
||||
this.bridge.fetchState();
|
||||
return;
|
||||
}
|
||||
if (payload.start >= this.logLines.length) {
|
||||
const appended = entries.map((entry) => describeLogEntry(base, entry));
|
||||
this.logLines = [...this.logLines, ...appended];
|
||||
this.seenLog = base.log.length;
|
||||
this.bridge.replaceLog(this.logLines);
|
||||
} else {
|
||||
this.bridge.fetchState();
|
||||
}
|
||||
}
|
||||
|
||||
private startReplay(): void {
|
||||
const live = this.liveState;
|
||||
if (!live) {
|
||||
return;
|
||||
}
|
||||
this.replay = { active: true, current: 1, end: live.log.length, state: replayEngine(live, { to: 1 }) };
|
||||
this.bridge.replayInfo({ start: 1, current: 1, end: live.log.length });
|
||||
}
|
||||
|
||||
private replayTo(to: number): void {
|
||||
const live = this.liveState;
|
||||
if (!live || !this.replay.active) {
|
||||
return;
|
||||
}
|
||||
const clamped = Math.max(1, Math.min(to, live.log.length));
|
||||
this.replay = { ...this.replay, current: clamped, state: replayEngine(live, { to: clamped }) };
|
||||
this.bridge.replayInfo({ start: 1, current: clamped, end: this.replay.end });
|
||||
}
|
||||
|
||||
replayToEntry(to: number): void {
|
||||
this.replayTo(to);
|
||||
}
|
||||
|
||||
private endReplay(): void {
|
||||
this.replay = { active: false, current: 0, end: 0, state: null };
|
||||
}
|
||||
|
||||
get me(): PlayerState | null {
|
||||
const s = this.liveState;
|
||||
return s && this.playerIndex !== undefined ? (s.players[this.playerIndex] ?? null) : null;
|
||||
}
|
||||
|
||||
get spectator(): boolean {
|
||||
return this.playerIndex === undefined;
|
||||
}
|
||||
|
||||
get iMustDiscard(): boolean {
|
||||
const s = this.liveState;
|
||||
return !!s && !s.ended && s.phase === "discard" && !this.replay.active && (this.me?.mustDiscard ?? false);
|
||||
}
|
||||
|
||||
get myActionTurn(): boolean {
|
||||
const s = this.liveState;
|
||||
return (
|
||||
!!s &&
|
||||
!s.ended &&
|
||||
s.phase === "actions" &&
|
||||
!this.replay.active &&
|
||||
this.playerIndex !== undefined &&
|
||||
s.activeSeat === this.playerIndex &&
|
||||
!(this.me?.done ?? true)
|
||||
);
|
||||
}
|
||||
|
||||
get myBidTurn(): boolean {
|
||||
const s = this.liveState;
|
||||
return (
|
||||
!!s && !s.ended && s.phase === "auction" && !this.replay.active && s.auction?.activeBidder === this.playerIndex
|
||||
);
|
||||
}
|
||||
|
||||
get myPayment(): boolean {
|
||||
const s = this.liveState;
|
||||
return (
|
||||
!!s &&
|
||||
!s.ended &&
|
||||
s.phase === "auctionPayment" &&
|
||||
!this.replay.active &&
|
||||
s.auction?.highBidder === this.playerIndex
|
||||
);
|
||||
}
|
||||
|
||||
get interactive(): boolean {
|
||||
return this.iMustDiscard || this.myActionTurn || this.myBidTurn || this.myPayment;
|
||||
}
|
||||
|
||||
get discardExcess(): number {
|
||||
const me = this.me;
|
||||
return me ? Math.max(0, countingHandSize(me) - handCapacity(me)) : 0;
|
||||
}
|
||||
|
||||
get popCost(): number {
|
||||
const me = this.me;
|
||||
return me ? populationCost(me) : 0;
|
||||
}
|
||||
|
||||
get maxBid(): number {
|
||||
const me = this.me;
|
||||
const auction = this.liveState?.auction;
|
||||
if (!me || !auction) {
|
||||
return 0;
|
||||
}
|
||||
return handValue(me) + upgradeDiscount(me, auction.upgrade);
|
||||
}
|
||||
|
||||
get finalRankings(): number[] {
|
||||
const s = this.liveState;
|
||||
return s && s.ended ? rankings(s) : [];
|
||||
}
|
||||
|
||||
get finalScores(): number[] {
|
||||
const s = this.liveState;
|
||||
return s ? scores(s) : [];
|
||||
}
|
||||
|
||||
get myHandValue(): number {
|
||||
const me = this.me;
|
||||
return me ? handValue(me) : 0;
|
||||
}
|
||||
|
||||
vpOf(index: number): number {
|
||||
const p = this.state?.players[index];
|
||||
return p ? victoryPoints(p) : 0;
|
||||
}
|
||||
|
||||
handCapOf(index: number): number {
|
||||
const p = this.state?.players[index];
|
||||
return p ? handCapacity(p) : 0;
|
||||
}
|
||||
|
||||
countingOf(index: number): number {
|
||||
const p = this.state?.players[index];
|
||||
return p ? countingHandSize(p) : 0;
|
||||
}
|
||||
|
||||
popMaxOf(index: number): number {
|
||||
const p = this.state?.players[index];
|
||||
return p ? populationMax(p) : 0;
|
||||
}
|
||||
|
||||
robotMaxOf(index: number): number {
|
||||
const p = this.state?.players[index];
|
||||
return p ? robotMax(p) : 0;
|
||||
}
|
||||
|
||||
discountOf(index: number, upgrade: Upgrade): number {
|
||||
const p = this.state?.players[index];
|
||||
return p ? upgradeDiscount(p, upgrade) : 0;
|
||||
}
|
||||
|
||||
auctionDue(): number {
|
||||
const me = this.me;
|
||||
const auction = this.liveState?.auction;
|
||||
if (!me || !auction) {
|
||||
return 0;
|
||||
}
|
||||
return Math.max(0, auction.highBid - upgradeDiscount(me, auction.upgrade));
|
||||
}
|
||||
|
||||
pickTotal(): number {
|
||||
const me = this.me;
|
||||
if (!me) {
|
||||
return 0;
|
||||
}
|
||||
return this.cardPick.reduce((sum, i) => sum + (me.hand[i]?.v ?? 0), 0);
|
||||
}
|
||||
|
||||
canBuy(type: FactoryType): boolean {
|
||||
const me = this.me;
|
||||
return !!me && canBuyFactory(me, type);
|
||||
}
|
||||
|
||||
canAffordFactory(type: FactoryType): boolean {
|
||||
const me = this.me;
|
||||
return !!me && this.canBuy(type) && this.myHandValue >= FACTORIES[type].cost;
|
||||
}
|
||||
|
||||
toggleCard(index: number): void {
|
||||
if (!this.interactive) {
|
||||
return;
|
||||
}
|
||||
this.cardPick = this.cardPick.includes(index)
|
||||
? this.cardPick.filter((i) => i !== index)
|
||||
: [...this.cardPick, index];
|
||||
}
|
||||
|
||||
openAuction(marketIndex: number): void {
|
||||
const s = this.liveState;
|
||||
const upgrade = s?.market[marketIndex];
|
||||
if (!this.myActionTurn || upgrade === undefined) {
|
||||
return;
|
||||
}
|
||||
this.cancel();
|
||||
this.auctionPick = { marketIndex, bid: UPGRADE_SPECS[upgrade].price };
|
||||
}
|
||||
|
||||
bumpAuctionBid(delta: number): void {
|
||||
const pick = this.auctionPick;
|
||||
const s = this.liveState;
|
||||
if (!pick || !s) {
|
||||
return;
|
||||
}
|
||||
const min = UPGRADE_SPECS[s.market[pick.marketIndex] as Upgrade].price;
|
||||
this.auctionPick = { ...pick, bid: Math.max(min, pick.bid + delta) };
|
||||
}
|
||||
|
||||
setAuctionBid(value: number): void {
|
||||
const pick = this.auctionPick;
|
||||
const s = this.liveState;
|
||||
if (!pick || !s || !Number.isFinite(value)) {
|
||||
return;
|
||||
}
|
||||
const min = UPGRADE_SPECS[s.market[pick.marketIndex] as Upgrade].price;
|
||||
this.auctionPick = { ...pick, bid: Math.max(min, Math.floor(value)) };
|
||||
}
|
||||
|
||||
confirmAuction(): void {
|
||||
const pick = this.auctionPick;
|
||||
if (!pick) {
|
||||
return;
|
||||
}
|
||||
this.send({ action: "auction", marketIndex: pick.marketIndex, bid: pick.bid });
|
||||
}
|
||||
|
||||
prepareBid(): void {
|
||||
const s = this.liveState;
|
||||
if (s?.auction) {
|
||||
this.bidAmount = s.auction.highBid + 1;
|
||||
}
|
||||
}
|
||||
|
||||
confirmBid(): void {
|
||||
const s = this.liveState;
|
||||
if (!s?.auction || !this.myBidTurn) {
|
||||
return;
|
||||
}
|
||||
const amount = Math.floor(this.bidAmount);
|
||||
if (!Number.isInteger(amount) || amount <= s.auction.highBid || amount > this.maxBid) {
|
||||
return;
|
||||
}
|
||||
this.send({ action: "bid", amount });
|
||||
}
|
||||
|
||||
passBid(): void {
|
||||
if (this.myBidTurn) {
|
||||
this.send({ action: "bidPass" });
|
||||
}
|
||||
}
|
||||
|
||||
startFactoryPayment(factory: FactoryType): void {
|
||||
const me = this.me;
|
||||
if (!this.myActionTurn || !me || !this.canBuy(factory)) {
|
||||
return;
|
||||
}
|
||||
this.cancel();
|
||||
this.pending = { kind: "factory", factory, cost: FACTORIES[factory].cost };
|
||||
}
|
||||
|
||||
startPopulationPayment(): void {
|
||||
const me = this.me;
|
||||
if (!this.myActionTurn || !me) {
|
||||
return;
|
||||
}
|
||||
const cost = populationCost(me);
|
||||
if (me.population >= populationMax(me) || this.myHandValue < cost) {
|
||||
return;
|
||||
}
|
||||
this.cancel();
|
||||
this.pending = { kind: "population", count: 1, cost };
|
||||
}
|
||||
|
||||
startRobotsPayment(): void {
|
||||
const me = this.me;
|
||||
if (!this.myActionTurn || !me) {
|
||||
return;
|
||||
}
|
||||
if (me.upgrades.robots === 0 || me.robots >= robotMax(me) || this.myHandValue < 10) {
|
||||
return;
|
||||
}
|
||||
this.cancel();
|
||||
this.pending = { kind: "robots", count: 1, cost: 10 };
|
||||
}
|
||||
|
||||
bumpPendingCount(delta: number): void {
|
||||
const me = this.me;
|
||||
const pending = this.pending;
|
||||
if (!me || !pending || pending.kind === "factory" || pending.kind === "payAuction") {
|
||||
return;
|
||||
}
|
||||
const unit = pending.kind === "population" ? populationCost(me) : 10;
|
||||
const cap = pending.kind === "population" ? populationMax(me) - me.population : robotMax(me) - me.robots;
|
||||
const affordable = Math.max(1, Math.floor(this.myHandValue / unit));
|
||||
const max = Math.max(1, Math.min(cap, affordable));
|
||||
const count = Math.min(max, Math.max(1, pending.count + delta));
|
||||
this.pending = { ...pending, count, cost: count * unit };
|
||||
}
|
||||
|
||||
startAuctionPayment(): void {
|
||||
if (!this.myPayment) {
|
||||
return;
|
||||
}
|
||||
this.cancel();
|
||||
this.pending = { kind: "payAuction", cost: this.auctionDue() };
|
||||
}
|
||||
|
||||
pendingValid(): boolean {
|
||||
const me = this.me;
|
||||
const pending = this.pending;
|
||||
if (!me || !pending) {
|
||||
return false;
|
||||
}
|
||||
if (this.pickTotal() < pending.cost) {
|
||||
return false;
|
||||
}
|
||||
if (pending.kind === "factory" && FACTORIES[pending.factory].needsResearchCard) {
|
||||
return this.cardPick.some((i) => me.hand[i]?.t === "research");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
confirmPending(): void {
|
||||
const pending = this.pending;
|
||||
if (!pending || !this.pendingValid()) {
|
||||
return;
|
||||
}
|
||||
const cards = this.cardPick;
|
||||
switch (pending.kind) {
|
||||
case "factory":
|
||||
this.send({ action: "buyFactory", factory: pending.factory, cards });
|
||||
break;
|
||||
case "population":
|
||||
this.send({ action: "buyPopulation", count: pending.count, cards });
|
||||
break;
|
||||
case "robots":
|
||||
this.send({ action: "buyRobots", count: pending.count, cards });
|
||||
break;
|
||||
case "payAuction":
|
||||
this.send({ action: "pay", cards });
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
confirmDiscard(): void {
|
||||
const me = this.me;
|
||||
if (!this.iMustDiscard || !me || this.cardPick.length === 0) {
|
||||
return;
|
||||
}
|
||||
const remaining = me.hand.filter((_, i) => !this.cardPick.includes(i));
|
||||
const counting = remaining.filter((c) => c.t !== "research" && c.t !== "microbiotics").length;
|
||||
if (counting > handCapacity(me)) {
|
||||
return;
|
||||
}
|
||||
this.send({ action: "discard", cards: this.cardPick });
|
||||
}
|
||||
|
||||
startManning(): void {
|
||||
const me = this.me;
|
||||
if (!this.myActionTurn || !me) {
|
||||
return;
|
||||
}
|
||||
this.cancel();
|
||||
this.manning = true;
|
||||
this.manningPick = me.factories.flatMap((f, i) => (f.manned ? [i] : [])).slice(0, me.population + me.robots);
|
||||
}
|
||||
|
||||
toggleManning(index: number): void {
|
||||
const me = this.me;
|
||||
if (!this.manning || !me) {
|
||||
return;
|
||||
}
|
||||
const limit = me.population + me.robots;
|
||||
if (this.manningPick.includes(index)) {
|
||||
this.manningPick = this.manningPick.filter((i) => i !== index);
|
||||
} else if (this.manningPick.length < limit) {
|
||||
this.manningPick = [...this.manningPick, index];
|
||||
}
|
||||
}
|
||||
|
||||
confirmEndTurn(): void {
|
||||
if (!this.manning) {
|
||||
return;
|
||||
}
|
||||
this.send({ action: "endTurn", manned: this.manningPick });
|
||||
}
|
||||
|
||||
cancel(): void {
|
||||
this.cardPick = [];
|
||||
this.pending = null;
|
||||
this.auctionPick = null;
|
||||
this.manning = false;
|
||||
this.manningPick = [];
|
||||
}
|
||||
|
||||
private send(move: Move): void {
|
||||
this.bridge.sendMove(move);
|
||||
this.cancel();
|
||||
this.applyOptimistic(move);
|
||||
}
|
||||
|
||||
// Apply my own move to the local (stripped) state right away so the UI feels
|
||||
// instant; the authoritative state from the server reconciles on arrival.
|
||||
// Only attempted with a move that's legal against my view — any failure just
|
||||
// skips the optimistic step (the server state will correct it).
|
||||
private applyOptimistic(move: Move): void {
|
||||
const s = this.liveState;
|
||||
if (!s || this.playerIndex === undefined || this.replay.active) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const clone = JSON.parse(JSON.stringify(s)) as GameState;
|
||||
applyMove(clone, move, this.playerIndex);
|
||||
this.setState(clone);
|
||||
} catch {
|
||||
// not applicable against the stripped view — wait for the server state
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function createStore(bridge: ViewerBridge): ViewerStore {
|
||||
return new ViewerStore(bridge);
|
||||
}
|
||||
177
packages/viewer/src/lib/theme.css
Normal file
177
packages/viewer/src/lib/theme.css
Normal file
|
|
@ -0,0 +1,177 @@
|
|||
:root {
|
||||
/* Light theme is the default (the BGS wrapper only adds a `dark` class on
|
||||
<html> for dark mode; no class means light). */
|
||||
--bg: #e9ebe4;
|
||||
--bg-panel: #f5f6f0;
|
||||
--bg-elevated: #ffffff;
|
||||
--line: #c9cec0;
|
||||
--text: #23271f;
|
||||
--text-dim: #68705f;
|
||||
--gold: #2f7fa8;
|
||||
--gold-soft: rgba(47, 127, 168, 0.4);
|
||||
--danger: #c24a3f;
|
||||
/* End-game banner: a mission-accomplished panel, sky-toned on light. */
|
||||
--banner-bg: linear-gradient(160deg, #dceef6, #c3dfeb 65%, #a9d0e0);
|
||||
/* Decorative "star chart" background: cool space glows over a light base. */
|
||||
--bg-decor:
|
||||
radial-gradient(55vmax 55vmax at -8% -8%, rgba(47, 127, 168, 0.24), transparent 62%),
|
||||
radial-gradient(50vmax 50vmax at 108% -4%, rgba(90, 141, 197, 0.22), transparent 62%),
|
||||
radial-gradient(48vmax 48vmax at -4% 108%, rgba(200, 149, 42, 0.18), transparent 62%),
|
||||
radial-gradient(52vmax 52vmax at 108% 108%, rgba(127, 111, 209, 0.2), transparent 62%), var(--bg);
|
||||
/* Resource colors (sci-fi tinted, one per production type). */
|
||||
--ore: #94a0ac;
|
||||
--water: #3f8fd2;
|
||||
--titanium: #c8952a;
|
||||
--research: #7a63d2;
|
||||
--microbiotics: #4aa84f;
|
||||
--newChemicals: #d26db0;
|
||||
--orbitalMedicine: #3fb8b2;
|
||||
--ringOre: #e07b39;
|
||||
--moonOre: #d9b13b;
|
||||
--radius: 10px;
|
||||
--card-w: 44px;
|
||||
--card-h: 60px;
|
||||
}
|
||||
|
||||
/* Dark theme: applied when the BGS wrapper sets <html class="dark">. */
|
||||
html.dark {
|
||||
--bg: #0e1016;
|
||||
--bg-panel: #181b23;
|
||||
--bg-elevated: #21252f;
|
||||
--line: #303642;
|
||||
--text: #e6e9e2;
|
||||
--text-dim: #8f9789;
|
||||
--gold: #58b6dc;
|
||||
--gold-soft: rgba(88, 182, 220, 0.35);
|
||||
--danger: #e0705f;
|
||||
--banner-bg: linear-gradient(160deg, #14222e, #0f1a24);
|
||||
--bg-decor:
|
||||
radial-gradient(120vmax 90vmax at 50% 40%, transparent 55%, rgba(0, 0, 0, 0.5) 100%),
|
||||
radial-gradient(60vmax 60vmax at -10% -10%, rgba(47, 127, 168, 0.2), transparent 60%),
|
||||
radial-gradient(55vmax 55vmax at 110% -5%, rgba(90, 141, 197, 0.16), transparent 60%),
|
||||
radial-gradient(50vmax 50vmax at -5% 110%, rgba(200, 149, 42, 0.14), transparent 60%),
|
||||
radial-gradient(55vmax 55vmax at 110% 110%, rgba(127, 111, 209, 0.16), transparent 60%), var(--bg);
|
||||
--ore: #a8b4c0;
|
||||
--water: #5aa5e0;
|
||||
--titanium: #d9a53a;
|
||||
--research: #9a86e8;
|
||||
--microbiotics: #5cbd62;
|
||||
--newChemicals: #e082c2;
|
||||
--orbitalMedicine: #55ccc6;
|
||||
--ringOre: #f08c48;
|
||||
--moonOre: #e8c550;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
/* `:root:root` and not plain `html` on purpose: the BGS iframe shell injects
|
||||
`<style>html.dark { background: #030712 }</style>` (anti-flash) after the
|
||||
viewer stylesheet, so at equal specificity it would win in dark mode and wipe
|
||||
out the decor. The doubled `:root` outranks `html.dark`. */
|
||||
:root:root {
|
||||
background: var(--bg-decor);
|
||||
background-attachment: fixed;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
color: var(--text);
|
||||
font-family: "Segoe UI", "Helvetica Neue", system-ui, sans-serif;
|
||||
font-size: 14px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
#app {
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
button {
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
border: 1px solid var(--line);
|
||||
background: var(--bg-elevated);
|
||||
color: var(--text);
|
||||
border-radius: 8px;
|
||||
padding: 6px 12px;
|
||||
transition:
|
||||
background 0.15s ease,
|
||||
border-color 0.15s ease;
|
||||
}
|
||||
|
||||
button:hover:not(:disabled) {
|
||||
border-color: var(--gold);
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
input[type="number"] {
|
||||
font: inherit;
|
||||
color: var(--text);
|
||||
background: var(--bg-elevated);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
padding: 5px 8px;
|
||||
width: 90px;
|
||||
}
|
||||
|
||||
input[type="number"]:focus {
|
||||
outline: none;
|
||||
border-color: var(--gold);
|
||||
}
|
||||
|
||||
.res-ore {
|
||||
--res: var(--ore);
|
||||
--res-text: #1a1c22;
|
||||
}
|
||||
.res-water {
|
||||
--res: var(--water);
|
||||
--res-text: #fff;
|
||||
}
|
||||
.res-titanium {
|
||||
--res: var(--titanium);
|
||||
--res-text: #1a1c22;
|
||||
}
|
||||
.res-research {
|
||||
--res: var(--research);
|
||||
--res-text: #fff;
|
||||
}
|
||||
.res-microbiotics {
|
||||
--res: var(--microbiotics);
|
||||
--res-text: #fff;
|
||||
}
|
||||
.res-newChemicals {
|
||||
--res: var(--newChemicals);
|
||||
--res-text: #fff;
|
||||
}
|
||||
.res-orbitalMedicine {
|
||||
--res: var(--orbitalMedicine);
|
||||
--res-text: #1a1c22;
|
||||
}
|
||||
.res-ringOre {
|
||||
--res: var(--ringOre);
|
||||
--res-text: #1a1c22;
|
||||
}
|
||||
.res-moonOre {
|
||||
--res: var(--moonOre);
|
||||
--res-text: #1a1c22;
|
||||
}
|
||||
|
||||
@keyframes glowPulse {
|
||||
0%,
|
||||
100% {
|
||||
box-shadow:
|
||||
0 0 0 2px var(--gold-soft),
|
||||
0 4px 10px rgba(0, 0, 0, 0.4);
|
||||
}
|
||||
50% {
|
||||
box-shadow:
|
||||
0 0 0 4px var(--gold),
|
||||
0 4px 14px var(--gold-soft);
|
||||
}
|
||||
}
|
||||
63
packages/viewer/src/viewer.ts
Normal file
63
packages/viewer/src/viewer.ts
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
import { mount } from "svelte";
|
||||
import App from "./App.svelte";
|
||||
import { launchBridge } from "./lib/bgs.svelte";
|
||||
import { createStore } from "./lib/store.svelte";
|
||||
import type { Emitter } from "./lib/emitter";
|
||||
import "./lib/theme.css";
|
||||
|
||||
// The BGS wrapper page sets <html class="dark"> for the initial paint, and the
|
||||
// shim re-emits { dark } on the launch emitter as "theme" whenever the site
|
||||
// theme changes. Light is the default (no `dark` class), so theme.css defines
|
||||
// light tokens on :root and overrides them under html.dark.
|
||||
function applyTheme(dark: boolean): void {
|
||||
document.documentElement.classList.toggle("dark", dark);
|
||||
}
|
||||
|
||||
export function launch(selector: string): Emitter {
|
||||
const target = document.querySelector(selector);
|
||||
if (!target) {
|
||||
throw new Error(`outpost-viewer: no element matches "${selector}"`);
|
||||
}
|
||||
|
||||
// Initial paint: the wrapper already set the class.
|
||||
applyTheme(document.documentElement.classList.contains("dark"));
|
||||
|
||||
const bridge = launchBridge();
|
||||
const store = createStore(bridge);
|
||||
|
||||
// Live theme changes via the emitter (shim re-emits the theme message).
|
||||
bridge.on("theme", ({ dark }) => applyTheme(dark));
|
||||
|
||||
mount(App, {
|
||||
target,
|
||||
props: {
|
||||
store,
|
||||
onPlayerClick: (index: number) => bridge.playerClicked(index),
|
||||
},
|
||||
});
|
||||
console.log("[outpost] viewer mounted");
|
||||
|
||||
// Emit ready only after the FIRST state has arrived and rendered — that's when
|
||||
// the game is actually shown. Emitting on mount (before state) makes the shim
|
||||
// post displayReady while the viewer still shows "Waiting for game state…",
|
||||
// and on a hard refresh that early displayReady can race ahead of the parent's
|
||||
// listener and get dropped, leaving the spinner up forever. A macrotask after
|
||||
// setState lets Svelte flush the DOM first (never rAF — hidden iframes skip it).
|
||||
let readySent = false;
|
||||
bridge.on("state", (s) => {
|
||||
console.log("[outpost] state received", { players: s?.players?.length, round: s?.round, readySent });
|
||||
if (readySent) {
|
||||
return;
|
||||
}
|
||||
readySent = true;
|
||||
setTimeout(() => {
|
||||
console.log("[outpost] emitting ready (after first state)");
|
||||
bridge.ready();
|
||||
}, 0);
|
||||
});
|
||||
return bridge.events as unknown as Emitter;
|
||||
}
|
||||
|
||||
if (typeof window !== "undefined") {
|
||||
(window as unknown as { outpost?: unknown }).outpost = { launch };
|
||||
}
|
||||
5
packages/viewer/svelte.config.js
Normal file
5
packages/viewer/svelte.config.js
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
import { vitePreprocess } from "@sveltejs/vite-plugin-svelte";
|
||||
|
||||
export default {
|
||||
preprocess: vitePreprocess(),
|
||||
};
|
||||
21
packages/viewer/tsconfig.json
Normal file
21
packages/viewer/tsconfig.json
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"strict": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"noImplicitOverride": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"types": ["vite/client"],
|
||||
"noEmit": true,
|
||||
"allowJs": true,
|
||||
"checkJs": false,
|
||||
"isolatedModules": true,
|
||||
"resolveJsonModule": true,
|
||||
"esModuleInterop": true
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.svelte", "src/**/*.svelte.ts", "vite.config.ts"]
|
||||
}
|
||||
31
packages/viewer/vite.config.ts
Normal file
31
packages/viewer/vite.config.ts
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
import { svelte } from "@sveltejs/vite-plugin-svelte";
|
||||
import { defineConfig } from "vite";
|
||||
|
||||
export default defineConfig(({ command }) => ({
|
||||
plugins: [svelte()],
|
||||
build: {
|
||||
outDir: "dist",
|
||||
emptyOutDir: true,
|
||||
cssCodeSplit: false,
|
||||
sourcemap: true,
|
||||
lib: {
|
||||
entry: "src/viewer.ts",
|
||||
name: "outpost",
|
||||
formats: ["iife"],
|
||||
fileName: () => "outpost-viewer.iife.js",
|
||||
},
|
||||
rollupOptions: {
|
||||
output: {
|
||||
assetFileNames: (asset) =>
|
||||
asset.names?.some((n) => n.endsWith(".css")) ? "outpost-viewer.css" : "[name]-[hash][extname]",
|
||||
},
|
||||
},
|
||||
},
|
||||
server: {
|
||||
port: 5173,
|
||||
strictPort: false,
|
||||
},
|
||||
define: {
|
||||
__DEV__: JSON.stringify(command === "serve"),
|
||||
},
|
||||
}));
|
||||
1199
pnpm-lock.yaml
generated
Normal file
1199
pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load diff
2
pnpm-workspace.yaml
Normal file
2
pnpm-workspace.yaml
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
packages:
|
||||
- "packages/*"
|
||||
14
tsconfig.base.json
Normal file
14
tsconfig.base.json
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"lib": ["ES2022"],
|
||||
"strict": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"noImplicitOverride": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue