Engine core: implement frozen DESIGN v1 (PR #17) and publish ENGINE_API.md

Interleaved reveal, alternating initiative, energy carry, onTopicBonus by cost,
consensus tie-break, hidden Portals with visible stats, laneCapacity 3, Portal
capacity/canPlay/atScoring/allOnTopic hooks, keywordsEnabled dispatch, §10.3
default Topic pool, global reveal seq. KEYWORDS/PORTALS left to engine-b.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 23:13:14 -05:00
co-authored by Claude Opus 5.5
parent f3b6097640
commit ec24437838
8 changed files with 641 additions and 248 deletions
+223
View File
@@ -0,0 +1,223 @@
# WikiDeck game engine API (v1)
**Owner:** engine-a (core and API) and engine-b (keywords, card derivation, tests). Issue: claude/wikideck#3.
**Rules:** `docs/game/DESIGN.md` v1 ("Edit War", as frozen in PR #17 @ cf2fceb). Where this file and DESIGN.md disagree, raise it on #3.
**Stability:** UI, simulation and modes build against this file. Any change to a name or shape below is
announced on #3 before it merges.
The engine is a pure TypeScript library in `shared/game/`:
- It does no I/O and has no clocks: no `Date.now()`, no `Math.random()`.
- It imports nothing from `server/` or `src/`.
- It runs entirely **off-chain**. A match never reads, moves, locks or burns an NFT.
- It is deterministic: the same `(ruleset, decks, seed, actions)` always gives the same state, byte for byte.
**Import only from `shared/game/index.ts`.**
```ts
import { createMatch, legalActions, applyAction, isOver, result, viewFor,
serialize, deserialize, replay, DEFAULT_RULESET, parseRuleset, validateDeck,
starterDeck, previewPool, type MatchState, type Action, type GameCard } from '../shared/game/index.ts';
```
## 1. Lifecycle
```ts
let state = createMatch(DEFAULT_RULESET, [deck0, deck1], seed); // turn 1, planning
while (!isOver(state)) {
// Each seat (in any order, any interleaving) queues plays, then commits.
const actions = legalActions(state, seat); // play / undo / commit
state = applyAction(state, chosen); // returns a NEW state
// When both seats have committed, the turn resolves inside applyAction.
}
const r = result(state); // { winner: 0 | 1 | null, reason, topicsLed, lanePower, totalPower, turns }
```
| Function | Description |
|---|---|
| `createMatch(ruleset, [deck0, deck1], seed: number \| string): MatchState` | Validates the ruleset (`parseRuleset`) and both decks (`validateDeck`), then performs DESIGN §4 setup and turn-1 start. A `seed` is a uint32. A string is hashed with FNV-1a (`seedFromString`). Throws `ZodError` for a bad ruleset and `IllegalActionError` for a bad deck. |
| `legalActions(state, seat): Action[]` | Lists every `play` (each card × each lane it can legally go into), every `undo`, and `commit`. Returns `[]` once the seat has committed or the match is over. It never lists `concede` (always legal while the match is running) or `timeout` (host only). |
| `applyAction(state, action): MatchState` | Pure: the input is never mutated. Throws `IllegalActionError` if the action is illegal. |
| `actionProblem(state, action): string \| null` | Explains why an action is illegal, without throwing. Use it for UI hints and for validating client input on a host. |
| `isOver(state)` / `result(state)` | `result` is `null` while the match is running. |
| `viewFor(state, seat): PlayerView` | The **hidden-information view**. Send only this to clients and AIs, never `MatchState`, because a `MatchState` contains both deck orders and the RNG state. |
| `serialize(state): string` / `deserialize(json): MatchState` | Lossless JSON. `MatchState` is plain data. |
| `replay(ruleset, decks, seed, actions): MatchState` | Rebuilds a match from its inputs. `state.actions` records every action applied, so a host can store `(ruleset, decks, seed, actions)` and verify a result later. |
| `validateDeck(ruleset, cards): string[]` | Returns the list of problems; empty means the deck is legal. |
| `cardPower(state, cardInPlay)`, `lanePower(state, lane)`, `laneLeader(state, lane)`, `topicsLed(state)` | Power queries (DESIGN §6). `laneLeader` and `topicsLed` apply the consensus tie-break. |
| `scoringPower(state, lane)` | Lane power plus revealed "at scoring" Portals (§7). `result().lanePower` uses this. |
| `laneCapacity(state, lane)` | Per-seat capacity of a lane. A Portal such as Stub may override it. |
| `isOnTopic(state, cardInPlay)` | §1.4/§6 on-topic test, including Disambiguation. |
| `starterDeck(seed): GameCard[]` | A 12-card loaner deck (DESIGN §2). **Placeholder** cards until starter-cards.json lands. |
| `previewPool(): GameCard[]` | Every loaner card once. For draft modes. |
| `placeCard(state, seat, lane, card)`, `revealPortal(state, lane)` | Test helpers for building boards by hand. |
## 2. Actions
```ts
type Action =
| { type: 'play'; player: 0 | 1; cardId: string; lane: number } // queue a card from hand (hidden)
| { type: 'undo'; player: 0 | 1; cardId: string } // un-queue it (refunds energy)
| { type: 'commit'; player: 0 | 1 } // lock in this turn (empty = pass)
| { type: 'timeout'; player: 0 | 1 } // HOST ONLY: turn timer expired
| { type: 'concede'; player: 0 | 1 };
```
**Queuing a play**
- `play` reserves the card's cost from this turn's energy. It checks the energy, the lane's room (cards already in the lane plus queued plays must stay under `laneCapacity(state, lane)`), and, once the Portal is revealed, whether it accepts the card (`canPlay`).
- Your plays reveal in **your queue order**, interleaved with the opponent's (see below).
- `undo` and new plays are allowed until the seat sends `commit`.
**Resolving a turn**
- When both seats have committed, `applyAction` resolves the turn (DESIGN §5.4–5.5):
1. Carry is set: min(`energyCarryMax`, energy not reserved by queued plays). Energy spent on a play that later fizzles is still spent.
2. **Interleaved reveal:** the initiative seat's 1st play, then the other seat's 1st, then the initiative seat's 2nd, and so on. When one seat runs out, the other's remaining plays reveal in order. Each card gets the next global `seq` number, and its on-reveal effects (keyword, then Portal) run at once.
3. End-of-turn effects run: the initiative seat's cards first, then lanes left→right, then `seq` order.
4. On the last turn, scoring follows (§7). Otherwise the next turn starts:
- initiative **alternates**
- any Portal scheduled by `portalReveal` is revealed
- energy = `energyByTurn[t-1]` + carry + `bonusEnergy`
- each seat draws
- the underdog bonus applies (only if `underdog` is on)
- **A play that is illegal at reveal** (the lane filled up, or a Portal rejects the card) fizzles. The card stays in hand and its energy is lost. A `fizzle` log event records it.
**Timeouts.** `timeout` is how a host enforces `turnSeconds`. It commits whatever is queued. A timeout with an empty queue counts toward `afkTurns`. When that count is reached, the seat concedes and the result has `reason: 'afk'`. An ordinary `commit` resets the count.
**Seat ownership.** The engine does not authenticate anyone. The host must check that the seat in `action.player` is the caller's.
## 3. Cards
```ts
interface GameCard {
cardId: string; // unique within a deck: the NFT card hash, or `loaner:<pageId>:<n>`
pageId: number; // at most ruleset.maxCopiesPerPage cards share a pageId
title: string;
faction: 'Space' | 'Nature' | 'People' | 'Science' | 'History' | 'Culture';
rarity: 'Common' | 'Rare' | 'Epic' | 'Legendary'; // cosmetic in v1
cost: number; // 0–6 (uncheckedCostCap already applied by derivation)
power: number; // 0–30, base power
home: 'attention' | 'depth' | 'reach';
trend: -1 | 0 | 1; // frozen at match start
keyword: string | null; // an id in KEYWORDS
source: 'owned' | 'loaner';
check?: 'verified' | 'unverified' | 'unchecked' | 'loaner'; // host plausibility result (§1.10), for logs
}
```
- **The engine takes already-derived cards and never reads raw stats.** The council asked for this, because snapshot stats are self-reported (#1, critic brief A.1).
- Derivation (DESIGN §1 and §10.1: percentile → fame → cost → power, home, trend, keyword and vanillaBonus) lives in `shared/game/derive.ts`, which engine-b owns. Hosts run it on host-frozen, plausibility-checked inputs before calling `createMatch`.
- Modes may adjust `GameCard` fields such as `power` before `createMatch`. The engine does not re-derive them.
- A keyword that isn't in `ruleset.keywordsEnabled` never runs. Derivation is responsible for not giving that card `vanillaBonus`.
- Lane power = `power` + `bonus` + `trend` + `onTopicBonus[cost]` if on-topic + ongoing keyword and Portal effects, floored at 0.
## 4. Ruleset
`Ruleset` holds the DESIGN §9 keys, **flat** (nothing deeper than one level, apart from `topicPool` entries and the param tables).
- `parseRuleset(unknown)` is a **strict** zod parse: unknown keys are rejected and every number is bounded, so any ruleset that passes terminates within `turns` turns.
- Modes merge overrides onto `DEFAULT_RULESET` and then call `parseRuleset`.
Notes on the §9 keys:
- `topicPool` is inline `TopicDef[] = { id, name, stat, portal: PortalId | null }[]`. `DEFAULT_TOPIC_POOL` is the 9 Topics of §10.3. A Portal id is one of `PORTAL_IDS` (`main-page, trending, featured-article, stub, interwiki, disambiguation`).
- `keywordParams[keywordId]` holds keyword numbers; keys must be in `KEYWORD_IDS`. `portalParams[topicId]` holds Portal numbers, and falls back to `portalParams[portalId]`, so a mode can add a Topic that reuses a Portal kind with new numbers.
- `keywordsEnabled` ⊆ `KEYWORD_IDS` (the 6 v1 ids plus `edition`, `obscure` and `wildcard`).
- `mulligan` must be `false`. Mulligans are not implemented in v1.
- `percentiles`, `starterDecks`, `trendUp/Down`, `trendMinDaily`, `uncheckedCostCap`, `vanillaBonus`, `costThresholds`, `powerByCost`, `verifyStats` and `factionSynergyCap` are for derivation and the host. The core loop doesn't read them.
Validation also enforces:
- `turns × turnSeconds ≤ 240`
- `energyByTurn.length ≥ turns`
- `portalReveal.length = topicCount`
- `openingHand ≤ handLimit`
- `costThresholds` in ascending order
- with `distinctStats`, `topicCount == 3` and the pool has all 3 stats
- the ranges in DESIGN §11 are **stricter** and are enforced by modes (`shared/game/modes.ts`). The engine's bounds only guarantee safety and termination.
## 5. Determinism and the RNG
- The RNG is **mulberry32(seed: uint32)**, as in DESIGN §4. Its state is a single uint32 in `state.rng`.
- Draw order:
1. p0's deck is shuffled.
2. p1's deck is shuffled.
3. **The Topics are drawn.** With `distinctStats`: for each stat in the order `attention, depth, reach`, take `group[floor(next() × group.length)]`, where `group` is that stat's Topics in `topicPool` order. Then the picks are shuffled, and that is the lane order. Without `distinctStats`: the whole pool is shuffled and the first `topicCount` are taken.
4. The initiative coin is flipped: p0 has initiative on turn 1 (and every odd turn) if `next() < 0.5`; otherwise p1 does. After that, initiative strictly alternates.
5. Keyword and Portal hooks draw in resolution order.
- Shuffles are Fisher–Yates with `i` from n−1 down to 1 and `j = floor(next() × (i+1))`.
- `ongoing` power hooks get a throwaway RNG copy, so computing power never changes the match RNG.
## 6. State and views
The full `MatchState` (plain JSON) is for the **host only**:
```ts
interface MatchState {
schema: 'wikideck-match/1'; engineVersion: number; ruleset: Ruleset; seed: number; rng: number;
turn: number /* 1-based */; phase: 'planning' | 'over'; initiative: 0 | 1;
players: [PlayerState, PlayerState]; // deck, hand, energy, queue, committed, afk
lanes: { topic: TopicDef; portalRevealed: boolean; cards: [CardInPlay[], CardInPlay[]] }[];
revealSeq: number; log: LogEvent[]; actions: Action[]; result: MatchResult | null;
}
interface PlayerState { deck; hand; energy; queue: { cardId; lane }[]; committed; afk; carry }
interface CardInPlay { card: GameCard; owner: 0 | 1; lane: number; turn: number; seq: number; bonus: number }
```
`PlayerView`, returned by `viewFor(state, seat)`, is what a seat may see. In it, "you" is always index 0 and the opponent is index 1:
```ts
interface PlayerView {
you: 0 | 1; ruleset; turn; phase; initiative;
energy: number; energyLeft: number; hand: GameCard[]; queue: { cardId; lane }[]; committed; deckCount;
opponent: { handCount; deckCount; queuedCount; committed }; // never their cards or queue
lanes: { topic: TopicDef /* stat always; id/name/portal masked until portalRevealed */, portalRevealed, cards: [mine, theirs],
cardPower: [number[], number[]], power: [mine, theirs], leader: 'you' | 'opponent' | null }[];
result: MatchResult | null;
}
```
`state.log` is an append-only event list for animation and replays. Event types: `turnStart`, `portalRevealed`, `underdog`, `draw`, `reveal`, `fizzle`, `effect`, `concede` and `matchOver`. It contains both seats' draws, so a host must filter it per seat before sending it.
## 7. Results
```ts
interface MatchResult {
winner: 0 | 1 | null; // null = draw
reason: 'topics' | 'totalPower' | 'draw' | 'concede' | 'afk';
topicsLed: [number, number]; lanePower: [number, number][]; totalPower: [number, number]; turns: number;
}
```
Scoring runs after the last turn's End phase. Lane powers include revealed "at scoring" Portals, and each lane's leader uses the consensus tie-break (§6). Winner, per DESIGN §7:
1. The seat that leads more Topics.
2. If tied on Topics, the seat with more total power.
3. If that is also tied, a draw.
## 8. Keywords and Portals (extension contract)
`KEYWORDS` and `PORTALS` in `shared/game/keywords.ts` (engine-b) are registries of hook objects. The header of that file is normative. Every hook gets `ctx = { state, rng, params, lane, log, power(card) }`.
**Keywords**
- `onReveal(ctx, self)` and `endOfTurn(ctx, self)` may change `bonus` on cards in `ctx.state`.
- `ongoing(ctx, self, target) → number` must be **pure**, and must not call `ctx.power`.
- Keyword hooks run only if the keyword is in `keywordsEnabled`.
**Portals** have the same hooks, plus:
- `onPortalReveal(ctx)`
- `canPlay(ctx, card, seat) → boolean`, checked when a play is queued and again at reveal
- `capacity(ctx) → number`
- `allOnTopic: true`
- `atScoring(ctx) → [delta0, delta1]`
Portal hooks act only once the Portal is revealed.
**Rules for all hooks**
- Hooks must not move or remove cards (DESIGN §10).
- Any randomness must come from `ctx.rng`. No v1 keyword uses it.
## 9. Testing
- `tests/game-core.test.ts` (engine-a) covers the core loop:
- the RNG reference value, ruleset bounds and setup
- hidden information and hidden Portals
- energy carry, interleaved reveal and alternating initiative
- on-topic power, the consensus tie-break, and Portal capacity, fizzle and at-scoring hooks
- disabled keywords, AFK and concede, and draws
- the random-play property: matches terminate, replay exactly, and serialise after every action
- `tests/game-*.test.ts` (engine-b): keywords, card derivation, property tests and the DESIGN §12 golden match.
+130 -69
View File
@@ -4,7 +4,7 @@
* All randomness comes from the match seed via state.rng (mulberry32, §4). * All randomness comes from the match seed via state.rng (mulberry32, §4).
* Contract: docs/game/ENGINE_API.md. * Contract: docs/game/ENGINE_API.md.
*/ */
import { KEYWORDS, PORTALS, type EffectContext } from './keywords.ts'; import { KEYWORDS, KEYWORD_IDS, activePortal, isOnTopic, type EffectContext, type KeywordDef, type PortalDef } from './keywords.ts';
import { Rng, normalizeSeed } from './rng.ts'; import { Rng, normalizeSeed } from './rng.ts';
import { parseRuleset } from './ruleset.ts'; import { parseRuleset } from './ruleset.ts';
import { import {
@@ -19,6 +19,7 @@ export const other = (player: PlayerId): PlayerId => (player === 0 ? 1 : 0);
const clone = <T>(value: T): T => structuredClone(value); const clone = <T>(value: T): T => structuredClone(value);
const RARITIES = new Set(['Common', 'Rare', 'Epic', 'Legendary']); const RARITIES = new Set(['Common', 'Rare', 'Epic', 'Legendary']);
const FACTION_SET = new Set(['Space', 'Nature', 'People', 'Science', 'History', 'Culture']); const FACTION_SET = new Set(['Space', 'Nature', 'People', 'Science', 'History', 'Culture']);
const CHECKS = new Set(['verified', 'unverified', 'unchecked', 'loaner']);
// ---------- validation ---------- // ---------- validation ----------
@@ -43,9 +44,11 @@ export function validateDeck(rules: Ruleset, deck: readonly GameCard[]): string[
if (!Number.isInteger(card.power) || card.power < 0 || card.power > 30) problems.push(`${label}: power must be 0–30`); if (!Number.isInteger(card.power) || card.power < 0 || card.power > 30) problems.push(`${label}: power must be 0–30`);
if (!STATS.includes(card.home)) problems.push(`${label}: bad home stat`); if (!STATS.includes(card.home)) problems.push(`${label}: bad home stat`);
if (card.trend !== -1 && card.trend !== 0 && card.trend !== 1) problems.push(`${label}: trend must be -1, 0 or 1`); if (card.trend !== -1 && card.trend !== 0 && card.trend !== 1) problems.push(`${label}: trend must be -1, 0 or 1`);
if (card.keyword !== null && !Object.hasOwn(KEYWORDS, card.keyword)) problems.push(`${label}: unknown keyword ${card.keyword}`); if (card.keyword !== null && !(KEYWORD_IDS as readonly string[]).includes(card.keyword)) problems.push(`${label}: unknown keyword ${card.keyword}`);
if (card.source !== 'owned' && card.source !== 'loaner') problems.push(`${label}: bad source`); if (card.source !== 'owned' && card.source !== 'loaner') problems.push(`${label}: bad source`);
if (card.check !== undefined && !CHECKS.has(card.check)) problems.push(`${label}: bad check`);
if (card.source === 'loaner') loaners++; if (card.source === 'loaner') loaners++;
if (card.source === 'owned' && !rules.ownedCards) problems.push(`${label}: owned cards are not allowed in this mode`);
const n = (copies.get(card.pageId) ?? 0) + 1; const n = (copies.get(card.pageId) ?? 0) + 1;
copies.set(card.pageId, n); copies.set(card.pageId, n);
if (n === rules.maxCopiesPerPage + 1) problems.push(`More than ${rules.maxCopiesPerPage} copies of page ${card.pageId}`); if (n === rules.maxCopiesPerPage + 1) problems.push(`More than ${rules.maxCopiesPerPage} copies of page ${card.pageId}`);
@@ -85,7 +88,7 @@ export function createMatch(ruleset: Ruleset, decks: readonly [readonly GameCard
} }
const rng = new Rng(seedValue); const rng = new Rng(seedValue);
const newPlayer = (player: PlayerId): PlayerState => ({ const newPlayer = (player: PlayerId): PlayerState => ({
deck: rng.shuffle(clone(decks[player])), hand: [], energy: 0, queue: [], committed: false, afk: 0, deck: rng.shuffle(clone(decks[player])), hand: [], energy: 0, queue: [], committed: false, afk: 0, carry: 0,
}); });
const p0 = newPlayer(0); const p0 = newPlayer(0);
const p1 = newPlayer(1); const p1 = newPlayer(1);
@@ -93,8 +96,8 @@ export function createMatch(ruleset: Ruleset, decks: readonly [readonly GameCard
const initiative: PlayerId = rng.next() < 0.5 ? 0 : 1; const initiative: PlayerId = rng.next() < 0.5 ? 0 : 1;
const state: MatchState = { const state: MatchState = {
schema: 'wikideck-match/1', engineVersion: ENGINE_VERSION, ruleset: rules, seed: seedValue, rng: rng.state, schema: 'wikideck-match/1', engineVersion: ENGINE_VERSION, ruleset: rules, seed: seedValue, rng: rng.state,
turn: 0, phase: 'planning', initiative, players: [p0, p1], turn: 0, phase: 'planning', initiative, revealSeq: 0, players: [p0, p1],
lanes: topics.map(topic => ({ topic: clone(topic), revealed: false, cards: [[], []] as [CardInPlay[], CardInPlay[]] })), lanes: topics.map(topic => ({ topic: clone(topic), portalRevealed: false, cards: [[], []] as [CardInPlay[], CardInPlay[]] })),
log: [], actions: [], result: null, log: [], actions: [], result: null,
}; };
for (const player of PLAYERS) for (let i = 0; i < rules.openingHand; i++) draw(state, player); for (const player of PLAYERS) for (let i = 0; i < rules.openingHand; i++) draw(state, player);
@@ -112,27 +115,51 @@ function draw(state: MatchState, player: PlayerId): void {
} }
function context(state: MatchState, rng: Rng, params: Record<string, number> | undefined, lane: number, source: string, player: PlayerId): EffectContext { function context(state: MatchState, rng: Rng, params: Record<string, number> | undefined, lane: number, source: string, player: PlayerId): EffectContext {
return { state, rng, params: params ?? {}, lane, log: text => state.log.push({ t: 'effect', source, player, text }) }; return {
state, rng, params: params ?? {}, lane,
log: text => state.log.push({ t: 'effect', source, player, text }),
power: card => cardPower(state, card),
};
} }
function portalOf(state: MatchState, lane: number) { /** Enabled keyword definition for a card, if any. */
const l = state.lanes[lane]; function keywordOf(state: MatchState, card: GameCard): KeywordDef | undefined {
return l?.revealed && l.topic.portal ? PORTALS[l.topic.portal] : undefined; return card.keyword && state.ruleset.keywordsEnabled.includes(card.keyword) ? KEYWORDS[card.keyword] : undefined;
} }
/** §5.1 Start, then §5.2 Underdog. */ function keywordCtx(state: MatchState, rng: Rng, keyword: KeywordDef, card: CardInPlay): EffectContext {
return context(state, rng, state.ruleset.keywordParams[keyword.id], card.lane, keyword.id, card.owner);
}
function portalCtx(state: MatchState, rng: Rng, lane: number, portal: PortalDef, player: PlayerId): EffectContext {
const topic = state.lanes[lane].topic;
const params = state.ruleset.portalParams[topic.id] ?? state.ruleset.portalParams[portal.id];
return context(state, rng, params, lane, portal.id, player);
}
/** Per-seat card capacity of a lane (a Portal may override it, e.g. Stub). */
export function laneCapacity(state: MatchState, lane: number): number {
const portal = activePortal(state, lane);
return portal?.capacity ? portal.capacity(portalCtx(state, new Rng(state.rng), lane, portal, state.initiative)) : state.ruleset.laneCapacity;
}
/** §5.1 Start (Portal reveal, energy, draw), then §5.2 Underdog. Initiative alternates (§5.5). */
function startTurn(state: MatchState, rng: Rng): void { function startTurn(state: MatchState, rng: Rng): void {
state.turn += 1; state.turn += 1;
if (state.turn > 1) state.initiative = other(state.initiative);
const rules = state.ruleset; const rules = state.ruleset;
state.lanes.forEach((lane, index) => { state.lanes.forEach((lane, index) => {
if (lane.revealed || (rules.revealSchedule[index] ?? 1) > state.turn) return; if (lane.portalRevealed || (rules.portalReveal[index] ?? 1) > state.turn) return;
lane.revealed = true; lane.portalRevealed = true;
state.log.push({ t: 'topicRevealed', lane: index, topic: clone(lane.topic) }); state.log.push({ t: 'portalRevealed', lane: index, topic: clone(lane.topic) });
const portal = portalOf(state, index); const portal = activePortal(state, index);
portal?.onTopicReveal?.(context(state, rng, rules.portalParams[portal.id], index, portal.id, state.initiative)); portal?.onPortalReveal?.(portalCtx(state, rng, index, portal, state.initiative));
}); });
const base = (rules.energyByTurn[state.turn - 1] ?? rules.energyByTurn.at(-1)!) + rules.bonusEnergy; const base = (rules.energyByTurn[state.turn - 1] ?? rules.energyByTurn.at(-1)!) + rules.bonusEnergy;
for (const player of PLAYERS) Object.assign(state.players[player], { energy: base, queue: [], committed: false }); for (const player of PLAYERS) {
const p = state.players[player];
Object.assign(p, { energy: base + p.carry, queue: [], committed: false });
}
for (const player of PLAYERS) draw(state, player); for (const player of PLAYERS) draw(state, player);
if (rules.underdog && state.turn >= 2) { if (rules.underdog && state.turn >= 2) {
const led = topicsLed(state); const led = topicsLed(state);
@@ -146,47 +173,63 @@ function startTurn(state: MatchState, rng: Rng): void {
// ---------- power (§6) ---------- // ---------- power (§6) ----------
/** A card's current lane power (never below 0). */ /** A card's current lane power (§6, never below 0). */
export function cardPower(state: MatchState, target: CardInPlay): number { export function cardPower(state: MatchState, target: CardInPlay): number {
const rules = state.ruleset; const rules = state.ruleset;
const lane = state.lanes[target.lane];
const scratch = new Rng(state.rng); // ongoing effects must not consume real randomness const scratch = new Rng(state.rng); // ongoing effects must not consume real randomness
let power = target.card.power + target.bonus + target.card.trend; let power = target.card.power + target.bonus + target.card.trend;
if (lane.revealed && lane.topic.stat === target.card.home) power += rules.onTopicBonus; if (isOnTopic(state, target)) power += rules.onTopicBonus[target.card.cost] ?? 0;
for (const l of state.lanes) for (const side of l.cards) for (const source of side) { for (const lane of state.lanes) for (const side of lane.cards) for (const source of side) {
const keyword = source.card.keyword ? KEYWORDS[source.card.keyword] : undefined; const keyword = keywordOf(state, source.card);
if (keyword?.ongoing) power += keyword.ongoing(context(state, scratch, rules.keywordParams[keyword.id], source.lane, keyword.id, source.owner), source, target); if (keyword?.ongoing) power += keyword.ongoing(keywordCtx(state, scratch, keyword, source), source, target);
} }
const portal = portalOf(state, target.lane); const portal = activePortal(state, target.lane);
if (portal?.ongoing) power += portal.ongoing(context(state, scratch, rules.portalParams[portal.id], target.lane, portal.id, target.owner), target); if (portal?.ongoing) power += portal.ongoing(portalCtx(state, scratch, target.lane, portal, target.owner), target);
return Math.max(0, power); return Math.max(0, power);
} }
/** [seat 0 power, seat 1 power] in one lane. */ /** [seat 0 power, seat 1 power] in one lane (during play; excludes "at scoring" Portals). */
export function lanePower(state: MatchState, lane: number): [number, number] { export function lanePower(state: MatchState, lane: number): [number, number] {
return PLAYERS.map(player => state.lanes[lane].cards[player].reduce((sum, card) => sum + cardPower(state, card), 0)) as [number, number]; return PLAYERS.map(player => state.lanes[lane].cards[player].reduce((sum, card) => sum + cardPower(state, card), 0)) as [number, number];
} }
/** Number of Topics each seat leads (strictly more power). */ /** §6: who leads a lane given its powers. Equal and > 0 → more on-topic cards leads (consensus). */
export function laneLeader(state: MatchState, lane: number, power: [number, number] = lanePower(state, lane)): PlayerId | null {
const [a, b] = power;
if (a !== b) return a > b ? 0 : 1;
if (a === 0) return null;
const onTopic = PLAYERS.map(player => state.lanes[lane].cards[player].filter(card => isOnTopic(state, card)).length);
return onTopic[0] === onTopic[1] ? null : onTopic[0] > onTopic[1] ? 0 : 1;
}
/** Number of Topics each seat leads right now (with the consensus tie-break). */
export function topicsLed(state: MatchState): [number, number] { export function topicsLed(state: MatchState): [number, number] {
const led: [number, number] = [0, 0]; const led: [number, number] = [0, 0];
state.lanes.forEach((_, lane) => { state.lanes.forEach((_, lane) => {
const [a, b] = lanePower(state, lane); const leader = laneLeader(state, lane);
if (a > b) led[0]++; else if (b > a) led[1]++; if (leader !== null) led[leader]++;
}); });
return led; return led;
} }
/** Final lane powers: lanePower plus revealed "at scoring" Portals (§7, §10.3). */
export function scoringPower(state: MatchState, lane: number): [number, number] {
const power = lanePower(state, lane);
const portal = activePortal(state, lane);
if (!portal?.atScoring) return power;
const [d0, d1] = portal.atScoring(portalCtx(state, new Rng(state.rng), lane, portal, state.initiative));
return [power[0] + d0, power[1] + d1];
}
// ---------- actions (§5.3) ---------- // ---------- actions (§5.3) ----------
const queuedCost = (p: PlayerState) => p.queue.reduce((sum, play) => sum + (p.hand.find(c => c.cardId === play.cardId)?.cost ?? 0), 0); const queuedCost = (p: PlayerState) => p.queue.reduce((sum, play) => sum + (p.hand.find(c => c.cardId === play.cardId)?.cost ?? 0), 0);
const queuedInLane = (p: PlayerState, lane: number) => p.queue.filter(play => play.lane === lane).length; const queuedInLane = (p: PlayerState, lane: number) => p.queue.filter(play => play.lane === lane).length;
function laneRejects(state: MatchState, lane: number, card: GameCard, player: PlayerId): string | null { function laneRejects(state: MatchState, lane: number, card: GameCard, player: PlayerId): string | null {
const portal = portalOf(state, lane); const portal = activePortal(state, lane);
if (!portal?.canPlay) return null; if (!portal?.canPlay) return null;
const ctx = context(state, new Rng(state.rng), state.ruleset.portalParams[portal.id], lane, portal.id, player); return portal.canPlay(portalCtx(state, new Rng(state.rng), lane, portal, player), card, player) ? null : `${portal.name} rejects this card`;
return portal.canPlay(ctx, card, player) ? null : `${portal.name} rejects this card`;
} }
function playProblem(state: MatchState, action: Extract<Action, { type: 'play' }>): string | null { function playProblem(state: MatchState, action: Extract<Action, { type: 'play' }>): string | null {
@@ -197,7 +240,7 @@ function playProblem(state: MatchState, action: Extract<Action, { type: 'play' }
if (p.queue.some(play => play.cardId === action.cardId)) return 'Card is already queued'; if (p.queue.some(play => play.cardId === action.cardId)) return 'Card is already queued';
if (!Number.isInteger(action.lane) || action.lane < 0 || action.lane >= state.lanes.length) return 'No such Topic'; if (!Number.isInteger(action.lane) || action.lane < 0 || action.lane >= state.lanes.length) return 'No such Topic';
if (card.cost > p.energy - queuedCost(p)) return 'Not enough energy'; if (card.cost > p.energy - queuedCost(p)) return 'Not enough energy';
if (state.lanes[action.lane].cards[action.player].length + queuedInLane(p, action.lane) >= state.ruleset.laneCapacity) return 'Topic is full'; if (state.lanes[action.lane].cards[action.player].length + queuedInLane(p, action.lane) >= laneCapacity(state, action.lane)) return 'Topic is full';
return laneRejects(state, action.lane, card, action.player); return laneRejects(state, action.lane, card, action.player);
} }
@@ -271,54 +314,69 @@ export function applyAction(state: MatchState, action: Action): MatchState {
return next; return next;
} }
/** §5.4 Reveal and §5.5 End. */ /** §5.4 Reveal (interleaved) and §5.5 End. */
function resolveTurn(state: MatchState, rng: Rng): void { function resolveTurn(state: MatchState, rng: Rng): void {
const rules = state.ruleset; const rules = state.ruleset;
const order: PlayerId[] = [state.initiative, other(state.initiative)]; const order: PlayerId[] = [state.initiative, other(state.initiative)];
for (const player of order) { // Carry (§5.1): energy not reserved by a queued play. Fizzled plays still spent theirs.
for (const player of PLAYERS) {
const p = state.players[player]; const p = state.players[player];
for (const play of p.queue) { p.carry = Math.min(rules.energyCarryMax, Math.max(0, p.energy - queuedCost(p)));
const index = p.hand.findIndex(c => c.cardId === play.cardId); }
const card = p.hand[index]; const queues = order.map(player => state.players[player].queue.slice());
if (index < 0 || state.lanes[play.lane].cards[player].length >= rules.laneCapacity || laneRejects(state, play.lane, card, player)) { for (let i = 0; i < Math.max(queues[0].length, queues[1].length); i++) {
state.log.push({ t: 'fizzle', player, cardId: play.cardId, lane: play.lane }); // stays in hand, energy lost for (const [k, player] of order.entries()) {
continue; const play = queues[k][i];
} if (play) reveal(state, rng, player, play.cardId, play.lane);
p.hand.splice(index, 1);
const inPlay: CardInPlay = { card, owner: player, lane: play.lane, turn: state.turn, bonus: 0 };
state.lanes[play.lane].cards[player].push(inPlay);
state.log.push({ t: 'reveal', player, cardId: card.cardId, lane: play.lane });
const keyword = card.keyword ? KEYWORDS[card.keyword] : undefined;
keyword?.onReveal?.(context(state, rng, rules.keywordParams[keyword.id], play.lane, keyword.id, player), inPlay);
const portal = portalOf(state, play.lane);
portal?.onReveal?.(context(state, rng, rules.portalParams[portal.id], play.lane, portal.id, player), inPlay);
} }
p.queue = [];
} }
for (const player of order) for (const lane of state.lanes) for (const card of lane.cards[player].slice()) { for (const player of PLAYERS) state.players[player].queue = [];
const keyword = card.card.keyword ? KEYWORDS[card.card.keyword] : undefined; for (const player of order) for (const lane of state.lanes) {
keyword?.endOfTurn?.(context(state, rng, rules.keywordParams[keyword.id], card.lane, keyword.id, player), card); for (const card of lane.cards[player].slice().sort((x, y) => x.seq - y.seq)) {
const keyword = keywordOf(state, card.card);
keyword?.endOfTurn?.(keywordCtx(state, rng, keyword, card), card);
}
} }
if (state.turn >= rules.turns) { finish(state, null, 'topics'); return; } if (state.turn >= rules.turns) finish(state, null, 'topics');
const led = topicsLed(state); else startTurn(state, rng);
state.initiative = led[0] !== led[1] ? (led[0] > led[1] ? 0 : 1) : other(state.initiative);
startTurn(state, rng);
} }
/** §7. */ function reveal(state: MatchState, rng: Rng, player: PlayerId, cardId: string, lane: number): void {
const p = state.players[player];
const index = p.hand.findIndex(c => c.cardId === cardId);
const card = p.hand[index];
if (index < 0 || state.lanes[lane].cards[player].length >= laneCapacity(state, lane) || laneRejects(state, lane, card, player)) {
state.log.push({ t: 'fizzle', player, cardId, lane }); // stays in hand, energy lost
return;
}
p.hand.splice(index, 1);
const inPlay: CardInPlay = { card, owner: player, lane, turn: state.turn, seq: ++state.revealSeq, bonus: 0 };
state.lanes[lane].cards[player].push(inPlay);
state.log.push({ t: 'reveal', player, cardId, lane });
const keyword = keywordOf(state, card);
keyword?.onReveal?.(keywordCtx(state, rng, keyword, inPlay), inPlay);
const portal = activePortal(state, lane);
portal?.onReveal?.(portalCtx(state, rng, lane, portal, player), inPlay);
}
/** §7 scoring (after the last End phase, with "at scoring" Portals), or a concede. */
function finish(state: MatchState, forcedWinner: PlayerId | null, reason: 'topics' | 'concede' | 'afk'): void { function finish(state: MatchState, forcedWinner: PlayerId | null, reason: 'topics' | 'concede' | 'afk'): void {
const lanePowers = state.lanes.map((_, lane) => lanePower(state, lane)); const lanePowers = state.lanes.map((_, lane) => scoringPower(state, lane));
const topicsLedNow = topicsLed(state); const led: [number, number] = [0, 0];
const totalPower: [number, number] = [0, 0]; const totalPower: [number, number] = [0, 0];
for (const [a, b] of lanePowers) { totalPower[0] += a; totalPower[1] += b; } lanePowers.forEach((power, lane) => {
const leader = laneLeader(state, lane, power);
if (leader !== null) led[leader]++;
totalPower[0] += power[0]; totalPower[1] += power[1];
});
let winner: PlayerId | null = forcedWinner; let winner: PlayerId | null = forcedWinner;
let why: MatchResult['reason'] = reason; let why: MatchResult['reason'] = reason;
if (reason === 'topics') { if (reason === 'topics') {
if (topicsLedNow[0] !== topicsLedNow[1]) winner = topicsLedNow[0] > topicsLedNow[1] ? 0 : 1; if (led[0] !== led[1]) winner = led[0] > led[1] ? 0 : 1;
else if (totalPower[0] !== totalPower[1]) { winner = totalPower[0] > totalPower[1] ? 0 : 1; why = 'totalPower'; } else if (totalPower[0] !== totalPower[1]) { winner = totalPower[0] > totalPower[1] ? 0 : 1; why = 'totalPower'; }
else why = 'draw'; else why = 'draw';
} }
state.result = { winner, reason: why, topicsLed: topicsLedNow, lanePower: lanePowers, totalPower, turns: state.turn }; state.result = { winner, reason: why, topicsLed: led, lanePower: lanePowers, totalPower, turns: state.turn };
state.phase = 'over'; state.phase = 'over';
state.log.push({ t: 'matchOver', result: clone(state.result) }); state.log.push({ t: 'matchOver', result: clone(state.result) });
} }
@@ -342,12 +400,15 @@ export function viewFor(state: MatchState, you: PlayerId): PlayerView {
lanes: state.lanes.map((lane, index) => { lanes: state.lanes.map((lane, index) => {
const power = lanePower(state, index); const power = lanePower(state, index);
const mine = power[you], theirs = power[them]; const mine = power[you], theirs = power[them];
const leader = laneLeader(state, index, power);
return { return {
topic: lane.revealed ? lane.topic : null, // Until its Portal is revealed only the stat is visible (the id/name would give the Portal away).
topic: lane.portalRevealed ? lane.topic : { id: `lane-${index + 1}`, name: '?', stat: lane.topic.stat, portal: null },
portalRevealed: lane.portalRevealed,
cards: [lane.cards[you], lane.cards[them]] as [CardInPlay[], CardInPlay[]], cards: [lane.cards[you], lane.cards[them]] as [CardInPlay[], CardInPlay[]],
cardPower: [lane.cards[you].map(c => cardPower(state, c)), lane.cards[them].map(c => cardPower(state, c))] as [number[], number[]], cardPower: [lane.cards[you].map(c => cardPower(state, c)), lane.cards[them].map(c => cardPower(state, c))] as [number[], number[]],
power: [mine, theirs] as [number, number], power: [mine, theirs] as [number, number],
leader: mine > theirs ? 'you' as const : theirs > mine ? 'opponent' as const : null, leader: leader === null ? null : leader === you ? 'you' as const : 'opponent' as const,
}; };
}), }),
result: state.result, result: state.result,
@@ -378,13 +439,13 @@ export function replay(ruleset: Ruleset, decks: readonly [readonly GameCard[], r
*/ */
export function placeCard(state: MatchState, player: PlayerId, lane: number, card: GameCard, bonus = 0): MatchState { export function placeCard(state: MatchState, player: PlayerId, lane: number, card: GameCard, bonus = 0): MatchState {
const next = clone(state); const next = clone(state);
next.lanes[lane].cards[player].push({ card: clone(card), owner: player, lane, turn: next.turn, bonus }); next.lanes[lane].cards[player].push({ card: clone(card), owner: player, lane, turn: next.turn, seq: ++next.revealSeq, bonus });
return next; return next;
} }
/** Test helper: flip a Topic face-up (runs nothing). */ /** Test helper: reveal a Topic's Portal now (runs nothing). */
export function revealTopic(state: MatchState, lane: number): MatchState { export function revealPortal(state: MatchState, lane: number): MatchState {
const next = clone(state); const next = clone(state);
next.lanes[lane].revealed = true; next.lanes[lane].portalRevealed = true;
return next; return next;
} }
+2 -2
View File
@@ -4,7 +4,7 @@ export { Rng, seedFromString, normalizeSeed, type RngState } from './rng.ts';
export { DEFAULT_RULESET, DEFAULT_TOPIC_POOL, RulesetSchema, TopicSchema, parseRuleset } from './ruleset.ts'; export { DEFAULT_RULESET, DEFAULT_TOPIC_POOL, RulesetSchema, TopicSchema, parseRuleset } from './ruleset.ts';
export { export {
ENGINE_VERSION, createMatch, legalActions, applyAction, actionProblem, isOver, result, viewFor, ENGINE_VERSION, createMatch, legalActions, applyAction, actionProblem, isOver, result, viewFor,
serialize, deserialize, replay, validateDeck, cardPower, lanePower, topicsLed, other, placeCard, revealTopic, serialize, deserialize, replay, validateDeck, cardPower, lanePower, laneLeader, laneCapacity, scoringPower, topicsLed, other, placeCard, revealPortal,
} from './engine.ts'; } from './engine.ts';
export { KEYWORDS, PORTALS, allies, type KeywordDef, type PortalDef, type EffectContext } from './keywords.ts'; export { KEYWORDS, PORTALS, KEYWORD_IDS, PORTAL_IDS, allies, activePortal, isOnTopic, type KeywordDef, type PortalDef, type EffectContext } from './keywords.ts';
export { STARTER_POOL, loanerCard, previewPool, starterDeck } from './starter.ts'; export { STARTER_POOL, loanerCard, previewPool, starterDeck } from './starter.ts';
+49 -41
View File
@@ -1,33 +1,46 @@
/** /**
* Keyword and Portal registry (DESIGN §10, §10.3). Effects are code here; which * Keyword and Portal registry (DESIGN §10.2, §10.3). Effects are code here; which
* ones a card/topic uses and their numbers are data (GameCard.keyword, * ones a card/topic uses and their numbers are data (GameCard.keyword,
* TopicDef.portal, Ruleset.keywordParams / portalParams). * TopicDef.portal, Ruleset.keywordsEnabled / keywordParams / portalParams).
* Owner of the effects: engine-b (claude/wikideck#3). engine-a owns the hook contract: * Owner of the effects: engine-b (claude/wikideck#3). engine-a owns the hook contract:
* *
* - Hooks get an EffectContext over the engine's *working copy* of the state and may * - Hooks get an EffectContext over the engine's *working copy* of the state and may
* mutate it (e.g. `bonus` on cards). Mutating is safe: applyAction already cloned. * mutate it (e.g. `bonus` on cards). Safe: applyAction already cloned.
* Any randomness must come from ctx.rng (the match RNG, in resolution order, §4.2.5). * Any randomness must come from ctx.rng (match RNG, resolution order, §4.2.5).
* - onReveal: once, right after the card enters its lane (§5.4). * - A keyword's hooks run only if its id is in ruleset.keywordsEnabled.
* - endOfTurn: every card in play, at §5.5, initiative player's cards first, lanes left→right, * - onReveal(ctx, self): right after `self` is pushed into its lane (§5.4). Cards revealed
* in play order. * earlier (any seat, any turn) are on the board; later ones are not. self.seq is its global
* - ongoing: PURE. Returns a power delta for `target` while `self` is in play. Called for every * reveal number; cards revealed this turn have `turn === ctx.state.turn`.
* (self, target) pair in play, including self === target. ctx.rng is a throwaway copy. * - endOfTurn(ctx, self): §5.5 order: initiative seat's cards first, then lanes 1→N, then seq.
* - Portals: same shape; ongoing/canPlay/onReveal only apply while the Topic is revealed. * Also runs on the last turn, before scoring (§7).
* onTopicReveal runs when the Topic flips face-up (§5.1). * - ongoing(ctx, self, target) → delta: PURE. Called for every (self, target) pair in play,
* - Hooks must not throw, must not move/remove cards (§10 v1 constraint). * including self === target. ctx.rng is a throwaway copy. Don't call ctx.power on a card from
* inside ongoing (infinite recursion); read base fields instead.
* - Portals: same, plus onPortalReveal(ctx), canPlay(ctx, card, seat), capacity(ctx) → number
* (lane capacity override), allOnTopic (Disambiguation) and atScoring(ctx) → [delta0, delta1]
* (Topic power added at scoring, §7). All Portal hooks apply only once the Portal is revealed.
* Params: ruleset.portalParams[topic.id], falling back to portalParams[portal id].
* - Hooks must not throw and must not move or remove cards (§10, v1).
*/ */
import type { Rng } from './rng.ts'; import type { Rng } from './rng.ts';
import type { CardInPlay, GameCard, MatchState, PlayerId } from './types.ts'; import type { CardInPlay, GameCard, MatchState, PlayerId } from './types.ts';
/** The 9 implemented keyword ids (§10.2; edition, obscure and wildcard are disabled by default). */
export const KEYWORD_IDS = ['viral', 'rising', 'local', 'encyclopedic', 'nostalgic', 'translated', 'edition', 'obscure', 'wildcard'] as const;
/** The 6 Portal kinds (§10.3), named after their default Topic. */
export const PORTAL_IDS = ['main-page', 'trending', 'featured-article', 'stub', 'interwiki', 'disambiguation'] as const;
export interface EffectContext { export interface EffectContext {
state: MatchState; state: MatchState;
rng: Rng; rng: Rng;
/** Tunable numbers for this keyword/portal from Ruleset.keywordParams / portalParams. */ /** Tunable numbers for this keyword/portal from the ruleset. */
params: Record<string, number>; params: Record<string, number>;
/** Lane the effect lives in. */ /** Lane the effect lives in. */
lane: number; lane: number;
/** Add a line to the match log (attributed to this keyword/portal). */ /** Add a line to the match log (attributed to this keyword/portal). */
log(text: string): void; log(text: string): void;
/** Current lane power of a card in play (the engine's cardPower). Not for use inside `ongoing`. */
power(card: CardInPlay): number;
} }
export interface KeywordDef { export interface KeywordDef {
@@ -44,12 +57,18 @@ export interface PortalDef {
id: string; id: string;
name: string; name: string;
text: string; text: string;
onTopicReveal?(ctx: EffectContext): void; onPortalReveal?(ctx: EffectContext): void;
/** Runs when any card is revealed in this Topic (after the card's own onReveal). */ /** Runs when any card is revealed in this Topic (after the card's own onReveal). */
onReveal?(ctx: EffectContext, card: CardInPlay): void; onReveal?(ctx: EffectContext, card: CardInPlay): void;
ongoing?(ctx: EffectContext, target: CardInPlay): number; ongoing?(ctx: EffectContext, target: CardInPlay): number;
/** Lets a Topic reject a card; checked when queuing and again at reveal. */ /** Lets a Topic reject a card; checked when queuing and again at reveal. */
canPlay?(ctx: EffectContext, card: GameCard, player: PlayerId): boolean; canPlay?(ctx: EffectContext, card: GameCard, player: PlayerId): boolean;
/** Per-player lane capacity in this Topic (replaces ruleset.laneCapacity). */
capacity?(ctx: EffectContext): number;
/** Every card here counts as on-topic. */
allOnTopic?: boolean;
/** Topic power added to [seat 0, seat 1] here at scoring. */
atScoring?(ctx: EffectContext): [number, number];
} }
/** Cards on the same side of the same lane, excluding `self`. */ /** Cards on the same side of the same lane, excluding `self`. */
@@ -57,31 +76,20 @@ export function allies(state: MatchState, self: CardInPlay): CardInPlay[] {
return state.lanes[self.lane].cards[self.owner].filter(card => card !== self); return state.lanes[self.lane].cards[self.owner].filter(card => card !== self);
} }
/** PLACEHOLDERS so the hook contract is exercised; engine-b replaces these per DESIGN §10. */ /** The lane's Portal, if it has one and it is revealed. */
export const KEYWORDS: Record<string, KeywordDef> = { export function activePortal(state: MatchState, lane: number): PortalDef | undefined {
rally: { const l = state.lanes[lane];
id: 'rally', name: 'Rally', text: 'On reveal: +{amount} to your other cards here.', return l?.portalRevealed && l.topic.portal ? PORTALS[l.topic.portal] : undefined;
onReveal(ctx, self) { }
const amount = ctx.params.amount ?? 1;
for (const ally of allies(ctx.state, self)) ally.bonus += amount;
ctx.log(`${self.card.title}: Rally +${amount}`);
},
},
anchor: {
id: 'anchor', name: 'Anchor', text: 'Ongoing: +{amount} if alone here.',
ongoing(ctx, self, target) {
return target === self && allies(ctx.state, self).length === 0 ? ctx.params.amount ?? 2 : 0;
},
},
};
export const PORTALS: Record<string, PortalDef> = { /** §1.4/§6 on-topic: home stat matches the Topic's stat, or an active Disambiguation-style Portal. */
spotlight: { export function isOnTopic(state: MatchState, card: CardInPlay): boolean {
id: 'spotlight', name: 'Spotlight', text: 'Cards here get +{amount}.', const lane = state.lanes[card.lane];
ongoing(ctx) { return ctx.params.amount ?? 1; }, return lane.topic.stat === card.card.home || activePortal(state, card.lane)?.allOnTopic === true;
}, }
paywall: {
id: 'paywall', name: 'Paywall', text: 'Only cards costing {maxCost} or less.', /** Filled in by engine-b (§10.2). Ids must be in KEYWORD_IDS. */
canPlay(ctx, card) { return card.cost <= (ctx.params.maxCost ?? 3); }, export const KEYWORDS: Record<string, KeywordDef> = {};
},
}; /** Filled in by engine-b (§10.3). Ids must be in PORTAL_IDS. */
export const PORTALS: Record<string, PortalDef> = {};
+45 -29
View File
@@ -5,7 +5,7 @@
* guarantee termination. * guarantee termination.
*/ */
import { z } from 'zod'; import { z } from 'zod';
import { KEYWORDS, PORTALS } from './keywords.ts'; import { KEYWORD_IDS, PORTAL_IDS } from './keywords.ts';
import { STATS, type Ruleset } from './types.ts'; import { STATS, type Ruleset } from './types.ts';
const int = (min: number, max: number) => z.number().int().min(min).max(max); const int = (min: number, max: number) => z.number().int().min(min).max(max);
@@ -15,7 +15,7 @@ const params = z.record(z.string().regex(/^[A-Za-z0-9]{1,24}$/), z.number().fini
const paramTable = z.record(id, params).refine(value => Object.keys(value).length <= 32, 'At most 32 entries'); const paramTable = z.record(id, params).refine(value => Object.keys(value).length <= 32, 'At most 32 entries');
export const TopicSchema = z.object({ export const TopicSchema = z.object({
id, name: z.string().min(1).max(32), stat: z.enum(STATS as [string, ...string[]]), portal: id.nullable(), id, name: z.string().min(1).max(32), stat: z.enum(STATS as [string, ...string[]]), portal: z.enum(PORTAL_IDS).nullable(),
}).strict(); }).strict();
export const RulesetSchema = z.object({ export const RulesetSchema = z.object({
@@ -30,34 +30,40 @@ export const RulesetSchema = z.object({
turnSeconds: int(5, 120), turnSeconds: int(5, 120),
afkTurns: int(1, 12), afkTurns: int(1, 12),
energyByTurn: z.array(int(0, 20)).min(1).max(12), energyByTurn: z.array(int(0, 20)).min(1).max(12),
energyCarryMax: int(0, 10),
bonusEnergy: int(0, 10), bonusEnergy: int(0, 10),
underdog: z.boolean(), underdog: z.boolean(),
topicCount: int(1, 5), topicCount: int(1, 5),
distinctStats: z.boolean(), distinctStats: z.boolean(),
revealSchedule: z.array(int(1, 12)).max(5), portalReveal: z.array(int(1, 12)).max(5),
laneCapacity: int(1, 8), laneCapacity: int(1, 8),
topicPool: z.array(TopicSchema).min(1).max(32), topicPool: z.array(TopicSchema).min(1).max(32),
keywordParams: paramTable,
portalParams: paramTable,
costThresholds: z.array(int(0, 100)).length(5), costThresholds: z.array(int(0, 100)).length(5),
powerByCost: z.array(int(0, 30)).length(7), powerByCost: z.array(int(0, 30)).length(7),
onTopicBonus: int(0, 10), onTopicBonus: z.array(int(0, 10)).length(7),
vanillaBonus: int(0, 10),
keywordsEnabled: z.array(z.enum(KEYWORD_IDS)).max(KEYWORD_IDS.length),
ownedCards: z.boolean(),
trendUp: z.number().finite().min(-1000).max(1000), trendUp: z.number().finite().min(-1000).max(1000),
trendDown: z.number().finite().min(-1000).max(1000), trendDown: z.number().finite().min(-1000).max(1000),
trendMinDaily: z.number().finite().min(0).max(1e9),
uncheckedCostCap: int(1, 6),
factionSynergyCap: int(0, 12), factionSynergyCap: int(0, 12),
verifyStats: z.boolean(), verifyStats: z.boolean(),
percentiles: id, percentiles: id,
starterDecks: id, starterDecks: id,
keywordParams: paramTable,
portalParams: paramTable,
}).strict().superRefine((rules, ctx) => { }).strict().superRefine((rules, ctx) => {
const issue = (message: string) => ctx.addIssue({ code: 'custom', message }); const issue = (message: string) => ctx.addIssue({ code: 'custom', message });
if (rules.turns * rules.turnSeconds > 240) issue('turns × turnSeconds must be ≤ 240'); if (rules.turns * rules.turnSeconds > 240) issue('turns × turnSeconds must be ≤ 240');
if (rules.energyByTurn.length < rules.turns) issue('energyByTurn needs one entry per turn'); if (rules.energyByTurn.length < rules.turns) issue('energyByTurn needs one entry per turn');
if (rules.revealSchedule.length !== rules.topicCount) issue('revealSchedule needs one entry per Topic'); if (rules.portalReveal.length !== rules.topicCount) issue('portalReveal needs one entry per Topic');
if (rules.openingHand > rules.handLimit) issue('openingHand > handLimit'); if (rules.openingHand > rules.handLimit) issue('openingHand > handLimit');
if (rules.trendDown > rules.trendUp) issue('trendDown > trendUp'); if (rules.trendDown > rules.trendUp) issue('trendDown > trendUp');
if (rules.costThresholds.some((value, i) => i > 0 && value < rules.costThresholds[i - 1])) issue('costThresholds must ascend'); if (rules.costThresholds.some((value, i) => i > 0 && value < rules.costThresholds[i - 1])) issue('costThresholds must ascend');
if (rules.distinctStats) { if (rules.distinctStats) {
if (rules.topicCount > STATS.length) issue('distinctStats allows at most 3 Topics'); if (rules.topicCount !== STATS.length) issue('distinctStats needs topicCount == 3');
const stats = new Set(rules.topicPool.map(topic => topic.stat)); const stats = new Set(rules.topicPool.map(topic => topic.stat));
if (stats.size < rules.topicCount) issue('topicPool lacks enough distinct stats'); if (stats.size < rules.topicCount) issue('topicPool lacks enough distinct stats');
} else if (rules.topicPool.length < rules.topicCount) issue('topicPool smaller than topicCount'); } else if (rules.topicPool.length < rules.topicCount) issue('topicPool smaller than topicCount');
@@ -65,10 +71,11 @@ export const RulesetSchema = z.object({
for (const topic of rules.topicPool) { for (const topic of rules.topicPool) {
if (topicIds.has(topic.id)) issue(`Duplicate topic id: ${topic.id}`); if (topicIds.has(topic.id)) issue(`Duplicate topic id: ${topic.id}`);
topicIds.add(topic.id); topicIds.add(topic.id);
if (topic.portal && !Object.hasOwn(PORTALS, topic.portal)) issue(`Unknown portal: ${topic.portal}`);
} }
for (const key of Object.keys(rules.keywordParams)) if (!Object.hasOwn(KEYWORDS, key)) issue(`Unknown keyword: ${key}`); if (new Set(rules.keywordsEnabled).size !== rules.keywordsEnabled.length) issue('Duplicate keywordsEnabled entry');
for (const key of Object.keys(rules.portalParams)) if (!Object.hasOwn(PORTALS, key)) issue(`Unknown portal: ${key}`); for (const key of Object.keys(rules.keywordParams)) if (!(KEYWORD_IDS as readonly string[]).includes(key)) issue(`Unknown keyword: ${key}`);
for (const key of Object.keys(rules.portalParams))
if (!topicIds.has(key) && !(PORTAL_IDS as readonly string[]).includes(key)) issue(`portalParams key is neither a Topic id nor a Portal id: ${key}`);
}); });
/** Validate untrusted ruleset JSON. Throws a ZodError with readable issues. */ /** Validate untrusted ruleset JSON. Throws a ZodError with readable issues. */
@@ -76,36 +83,45 @@ export function parseRuleset(input: unknown): Ruleset {
return RulesetSchema.parse(input) as Ruleset; return RulesetSchema.parse(input) as Ruleset;
} }
/** DESIGN §3: 9 Topics, each stat 3 times: one plain and two with Portals (portals are placeholders until §10.3). */ /** DESIGN §10.3 default Topic pool: per stat one plain Topic and two with Portals. Portal kind = Topic id. */
export const DEFAULT_TOPIC_POOL: Ruleset['topicPool'] = [ export const DEFAULT_TOPIC_POOL: Ruleset['topicPool'] = [
{ id: 'front-page', name: 'Front Page', stat: 'attention', portal: null }, { id: 'current-events', name: 'Current Events', stat: 'attention', portal: null },
{ id: 'trending', name: 'Trending', stat: 'attention', portal: 'spotlight' }, { id: 'main-page', name: 'Main Page', stat: 'attention', portal: 'main-page' },
{ id: 'viral', name: 'Viral', stat: 'attention', portal: 'paywall' }, { id: 'trending', name: 'Trending', stat: 'attention', portal: 'trending' },
{ id: 'deep-dive', name: 'Deep Dive', stat: 'depth', portal: null }, { id: 'archive', name: 'Archive', stat: 'depth', portal: null },
{ id: 'archive', name: 'Archive', stat: 'depth', portal: 'spotlight' }, { id: 'featured-article', name: 'Featured Article', stat: 'depth', portal: 'featured-article' },
{ id: 'citation-needed', name: 'Citation Needed', stat: 'depth', portal: 'paywall' }, { id: 'stub', name: 'Stub', stat: 'depth', portal: 'stub' },
{ id: 'world-tour', name: 'World Tour', stat: 'reach', portal: null }, { id: 'translations', name: 'Translations', stat: 'reach', portal: null },
{ id: 'translation', name: 'Translation', stat: 'reach', portal: 'spotlight' }, { id: 'interwiki', name: 'Interwiki', stat: 'reach', portal: 'interwiki' },
{ id: 'interwiki', name: 'Interwiki', stat: 'reach', portal: 'paywall' }, { id: 'disambiguation', name: 'Disambiguation', stat: 'reach', portal: 'disambiguation' },
]; ];
/** DESIGN §9 defaults. */ /** DESIGN §9 defaults (v1). */
export const DEFAULT_RULESET: Ruleset = { export const DEFAULT_RULESET: Ruleset = {
version: '1.0', version: '1.0',
deckSize: 12, maxCopiesPerPage: 2, maxLoaners: 12, deckSize: 12, maxCopiesPerPage: 2, maxLoaners: 12,
openingHand: 3, handLimit: 7, mulligan: false, openingHand: 3, handLimit: 7, mulligan: false,
turns: 6, turnSeconds: 25, afkTurns: 2, turns: 6, turnSeconds: 25, afkTurns: 2,
energyByTurn: [1, 2, 3, 4, 5, 6], bonusEnergy: 0, underdog: true, energyByTurn: [1, 2, 3, 4, 5, 6], energyCarryMax: 1, bonusEnergy: 0, underdog: false,
topicCount: 3, distinctStats: true, revealSchedule: [1, 2, 3], laneCapacity: 4, topicCount: 3, distinctStats: true, portalReveal: [2, 3, 4], laneCapacity: 3,
topicPool: DEFAULT_TOPIC_POOL, topicPool: DEFAULT_TOPIC_POOL,
keywordParams: {
viral: { amount: 1, cap: 2, powerDelta: 0 }, rising: { amount: 1, cap: 2, powerDelta: 0 },
local: { amount: 1, powerDelta: 0 }, encyclopedic: { amount: 2, powerDelta: 0 },
nostalgic: { amount: 2, powerDelta: 0 }, translated: { amount: 1, powerDelta: 0 },
edition: { amount: 2, powerDelta: 0 }, obscure: { powerDelta: 0 }, wildcard: { powerDelta: 0 },
},
portalParams: {
'main-page': { amount: 1 }, trending: { factor: 2 }, 'featured-article': { amount: 2 },
stub: { value: 2 }, interwiki: { amount: 1 },
},
costThresholds: [15, 35, 55, 75, 90], costThresholds: [15, 35, 55, 75, 90],
powerByCost: [0, 1, 2, 4, 5, 7, 9], powerByCost: [0, 1, 2, 4, 6, 8, 10],
onTopicBonus: 2, onTopicBonus: [0, 1, 1, 2, 2, 3, 3], vanillaBonus: 1,
trendUp: 25, trendDown: -25, keywordsEnabled: ['viral', 'rising', 'local', 'encyclopedic', 'nostalgic', 'translated'], ownedCards: true,
trendUp: 25, trendDown: -25, trendMinDaily: 20, uncheckedCostCap: 4,
factionSynergyCap: 3, factionSynergyCap: 3,
verifyStats: true, verifyStats: true,
percentiles: 'card-sample-2026-11-16', percentiles: 'card-sample-2026-11-16',
starterDecks: 'default', starterDecks: 'default',
keywordParams: { rally: { amount: 1 }, anchor: { amount: 2 } },
portalParams: { spotlight: { amount: 1 }, paywall: { maxCost: 3 } },
}; };
+37 -29
View File
@@ -7,41 +7,49 @@
import { Rng } from './rng.ts'; import { Rng } from './rng.ts';
import type { Faction, GameCard, Stat } from './types.ts'; import type { Faction, GameCard, Stat } from './types.ts';
type Spec = [pageId: number, title: string, faction: Faction, cost: number, home: Stat, keyword: string | null]; type Spec = [pageId: number, title: string, faction: Faction, cost: number, home: Stat];
/** Power follows DESIGN §1.3 powerByCost [0,1,2,4,5,7,9]. pageIds outside shared/catalog.ts are unverified. */ /** DESIGN §1.3 powerByCost and §10.1 keyword choice (cost 1 = vanilla +vanillaBonus). pageIds outside shared/catalog.ts are unverified. */
const POWER_BY_COST = [0, 1, 2, 4, 5, 7, 9]; const POWER_BY_COST = [0, 1, 2, 4, 6, 8, 10];
const VANILLA_BONUS = 1;
const FACTION_KEYWORD: Record<Faction, string> = {
Culture: 'viral', Nature: 'rising', People: 'local', Science: 'encyclopedic', History: 'nostalgic', Space: 'translated',
};
export const STARTER_POOL: readonly Spec[] = [ export const STARTER_POOL: readonly Spec[] = [
[22780, 'Octopus', 'Nature', 1, 'depth', null], [22780, 'Octopus', 'Nature', 1, 'depth'],
[19331, 'Moon', 'Space', 1, 'reach', 'anchor'], [19331, 'Moon', 'Space', 1, 'reach'],
[23053, 'Periodic table', 'Science', 1, 'depth', null], [23053, 'Periodic table', 'Science', 1, 'depth'],
[3383, 'Bronze Age', 'History', 1, 'depth', 'rally'], [3383, 'Bronze Age', 'History', 1, 'depth'],
[5843419, 'Chess', 'Culture', 2, 'attention', null], [5843419, 'Chess', 'Culture', 2, 'attention'],
[9228, 'Earth', 'Space', 2, 'reach', 'rally'], [9228, 'Earth', 'Space', 2, 'reach'],
[2008, 'Ada Lovelace', 'People', 2, 'attention', null], [2008, 'Ada Lovelace', 'People', 2, 'attention'],
[21830, 'Honey bee', 'Nature', 2, 'depth', 'anchor'], [21830, 'Honey bee', 'Nature', 2, 'depth'],
[736, 'Albert Einstein', 'People', 3, 'reach', null], [736, 'Albert Einstein', 'People', 3, 'reach'],
[10979, 'Fungus', 'Nature', 3, 'depth', 'rally'], [10979, 'Fungus', 'Nature', 3, 'depth'],
[26903, 'Solar System', 'Space', 3, 'reach', null], [26903, 'Solar System', 'Space', 3, 'reach'],
[30758, 'Roman Empire', 'History', 3, 'depth', 'anchor'], [30758, 'Roman Empire', 'History', 3, 'depth'],
[9649, 'Evolution', 'Science', 4, 'depth', null], [9649, 'Evolution', 'Science', 4, 'depth'],
[8424, 'Jazz', 'Culture', 4, 'attention', 'rally'], [8424, 'Jazz', 'Culture', 4, 'attention'],
[12898, 'Marie Curie', 'People', 4, 'reach', null], [12898, 'Marie Curie', 'People', 4, 'reach'],
[14533, 'Silk Road', 'History', 4, 'reach', 'anchor'], [14533, 'Silk Road', 'History', 4, 'reach'],
[19468, 'Mount Everest', 'Nature', 5, 'attention', null], [19468, 'Mount Everest', 'Nature', 5, 'attention'],
[22936, 'Photosynthesis', 'Science', 5, 'depth', 'rally'], [22936, 'Photosynthesis', 'Science', 5, 'depth'],
[18110, 'Leonardo da Vinci', 'People', 5, 'reach', null], [18110, 'Leonardo da Vinci', 'People', 5, 'reach'],
[14627, 'Ancient Egypt', 'History', 5, 'attention', 'anchor'], [14627, 'Ancient Egypt', 'History', 5, 'attention'],
[4177, 'Black hole', 'Space', 6, 'attention', null], [4177, 'Black hole', 'Space', 6, 'attention'],
[25443, 'Quantum mechanics', 'Science', 6, 'depth', 'rally'], [25443, 'Quantum mechanics', 'Science', 6, 'depth'],
[17867, 'Library of Alexandria', 'History', 6, 'depth', 'anchor'], [17867, 'Library of Alexandria', 'History', 6, 'depth'],
[20217, 'Music', 'Culture', 6, 'reach', null], [20217, 'Music', 'Culture', 6, 'reach'],
]; ];
export function loanerCard(spec: Spec, copy = 0): GameCard { export function loanerCard(spec: Spec, copy = 0): GameCard {
const [pageId, title, faction, cost, home, keyword] = spec; const [pageId, title, faction, cost, home] = spec;
return { cardId: `loaner:${pageId}:${copy}`, pageId, title, faction, rarity: 'Common', cost, power: POWER_BY_COST[cost], home, trend: 0, keyword, source: 'loaner' }; const keyword = cost === 1 ? null : FACTION_KEYWORD[faction];
return {
cardId: `loaner:${pageId}:${copy}`, pageId, title, faction, rarity: 'Common', cost,
power: POWER_BY_COST[cost] + (keyword ? 0 : VANILLA_BONUS), home, trend: 0, keyword, source: 'loaner', check: 'loaner',
};
} }
/** Every placeholder loaner card, once each (24 cards). Draft modes can sample from this. */ /** Every placeholder loaner card, once each (24 cards). Draft modes can sample from this. */
+35 -16
View File
@@ -37,6 +37,8 @@ export interface GameCard {
keyword: string | null; keyword: string | null;
/** 'owned' = an NFT the player holds (never moved or burned by a match). */ /** 'owned' = an NFT the player holds (never moved or burned by a match). */
source: 'owned' | 'loaner'; source: 'owned' | 'loaner';
/** Host plausibility result (§1.10). Derivation already applied uncheckedCostCap. Default: 'loaner' for loaners, 'verified' for owned. */
check?: 'verified' | 'unverified' | 'unchecked' | 'loaner';
} }
/** A Topic (lane) definition in a ruleset's topic pool (§3). */ /** A Topic (lane) definition in a ruleset's topic pool (§3). */
@@ -44,15 +46,13 @@ export interface TopicDef {
id: string; id: string;
name: string; name: string;
stat: Stat; stat: Stat;
/** Portal modifier id (§10.3), or null for a plain Topic. */ /** Portal kind id in PORTALS (§10.3), or null for a plain Topic. Numbers: Ruleset.portalParams[topic id] (falls back to [portal id]). */
portal: string | null; portal: string | null;
} }
/** /**
* DESIGN §9 RulesConfig: every rule number as flat data so peer-hosted modes can * DESIGN §9 RulesConfig: every rule number as flat data so peer-hosted modes can
* override it. Use parseRuleset() for untrusted input. * override it. Use parseRuleset() for untrusted input.
* Engine additions beyond §9: topicPool holds TopicDefs inline (not a name);
* keywordParams / portalParams hold tunable numbers per keyword / portal id.
*/ */
export interface Ruleset { export interface Ruleset {
version: string; version: string;
@@ -67,28 +67,39 @@ export interface Ruleset {
afkTurns: number; afkTurns: number;
/** energyByTurn[t-1] is the base energy on turn t. Length must be ≥ turns. */ /** energyByTurn[t-1] is the base energy on turn t. Length must be ≥ turns. */
energyByTurn: number[]; energyByTurn: number[];
/** Unspent energy carried to next turn, capped at this. */
energyCarryMax: number;
bonusEnergy: number; bonusEnergy: number;
underdog: boolean; underdog: boolean;
topicCount: number; topicCount: number;
distinctStats: boolean; distinctStats: boolean;
/** revealSchedule[i] = turn on which Topic i is revealed. Length = topicCount. */ /** portalReveal[i] = turn on which Topic i's Portal is revealed (stats are always visible). Length = topicCount. */
revealSchedule: number[]; portalReveal: number[];
laneCapacity: number; laneCapacity: number;
topicPool: TopicDef[]; topicPool: TopicDef[];
/** Per-keyword numbers, keyed by keyword id. */
keywordParams: Record<string, Record<string, number>>;
/** Per-Portal numbers, keyed by Topic id (or Portal kind id as a fallback). */
portalParams: Record<string, Record<string, number>>;
costThresholds: number[]; costThresholds: number[];
/** Index = cost (0–6). */ /** Index = cost (0–6). */
powerByCost: number[]; powerByCost: number[];
onTopicBonus: number; /** Index = cost (0–6): on-topic bonus. */
onTopicBonus: number[];
vanillaBonus: number;
/** Keyword ids whose hooks run. Cards with a disabled keyword are vanilla (derivation handles power). */
keywordsEnabled: string[];
ownedCards: boolean;
trendUp: number; trendUp: number;
trendDown: number; trendDown: number;
trendMinDaily: number;
uncheckedCostCap: number;
factionSynergyCap: number; factionSynergyCap: number;
verifyStats: boolean; verifyStats: boolean;
/** Id of the percentile reference table used by cards.ts. */ /** Id of the percentile reference table used by derive.ts. */
percentiles: string; percentiles: string;
/** Id of the starter deck list used by cards.ts. */ /** Id of the starter deck list. */
starterDecks: string; starterDecks: string;
keywordParams: Record<string, Record<string, number>>;
portalParams: Record<string, Record<string, number>>;
} }
export interface CardInPlay { export interface CardInPlay {
@@ -97,6 +108,8 @@ export interface CardInPlay {
lane: number; lane: number;
/** Turn the card was revealed. */ /** Turn the card was revealed. */
turn: number; turn: number;
/** Global reveal sequence number (1, 2, 3 … across both seats and all turns). */
seq: number;
/** Permanent power changes from effects (on-reveal buffs etc.). */ /** Permanent power changes from effects (on-reveal buffs etc.). */
bonus: number; bonus: number;
} }
@@ -113,11 +126,14 @@ export interface PlayerState {
committed: boolean; committed: boolean;
/** Consecutive timeouts with nothing queued (§7 afkTurns). */ /** Consecutive timeouts with nothing queued (§7 afkTurns). */
afk: number; afk: number;
/** Energy carried into this turn (already included in `energy`). */
carry: number;
} }
export interface LaneState { export interface LaneState {
/** Stat and name are always visible; the Portal only once portalRevealed. */
topic: TopicDef; topic: TopicDef;
revealed: boolean; portalRevealed: boolean;
cards: [CardInPlay[], CardInPlay[]]; cards: [CardInPlay[], CardInPlay[]];
} }
@@ -125,7 +141,7 @@ export type MatchPhase = 'planning' | 'over';
export type LogEvent = export type LogEvent =
| { t: 'turnStart'; turn: number; energy: [number, number]; initiative: PlayerId } | { t: 'turnStart'; turn: number; energy: [number, number]; initiative: PlayerId }
| { t: 'topicRevealed'; lane: number; topic: TopicDef } | { t: 'portalRevealed'; lane: number; topic: TopicDef }
| { t: 'underdog'; player: PlayerId } | { t: 'underdog'; player: PlayerId }
| { t: 'draw'; player: PlayerId; cardId: string } | { t: 'draw'; player: PlayerId; cardId: string }
| { t: 'reveal'; player: PlayerId; cardId: string; lane: number } | { t: 'reveal'; player: PlayerId; cardId: string; lane: number }
@@ -143,8 +159,10 @@ export interface MatchState {
/** 1-based current turn. */ /** 1-based current turn. */
turn: number; turn: number;
phase: MatchPhase; phase: MatchPhase;
/** Player who reveals first this turn (§5.4). */ /** Player who reveals first this turn (§5.4). Alternates every turn. */
initiative: PlayerId; initiative: PlayerId;
/** Last reveal sequence number handed out (CardInPlay.seq). */
revealSeq: number;
players: [PlayerState, PlayerState]; players: [PlayerState, PlayerState];
lanes: LaneState[]; lanes: LaneState[];
log: LogEvent[]; log: LogEvent[];
@@ -169,7 +187,7 @@ export interface MatchResult {
winner: PlayerId | null; winner: PlayerId | null;
reason: 'topics' | 'totalPower' | 'draw' | 'concede' | 'afk'; reason: 'topics' | 'totalPower' | 'draw' | 'concede' | 'afk';
topicsLed: [number, number]; topicsLed: [number, number];
/** lanePower[lane][player] at the end. */ /** lanePower[lane][player] at the end, including "at scoring" Portals. */
lanePower: [number, number][]; lanePower: [number, number][];
totalPower: [number, number]; totalPower: [number, number];
turns: number; turns: number;
@@ -191,8 +209,9 @@ export interface PlayerView {
deckCount: number; deckCount: number;
opponent: { handCount: number; deckCount: number; queuedCount: number; committed: boolean }; opponent: { handCount: number; deckCount: number; queuedCount: number; committed: boolean };
lanes: { lanes: {
/** null while face-down. */ /** Always visible; `portal` is null until the Portal is revealed. */
topic: TopicDef | null; topic: TopicDef;
portalRevealed: boolean;
/** cards[0] = yours, cards[1] = opponent's (revealed cards only). */ /** cards[0] = yours, cards[1] = opponent's (revealed cards only). */
cards: [CardInPlay[], CardInPlay[]]; cards: [CardInPlay[], CardInPlay[]];
/** Lane power of each card in `cards`, same shape. */ /** Lane power of each card in `cards`, same shape. */
+120 -62
View File
@@ -1,16 +1,27 @@
// Core-loop tests owned by engine-a. Keyword, property and golden tests: engine-b (tests/game-*.test.ts). // Core-loop tests owned by engine-a. Keyword/Portal, derivation, property and golden tests: engine-b (tests/game-*.test.ts).
import test from 'node:test'; import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { import {
DEFAULT_RULESET, IllegalActionError, Rng, applyAction, cardPower, createMatch, deserialize, isOver, legalActions, DEFAULT_RULESET, IllegalActionError, KEYWORDS, PORTALS, Rng, applyAction, cardPower, createMatch, deserialize, isOver,
loanerCard, parseRuleset, placeCard, replay, result, revealTopic, serialize, starterDeck, STARTER_POOL, topicsLed, viewFor, laneLeader, legalActions, loanerCard, parseRuleset, placeCard, replay, result, revealPortal, serialize, starterDeck,
type Action, type GameCard, type MatchState, type PlayerId, type Ruleset, STARTER_POOL, viewFor, type Action, type GameCard, type KeywordDef, type MatchState, type PlayerId, type PortalDef, type Ruleset,
} from '../shared/game/index.ts'; } from '../shared/game/index.ts';
const decks = (seed = 'd'): [GameCard[], GameCard[]] => [starterDeck(`${seed}-a`), starterDeck(`${seed}-b`)]; const decks = (seed = 'd'): [GameCard[], GameCard[]] => [starterDeck(`${seed}-a`), starterDeck(`${seed}-b`)];
const commitBoth = (s: MatchState) => applyAction(applyAction(s, { type: 'commit', player: 0 }), { type: 'commit', player: 1 }); const commit = (s: MatchState, player: PlayerId) => applyAction(s, { type: 'commit', player });
const vanilla = (cost: number, overrides: Partial<GameCard> = {}): GameCard => const commitBoth = (s: MatchState) => commit(commit(s, 0), 1);
({ ...loanerCard(STARTER_POOL.find(s => s[3] === cost && s[5] === null)!), keyword: null, ...overrides }); const card = (cost: number, overrides: Partial<GameCard> = {}): GameCard =>
({ ...loanerCard(STARTER_POOL.find(s => s[3] === cost)!), keyword: null, trend: 0, ...overrides });
/** A deck whose every card costs `cost`, so the first plays are predictable. */
const flatDeck = (cost: number, prefix: string, home: GameCard['home'] = 'depth'): GameCard[] =>
Array.from({ length: 12 }, (_, i) => card(cost, { cardId: `${prefix}${i}`, pageId: 1000 + Math.floor(i / 2), home }));
/** Temporarily register a keyword/portal implementation under a v1 id. */
function withHook<T>(registry: Record<string, T>, id: string, def: T, run: () => void) {
const saved = registry[id];
registry[id] = def;
try { run(); } finally { if (saved === undefined) delete registry[id]; else registry[id] = saved; }
}
function randomPlay(seed: number, ruleset: Ruleset = DEFAULT_RULESET): MatchState { function randomPlay(seed: number, ruleset: Ruleset = DEFAULT_RULESET): MatchState {
let state = createMatch(ruleset, decks(String(seed)), seed); let state = createMatch(ruleset, decks(String(seed)), seed);
@@ -20,12 +31,12 @@ function randomPlay(seed: number, ruleset: Ruleset = DEFAULT_RULESET): MatchStat
const player = chooser.int(2) as PlayerId; const player = chooser.int(2) as PlayerId;
const actions = legalActions(state, player); const actions = legalActions(state, player);
if (actions.length) state = applyAction(state, chooser.pick(actions)); if (actions.length) state = applyAction(state, chooser.pick(actions));
assert.deepEqual(deserialize(serialize(state)), state);
} }
return state; return state;
} }
test('mulberry32 matches the reference sequence and is seed-deterministic', () => { test('mulberry32 matches the reference value and is seed-deterministic', () => {
// Reference: mulberry32(1) first output = 0.6270739405881613.
assert.equal(new Rng(1).next(), 0.6270739405881613); assert.equal(new Rng(1).next(), 0.6270739405881613);
const seq = (r: Rng) => Array.from({ length: 8 }, () => r.next()); const seq = (r: Rng) => Array.from({ length: 8 }, () => r.next());
assert.deepEqual(seq(Rng.fromSeed(42)), seq(Rng.fromSeed(42))); assert.deepEqual(seq(Rng.fromSeed(42)), seq(Rng.fromSeed(42)));
@@ -35,31 +46,43 @@ test('mulberry32 matches the reference sequence and is seed-deterministic', () =
test('DEFAULT_RULESET matches DESIGN §9 and parses; bad rulesets are rejected', () => { test('DEFAULT_RULESET matches DESIGN §9 and parses; bad rulesets are rejected', () => {
assert.deepEqual(parseRuleset(DEFAULT_RULESET), DEFAULT_RULESET); assert.deepEqual(parseRuleset(DEFAULT_RULESET), DEFAULT_RULESET);
assert.equal(DEFAULT_RULESET.turns, 6); assert.equal(DEFAULT_RULESET.laneCapacity, 3);
assert.deepEqual(DEFAULT_RULESET.powerByCost, [0, 1, 2, 4, 5, 7, 9]); assert.deepEqual(DEFAULT_RULESET.powerByCost, [0, 1, 2, 4, 6, 8, 10]);
for (const bad of [{ turns: 13 }, { turnSeconds: 60 }, { energyByTurn: [1, 2] }, { revealSchedule: [1, 2] }, assert.deepEqual(DEFAULT_RULESET.onTopicBonus, [0, 1, 1, 2, 2, 3, 3]);
{ keywordParams: { nope: {} } }, { extra: 1 }, { mulligan: true }, { costThresholds: [90, 1, 2, 3, 4] }]) assert.equal(DEFAULT_RULESET.topicPool.length, 9);
for (const bad of [{ turns: 13 }, { turnSeconds: 60 }, { energyByTurn: [1, 2] }, { portalReveal: [1, 2] },
{ keywordParams: { nope: {} } }, { keywordsEnabled: ['nope'] }, { extra: 1 }, { mulligan: true },
{ costThresholds: [90, 1, 2, 3, 4] }, { onTopicBonus: 2 }, { topicCount: 2 }, { portalParams: { nope: {} } }])
assert.throws(() => parseRuleset({ ...DEFAULT_RULESET, ...bad }), JSON.stringify(bad)); assert.throws(() => parseRuleset({ ...DEFAULT_RULESET, ...bad }), JSON.stringify(bad));
}); });
test('setup: one Topic per stat, all face-down except Topic 1 on turn 1, hands of 4, energy 1', () => { test('setup: one Topic per stat, stats visible, Portals hidden until portalReveal, hands of 4, energy 1', () => {
const state = createMatch(DEFAULT_RULESET, decks(), 7); const state = createMatch(DEFAULT_RULESET, decks(), 7);
assert.equal(state.turn, 1); assert.equal(state.turn, 1);
assert.deepEqual(state.lanes.map(l => l.topic.stat).sort(), ['attention', 'depth', 'reach']); assert.deepEqual(state.lanes.map(l => l.topic.stat).sort(), ['attention', 'depth', 'reach']);
assert.deepEqual(state.lanes.map(l => l.revealed), [true, false, false]); assert.deepEqual(state.lanes.map(l => l.portalRevealed), [false, false, false]);
for (const p of state.players) { assert.equal(p.hand.length, 4); assert.equal(p.deck.length, 8); assert.equal(p.energy, 1); } for (const p of state.players) { assert.equal(p.hand.length, 4); assert.equal(p.deck.length, 8); assert.equal(p.energy, 1); }
assert.deepEqual(viewFor(state, 0).lanes.map(l => l.topic === null), [false, true, true]); const view = viewFor(state, 0);
assert.deepEqual(view.lanes.map(l => l.topic.stat), state.lanes.map(l => l.topic.stat));
assert.ok(view.lanes.every(l => l.topic.portal === null && l.topic.name === '?'));
let next = commitBoth(state);
assert.deepEqual(next.lanes.map(l => l.portalRevealed), [true, false, false]);
next = commitBoth(commitBoth(next));
assert.deepEqual(next.lanes.map(l => l.portalRevealed), [true, true, true]);
}); });
test('decks are validated: size, copies per page, unknown keyword', () => { test('decks are validated: size, copies per page, keyword ids, ownedCards', () => {
const [a, b] = decks(); const [a, b] = decks();
assert.throws(() => createMatch(DEFAULT_RULESET, [a.slice(0, 11), b], 1), IllegalActionError); assert.throws(() => createMatch(DEFAULT_RULESET, [a.slice(0, 11), b], 1), IllegalActionError);
const triple = [...a.slice(0, 9), ...[0, 1, 2].map(n => ({ ...a[0], cardId: `x${n}` }))]; const triple = [...a.slice(0, 9), ...[0, 1, 2].map(n => ({ ...a[0], cardId: `x${n}` }))];
assert.throws(() => createMatch(DEFAULT_RULESET, [triple, b], 1), /copies/); assert.throws(() => createMatch(DEFAULT_RULESET, [triple, b], 1), /copies/);
assert.throws(() => createMatch(DEFAULT_RULESET, [[{ ...a[0], keyword: 'nope' }, ...a.slice(1)], b], 1), /unknown keyword/); assert.throws(() => createMatch(DEFAULT_RULESET, [[{ ...a[0], keyword: 'nope' }, ...a.slice(1)], b], 1), /unknown keyword/);
const owned = [{ ...a[0], source: 'owned' as const }, ...a.slice(1)];
assert.doesNotThrow(() => createMatch(DEFAULT_RULESET, [owned, b], 1));
assert.throws(() => createMatch({ ...DEFAULT_RULESET, ownedCards: false }, [owned, b], 1), /owned/);
}); });
test('queued plays are hidden from the opponent until reveal; undo refunds', () => { test('queued plays are hidden until reveal; undo refunds; committed seats get no actions', () => {
let state = createMatch(DEFAULT_RULESET, decks(), 11); let state = createMatch(DEFAULT_RULESET, decks(), 11);
const play = legalActions(state, 0).find(a => a.type === 'play') as Extract<Action, { type: 'play' }>; const play = legalActions(state, 0).find(a => a.type === 'play') as Extract<Action, { type: 'play' }>;
assert.ok(play, 'turn 1 should have a 1-cost play'); assert.ok(play, 'turn 1 should have a 1-cost play');
@@ -67,59 +90,94 @@ test('queued plays are hidden from the opponent until reveal; undo refunds', ()
assert.equal(viewFor(state, 0).energyLeft, 0); assert.equal(viewFor(state, 0).energyLeft, 0);
assert.equal(viewFor(state, 1).opponent.queuedCount, 1); assert.equal(viewFor(state, 1).opponent.queuedCount, 1);
assert.equal(JSON.stringify(viewFor(state, 1)).includes(`"${play.cardId}"`), false); assert.equal(JSON.stringify(viewFor(state, 1)).includes(`"${play.cardId}"`), false);
const undone = applyAction(state, { type: 'undo', player: 0, cardId: play.cardId }); assert.equal(viewFor(applyAction(state, { type: 'undo', player: 0, cardId: play.cardId }), 0).energyLeft, 1);
assert.equal(viewFor(undone, 0).energyLeft, 1); state = commit(state, 0);
state = commitBoth(state); assert.deepEqual(legalActions(state, 0), []);
state = commit(state, 1);
assert.equal(state.turn, 2); assert.equal(state.turn, 2);
assert.equal(viewFor(state, 1).lanes[play.lane].cards[1][0].card.cardId, play.cardId); assert.equal(viewFor(state, 1).lanes[play.lane].cards[1][0].card.cardId, play.cardId);
assert.throws(() => applyAction(state, { type: 'play', player: 0, cardId: play.cardId, lane: 0 }), IllegalActionError); assert.throws(() => applyAction(state, { type: 'play', player: 0, cardId: play.cardId, lane: 0 }), IllegalActionError);
}); });
test('energy cap and lane capacity are enforced when queuing', () => { test('energy: energyByTurn + carry (max 1) of unspent energy', () => {
const state = createMatch(DEFAULT_RULESET, decks(), 3); let state = createMatch(DEFAULT_RULESET, [flatDeck(1, 'a'), flatDeck(1, 'b')], 3);
for (const a of legalActions(state, 0)) if (a.type === 'play') assert.ok(state.players[0].hand.find(c => c.cardId === a.cardId)!.cost <= 1); const first = state.players[0].hand[0].cardId;
let full = state; state = applyAction(state, { type: 'play', player: 0, cardId: first, lane: 0 }); // p0 spends 1, p1 saves 1
for (let i = 0; i < 4; i++) full = placeCard(full, 0, 0, vanilla(1, { cardId: `f${i}` }));
assert.ok(legalActions(full, 0).every(a => a.type !== 'play' || a.lane !== 0));
});
test('lane power: base + on-topic bonus (revealed only) + trend, floored at 0', () => {
let state = createMatch(DEFAULT_RULESET, decks(), 5);
const lane = 1; // face-down on turn 1
const stat = state.lanes[lane].topic.stat;
state = placeCard(state, 0, lane, vanilla(3, { cardId: 'on', home: stat, trend: 1 }));
const card = () => state.lanes[lane].cards[0][0];
assert.equal(cardPower(state, card()), 4 + 1);
state = revealTopic(state, lane);
assert.equal(cardPower(state, card()), 4 + 2 + 1);
state = placeCard(state, 1, lane, vanilla(1, { cardId: 'neg', home: stat === 'depth' ? 'reach' : 'depth', trend: -1, power: 0 }));
assert.equal(cardPower(state, state.lanes[lane].cards[1][0]), 0);
});
test('initiative: leader reveals first next turn; even board alternates', () => {
let state = createMatch(DEFAULT_RULESET, decks(), 9);
const first = state.initiative;
state = commitBoth(state); // nobody played: even
assert.equal(state.initiative, first === 0 ? 1 : 0);
});
test('underdog: +1 energy for a player leading 0 Topics while the opponent leads 2+', () => {
let state = createMatch(DEFAULT_RULESET, decks(), 13);
state = placeCard(state, 1, 0, vanilla(1, { cardId: 'u1' }));
state = placeCard(state, 1, 1, vanilla(1, { cardId: 'u2' }));
state = commitBoth(state); state = commitBoth(state);
assert.deepEqual(topicsLed(state), [0, 2]); assert.deepEqual(state.players.map(p => p.energy), [2, 3]);
assert.equal(state.players[0].energy, 3); state = commitBoth(state); // both save everything; carry is capped at 1
assert.equal(state.players[1].energy, 2); assert.deepEqual(state.players.map(p => p.energy), [4, 4]);
});
test('reveal is interleaved: initiative 1st, other 1st, initiative 2nd, …; initiative alternates', () => {
let state = createMatch(DEFAULT_RULESET, [flatDeck(1, 'a'), flatDeck(1, 'b')], 5);
state = commitBoth(state); // turn 2: 3 energy each (2 + carry 1)
const init = state.initiative;
const ids = (p: PlayerId) => state.players[p].hand.slice(0, 3).map(c => c.cardId);
const [mine, theirs] = [ids(init), ids(init === 0 ? 1 : 0)];
for (const [player, cards] of [[init, mine], [init === 0 ? 1 : 0, theirs.slice(0, 2)]] as const)
cards.forEach((cardId, lane) => { state = applyAction(state, { type: 'play', player, cardId, lane }); });
const before = state.log.length;
state = commitBoth(state);
const order = state.log.slice(before).filter(e => e.t === 'reveal').map(e => (e as { cardId: string }).cardId);
assert.deepEqual(order, [mine[0], theirs[0], mine[1], theirs[1], mine[2]]);
assert.equal(state.initiative, init === 0 ? 1 : 0);
assert.deepEqual(state.lanes.flatMap(l => [...l.cards[0], ...l.cards[1]]).map(c => c.seq).sort((x, y) => x - y), [1, 2, 3, 4, 5]);
});
test('lane power: base + onTopicBonus[cost] + trend, floored at 0', () => {
let state = createMatch(DEFAULT_RULESET, decks(), 5);
const stat = state.lanes[1].topic.stat;
const off = stat === 'depth' ? 'reach' : 'depth';
state = placeCard(state, 0, 1, card(5, { cardId: 'on', home: stat, trend: 1 }));
assert.equal(cardPower(state, state.lanes[1].cards[0][0]), 8 + 3 + 1);
state = placeCard(state, 0, 1, card(2, { cardId: 'off', home: off }));
assert.equal(cardPower(state, state.lanes[1].cards[0][1]), 2);
state = placeCard(state, 1, 1, card(1, { cardId: 'neg', home: off, trend: -1, power: 0 }));
assert.equal(cardPower(state, state.lanes[1].cards[1][0]), 0);
});
test('consensus tie-break: equal power > 0 goes to more on-topic cards; 0–0 has no leader', () => {
let state = createMatch(DEFAULT_RULESET, decks(), 8);
const stat = state.lanes[0].topic.stat;
const off = stat === 'depth' ? 'reach' : 'depth';
assert.equal(laneLeader(state, 0), null);
state = placeCard(state, 0, 0, card(2, { cardId: 'a', home: stat, power: 1 })); // 1 + 1 on-topic = 2
state = placeCard(state, 1, 0, card(2, { cardId: 'b', home: off, power: 2 })); // 2 off-topic
assert.equal(laneLeader(state, 0), 0);
state = placeCard(state, 1, 0, card(1, { cardId: 'c', home: stat, power: 0 })); // +1 on-topic: 3 vs 2
assert.equal(laneLeader(state, 0), 1);
});
test('Portals: capacity override and fizzle at reveal, at-scoring bonus, disabled keywords do not run', () => {
const stub: PortalDef = { id: 'stub', name: 'Stub', text: '', capacity: ctx => ctx.params.value ?? 2 };
const mainPage: PortalDef = { id: 'main-page', name: 'Main Page', text: '', atScoring: ctx => [0, 1].map(p => ctx.state.lanes[ctx.lane].cards[p].length * (ctx.params.amount ?? 1)) as [number, number] };
const bump: KeywordDef = { id: 'rising', name: 'Rising', text: '', onReveal: (_ctx, self) => { self.bonus += 5; } };
withHook(PORTALS, 'stub', stub, () => withHook(PORTALS, 'main-page', mainPage, () => withHook(KEYWORDS, 'rising', bump, () => {
let state = createMatch(DEFAULT_RULESET, [flatDeck(1, 'a'), flatDeck(1, 'b')], 2);
state.lanes[0].topic = { id: 'stub', name: 'Stub', stat: 'depth', portal: 'stub' };
state.lanes[1].topic = { id: 'main-page', name: 'Main Page', stat: 'attention', portal: 'main-page' };
state = revealPortal(revealPortal(state, 0), 1);
state = placeCard(placeCard(state, 0, 0, card(1, { cardId: 'p1' })), 0, 0, card(1, { cardId: 'p2' }));
assert.ok(legalActions(state, 0).every(a => a.type !== 'play' || a.lane !== 0), 'Stub holds 2');
state = placeCard(state, 1, 1, card(2, { cardId: 'r', keyword: 'rising' }));
state.ruleset.keywordsEnabled = [];
const hand = state.players[1].hand[0];
state = applyAction(state, { type: 'play', player: 1, cardId: hand.cardId, lane: 1 });
state.players[1].hand[0] = { ...hand, keyword: 'rising' }; // disabled: no +5
while (!isOver(state)) state = commitBoth(state);
const r = result(state)!;
assert.equal(r.lanePower[1][1], cardPower(state, state.lanes[1].cards[1][0]) + cardPower(state, state.lanes[1].cards[1][1]) + 2);
assert.ok(state.lanes[1].cards[1].every(c => c.bonus === 0));
})));
}); });
test('timeouts with nothing queued concede after afkTurns; concede ends the match', () => { test('timeouts with nothing queued concede after afkTurns; concede ends the match', () => {
let state = createMatch(DEFAULT_RULESET, decks(), 17); let state = createMatch(DEFAULT_RULESET, decks(), 17);
state = applyAction(applyAction(state, { type: 'timeout', player: 0 }), { type: 'commit', player: 1 }); state = commit(applyAction(state, { type: 'timeout', player: 0 }), 1);
assert.equal(isOver(state), false); assert.equal(isOver(state), false);
state = applyAction(state, { type: 'timeout', player: 0 }); state = applyAction(state, { type: 'timeout', player: 0 });
assert.equal(result(state)?.winner, 1); assert.deepEqual([result(state)?.winner, result(state)?.reason], [1, 'afk']);
assert.equal(result(state)?.reason, 'afk');
const conceded = applyAction(createMatch(DEFAULT_RULESET, decks(), 1), { type: 'concede', player: 1 }); const conceded = applyAction(createMatch(DEFAULT_RULESET, decks(), 1), { type: 'concede', player: 1 });
assert.equal(result(conceded)?.winner, 0); assert.equal(result(conceded)?.winner, 0);
assert.deepEqual(legalActions(conceded, 0), []); assert.deepEqual(legalActions(conceded, 0), []);
@@ -128,15 +186,15 @@ test('timeouts with nothing queued concede after afkTurns; concede ends the matc
test('two passing players draw after 6 turns', () => { test('two passing players draw after 6 turns', () => {
let state = createMatch(DEFAULT_RULESET, decks(), 21); let state = createMatch(DEFAULT_RULESET, decks(), 21);
while (!isOver(state)) state = commitBoth(state); while (!isOver(state)) state = commitBoth(state);
assert.deepEqual({ winner: result(state)!.winner, reason: result(state)!.reason, turns: result(state)!.turns }, { winner: null, reason: 'draw', turns: 6 }); const r = result(state)!;
assert.deepEqual([r.winner, r.reason, r.turns], [null, 'draw', 6]);
}); });
test('random legal play terminates, replays exactly, and survives serialisation after every action', () => { test('random legal play terminates, replays exactly, and survives serialisation after every action', () => {
for (let seed = 0; seed < 30; seed++) { for (let seed = 0; seed < 20; seed++) {
const end = randomPlay(seed); const end = randomPlay(seed);
assert.ok(result(end)!.turns <= DEFAULT_RULESET.turns); assert.ok(result(end)!.turns <= DEFAULT_RULESET.turns);
assert.deepEqual(randomPlay(seed), end); assert.deepEqual(randomPlay(seed), end);
assert.deepEqual(replay(DEFAULT_RULESET, decks(String(seed)), seed, end.actions), end); assert.deepEqual(replay(DEFAULT_RULESET, decks(String(seed)), seed, end.actions), end);
assert.deepEqual(deserialize(serialize(end)), end);
} }
}); });