forked from WikiDeck/wikideck
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c938407d36 | ||
|
|
e0ac157ee1 | ||
|
|
ec24437838 | ||
|
|
f3b6097640 | ||
|
|
7c86ed35f5 |
@@ -1,518 +0,0 @@
|
||||
# WikiDeck: Edit War — game design v1 (draft)
|
||||
|
||||
**Status:** v1 DRAFT, freeze target 23:30 EST 2026-11-16.
|
||||
**Owners:** council-designer-a owns sections 0–9 (research, card derivation, rules). council-designer-b
|
||||
owns sections 10–12 (keywords, peer-hosted modes, worked example). council-critic reviews.
|
||||
Every number in **`code font`** is a rules-config key (see §9). Modes can override any of them.
|
||||
|
||||
A two-player lane game for 3–6 minute matches. Each player has a 12-card deck and there are 3
|
||||
**Topics** (lanes) with 3 slots per side. There are 6 turns, both players plan at the same time, and
|
||||
energy ramps from 1 to 6, with 1 unspent energy carried over. Reveals interleave one card at a time.
|
||||
Win 2 of the 3 Topics. Each Topic is judged on one Wikipedia stat (**Attention**, **Depth** or
|
||||
**Reach**), and a card is stronger in a Topic that matches its best stat. Fame (how high a card's
|
||||
stats are overall) sets its **cost**, not its efficiency, so famous cards are sidegrades. They are
|
||||
not upgrades.
|
||||
|
||||
---
|
||||
|
||||
## 0. Research summary (what we took, what we left)
|
||||
|
||||
| Game | Why it's fun | Taken | Left |
|
||||
|---|---|---|---|
|
||||
| Marvel Snap | 3-minute matches; simultaneous turns; 3 lanes, so the decision is *where*, not just *what* | lanes, about 6 turns, simultaneous planning, small deck | stakes betting (modes only); we deliberately diverge in lane size (3), energy carry-over, interleaved alternating reveals, stats visible from turn 1 with hidden Portals, and on-topic tie-breaks |
|
||||
| Hearthstone | mana curve; readable cards; tempo | energy = turn number, curve-shaped costs | 30-card decks and 15-minute matches; hero powers |
|
||||
| Magic: The Gathering | factions (colours) with distinct identities; deckbuilding depth | 6 factions with their own keyword flavour | land screw (resource variance); the stack; long text |
|
||||
| Balatro | huge "moment" when a combo goes off; simple base rules plus modifiers | lane modifiers (Portals) as the run-to-run variety | single-player scoring |
|
||||
| Slay the Spire | readable intents; every card is a choice | open information about lane state and power | roguelike runs (could be a mode) |
|
||||
| Gwent | rows; best 2 of 3; passing and bluffing | best 2 of 3 Topics; hidden commitments | multi-round card advantage (too long) |
|
||||
| Pokémon TCG | type advantage | on-topic bonus (card stat matches lane stat) | energy attachment; coin flips |
|
||||
| Top Trumps | instantly understood: "my number beats yours" | lanes judged on one stat | picking the stat is solved play (always pick your best) |
|
||||
| Dominion | deck building as play | — (too long for 3–6 min) | — |
|
||||
|
||||
**What is ours, not borrowed:**
|
||||
- (a) each Topic is judged on one Wikipedia stat (the Top Trumps twist)
|
||||
- (b) cost comes from an article's fame instead of being printed
|
||||
- (c) a trend arrow driven by live pageviews
|
||||
- (d) a total-power and consensus tie-break instead of stakes betting
|
||||
- smaller choices: 3 slots per lane, 1 carried-over energy, interleaved reveals, and stats visible
|
||||
from turn 1 with hidden Portals
|
||||
|
||||
The core loop is a lanes game in the style of Snap. The Top Trumps twist is that each lane asks for
|
||||
one Wikipedia stat. That makes every stat matter and gives each turn its main decision: play the card
|
||||
on-topic for the bonus, or put it where the fight is.
|
||||
|
||||
---
|
||||
|
||||
## 1. Card derivation (card data → game card)
|
||||
|
||||
The engine never reads raw 0–100 stats as power. Every game card is derived **deterministically** from a
|
||||
`CardInput` that the match host freezes at match start:
|
||||
|
||||
```
|
||||
CardInput = { cardId, pageId, title, category, rarity,
|
||||
snapshot: MintStatsSnapshot, // at mint, immutable
|
||||
live: { trendPercent: number | null, dailyAverage: number | null }, // frozen at match start
|
||||
check: 'verified' | 'unverified' | 'unchecked' | 'loaner' } // set by the host (§1.10)
|
||||
```
|
||||
|
||||
### 1.1 Percentiles (rank-normalisation)
|
||||
For each stat `s` in {attention, depth, reach}, `pct_s` = the percentile (0–100, integer) of the card's
|
||||
snapshot score in the reference table `percentiles.<s>`. That table holds 99 ascending cut points from
|
||||
council-data's `docs/game/card-sample.json`.
|
||||
`pct_s` = the number of cut points strictly below the score, plus half the number equal to it, rounded
|
||||
down. A `null` attention gives `pct_attention = null`.
|
||||
|
||||
### 1.2 Fame → Cost
|
||||
`fame` = the integer mean (rounded half up) of the non-null percentiles.
|
||||
`cost` = 1 + the number of thresholds in `costThresholds` (5 ascending values, default
|
||||
`[15, 35, 55, 75, 90]`) that are ≤ `fame`. So cost runs 1–6.
|
||||
The defaults aim at a pool cost spread of about 15/20/20/20/15/10 %. They are retuned from the
|
||||
sample's fame distribution.
|
||||
|
||||
### 1.3 Power
|
||||
`power` = `powerByCost[cost]`, default `[_, 1, 2, 4, 6, 8, 10]` (cost 1 → 1 … cost 6 → 10). The
|
||||
critic's sim showed that heavy decks were too weak with `[…5,7,9]`.
|
||||
Power depends **only on cost**. Two cards of the same cost have the same base power, whatever their
|
||||
fame. Inflating stats (forged snapshots, template shopping) only moves a card up the curve. It never
|
||||
makes a card more efficient.
|
||||
|
||||
### 1.4 Home stat
|
||||
`home` = the stat with the highest `pct_s`. Ties are broken in this order: depth, reach, attention.
|
||||
Depth and reach are the hardest to inflate. A `null` stat can never be home.
|
||||
When a card is in a Topic whose stat equals its `home`, it gets **+`onTopicBonus[cost]`** power
|
||||
(default `[0, 1, 1, 2, 2, 3, 3]`, i.e. ⌈cost/2⌉).
|
||||
On-topic efficiency is then about 2 power per energy at every cost (2.0 / 1.5 / 2.0 / 1.75 / 2.0 / 2.0).
|
||||
Off-topic, cheap cards are weaker (1.0) than expensive ones (1.5). Cheap cards want their Topic, and
|
||||
big cards are flexible.
|
||||
|
||||
### 1.5 Faction
|
||||
`faction` = the card's `category` (Space, Nature, People, Science, History, Culture), from
|
||||
`server/wiki.ts`. Culture is about half the pool, so faction keywords are written so that a
|
||||
mono-faction deck gains no consistency edge (§10: no v1 keyword scales with faction count).
|
||||
|
||||
### 1.6 Trend (live, small, capped)
|
||||
`trend` = +1 if `live.trendPercent ≥ trendUp` (default 25), −1 if `≤ trendDown` (default −25),
|
||||
otherwise 0. A `null` value gives 0. Trend also needs `live.dailyAverage ≥ trendMinDaily` (default
|
||||
**20**), because percentages on tiny articles are noise; otherwise trend is 0. The host computes it **once at match start**, and it is frozen for
|
||||
the match. It shows as an arrow (▲/▼), not a number. It adds to power in every Topic.
|
||||
|
||||
### 1.7 Rarity
|
||||
The hash-derived `rarity` (`shared/protocol.ts:38`) is **cosmetic in v1** (frame colour only). Mining luck must not
|
||||
become power or keyword choice.
|
||||
|
||||
### 1.8 Keyword
|
||||
Each card has at most **one** keyword: cost-1 cards are vanilla, and the others get their faction's keyword (§10.1).
|
||||
|
||||
### 1.9 Card face (phone)
|
||||
The card face shows **cost** (top-left), **power** (big, centre; the bonus shows as a "+N" badge on the home icon when the card is on-topic), a **home-stat icon**
|
||||
(📣 attention / 📚 depth / 🌐 reach), an optional trend arrow, and one keyword word. That is two
|
||||
numbers, plus the live lane power when the card is on the board.
|
||||
|
||||
### 1.10 Plausibility (anti-forgery, off-chain)
|
||||
When `verifyStats` is true (the default for hosted matches), the match host checks each owned card's
|
||||
snapshot before the match:
|
||||
`pageBytes` against that revision's byte size, `languageCount` ≤ the live count + 5, and views for the
|
||||
snapshot month within ±10 % of the pageviews API.
|
||||
A card that fails is played with its live values. The **host replaces `snapshot`** with a snapshot
|
||||
built from the live values (`deriveStats` on the live bytes, languages and views) **before** it builds
|
||||
the `CardInput`. The match log marks the card `unverified`.
|
||||
The engine does no I/O and only ever sees one version of each card.
|
||||
- **Caching:** results are cached per `(pageId, revisionId, snapshotMonth)`. They are immutable, so a
|
||||
cached pass or fail never expires. Live values for a failed card are cached for 24 h.
|
||||
- **Card can't be verified** (the pageId or revision doesn't exist, or the title or category doesn't
|
||||
match): the card is **rejected at deck validation**, and the player is asked to swap in a loaner.
|
||||
- **API failure:** if Wikipedia can't be reached and nothing is cached, the card plays from its snapshot
|
||||
with `check: 'unchecked'`. The engine then caps its cost at `uncheckedCostCap` (default **4**), and
|
||||
power follows the capped cost. Matches are never blocked.
|
||||
- The engine's only use of `check` is that cost cap. Loaner cards are `check: 'loaner'`.
|
||||
|
||||
---
|
||||
|
||||
## 2. Decks
|
||||
|
||||
- **Deck size:** exactly `deckSize` cards (default **12**).
|
||||
- **Copies:** at most `maxCopiesPerPage` cards with the same `pageId` (default **2**). Owned and loaner
|
||||
copies count **together**. Each copy keeps its own snapshot, so the two copies may differ in cost.
|
||||
- **Deck validation** (engine): the size is right, the copy limit holds, every card's `check` is
|
||||
valid, and there are no more loaners than `maxLoaners`. An invalid deck can't start a match.
|
||||
- **Owned cards:** any card the player's wallet owns at match start. Ownership is read off-chain. The
|
||||
match never moves, locks or burns a card.
|
||||
- **Loaner cards:** off-chain preview cards with a fixed `CardInput`, shipped with the game data
|
||||
(`docs/game/starter-cards.json`, picked by council-data: about 24 pageIds across all 6 categories,
|
||||
with frozen, hand-checked snapshot stats, including the 4 cards in `shared/catalog.ts`).
|
||||
Loaners follow the same derivation, so they are no weaker or stronger than owned cards.
|
||||
- **Starter decks:** `starterDecks` (default: 4 fixed 12-card loaner decks). Each one has two leading
|
||||
factions and an average cost of 3.0–3.3, and is **curve-shaped**: at least 3 cards of cost 4 or more,
|
||||
and at most 4 of cost 1. A new player picks one and can play at once.
|
||||
- **Mixed decks:** an owned deck may fill any slots with loaners, up to `maxLoaners` (default 12, which
|
||||
means no limit). Owning NFTs gives **variety**, not power: owned and loaner cards follow the same
|
||||
curve.
|
||||
|
||||
---
|
||||
|
||||
## 3. Board
|
||||
|
||||
- 3 **Topics** (lanes), numbered 1–3 from left to right (top to bottom in portrait).
|
||||
- Each Topic has a **stat** (attention, depth or reach) and an optional **Portal** modifier (§10.3).
|
||||
Topics have **no faction**. No v1 keyword counts factions: faction only picks the keyword.
|
||||
- Each player has at most `laneCapacity` cards per Topic (default **3**). That gives 9 slots per side,
|
||||
which caps cheap-card flooding and fits 3 cards across a 360 px phone.
|
||||
- **Topic pool:** `topicPool` is a list of Topics, each `{ id, name, stat, portal | null }`. The default
|
||||
pool has 9 Topics: 3 per stat, one plain and two with Portals. `pool_s` is the sub-list with stat
|
||||
`s`, in file order.
|
||||
- **Topic draw (exact):**
|
||||
- If `distinctStats` is true (the default): for each stat in the fixed order
|
||||
`[attention, depth, reach]`, pick `pool_s[floor(next() × len(pool_s))]`. That uses 3 `next()`
|
||||
calls. Then Fisher–Yates the 3 picks into lanes 1–3 (i = 2, 1; j = floor(next() × (i+1))), which
|
||||
uses 2 calls.
|
||||
- If `distinctStats` is false: Fisher–Yates the whole pool (i from n−1 down to 1) and take the first
|
||||
`topicCount` entries as lanes 1–3.
|
||||
- **Stats visible, Portals hidden:** every Topic's **stat** is face-up from turn 1. Its **Portal**
|
||||
modifier is face-down until the start of turn `portalReveal[i]` (default `[2, 3, 4]`). You always
|
||||
know where your card is on-topic, but not what twist a lane will get.
|
||||
|
||||
---
|
||||
|
||||
## 4. Match setup (deterministic)
|
||||
|
||||
1. The input is `{ seed: uint32, rules, players: [p0, p1] }`, and each player's input is
|
||||
`{ id, deck: CardInput[12] }`. Seat order is input order.
|
||||
2. RNG: **mulberry32(seed)**. Every random choice draws `next()` in this fixed order:
|
||||
1. shuffle p0's deck (Fisher–Yates, i from n−1 down to 1, j = floor(next() × (i+1)))
|
||||
2. shuffle p1's deck the same way
|
||||
3. draw and shuffle the Topics
|
||||
4. the initiative coin: p0 has initiative on odd turns if next() < 0.5, otherwise p1
|
||||
5. later random events (keywords only), in resolution order
|
||||
3. Each player draws `openingHand` cards (default **3**). There are no mulligans in v1
|
||||
(`mulligan: false`).
|
||||
4. **Seed fairness (hosted PvP):** commit–reveal. Each party *i* (host, p0, p1) sends
|
||||
`sha256(r_i)` for a random 32-byte `r_i`, then reveals `r_i` once all commits are in.
|
||||
`seed` = the first 4 bytes (big-endian uint32) of `sha256(r_host ‖ r_p0 ‖ r_p1)`.
|
||||
The host still relays the hidden plans, so hosted PvP trusts the host not to leak them.
|
||||
Local and bot matches use any seed.
|
||||
|
||||
---
|
||||
|
||||
## 5. Turn structure
|
||||
|
||||
The match lasts `turns` turns (default **6**, hard cap). Each turn has these phases:
|
||||
|
||||
1. **Start**
|
||||
- Reveal any Portal scheduled for turn *t* (resolve its "on reveal").
|
||||
- Each player's energy = `energyByTurn[t-1]` + carry + `bonusEnergy`. Carry is
|
||||
min(`energyCarryMax`, unspent energy from last turn), default max **1**. Saving one energy on
|
||||
turn 2 makes a turn-3 four-drop possible: a real tempo choice.
|
||||
- Each player draws 1 card if their deck isn't empty and their hand holds fewer than `handLimit`
|
||||
(default **7**) cards. Otherwise they don't draw. This includes turn 1, so the turn-1 hand is
|
||||
3 + 1 = 4 cards.
|
||||
- Order within Start: Portal reveal, then energy, then draw. The Underdog check (step 2) comes after
|
||||
all three.
|
||||
2. **Underdog check** (mode option, `underdog: false` by default, because it can be sandbagged). When
|
||||
it's on, from turn 2, a player who leads in 0 Topics while the opponent leads in ≥ 2 gets
|
||||
**+1 energy** this turn.
|
||||
3. **Plan** (simultaneous, hidden)
|
||||
- Each player queues an ordered list of plays `(handIndex, topic)`.
|
||||
- Total cost must be ≤ their energy, and each Topic needs room on that player's side.
|
||||
- Plays can be undone freely until **Commit**. Passing is an empty commit.
|
||||
- The turn timer is `turnSeconds` (default **25**). On timeout, whatever is queued is committed.
|
||||
4. **Reveal (interleaved)**
|
||||
- Plays reveal **one at a time, alternating**: the initiative player's 1st, the other player's
|
||||
1st, the initiative player's 2nd, and so on. When one player runs out, the rest of the other's
|
||||
reveal in order.
|
||||
- Each card enters its Topic and its "on reveal" effect resolves at once.
|
||||
- So the order in which you queue cards matters: lead with the card you want resolved first.
|
||||
- Energy is reserved when a card is queued. A queued play that is no longer legal at reveal (the
|
||||
lane is full, or a Portal rejects it) **fizzles**: the card stays in hand and its energy is lost.
|
||||
5. **End**
|
||||
- Recompute all Topic powers (§6).
|
||||
- End-of-turn effects resolve, the initiative player's first.
|
||||
- Initiative strictly **alternates** each turn (set by the coin in §4).
|
||||
- Plans are locked before anything reveals, so initiative gives away no information. It only
|
||||
decides the order of on-reveal effects. §10 includes keywords where that order matters.
|
||||
|
||||
A typical turn is: look at the lanes, tap a card, tap a Topic (×1–3), tap Commit. That is under 10
|
||||
seconds, done with one thumb, with no dragging.
|
||||
|
||||
---
|
||||
|
||||
## 6. Power and Topic control
|
||||
|
||||
- A card's **lane power** = `power` + (`onTopicBonus[cost]` if its home stat is the Topic's stat) + `trend`
|
||||
+ keyword and Portal modifiers. It is never below 0.
|
||||
- A player's **Topic power** = the sum of their cards' lane power in that Topic.
|
||||
- A player **leads** a Topic if their Topic power is strictly greater than the opponent's.
|
||||
- **Consensus tie-break:** if the powers are equal and > 0, the player with more **on-topic** cards
|
||||
there leads. If that is also equal, nobody leads. 0–0 has no leader.
|
||||
|
||||
---
|
||||
|
||||
## 7. Win conditions and tie-breaks
|
||||
|
||||
**Scoring** happens after the last turn's End phase (§5.5): every end-of-turn effect, including
|
||||
the last turn's, and every "at scoring" Portal resolves **before** Topics are judged. Then:
|
||||
1. The player who leads **more Topics** wins (2–1, 2–0, 1–0 and 3–0 all count).
|
||||
2. If they lead the same number of Topics: the higher **total power across all Topics** wins.
|
||||
3. If that is also equal: the match is a **draw**.
|
||||
|
||||
**Concede:** a player can concede at any time, and the opponent wins at once. A player who misses
|
||||
`afkTurns` timeouts in a row (default **2**) with nothing queued concedes.
|
||||
|
||||
---
|
||||
|
||||
## 8. Degenerate lines and why they fail (for the critic)
|
||||
|
||||
| Line | Why it isn't dominant |
|
||||
|---|---|
|
||||
| All-famous (all max-stat) deck | It becomes an all-cost-5/6 deck with dead early turns. Cheap cards are more efficient **per energy**, expensive cards **per card**. Only 9 cards are seen per match (3 + 6 draws), so both matter. The 1-energy carry-over lets a heavy deck bank energy for a turn-5 six-drop. **sim-balance target: heavy vs curve ≥ 40%.** |
|
||||
| All-cheap flood (cost 1–2) | Weak by design: only 9 slots and 9 cards seen. Critic's sim under these rules: swarm vs curve about 7–11%. Its home is Culture's wide-turn keyword (§10). |
|
||||
| All one faction | No v1 keyword scales with faction count. `factionSynergyCap` is reserved for modes. Culture, the largest pool, has the weakest keyword (viral). |
|
||||
| "Always play the highest-power card" | It ignores the on-topic bonus, lane capacity and the hidden Portals. Critic's sim: 18–21% against a smart bot (target < 55%). |
|
||||
| Stall or pass | Passing leaves lanes to any 1-power card. Two passing players draw. |
|
||||
| Mirror the AI | Hidden simultaneous commits: you only see the opponent's cards after you commit. |
|
||||
| Seat or initiative | Planning is simultaneous and initiative strictly alternates (each seat has it for 3 of the 6 turns). Target: each seat wins 48–52%. |
|
||||
| Forged or shopped stats | They only raise cost (§1.3), the host check falls back to live stats (§1.10), and trend is capped at ±1. |
|
||||
| Inflated live pageviews | Worth at most +1, frozen at match start, and only counts for articles with ≥ 20 views a day. |
|
||||
| Swinginess | No effect may change a lane by more than 6 power or move cards between lanes in v1 (a keyword-design rule for §10). |
|
||||
|
||||
---
|
||||
|
||||
## 9. Rules config (all defaults)
|
||||
|
||||
The engine takes a `RulesConfig` object. Peer-hosted modes override it (§11). Defaults:
|
||||
|
||||
```json
|
||||
{
|
||||
"version": "1.0",
|
||||
"deckSize": 12, "maxCopiesPerPage": 2, "maxLoaners": 12,
|
||||
"openingHand": 3, "handLimit": 7, "mulligan": false,
|
||||
"turns": 6, "turnSeconds": 25, "afkTurns": 2,
|
||||
"energyByTurn": [1, 2, 3, 4, 5, 6], "energyCarryMax": 1, "bonusEnergy": 0, "underdog": false,
|
||||
"topicCount": 3, "distinctStats": true, "portalReveal": [2, 3, 4], "laneCapacity": 3,
|
||||
"topicPool": [ /* inline Topic objects {id, name, stat, portal}; default = the 9 in §10.3 */ ],
|
||||
"keywordParams": { /* per-keyword numbers, keyed by keyword id (§10) */ },
|
||||
"portalParams": { /* per-Portal numbers, keyed by Topic id (§10.3) */ },
|
||||
"costThresholds": [15, 35, 55, 75, 90],
|
||||
"powerByCost": [0, 1, 2, 4, 6, 8, 10],
|
||||
"onTopicBonus": [0, 1, 1, 2, 2, 3, 3], "vanillaBonus": 1,
|
||||
"keywordsEnabled": ["viral","rising","local","encyclopedic","nostalgic","translated"], "ownedCards": true,
|
||||
"trendUp": 25, "trendDown": -25, "trendMinDaily": 20, "uncheckedCostCap": 4,
|
||||
"factionSynergyCap": 3,
|
||||
"verifyStats": true,
|
||||
"percentiles": "card-sample-2026-11-16",
|
||||
"starterDecks": "default"
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
**What modes may vary:** every key above, plus `topicPool` contents and the starter-deck lists.
|
||||
**Fixed for all modes:** matches are off-chain and never move or burn NFTs; the RNG and its draw order
|
||||
(§4); the shape of the derivation (§1: percentile → fame → cost → power); at most one keyword per card;
|
||||
the phases of a turn (§5).
|
||||
A mode must keep `turns × turnSeconds ≤ 240` so that matches stay within 3–6 minutes.
|
||||
|
||||
---
|
||||
|
||||
## 10. Keywords *(owner: council-designer-b)*
|
||||
|
||||
**The v1 keyword set is these six, one per faction.** The ids are the ones engine-b already uses on `night/engine/keywords`.
|
||||
Topics carry only a **stat**, never a faction. Every keyword below that mentions a Topic keys off stats or board state.
|
||||
|
||||
### 10.1 Which keyword a card gets
|
||||
First rule that matches:
|
||||
1. `cost == 1` → **no keyword** (vanilla). The card gets +`vanillaBonus` power (default **1**), so a cost-1 card is 2.
|
||||
2. `"edition"` is in `keywordsEnabled` (off by default) and the deck holds another card with the same `pageId` → **edition**.
|
||||
3. Otherwise → the card's **faction keyword** from 10.2, if it's in `keywordsEnabled`. If not, the card is vanilla, *without* `vanillaBonus`.
|
||||
|
||||
Rarity plays no part here (it's cosmetic, §1.7). Keywords don't lower power, and v1 has no per-keyword power deltas.
|
||||
If sim shows that a keyword is worth more than about 1 power on average, sim-balance sets `keywordParams.<id>.powerDelta` (default 0, range −3 to 0).
|
||||
|
||||
### 10.2 Keyword list (v1)
|
||||
|
||||
| Faction | id (card word) | Trigger | Reminder text | Cap | Order-sensitive? |
|
||||
|---|---|---|---|---|---|
|
||||
| Culture | **viral** | On reveal | +1 power for each other card you revealed earlier this turn. | +2 | yes: your queue order |
|
||||
| Nature | **rising** | End of turn | +1 power. | +2 total | no |
|
||||
| People | **local** | Ongoing | +1 power while on-topic (the Topic's stat is its home stat). | +1 | no |
|
||||
| Science | **encyclopedic** | On reveal | +2 power if there are no other cards here (either side). | +2 | **yes: interleaving** |
|
||||
| History | **nostalgic** | On reveal | +2 power if you are losing here. | +2 | **yes: interleaving** |
|
||||
| Space | **translated** | On reveal | +1 power to your most recently revealed card in each *other* Topic. | +2 | yes |
|
||||
|
||||
Why this set: every keyword is one line and one trigger, and only adds power. The largest swing is +2 on one card,
|
||||
so no lane moves by more than 2 from a keyword. Nothing scales with faction count, so a mono-Culture deck gets no
|
||||
consistency edge (`factionSynergyCap` is unused in v1). Viral is Culture's weakest keyword, and it rewards wide turns.
|
||||
Three keywords (encyclopedic, nostalgic, translated) react to the interleaved reveal (§5.4), so initiative and queue order matter.
|
||||
|
||||
Precise rules (for engine-b):
|
||||
- **On reveal** resolves the moment the card enters its Topic, and sees every card revealed before it (both players,
|
||||
including earlier reveals this turn). The bonuses it grants are permanent counters.
|
||||
- **Ongoing** is a condition, recalculated whenever power is read.
|
||||
- **End of turn** resolves in §5.5 order: the initiative player's cards first, then Topic 1→3, then reveal order.
|
||||
- **viral:** counts the owner's cards revealed earlier in *this* turn's Reveal phase, in any Topic. Cards that went back to hand don't count.
|
||||
- **rising:** stops after it has gained +2 in total.
|
||||
- **local:** "on-topic" is exactly the §1.4/§6 condition. It's simply an extra +1 on top of `onTopicBonus`.
|
||||
- **encyclopedic:** "no other cards here" means both sides of this Topic are empty, apart from this card, when it reveals.
|
||||
- **nostalgic:** "losing here" means the opponent's Topic power here is strictly greater than yours, counted just *before* this card is added.
|
||||
The consensus tie-break doesn't count: a tie is not losing.
|
||||
- **translated:** "most recently revealed" means the highest global reveal sequence number among your cards in that Topic. Topics where you have no card are skipped.
|
||||
- No v1 keyword uses the RNG. §4's "later random events" slot stays empty in v1.
|
||||
|
||||
**Already in code, disabled by default (`keywordsEnabled` excludes them; for modes only):**
|
||||
- **edition:** +2 for each other copy of this `pageId` on your side.
|
||||
- **obscure:** the opponent sees it face down until the end of the match.
|
||||
- **wildcard:** its home stat becomes the Topic's stat on reveal.
|
||||
|
||||
These are engine-b's existing implementations. The faction-based versions of `local` and `wildcard`, and the token version of `viral`, are
|
||||
**replaced** by the definitions above.
|
||||
|
||||
**`keywordParams` defaults** (keyed by keyword id; modes may change them within the §11 ranges):
|
||||
```json
|
||||
{ "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} }
|
||||
```
|
||||
End-of-turn effects on the last turn resolve **before** scoring (§7).
|
||||
|
||||
### 10.3 Portals (Topic modifiers) and the default Topic pool
|
||||
Each Topic has `{ id, name, stat, portal | null }`. The default `topicPool` has 9 Topics, one plain and two with
|
||||
Portals for each stat. A Portal applies from the moment its Topic is revealed (§3), except where it says otherwise.
|
||||
|
||||
| Topic | Stat | Portal rule |
|
||||
|---|---|---|
|
||||
| Current Events | attention | – |
|
||||
| Main Page | attention | At scoring, each card here gets +1 power. |
|
||||
| Trending | attention | Trend arrows (§1.6) count double here (±2). |
|
||||
| Archive | depth | – |
|
||||
| Featured Article | depth | At end of the match, the player with the single highest-power card here gets +2 Topic power here. If the highest card power here is tied (between the two players), nobody gets the bonus. |
|
||||
| Stub | depth | Lane capacity here is 2 per player. |
|
||||
| Translations | reach | – |
|
||||
| Interwiki | reach | +1 Topic power here for a player who has at least one card in all 3 Topics. |
|
||||
| Disambiguation | reach | Every card here counts as on-topic, whatever its home stat. |
|
||||
|
||||
As data: `portal = { kind: "scoringCardBonus", amount: 1 } | { kind: "trendMultiplier", factor: 2 } |
|
||||
{ kind: "highestCardBonus", amount: 2 } | { kind: "laneCapacity", value: 2 } | { kind: "spreadBonus", amount: 1 } |
|
||||
{ kind: "allOnTopic" }`. Modes may add Topics with these kinds, using new numbers, but not new kinds (engine code).
|
||||
|
||||
**`portalParams` defaults** (keyed by Topic id): `{ "main-page": {"amount": 1}, "trending": {"factor": 2},
|
||||
"featured-article": {"amount": 2}, "stub": {"value": 2}, "interwiki": {"amount": 1} }`. Disambiguation has no numbers.
|
||||
Topic ids are the names in kebab-case: `current-events, main-page, trending, archive, featured-article, stub,
|
||||
translations, interwiki, disambiguation`. The UI shows each Portal's one-line rule **on the lane itself**, not behind a tap.
|
||||
|
||||
---
|
||||
|
||||
## 11. Peer-hosted modes *(owner: council-designer-b)*
|
||||
|
||||
A **mode** is data, published by a node operator and run by the match host:
|
||||
```json
|
||||
{
|
||||
"id": "blitz", // [a-z0-9-]{3,32}, unique per host
|
||||
"name": "Blitz", "description": "Four quick turns.", // ≤ 40 and ≤ 280 chars, plain text
|
||||
"rules": { "turns": 4, "energyByTurn": [2, 3, 4, 5], "portalReveal": [1, 1, 2], "deckSize": 10 },
|
||||
"topicPool": [ /* optional: Topic objects (10.3); default if omitted */ ],
|
||||
"starterDecks": [ /* optional: lists of loaner pageIds */ ]
|
||||
}
|
||||
```
|
||||
- `rules` is a **partial** `RulesConfig` (§9) merged over the defaults. Unknown keys are rejected.
|
||||
- **Validation** (modes owns the code; these are the limits). If any check fails, the mode is refused:
|
||||
|
||||
| Key | Allowed |
|
||||
|---|---|
|
||||
| `turns` | 3–8, and `turns × turnSeconds ≤ 240` |
|
||||
| `energyByTurn` | length = `turns`, each 0–10 |
|
||||
| `bonusEnergy` | 0–3 |
|
||||
| `portalReveal` | length = `topicCount`, each 1..`turns`, non-decreasing |
|
||||
| `topicCount` | 1–5; `distinctStats` only if ≤ 3 |
|
||||
| `laneCapacity` | 1–6 |
|
||||
| `deckSize` | 6–20; `maxCopiesPerPage` 1–4; `maxLoaners` 0..`deckSize` |
|
||||
| `openingHand` | 0–6; `handLimit` 1–10 |
|
||||
| `turnSeconds` | 10–60; `afkTurns` 1–5 |
|
||||
| `costThresholds` | 5 strictly ascending integers in 0–100 |
|
||||
| `powerByCost` | 7 integers in 0–20, non-decreasing from index 1 |
|
||||
| `onTopicBonus` (7 entries), `vanillaBonus` | 0–5 each |
|
||||
| `trendUp` / `trendDown` | 0–200 / −200–0 |
|
||||
| `factionSynergyCap` | 0–6 |
|
||||
| `keywordsEnabled` | any subset of the 9 implemented ids (the 6 v1 defaults + edition, obscure, wildcard); a card whose keyword is disabled is vanilla, *without* `vanillaBonus` |
|
||||
| `keywordParams`, `portalParams` | only the keys listed in §10 / §10.3; amounts and caps 0–6, `powerDelta` −3–0 |
|
||||
| `verifyStats` | the host may only turn this off for modes that use only loaners (`maxLoaners == deckSize` and owned cards banned) |
|
||||
| `topicPool` | 3–20 Topics, Portal kinds only from 10.3 |
|
||||
|
||||
- **Identity:** `modeHash` = SHA-256 of the canonical JSON (sorted keys, no whitespace) of the *merged* rules
|
||||
plus the topicPool. A match record holds `{ modeHash, seed, both decks' CardInputs, both players' commit lists }`,
|
||||
and that is enough to replay it exactly.
|
||||
- **What modes can't change** is the "Fixed for all modes" list in §9. Modes also can't add keywords or Portal kinds, or
|
||||
stake, move or burn NFTs.
|
||||
|
||||
Example modes (good defaults for operators to publish):
|
||||
| Mode | Overrides | Feel |
|
||||
|---|---|---|
|
||||
| **Blitz** | `turns 4`, `energyByTurn [2,3,4,5]`, `portalReveal [1,1,2]`, `deckSize 10`, `turnSeconds 20` | about 2 minutes |
|
||||
| **Deep Cuts** | `topicPool`: only the 3 depth Topics, `distinctStats false` | rewards long, obscure articles |
|
||||
| **Loaner League** | `maxLoaners 12` and owned cards banned (`"ownedCards": false`, a new boolean key, default true) | fully level, for tournaments |
|
||||
| **Big Board** | `topicCount 5`, `distinctStats false`, `portalReveal [1,2,3,4,5]`, `laneCapacity 3` | win 3 of 5; **tablet/desktop only** (5 × 3 slots won't fit a 360 px phone) |
|
||||
| **No Keywords** | `keywordsEnabled []`, `onTopicBonus [0,3,3,3,3,3,3]` | Top Trumps–style tutorial mode |
|
||||
|
||||
---
|
||||
|
||||
## 12. Worked example match *(owner: council-designer-b)*
|
||||
|
||||
These are the §1–9 rules as of this PR:
|
||||
- `powerByCost [0,1,2,4,6,8,10]`, `onTopicBonus [0,1,1,2,2,3,3]`, `vanillaBonus 1`
|
||||
- `laneCapacity 3`, `energyCarryMax 1`, interleaved reveals, alternating initiative, `portalReveal [2,3,4]`
|
||||
- `underdog false`, no trend arrows
|
||||
|
||||
The derived cards are given directly (the §1 output), so the test needs no percentile table.
|
||||
Topics: **T1 Archive (depth, plain)**, **T2 Main Page (attention; Portal revealed turn 3; at scoring, each card here gets +1)**,
|
||||
**T3 Translations (reach, plain; revealed turn 4)**. Ana (p0) has initiative on odd turns and Bo (p1) on even turns.
|
||||
|
||||
| Player | Card | Faction | Cost | Base | Home | Keyword |
|
||||
|---|---|---|---|---|---|---|
|
||||
| Ana | Octopus | Nature | 1 | 2 | depth | – (vanilla) |
|
||||
| Ana | Moon | Space | 2 | 2 | reach | translated |
|
||||
| Ana | Coral reef | Nature | 2 | 2 | depth | rising |
|
||||
| Ana | Albert Einstein | People | 4 | 6 | attention | local |
|
||||
| Ana | Ancient Rome | History | 5 | 8 | depth | nostalgic |
|
||||
| Ana | Library of Alexandria | History | 4 | 6 | depth | nostalgic |
|
||||
| Ana | Periodic table | Science | 3 | 4 | depth | encyclopedic |
|
||||
| Bo | Haiku | Culture | 1 | 2 | attention | – (vanilla) |
|
||||
| Bo | Mars | Space | 2 | 2 | reach | translated |
|
||||
| Bo | Jazz | Culture | 2 | 2 | attention | viral |
|
||||
| Bo | Pop music | Culture | 4 | 6 | attention | viral |
|
||||
| Bo | Jupiter | Space | 5 | 8 | reach | translated |
|
||||
| Bo | Fern | Nature | 3 | 4 | depth | rising |
|
||||
| Bo | Mona Lisa | Culture | 3 | 4 | attention | viral |
|
||||
|
||||
Topic power is written as **Ana–Bo** after End of turn. Energy is "available / spent".
|
||||
|
||||
| Turn | Init | Energy Ana / Bo | Reveals, in interleaved order | T1 | T2 | T3 |
|
||||
|---|---|---|---|---|---|---|
|
||||
| 1 | Ana | 1/1, 1/1 | Ana Octopus → T1: 2 +1 on-topic = **3**. Bo Haiku → T2: 2+1 = **3** | 3–0 | 0–3 | 0–0 |
|
||||
| 2 | Bo | 2/2, 2/0 | Bo passes (to carry 1). Ana Moon → T3: 2+1 = 3. translated: Octopus +1 → 4 | 4–0 | 0–3 | 3–0 |
|
||||
| 3 | Ana | 3/2, **4**/4 | Main Page Portal revealed. Ana Coral reef → T1: 2+1 = 3. Bo Mars → T3: 2+1 = 3, translated: Haiku +1 → 4. Bo Jazz → T2: 2+1 = 3, viral (Mars earlier) +1 → 4. End: rising Coral reef → 4 | 8–0 | 0–8 | 3–3 (tie; on-topic 1–1, so no leader) |
|
||||
| 4 | Bo | **5**/4, 4/4 | Bo Pop music → T3: 6 (off-topic), viral +0. Ana Einstein → T2: 6+2 on-topic, local +1 = **9**. End: rising Coral reef → 5 (cap reached) | 9–0 | 9–8 | 3–9 |
|
||||
| 5 | Ana | **6**/5, 5/5 | Ana Ancient Rome → T3: 8 (off-topic). nostalgic: losing 3–9, so +2 → **10**. Bo Jupiter → T1: 8 (off-topic). translated: Jazz → 5 (T2), Pop music → 7 (T3) | 9–8 | 9–9: **Bo leads** (consensus: on-topic 1 vs 2) | 13–10 |
|
||||
| 6 (last) | Bo | **7**/7, 6/6 | Bo Fern → T1: 4+2 = 6. Ana Library → T1: 6+2 = 8. nostalgic: losing 9–14, so +2 → **10**. Bo Mona Lisa → T2: 4+2 = 6, viral (Fern earlier) +1 → 7. Ana Periodic table → T2: 4 (off-topic), encyclopedic: no (cards here). End: rising Fern → 7. Scoring: Main Page +1 per card in T2 | **19–15** | **15–19** | **13–10** |
|
||||
|
||||
Final card values:
|
||||
- **T1:**
|
||||
- Ana: Octopus 4 + Coral reef 5 + Library 10 = 19.
|
||||
- Bo: Jupiter 8 + Fern 7 = 15.
|
||||
- **T2:** each card +1 from Main Page.
|
||||
- Ana: Einstein 10 + Periodic table 5 = 15.
|
||||
- Bo: Haiku 5 + Jazz 6 + Mona Lisa 8 = 19.
|
||||
- **T3:**
|
||||
- Ana: Moon 3 + Ancient Rome 10 = 13.
|
||||
- Bo: Mars 3 + Pop music 7 = 10.
|
||||
|
||||
**Ana wins 2–1.** Three moments show the v1 mechanics:
|
||||
- **Carry-over:** Bo passed on turn 2 to afford two plays on turn 3 (4 energy).
|
||||
- **Consensus:** T2 at 9–9 after turn 5 went to Bo, who had two on-topic attention cards to Ana's one.
|
||||
- **Interleaving decides the match:** on turn 6 Bo had initiative, so Fern revealed before Library. Ana was then losing T1 (9 vs 14) and nostalgic fired (+2).
|
||||
If Ana had revealed first, she'd have been ahead 9–8, nostalgic would not have fired, and T1 would have been 17–15. Ana still wins that lane, but by 2 instead of 4.
|
||||
|
||||
**Golden test for engine-b:**
|
||||
- **Inject:** the Topic order, the opening hands and the draw order directly, with each player's commit list per turn as in the table. The queue order within a turn is as listed.
|
||||
- **Expected final Topic powers:** `T1 19–15, T2 15–19, T3 13–10`. Winner: p0, by 2 Topics to 1.
|
||||
- **Also assert:**
|
||||
- after turn 5, T2 is a 9–9 tie with Bo leading by consensus
|
||||
- Ana's carried energy is 1 at the start of turns 4, 5 and 6
|
||||
- Bo's carried energy is 1 at the start of turn 3
|
||||
@@ -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 | null; // at most maxCopiesPerPage cards share a pageId; null (unpinned loaners) → counted per cardId
|
||||
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.
|
||||
@@ -1,53 +0,0 @@
|
||||
# Night 1: module boundaries
|
||||
|
||||
Owner: `night-lead`. This file is the rule when two PRs touch the same path. If you need to edit a path you don't own, comment on the owner's issue (`[from <you>]`) or keep your change to the "shared hook" listed below.
|
||||
|
||||
## Who owns what
|
||||
|
||||
| Path | Owner | Issue |
|
||||
|---|---|---|
|
||||
| `docs/game/DESIGN.md` | council (designer-a, designer-b, critic) | #1 |
|
||||
| `docs/game/CARD_DATA.md`, `docs/game/card-sample.json` | council-data | #2 |
|
||||
| `shared/game/` (types, RNG, state machine, rules, keywords, `Ruleset`, `starterDeck`) | engine-a (core, API), engine-b (keywords, effects) | #3 |
|
||||
| `docs/game/ENGINE_API.md` | engine-a | #3 |
|
||||
| `shared/game/modes.ts` | modes | #6 |
|
||||
| `server/game*` (e.g. `server/game/`, `server/game-*.ts`) | modes | #6 |
|
||||
| `docs/game/HOSTING.md` | modes | #6 |
|
||||
| `src/game/` (screens, lobby, deck builder, match, tutorial) | ui-a | #5 |
|
||||
| `src/game/ai/` (browser bots, easy and normal) | ui-b | #5 |
|
||||
| beta-fix files outside `src/game/` (landing page, `Card.tsx`, etc.) | ui-b, one PR per upstream issue | #5 |
|
||||
| `shared/bots/`, `scripts/sim/` (bots and the simulation runner) | sim-balance | #4 |
|
||||
| `docs/game/BALANCE.md` | sim-balance | #4 |
|
||||
| `compose.testnet.yaml` overrides, `deploy/night/` (testnet config, per-node mode files) | sim-testnet | #4 |
|
||||
| `server/account*` (e.g. `server/account/`), `src/auth/` | sso | #7 |
|
||||
| `android/`, `capacitor.config.ts` | mobile-android | #8 |
|
||||
| `ios/`, `docs/night/IOS.md` | mobile-ios, macos-fetch | #9 |
|
||||
| `docs/night/` (except `IOS.md`), this file, `REPORT.md` | night-lead | #10 |
|
||||
|
||||
## Tests
|
||||
|
||||
`scripts/run-tests.mjs` only picks up **top-level** `tests/*.test.ts`. Name your files with your team as a prefix so they never collide:
|
||||
`tests/game-*.test.ts` (engine), `tests/modes-*.test.ts`, `tests/ui-*.test.ts`, `tests/bots-*.test.ts`, `tests/account-*.test.ts`.
|
||||
|
||||
## Shared hooks (the only places two teams touch the same file)
|
||||
|
||||
1. **`server/testnet/http.ts`**: modes and sso each export an Express `Router` from their own files and add **exactly one** `app.use(...)` mount line just **above** the `/api` 404 handler (`app.use(['/api','/p2p'],(_req,res)=>{res.status(404)...`). Nothing else in this file. If SSO needs a CSP change (`connect-src` for `https://dex.eom.dev`), keep it to the `helmet` directive and say so in the PR.
|
||||
2. **`src/App.tsx`**: ui-a owns it. Others get one import and one element each (sso: a login button or provider; mobile: hide the mining controls behind a `isNativeApp()` check from `src/game/` or `src/auth/`, never by deleting code).
|
||||
3. **`package.json` and `package-lock.json`**: additive changes only (new dependencies or scripts). Don't reformat or bump existing versions. Lockfile conflicts are resolved by night-lead regenerating the lockfile.
|
||||
4. **`shared/enrichment.ts`**: read-only for everyone tonight. Map card data into game stats inside `shared/game/`.
|
||||
|
||||
## Off limits (consensus and protocol; PRs touching these are rejected)
|
||||
|
||||
`server/chain.ts`, `shared/protocol.ts`, `shared/trade-offer.ts`, `shared/chain-identity.ts`, `shared/network.ts`, `server/testnet/consensus.ts`, `server/testnet/ledger.ts`, `server/testnet/canonical-index.ts`, `server/testnet/randomx.ts`, `server/testnet/miner.ts`, `server/testnet/peers.ts`, `native/`.
|
||||
|
||||
If you think you need a change there, write it up in your issue instead.
|
||||
|
||||
## Dependency direction
|
||||
|
||||
`shared/game/` imports nothing from `server/` or `src/` and does no I/O. `shared/game/modes.ts`, `shared/bots/`, `server/game*`, `src/game/` import from `shared/game/` through the API in `ENGINE_API.md`, not from its internals.
|
||||
|
||||
## Merging
|
||||
|
||||
- Branch `night/<team>/<topic>`, PR into `night/2026-11-16`, squash-merged by night-lead after night-review approves and `npm test` and `npm run build` pass.
|
||||
- Small PRs merge faster. Rebase on the integration branch before asking for review if it moved under you.
|
||||
- After 01:10 (code freeze), only fixes merge.
|
||||
@@ -0,0 +1,454 @@
|
||||
/**
|
||||
* WikiDeck game engine core ("Edit War", docs/game/DESIGN.md): pure,
|
||||
* deterministic, off-chain. Exported functions never mutate their inputs.
|
||||
* All randomness comes from the match seed via state.rng (mulberry32, §4).
|
||||
* Contract: docs/game/ENGINE_API.md.
|
||||
*/
|
||||
import { KEYWORDS, KEYWORD_IDS, activePortal, isOnTopic, type EffectContext, type KeywordDef, type PortalDef } from './keywords.ts';
|
||||
import { Rng, normalizeSeed } from './rng.ts';
|
||||
import { parseRuleset } from './ruleset.ts';
|
||||
import {
|
||||
IllegalActionError, PLAYERS, STATS,
|
||||
type Action, type CardInPlay, type GameCard, type MatchResult, type MatchState,
|
||||
type PlayerId, type PlayerState, type PlayerView, type Ruleset, type TopicDef,
|
||||
} from './types.ts';
|
||||
|
||||
export const ENGINE_VERSION = 1;
|
||||
|
||||
export const other = (player: PlayerId): PlayerId => (player === 0 ? 1 : 0);
|
||||
const clone = <T>(value: T): T => structuredClone(value);
|
||||
const RARITIES = new Set(['Common', 'Rare', 'Epic', 'Legendary']);
|
||||
const FACTION_SET = new Set(['Space', 'Nature', 'People', 'Science', 'History', 'Culture']);
|
||||
const CHECKS = new Set(['verified', 'unverified', 'unchecked', 'loaner']);
|
||||
|
||||
// ---------- validation ----------
|
||||
|
||||
/** Problems with a deck under `rules` (empty = legal). DESIGN §2. */
|
||||
export function validateDeck(rules: Ruleset, deck: readonly GameCard[]): string[] {
|
||||
const problems: string[] = [];
|
||||
if (!Array.isArray(deck)) return ['Deck must be an array'];
|
||||
if (deck.length !== rules.deckSize) problems.push(`Deck must have exactly ${rules.deckSize} cards (has ${deck.length})`);
|
||||
const ids = new Set<string>();
|
||||
const copies = new Map<string, number>();
|
||||
let loaners = 0;
|
||||
for (const card of deck) {
|
||||
if (typeof card?.cardId !== 'string' || !card.cardId || card.cardId.length > 128) { problems.push('cardId must be a non-empty string'); continue; }
|
||||
const label = card.cardId;
|
||||
if (ids.has(card.cardId)) problems.push(`Duplicate cardId ${label}`);
|
||||
ids.add(card.cardId);
|
||||
if (card.pageId !== null && !Number.isInteger(card.pageId)) problems.push(`${label}: bad pageId`);
|
||||
if (card.pageId === null && card.source !== 'loaner') problems.push(`${label}: owned cards need a pageId`);
|
||||
if (typeof card.title !== 'string' || card.title.length > 256) problems.push(`${label}: bad title`);
|
||||
if (!FACTION_SET.has(card.faction)) problems.push(`${label}: bad faction`);
|
||||
if (!RARITIES.has(card.rarity)) problems.push(`${label}: bad rarity`);
|
||||
if (!Number.isInteger(card.cost) || card.cost < 0 || card.cost > 6) problems.push(`${label}: cost must be 0–6`);
|
||||
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 (card.trend !== -1 && card.trend !== 0 && card.trend !== 1) problems.push(`${label}: trend must be -1, 0 or 1`);
|
||||
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.check !== undefined && !CHECKS.has(card.check)) problems.push(`${label}: bad check`);
|
||||
if (card.source === 'loaner') loaners++;
|
||||
if (card.source === 'owned' && !rules.ownedCards) problems.push(`${label}: owned cards are not allowed in this mode`);
|
||||
// §2 / §2.1: owned and loaner copies count together by pageId; unpinned loaners (pageId null) by cardId.
|
||||
const key = card.pageId !== null ? `page:${card.pageId}` : `card:${card.cardId}`;
|
||||
const n = (copies.get(key) ?? 0) + 1;
|
||||
copies.set(key, n);
|
||||
if (n === rules.maxCopiesPerPage + 1) problems.push(`More than ${rules.maxCopiesPerPage} copies of ${card.pageId !== null ? `page ${card.pageId}` : card.cardId}`);
|
||||
}
|
||||
if (loaners > rules.maxLoaners) problems.push(`At most ${rules.maxLoaners} loaner cards`);
|
||||
return problems;
|
||||
}
|
||||
|
||||
// ---------- match setup (§4) ----------
|
||||
|
||||
/**
|
||||
* Draw the match's Topics (§4.2.3). distinctStats: for each stat in STATS order
|
||||
* (attention, depth, reach) pick one Topic of that stat with rng.int(groupSize),
|
||||
* then Fisher–Yates the picks, then keep the first topicCount. Otherwise
|
||||
* Fisher–Yates the whole pool and keep the first topicCount.
|
||||
*/
|
||||
function drawTopics(rules: Ruleset, rng: Rng): TopicDef[] {
|
||||
if (!rules.distinctStats) return rng.shuffle(rules.topicPool).slice(0, rules.topicCount);
|
||||
const picked: TopicDef[] = [];
|
||||
for (const stat of STATS) {
|
||||
const group = rules.topicPool.filter(topic => topic.stat === stat);
|
||||
if (group.length) picked.push(group[rng.int(group.length)]);
|
||||
}
|
||||
return rng.shuffle(picked).slice(0, rules.topicCount);
|
||||
}
|
||||
|
||||
/**
|
||||
* Start a match. `decks[0]` belongs to seat 0. Seed is a uint32 (or a string,
|
||||
* hashed with FNV-1a). Throws ZodError for a bad ruleset, IllegalActionError for a bad deck.
|
||||
*/
|
||||
export function createMatch(ruleset: Ruleset, decks: readonly [readonly GameCard[], readonly GameCard[]], seed: number | string): MatchState {
|
||||
const rules = parseRuleset(clone(ruleset));
|
||||
const seedValue = normalizeSeed(seed);
|
||||
for (const player of PLAYERS) {
|
||||
const problems = validateDeck(rules, decks?.[player] as GameCard[]);
|
||||
if (problems.length) throw new IllegalActionError(`Seat ${player} deck: ${problems.join('; ')}`);
|
||||
}
|
||||
const rng = new Rng(seedValue);
|
||||
const newPlayer = (player: PlayerId): PlayerState => ({
|
||||
deck: rng.shuffle(clone(decks[player])), hand: [], energy: 0, queue: [], committed: false, afk: 0, carry: 0,
|
||||
});
|
||||
const p0 = newPlayer(0);
|
||||
const p1 = newPlayer(1);
|
||||
const topics = drawTopics(rules, rng);
|
||||
const initiative: PlayerId = rng.next() < 0.5 ? 0 : 1;
|
||||
const state: MatchState = {
|
||||
schema: 'wikideck-match/1', engineVersion: ENGINE_VERSION, ruleset: rules, seed: seedValue, rng: rng.state,
|
||||
turn: 0, phase: 'planning', initiative, revealSeq: 0, players: [p0, p1],
|
||||
lanes: topics.map(topic => ({ topic: clone(topic), portalRevealed: false, cards: [[], []] as [CardInPlay[], CardInPlay[]] })),
|
||||
log: [], actions: [], result: null,
|
||||
};
|
||||
for (const player of PLAYERS) for (let i = 0; i < rules.openingHand; i++) draw(state, player);
|
||||
startTurn(state, rng);
|
||||
state.rng = rng.state;
|
||||
return state;
|
||||
}
|
||||
|
||||
function draw(state: MatchState, player: PlayerId): void {
|
||||
const p = state.players[player];
|
||||
if (!p.deck.length || p.hand.length >= state.ruleset.handLimit) return;
|
||||
const card = p.deck.shift()!;
|
||||
p.hand.push(card);
|
||||
state.log.push({ t: 'draw', player, cardId: card.cardId });
|
||||
}
|
||||
|
||||
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 }),
|
||||
power: card => cardPower(state, card),
|
||||
};
|
||||
}
|
||||
|
||||
/** Enabled keyword definition for a card, if any. */
|
||||
function keywordOf(state: MatchState, card: GameCard): KeywordDef | undefined {
|
||||
return card.keyword && state.ruleset.keywordsEnabled.includes(card.keyword) ? KEYWORDS[card.keyword] : undefined;
|
||||
}
|
||||
|
||||
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 {
|
||||
state.turn += 1;
|
||||
if (state.turn > 1) state.initiative = other(state.initiative);
|
||||
const rules = state.ruleset;
|
||||
state.lanes.forEach((lane, index) => {
|
||||
if (lane.portalRevealed || (rules.portalReveal[index] ?? 1) > state.turn) return;
|
||||
lane.portalRevealed = true;
|
||||
state.log.push({ t: 'portalRevealed', lane: index, topic: clone(lane.topic) });
|
||||
const portal = activePortal(state, index);
|
||||
portal?.onPortalReveal?.(portalCtx(state, rng, index, portal, state.initiative));
|
||||
});
|
||||
const base = (rules.energyByTurn[state.turn - 1] ?? rules.energyByTurn.at(-1)!) + rules.bonusEnergy;
|
||||
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);
|
||||
if (rules.underdog && state.turn >= 2) {
|
||||
const led = topicsLed(state);
|
||||
for (const player of PLAYERS) if (led[player] === 0 && led[other(player)] >= 2) {
|
||||
state.players[player].energy += 1;
|
||||
state.log.push({ t: 'underdog', player });
|
||||
}
|
||||
}
|
||||
state.log.push({ t: 'turnStart', turn: state.turn, energy: [state.players[0].energy, state.players[1].energy], initiative: state.initiative });
|
||||
}
|
||||
|
||||
// ---------- power (§6) ----------
|
||||
|
||||
/** A card's current lane power (§6, never below 0). */
|
||||
export function cardPower(state: MatchState, target: CardInPlay): number {
|
||||
const rules = state.ruleset;
|
||||
const scratch = new Rng(state.rng); // ongoing effects must not consume real randomness
|
||||
let power = target.card.power + target.bonus + target.card.trend;
|
||||
if (isOnTopic(state, target)) power += rules.onTopicBonus[target.card.cost] ?? 0;
|
||||
for (const lane of state.lanes) for (const side of lane.cards) for (const source of side) {
|
||||
const keyword = keywordOf(state, source.card);
|
||||
if (keyword?.ongoing) power += keyword.ongoing(keywordCtx(state, scratch, keyword, source), source, target);
|
||||
}
|
||||
const portal = activePortal(state, target.lane);
|
||||
if (portal?.ongoing) power += portal.ongoing(portalCtx(state, scratch, target.lane, portal, target.owner), target);
|
||||
return Math.max(0, power);
|
||||
}
|
||||
|
||||
/** [seat 0 power, seat 1 power] in one lane (during play; excludes "at scoring" Portals). */
|
||||
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];
|
||||
}
|
||||
|
||||
/** §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] {
|
||||
const led: [number, number] = [0, 0];
|
||||
state.lanes.forEach((_, lane) => {
|
||||
const leader = laneLeader(state, lane);
|
||||
if (leader !== null) led[leader]++;
|
||||
});
|
||||
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) ----------
|
||||
|
||||
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;
|
||||
|
||||
function laneRejects(state: MatchState, lane: number, card: GameCard, player: PlayerId): string | null {
|
||||
const portal = activePortal(state, lane);
|
||||
if (!portal?.canPlay) return null;
|
||||
return portal.canPlay(portalCtx(state, new Rng(state.rng), lane, portal, player), card, player) ? null : `${portal.name} rejects this card`;
|
||||
}
|
||||
|
||||
function playProblem(state: MatchState, action: Extract<Action, { type: 'play' }>): string | null {
|
||||
const p = state.players[action.player];
|
||||
if (p.committed) return 'Already committed this turn';
|
||||
const card = p.hand.find(c => c.cardId === action.cardId);
|
||||
if (!card) return 'Card is not in your hand';
|
||||
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 (card.cost > p.energy - queuedCost(p)) return 'Not enough energy';
|
||||
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);
|
||||
}
|
||||
|
||||
/** Why `action` is illegal in `state`, or null if it is legal. */
|
||||
export function actionProblem(state: MatchState, action: Action): string | null {
|
||||
if (state.phase === 'over') return 'Match is over';
|
||||
if (!action || (action.player !== 0 && action.player !== 1)) return 'Unknown player';
|
||||
const p = state.players[action.player];
|
||||
switch (action.type) {
|
||||
case 'play': return playProblem(state, action);
|
||||
case 'undo':
|
||||
if (p.committed) return 'Already committed this turn';
|
||||
return p.queue.some(play => play.cardId === action.cardId) ? null : 'Card is not queued';
|
||||
case 'commit':
|
||||
case 'timeout':
|
||||
return p.committed ? 'Already committed this turn' : null;
|
||||
case 'concede': return null;
|
||||
default: return 'Unknown action';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Legal actions for `player`: every `play`, every `undo`, and `commit`.
|
||||
* `concede` (always legal while running) and `timeout` (host-only) are not listed.
|
||||
* Empty once the player has committed or the match is over.
|
||||
*/
|
||||
export function legalActions(state: MatchState, player: PlayerId): Action[] {
|
||||
if (state.phase === 'over') return [];
|
||||
const p = state.players[player];
|
||||
if (p.committed) return [];
|
||||
const actions: Action[] = [];
|
||||
for (const card of p.hand) {
|
||||
if (p.queue.some(play => play.cardId === card.cardId)) continue;
|
||||
for (let lane = 0; lane < state.lanes.length; lane++) {
|
||||
const action: Action = { type: 'play', player, cardId: card.cardId, lane };
|
||||
if (!playProblem(state, action)) actions.push(action);
|
||||
}
|
||||
}
|
||||
for (const play of p.queue) actions.push({ type: 'undo', player, cardId: play.cardId });
|
||||
actions.push({ type: 'commit', player });
|
||||
return actions;
|
||||
}
|
||||
|
||||
/** Apply one action and return the new state. Throws IllegalActionError if illegal. */
|
||||
export function applyAction(state: MatchState, action: Action): MatchState {
|
||||
const problem = actionProblem(state, action);
|
||||
if (problem) throw new IllegalActionError(problem);
|
||||
const next = clone(state);
|
||||
next.actions.push(clone(action));
|
||||
const p = next.players[action.player];
|
||||
const rng = new Rng(next.rng);
|
||||
switch (action.type) {
|
||||
case 'play': p.queue.push({ cardId: action.cardId, lane: action.lane }); break;
|
||||
case 'undo': p.queue.splice(p.queue.findIndex(play => play.cardId === action.cardId), 1); break;
|
||||
case 'commit': p.committed = true; p.afk = 0; break;
|
||||
case 'timeout':
|
||||
p.committed = true;
|
||||
p.afk = p.queue.length ? 0 : p.afk + 1;
|
||||
if (p.afk >= next.ruleset.afkTurns) {
|
||||
next.log.push({ t: 'concede', player: action.player, afk: true });
|
||||
finish(next, other(action.player), 'afk');
|
||||
}
|
||||
break;
|
||||
case 'concede':
|
||||
next.log.push({ t: 'concede', player: action.player, afk: false });
|
||||
finish(next, other(action.player), 'concede');
|
||||
break;
|
||||
}
|
||||
if (next.phase !== 'over' && next.players.every(player => player.committed)) resolveTurn(next, rng);
|
||||
next.rng = rng.state;
|
||||
return next;
|
||||
}
|
||||
|
||||
/** §5.4 Reveal (interleaved) and §5.5 End. */
|
||||
function resolveTurn(state: MatchState, rng: Rng): void {
|
||||
const rules = state.ruleset;
|
||||
const order: PlayerId[] = [state.initiative, other(state.initiative)];
|
||||
// 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];
|
||||
p.carry = Math.min(rules.energyCarryMax, Math.max(0, p.energy - queuedCost(p)));
|
||||
}
|
||||
const queues = order.map(player => state.players[player].queue.slice());
|
||||
for (let i = 0; i < Math.max(queues[0].length, queues[1].length); i++) {
|
||||
for (const [k, player] of order.entries()) {
|
||||
const play = queues[k][i];
|
||||
if (play) reveal(state, rng, player, play.cardId, play.lane);
|
||||
}
|
||||
}
|
||||
for (const player of PLAYERS) state.players[player].queue = [];
|
||||
for (const player of order) for (const lane of state.lanes) {
|
||||
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');
|
||||
else startTurn(state, rng);
|
||||
}
|
||||
|
||||
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 {
|
||||
const lanePowers = state.lanes.map((_, lane) => scoringPower(state, lane));
|
||||
const led: [number, number] = [0, 0];
|
||||
const totalPower: [number, number] = [0, 0];
|
||||
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 why: MatchResult['reason'] = reason;
|
||||
if (reason === 'topics') {
|
||||
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 why = 'draw';
|
||||
}
|
||||
state.result = { winner, reason: why, topicsLed: led, lanePower: lanePowers, totalPower, turns: state.turn };
|
||||
state.phase = 'over';
|
||||
state.log.push({ t: 'matchOver', result: clone(state.result) });
|
||||
}
|
||||
|
||||
// ---------- queries ----------
|
||||
|
||||
export function isOver(state: MatchState): boolean { return state.phase === 'over'; }
|
||||
|
||||
/** The final result, or null while the match is running. */
|
||||
export function result(state: MatchState): MatchResult | null { return state.result; }
|
||||
|
||||
/** Hidden-information view for one seat. Send only this to clients and AIs. */
|
||||
export function viewFor(state: MatchState, you: PlayerId): PlayerView {
|
||||
const them = other(you);
|
||||
const me = state.players[you], opp = state.players[them];
|
||||
return clone({
|
||||
you, ruleset: state.ruleset, turn: state.turn, phase: state.phase, initiative: state.initiative,
|
||||
energy: me.energy, energyLeft: me.energy - queuedCost(me), hand: me.hand, queue: me.queue,
|
||||
committed: me.committed, deckCount: me.deck.length,
|
||||
opponent: { handCount: opp.hand.length - opp.queue.length, deckCount: opp.deck.length, queuedCount: opp.queue.length, committed: opp.committed },
|
||||
lanes: state.lanes.map((lane, index) => {
|
||||
const power = lanePower(state, index);
|
||||
const mine = power[you], theirs = power[them];
|
||||
const leader = laneLeader(state, index, power);
|
||||
return {
|
||||
// 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[]],
|
||||
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],
|
||||
leader: leader === null ? null : leader === you ? 'you' as const : 'opponent' as const,
|
||||
};
|
||||
}),
|
||||
result: state.result,
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- serialisation, replay, test helpers ----------
|
||||
|
||||
export function serialize(state: MatchState): string { return JSON.stringify(state); }
|
||||
|
||||
export function deserialize(json: string): MatchState {
|
||||
const state = JSON.parse(json) as MatchState;
|
||||
if (state?.schema !== 'wikideck-match/1') throw new Error('Not a wikideck-match/1 state');
|
||||
state.ruleset = parseRuleset(state.ruleset);
|
||||
return state;
|
||||
}
|
||||
|
||||
/** Rebuild a match from its inputs; a host can verify a reported result this way. */
|
||||
export function replay(ruleset: Ruleset, decks: readonly [readonly GameCard[], readonly GameCard[]], seed: number | string, actions: readonly Action[]): MatchState {
|
||||
let state = createMatch(ruleset, decks, seed);
|
||||
for (const action of actions) state = applyAction(state, action);
|
||||
return state;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test helper: put `card` straight into a lane (no on-reveal, no energy, no hand).
|
||||
* Returns a new state. For unit-testing keywords against hand-built boards.
|
||||
*/
|
||||
export function placeCard(state: MatchState, player: PlayerId, lane: number, card: GameCard, bonus = 0): MatchState {
|
||||
const next = clone(state);
|
||||
next.lanes[lane].cards[player].push({ card: clone(card), owner: player, lane, turn: next.turn, seq: ++next.revealSeq, bonus });
|
||||
return next;
|
||||
}
|
||||
|
||||
/** Test helper: reveal a Topic's Portal now (runs nothing). */
|
||||
export function revealPortal(state: MatchState, lane: number): MatchState {
|
||||
const next = clone(state);
|
||||
next.lanes[lane].portalRevealed = true;
|
||||
return next;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/** Public entry point of the WikiDeck game engine. Other teams import only from here. See docs/game/ENGINE_API.md. */
|
||||
export * from './types.ts';
|
||||
export { Rng, seedFromString, normalizeSeed, type RngState } from './rng.ts';
|
||||
export { DEFAULT_RULESET, DEFAULT_TOPIC_POOL, RulesetSchema, TopicSchema, parseRuleset } from './ruleset.ts';
|
||||
export {
|
||||
ENGINE_VERSION, createMatch, legalActions, applyAction, actionProblem, isOver, result, viewFor,
|
||||
serialize, deserialize, replay, validateDeck, cardPower, lanePower, laneLeader, laneCapacity, scoringPower, topicsLed, other, placeCard, revealPortal,
|
||||
} from './engine.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';
|
||||
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* 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,
|
||||
* TopicDef.portal, Ruleset.keywordsEnabled / keywordParams / portalParams).
|
||||
* 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
|
||||
* mutate it (e.g. `bonus` on cards). Safe: applyAction already cloned.
|
||||
* Any randomness must come from ctx.rng (match RNG, resolution order, §4.2.5).
|
||||
* - A keyword's hooks run only if its id is in ruleset.keywordsEnabled.
|
||||
* - onReveal(ctx, self): right after `self` is pushed into its lane (§5.4). Cards revealed
|
||||
* earlier (any seat, any turn) are on the board; later ones are not. self.seq is its global
|
||||
* reveal number; cards revealed this turn have `turn === ctx.state.turn`.
|
||||
* - endOfTurn(ctx, self): §5.5 order: initiative seat's cards first, then lanes 1→N, then seq.
|
||||
* Also runs on the last turn, before scoring (§7).
|
||||
* - ongoing(ctx, self, target) → delta: PURE. Called for every (self, target) pair in play,
|
||||
* 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 { 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 {
|
||||
state: MatchState;
|
||||
rng: Rng;
|
||||
/** Tunable numbers for this keyword/portal from the ruleset. */
|
||||
params: Record<string, number>;
|
||||
/** Lane the effect lives in. */
|
||||
lane: number;
|
||||
/** Add a line to the match log (attributed to this keyword/portal). */
|
||||
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 {
|
||||
id: string;
|
||||
name: string;
|
||||
/** One short line of reminder text with {param} placeholders. */
|
||||
text: string;
|
||||
onReveal?(ctx: EffectContext, self: CardInPlay): void;
|
||||
endOfTurn?(ctx: EffectContext, self: CardInPlay): void;
|
||||
ongoing?(ctx: EffectContext, self: CardInPlay, target: CardInPlay): number;
|
||||
}
|
||||
|
||||
export interface PortalDef {
|
||||
id: string;
|
||||
name: string;
|
||||
text: string;
|
||||
onPortalReveal?(ctx: EffectContext): void;
|
||||
/** Runs when any card is revealed in this Topic (after the card's own onReveal). */
|
||||
onReveal?(ctx: EffectContext, card: CardInPlay): void;
|
||||
ongoing?(ctx: EffectContext, target: CardInPlay): number;
|
||||
/** Lets a Topic reject a card; checked when queuing and again at reveal. */
|
||||
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`. */
|
||||
export function allies(state: MatchState, self: CardInPlay): CardInPlay[] {
|
||||
return state.lanes[self.lane].cards[self.owner].filter(card => card !== self);
|
||||
}
|
||||
|
||||
/** The lane's Portal, if it has one and it is revealed. */
|
||||
export function activePortal(state: MatchState, lane: number): PortalDef | undefined {
|
||||
const l = state.lanes[lane];
|
||||
return l?.portalRevealed && l.topic.portal ? PORTALS[l.topic.portal] : undefined;
|
||||
}
|
||||
|
||||
/** §1.4/§6 on-topic: home stat matches the Topic's stat, or an active Disambiguation-style Portal. */
|
||||
export function isOnTopic(state: MatchState, card: CardInPlay): boolean {
|
||||
const lane = state.lanes[card.lane];
|
||||
return lane.topic.stat === card.card.home || activePortal(state, card.lane)?.allOnTopic === true;
|
||||
}
|
||||
|
||||
/** Filled in by engine-b (§10.2). Ids must be in KEYWORD_IDS. */
|
||||
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> = {};
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Seeded, serialisable PRNG for the game engine (off-chain only).
|
||||
* DESIGN.md §4: mulberry32(seed: uint32). The state is one uint32, so it
|
||||
* round-trips through JSON and a match can be resumed or replayed exactly.
|
||||
*/
|
||||
export type RngState = number;
|
||||
|
||||
/** Hash a string seed (e.g. a lobby id) to a uint32 with FNV-1a. */
|
||||
export function seedFromString(text: string): number {
|
||||
let h = 0x811c9dc5;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
h ^= text.charCodeAt(i);
|
||||
h = Math.imul(h, 0x01000193);
|
||||
}
|
||||
return h >>> 0;
|
||||
}
|
||||
|
||||
export function normalizeSeed(seed: number | string): number {
|
||||
if (typeof seed === 'string') return seedFromString(seed);
|
||||
if (!Number.isInteger(seed) || seed < 0 || seed > 0xffffffff) throw new RangeError('Seed must be a uint32 or a string');
|
||||
return seed >>> 0;
|
||||
}
|
||||
|
||||
/** Mutable wrapper over an RngState. The engine keeps `state` inside MatchState. */
|
||||
export class Rng {
|
||||
state: RngState;
|
||||
constructor(state: RngState) { this.state = state >>> 0; }
|
||||
static fromSeed(seed: number | string): Rng { return new Rng(normalizeSeed(seed)); }
|
||||
|
||||
/** mulberry32: float in [0, 1). */
|
||||
next(): number {
|
||||
this.state = (this.state + 0x6d2b79f5) >>> 0;
|
||||
let t = this.state;
|
||||
t = Math.imul(t ^ (t >>> 15), t | 1);
|
||||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
}
|
||||
/** Integer in [0, n): floor(next() × n), as DESIGN.md §4 specifies. */
|
||||
int(n: number): number {
|
||||
if (!Number.isInteger(n) || n <= 0) throw new RangeError('Rng.int needs a positive integer bound');
|
||||
return Math.floor(this.next() * n);
|
||||
}
|
||||
pick<T>(items: readonly T[]): T {
|
||||
if (!items.length) throw new RangeError('Rng.pick on empty list');
|
||||
return items[this.int(items.length)];
|
||||
}
|
||||
/** Fisher–Yates per DESIGN.md §4: i from n−1 down to 1, j = floor(next() × (i+1)). Returns a new array. */
|
||||
shuffle<T>(items: readonly T[]): T[] {
|
||||
const out = items.slice();
|
||||
for (let i = out.length - 1; i > 0; i--) {
|
||||
const j = this.int(i + 1);
|
||||
[out[i], out[j]] = [out[j], out[i]];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* Ruleset (DESIGN §9 RulesConfig): every rule number as data, so peer-hosted
|
||||
* modes can vary them without running code. parseRuleset() is the only way
|
||||
* untrusted JSON should become a Ruleset; its bounds keep matches short and
|
||||
* guarantee termination.
|
||||
*/
|
||||
import { z } from 'zod';
|
||||
import { KEYWORD_IDS, PORTAL_IDS } from './keywords.ts';
|
||||
import { STATS, type Ruleset } from './types.ts';
|
||||
|
||||
const int = (min: number, max: number) => z.number().int().min(min).max(max);
|
||||
const id = z.string().regex(/^[a-z0-9][a-z0-9-]{0,31}$/);
|
||||
const params = z.record(z.string().regex(/^[A-Za-z0-9]{1,24}$/), z.number().finite().min(-100).max(100))
|
||||
.refine(value => Object.keys(value).length <= 8, 'At most 8 params');
|
||||
const paramTable = z.record(id, params).refine(value => Object.keys(value).length <= 32, 'At most 32 entries');
|
||||
|
||||
export const TopicSchema = z.object({
|
||||
id, name: z.string().min(1).max(32), stat: z.enum(STATS as [string, ...string[]]), portal: z.enum(PORTAL_IDS).nullable(),
|
||||
}).strict();
|
||||
|
||||
export const RulesetSchema = z.object({
|
||||
version: z.string().min(1).max(16),
|
||||
deckSize: int(1, 30),
|
||||
maxCopiesPerPage: int(1, 30),
|
||||
maxLoaners: int(0, 30),
|
||||
openingHand: int(0, 10),
|
||||
handLimit: int(1, 12),
|
||||
mulligan: z.literal(false), // not implemented in v1
|
||||
turns: int(1, 12),
|
||||
turnSeconds: int(5, 120),
|
||||
afkTurns: int(1, 12),
|
||||
energyByTurn: z.array(int(0, 20)).min(1).max(12),
|
||||
energyCarryMax: int(0, 10),
|
||||
bonusEnergy: int(0, 10),
|
||||
underdog: z.boolean(),
|
||||
topicCount: int(1, 5),
|
||||
distinctStats: z.boolean(),
|
||||
portalReveal: z.array(int(1, 12)).max(5),
|
||||
laneCapacity: int(1, 8),
|
||||
topicPool: z.array(TopicSchema).min(1).max(32),
|
||||
keywordParams: paramTable,
|
||||
portalParams: paramTable,
|
||||
costThresholds: z.array(int(0, 100)).length(5),
|
||||
powerByCost: z.array(int(0, 30)).length(7),
|
||||
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),
|
||||
trendDown: z.number().finite().min(-1000).max(1000),
|
||||
trendMinDaily: z.number().finite().min(0).max(1e9),
|
||||
uncheckedCostCap: int(1, 6),
|
||||
factionSynergyCap: int(0, 12),
|
||||
verifyStats: z.boolean(),
|
||||
percentiles: id,
|
||||
starterDecks: id,
|
||||
}).strict().superRefine((rules, ctx) => {
|
||||
const issue = (message: string) => ctx.addIssue({ code: 'custom', message });
|
||||
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.portalReveal.length !== rules.topicCount) issue('portalReveal needs one entry per Topic');
|
||||
if (rules.openingHand > rules.handLimit) issue('openingHand > handLimit');
|
||||
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.distinctStats) {
|
||||
if (rules.topicCount !== STATS.length) issue('distinctStats needs topicCount == 3');
|
||||
const stats = new Set(rules.topicPool.map(topic => topic.stat));
|
||||
if (stats.size < rules.topicCount) issue('topicPool lacks enough distinct stats');
|
||||
} else if (rules.topicPool.length < rules.topicCount) issue('topicPool smaller than topicCount');
|
||||
const topicIds = new Set<string>();
|
||||
for (const topic of rules.topicPool) {
|
||||
if (topicIds.has(topic.id)) issue(`Duplicate topic id: ${topic.id}`);
|
||||
topicIds.add(topic.id);
|
||||
}
|
||||
if (new Set(rules.keywordsEnabled).size !== rules.keywordsEnabled.length) issue('Duplicate keywordsEnabled entry');
|
||||
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. */
|
||||
export function parseRuleset(input: unknown): Ruleset {
|
||||
return RulesetSchema.parse(input) as Ruleset;
|
||||
}
|
||||
|
||||
/** 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'] = [
|
||||
{ id: 'current-events', name: 'Current Events', stat: 'attention', portal: null },
|
||||
{ id: 'main-page', name: 'Main Page', stat: 'attention', portal: 'main-page' },
|
||||
{ id: 'trending', name: 'Trending', stat: 'attention', portal: 'trending' },
|
||||
{ id: 'archive', name: 'Archive', stat: 'depth', portal: null },
|
||||
{ id: 'featured-article', name: 'Featured Article', stat: 'depth', portal: 'featured-article' },
|
||||
{ id: 'stub', name: 'Stub', stat: 'depth', portal: 'stub' },
|
||||
{ id: 'translations', name: 'Translations', stat: 'reach', portal: null },
|
||||
{ id: 'interwiki', name: 'Interwiki', stat: 'reach', portal: 'interwiki' },
|
||||
{ id: 'disambiguation', name: 'Disambiguation', stat: 'reach', portal: 'disambiguation' },
|
||||
];
|
||||
|
||||
/** DESIGN §9 defaults (v1). */
|
||||
export const DEFAULT_RULESET: Ruleset = {
|
||||
version: '1.0',
|
||||
deckSize: 12, maxCopiesPerPage: 2, maxLoaners: 12,
|
||||
openingHand: 3, handLimit: 7, mulligan: false,
|
||||
turns: 6, turnSeconds: 25, afkTurns: 2,
|
||||
energyByTurn: [1, 2, 3, 4, 5, 6], energyCarryMax: 1, bonusEnergy: 0, underdog: false,
|
||||
topicCount: 3, distinctStats: true, portalReveal: [2, 3, 4], laneCapacity: 3,
|
||||
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],
|
||||
powerByCost: [0, 1, 2, 4, 6, 8, 10],
|
||||
onTopicBonus: [0, 1, 1, 2, 2, 3, 3], vanillaBonus: 1,
|
||||
keywordsEnabled: ['viral', 'rising', 'local', 'encyclopedic', 'nostalgic', 'translated'], ownedCards: true,
|
||||
trendUp: 25, trendDown: -200, trendMinDaily: 20, uncheckedCostCap: 4,
|
||||
factionSynergyCap: 3,
|
||||
verifyStats: true,
|
||||
percentiles: 'card-sample-2026-11-16',
|
||||
starterDecks: 'default',
|
||||
};
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* PLACEHOLDER loaner cards and starter decks (DESIGN §2) so the engine, UI and
|
||||
* sims can run before council-data's docs/game/starter-cards.json lands.
|
||||
* Loaners are off-chain preview cards: not NFTs, never minted or moved.
|
||||
* engine-b / council-data replace STARTER_POOL with derived cards (cards.ts).
|
||||
*/
|
||||
import { Rng } from './rng.ts';
|
||||
import type { Faction, GameCard, Stat } from './types.ts';
|
||||
|
||||
type Spec = [pageId: number, title: string, faction: Faction, cost: number, home: Stat];
|
||||
|
||||
/** 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, 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[] = [
|
||||
[22780, 'Octopus', 'Nature', 1, 'depth'],
|
||||
[19331, 'Moon', 'Space', 1, 'reach'],
|
||||
[23053, 'Periodic table', 'Science', 1, 'depth'],
|
||||
[3383, 'Bronze Age', 'History', 1, 'depth'],
|
||||
[5843419, 'Chess', 'Culture', 2, 'attention'],
|
||||
[9228, 'Earth', 'Space', 2, 'reach'],
|
||||
[2008, 'Ada Lovelace', 'People', 2, 'attention'],
|
||||
[21830, 'Honey bee', 'Nature', 2, 'depth'],
|
||||
[736, 'Albert Einstein', 'People', 3, 'reach'],
|
||||
[10979, 'Fungus', 'Nature', 3, 'depth'],
|
||||
[26903, 'Solar System', 'Space', 3, 'reach'],
|
||||
[30758, 'Roman Empire', 'History', 3, 'depth'],
|
||||
[9649, 'Evolution', 'Science', 4, 'depth'],
|
||||
[8424, 'Jazz', 'Culture', 4, 'attention'],
|
||||
[12898, 'Marie Curie', 'People', 4, 'reach'],
|
||||
[14533, 'Silk Road', 'History', 4, 'reach'],
|
||||
[19468, 'Mount Everest', 'Nature', 5, 'attention'],
|
||||
[22936, 'Photosynthesis', 'Science', 5, 'depth'],
|
||||
[18110, 'Leonardo da Vinci', 'People', 5, 'reach'],
|
||||
[14627, 'Ancient Egypt', 'History', 5, 'attention'],
|
||||
[4177, 'Black hole', 'Space', 6, 'attention'],
|
||||
[25443, 'Quantum mechanics', 'Science', 6, 'depth'],
|
||||
[17867, 'Library of Alexandria', 'History', 6, 'depth'],
|
||||
[20217, 'Music', 'Culture', 6, 'reach'],
|
||||
];
|
||||
|
||||
export function loanerCard(spec: Spec, copy = 0): GameCard {
|
||||
const [pageId, title, faction, cost, home] = spec;
|
||||
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. */
|
||||
export function previewPool(): GameCard[] { return STARTER_POOL.map(spec => loanerCard(spec)); }
|
||||
|
||||
/** A deterministic 12-card loaner deck: 2 cards of each cost 1–6, chosen by `seed`. */
|
||||
export function starterDeck(seed: number | string): GameCard[] {
|
||||
const rng = Rng.fromSeed(`starter:${seed}`);
|
||||
const deck: GameCard[] = [];
|
||||
for (let cost = 1; cost <= 6; cost++) {
|
||||
deck.push(...rng.shuffle(STARTER_POOL.filter(spec => spec[3] === cost)).slice(0, 2).map(spec => loanerCard(spec)));
|
||||
}
|
||||
return deck;
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
/**
|
||||
* WikiDeck game engine types (off-chain). Implements docs/game/DESIGN.md ("Edit War").
|
||||
* Everything here is plain JSON data: MatchState round-trips through
|
||||
* JSON.stringify/parse with no loss (no Maps, classes or functions).
|
||||
* Contract: docs/game/ENGINE_API.md. Announce changes on claude/wikideck#3.
|
||||
*/
|
||||
import type { RngState } from './rng.ts';
|
||||
|
||||
export type PlayerId = 0 | 1;
|
||||
export const PLAYERS: readonly PlayerId[] = [0, 1];
|
||||
|
||||
/** Category buckets from server/wiki.ts; a card's faction (DESIGN §1.5). */
|
||||
export type Faction = 'Space' | 'Nature' | 'People' | 'Science' | 'History' | 'Culture';
|
||||
export const FACTIONS: readonly Faction[] = ['Space', 'Nature', 'People', 'Science', 'History', 'Culture'];
|
||||
export type Stat = 'attention' | 'depth' | 'reach';
|
||||
export const STATS: readonly Stat[] = ['attention', 'depth', 'reach'];
|
||||
export type Rarity = 'Common' | 'Rare' | 'Epic' | 'Legendary';
|
||||
|
||||
/**
|
||||
* A card as the engine sees it: already derived (DESIGN §1) by cards.ts from a
|
||||
* host-frozen CardInput. The engine never reads raw snapshot stats. Hosts/modes
|
||||
* may adjust fields (e.g. power) before createMatch; the engine does not re-derive.
|
||||
*/
|
||||
export interface GameCard {
|
||||
/** Unique within one deck (the NFT card hash, or `loaner:<pageId>:<n>`). */
|
||||
cardId: string;
|
||||
/** null for unpinned loaners (DESIGN §2.1): copies then count per cardId. */
|
||||
pageId: number | null;
|
||||
title: string;
|
||||
faction: Faction;
|
||||
/** Cosmetic in v1 (§1.7). */
|
||||
rarity: Rarity;
|
||||
cost: number;
|
||||
power: number;
|
||||
home: Stat;
|
||||
/** Live trend arrow, frozen at match start (§1.6). Adds to power in every Topic. */
|
||||
trend: -1 | 0 | 1;
|
||||
keyword: string | null;
|
||||
/** 'owned' = an NFT the player holds (never moved or burned by a match). */
|
||||
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). */
|
||||
export interface TopicDef {
|
||||
id: string;
|
||||
name: string;
|
||||
stat: Stat;
|
||||
/** 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* DESIGN §9 RulesConfig: every rule number as flat data so peer-hosted modes can
|
||||
* override it. Use parseRuleset() for untrusted input.
|
||||
*/
|
||||
export interface Ruleset {
|
||||
version: string;
|
||||
deckSize: number;
|
||||
maxCopiesPerPage: number;
|
||||
maxLoaners: number;
|
||||
openingHand: number;
|
||||
handLimit: number;
|
||||
mulligan: boolean;
|
||||
turns: number;
|
||||
turnSeconds: number;
|
||||
afkTurns: number;
|
||||
/** energyByTurn[t-1] is the base energy on turn t. Length must be ≥ turns. */
|
||||
energyByTurn: number[];
|
||||
/** Unspent energy carried to next turn, capped at this. */
|
||||
energyCarryMax: number;
|
||||
bonusEnergy: number;
|
||||
underdog: boolean;
|
||||
topicCount: number;
|
||||
distinctStats: boolean;
|
||||
/** portalReveal[i] = turn on which Topic i's Portal is revealed (stats are always visible). Length = topicCount. */
|
||||
portalReveal: number[];
|
||||
laneCapacity: number;
|
||||
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[];
|
||||
/** Index = cost (0–6). */
|
||||
powerByCost: 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;
|
||||
trendDown: number;
|
||||
trendMinDaily: number;
|
||||
uncheckedCostCap: number;
|
||||
factionSynergyCap: number;
|
||||
verifyStats: boolean;
|
||||
/** Id of the percentile reference table used by derive.ts. */
|
||||
percentiles: string;
|
||||
/** Id of the starter deck list. */
|
||||
starterDecks: string;
|
||||
}
|
||||
|
||||
export interface CardInPlay {
|
||||
card: GameCard;
|
||||
owner: PlayerId;
|
||||
lane: number;
|
||||
/** Turn the card was revealed. */
|
||||
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.). */
|
||||
bonus: number;
|
||||
}
|
||||
|
||||
export interface QueuedPlay { cardId: string; lane: number }
|
||||
|
||||
export interface PlayerState {
|
||||
deck: GameCard[];
|
||||
hand: GameCard[];
|
||||
/** Energy available this turn (before queued plays). */
|
||||
energy: number;
|
||||
/** Plays chosen this turn, hidden from the opponent until reveal. Order matters. */
|
||||
queue: QueuedPlay[];
|
||||
committed: boolean;
|
||||
/** Consecutive timeouts with nothing queued (§7 afkTurns). */
|
||||
afk: number;
|
||||
/** Energy carried into this turn (already included in `energy`). */
|
||||
carry: number;
|
||||
}
|
||||
|
||||
export interface LaneState {
|
||||
/** Stat and name are always visible; the Portal only once portalRevealed. */
|
||||
topic: TopicDef;
|
||||
portalRevealed: boolean;
|
||||
cards: [CardInPlay[], CardInPlay[]];
|
||||
}
|
||||
|
||||
export type MatchPhase = 'planning' | 'over';
|
||||
|
||||
export type LogEvent =
|
||||
| { t: 'turnStart'; turn: number; energy: [number, number]; initiative: PlayerId }
|
||||
| { t: 'portalRevealed'; lane: number; topic: TopicDef }
|
||||
| { t: 'underdog'; player: PlayerId }
|
||||
| { t: 'draw'; player: PlayerId; cardId: string }
|
||||
| { t: 'reveal'; player: PlayerId; cardId: string; lane: number }
|
||||
| { t: 'fizzle'; player: PlayerId; cardId: string; lane: number }
|
||||
| { t: 'effect'; source: string; player: PlayerId; text: string }
|
||||
| { t: 'concede'; player: PlayerId; afk: boolean }
|
||||
| { t: 'matchOver'; result: MatchResult };
|
||||
|
||||
export interface MatchState {
|
||||
schema: 'wikideck-match/1';
|
||||
engineVersion: number;
|
||||
ruleset: Ruleset;
|
||||
seed: number;
|
||||
rng: RngState;
|
||||
/** 1-based current turn. */
|
||||
turn: number;
|
||||
phase: MatchPhase;
|
||||
/** Player who reveals first this turn (§5.4). Alternates every turn. */
|
||||
initiative: PlayerId;
|
||||
/** Last reveal sequence number handed out (CardInPlay.seq). */
|
||||
revealSeq: number;
|
||||
players: [PlayerState, PlayerState];
|
||||
lanes: LaneState[];
|
||||
log: LogEvent[];
|
||||
/** Every action applied so far: (ruleset, decks, seed, actions) replays the match exactly. */
|
||||
actions: Action[];
|
||||
result: MatchResult | null;
|
||||
}
|
||||
|
||||
export type Action =
|
||||
/** Queue a card from hand into a lane (§5.3). */
|
||||
| { type: 'play'; player: PlayerId; cardId: string; lane: number }
|
||||
/** Take back a queued play this turn (refunds its energy). */
|
||||
| { type: 'undo'; player: PlayerId; cardId: string }
|
||||
/** Commit the queue (empty = pass). When both have committed, the turn resolves. */
|
||||
| { type: 'commit'; player: PlayerId }
|
||||
/** The host's turn timer expired for this player: commits what's queued, counts toward afkTurns if empty. */
|
||||
| { type: 'timeout'; player: PlayerId }
|
||||
| { type: 'concede'; player: PlayerId };
|
||||
|
||||
export interface MatchResult {
|
||||
/** null = draw. */
|
||||
winner: PlayerId | null;
|
||||
reason: 'topics' | 'totalPower' | 'draw' | 'concede' | 'afk';
|
||||
topicsLed: [number, number];
|
||||
/** lanePower[lane][player] at the end, including "at scoring" Portals. */
|
||||
lanePower: [number, number][];
|
||||
totalPower: [number, number];
|
||||
turns: number;
|
||||
}
|
||||
|
||||
/** What one player is allowed to see. UI and AI read only this, never raw MatchState. */
|
||||
export interface PlayerView {
|
||||
you: PlayerId;
|
||||
ruleset: Ruleset;
|
||||
turn: number;
|
||||
phase: MatchPhase;
|
||||
initiative: PlayerId;
|
||||
energy: number;
|
||||
/** Energy left after your queued plays. */
|
||||
energyLeft: number;
|
||||
hand: GameCard[];
|
||||
queue: QueuedPlay[];
|
||||
committed: boolean;
|
||||
deckCount: number;
|
||||
opponent: { handCount: number; deckCount: number; queuedCount: number; committed: boolean };
|
||||
lanes: {
|
||||
/** Always visible; `portal` is null until the Portal is revealed. */
|
||||
topic: TopicDef;
|
||||
portalRevealed: boolean;
|
||||
/** cards[0] = yours, cards[1] = opponent's (revealed cards only). */
|
||||
cards: [CardInPlay[], CardInPlay[]];
|
||||
/** Lane power of each card in `cards`, same shape. */
|
||||
cardPower: [number[], number[]];
|
||||
/** power[0] = yours, power[1] = opponent's. */
|
||||
power: [number, number];
|
||||
/** Who leads this Topic from your point of view. */
|
||||
leader: 'you' | 'opponent' | null;
|
||||
}[];
|
||||
result: MatchResult | null;
|
||||
}
|
||||
|
||||
export class IllegalActionError extends Error {
|
||||
constructor(message: string) { super(message); this.name = 'IllegalActionError'; }
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
// 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 assert from 'node:assert/strict';
|
||||
import {
|
||||
DEFAULT_RULESET, IllegalActionError, KEYWORDS, PORTALS, Rng, applyAction, cardPower, createMatch, deserialize, isOver,
|
||||
laneLeader, legalActions, loanerCard, parseRuleset, placeCard, replay, result, revealPortal, serialize, starterDeck,
|
||||
STARTER_POOL, viewFor, type Action, type GameCard, type KeywordDef, type MatchState, type PlayerId, type PortalDef, type Ruleset,
|
||||
} from '../shared/game/index.ts';
|
||||
|
||||
const decks = (seed = 'd'): [GameCard[], GameCard[]] => [starterDeck(`${seed}-a`), starterDeck(`${seed}-b`)];
|
||||
const commit = (s: MatchState, player: PlayerId) => applyAction(s, { type: 'commit', player });
|
||||
const commitBoth = (s: MatchState) => commit(commit(s, 0), 1);
|
||||
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 {
|
||||
let state = createMatch(ruleset, decks(String(seed)), seed);
|
||||
const chooser = Rng.fromSeed(`bot:${seed}`);
|
||||
for (let steps = 0; !isOver(state); steps++) {
|
||||
assert.ok(steps < 2000, 'match must terminate');
|
||||
const player = chooser.int(2) as PlayerId;
|
||||
const actions = legalActions(state, player);
|
||||
if (actions.length) state = applyAction(state, chooser.pick(actions));
|
||||
assert.deepEqual(deserialize(serialize(state)), state);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
test('mulberry32 matches the reference value and is seed-deterministic', () => {
|
||||
assert.equal(new Rng(1).next(), 0.6270739405881613);
|
||||
const seq = (r: Rng) => Array.from({ length: 8 }, () => r.next());
|
||||
assert.deepEqual(seq(Rng.fromSeed(42)), seq(Rng.fromSeed(42)));
|
||||
assert.notDeepEqual(seq(Rng.fromSeed(42)), seq(Rng.fromSeed(43)));
|
||||
assert.equal(Rng.fromSeed('lobby-1').state, Rng.fromSeed('lobby-1').state);
|
||||
});
|
||||
|
||||
test('DEFAULT_RULESET matches DESIGN §9 and parses; bad rulesets are rejected', () => {
|
||||
assert.deepEqual(parseRuleset(DEFAULT_RULESET), DEFAULT_RULESET);
|
||||
assert.equal(DEFAULT_RULESET.laneCapacity, 3);
|
||||
assert.deepEqual(DEFAULT_RULESET.powerByCost, [0, 1, 2, 4, 6, 8, 10]);
|
||||
assert.deepEqual(DEFAULT_RULESET.onTopicBonus, [0, 1, 1, 2, 2, 3, 3]);
|
||||
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));
|
||||
});
|
||||
|
||||
test('setup: one Topic per stat, stats visible, Portals hidden until portalReveal, hands of 4, energy 1', () => {
|
||||
const state = createMatch(DEFAULT_RULESET, decks(), 7);
|
||||
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.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); }
|
||||
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, keyword ids, ownedCards', () => {
|
||||
const [a, b] = decks();
|
||||
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}` }))];
|
||||
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/);
|
||||
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 until reveal; undo refunds; committed seats get no actions', () => {
|
||||
let state = createMatch(DEFAULT_RULESET, decks(), 11);
|
||||
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');
|
||||
state = applyAction(state, play);
|
||||
assert.equal(viewFor(state, 0).energyLeft, 0);
|
||||
assert.equal(viewFor(state, 1).opponent.queuedCount, 1);
|
||||
assert.equal(JSON.stringify(viewFor(state, 1)).includes(`"${play.cardId}"`), false);
|
||||
assert.equal(viewFor(applyAction(state, { type: 'undo', player: 0, cardId: play.cardId }), 0).energyLeft, 1);
|
||||
state = commit(state, 0);
|
||||
assert.deepEqual(legalActions(state, 0), []);
|
||||
state = commit(state, 1);
|
||||
assert.equal(state.turn, 2);
|
||||
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);
|
||||
});
|
||||
|
||||
test('viewFor never leaks the opponent hand, deck order, queue, seed or RNG state', () => {
|
||||
let state = createMatch(DEFAULT_RULESET, [flatDeck(1, 'mine'), flatDeck(1, 'opp')], 'leak-seed');
|
||||
const play = legalActions(state, 1).find(x => x.type === 'play')!;
|
||||
state = applyAction(state, play);
|
||||
const view = viewFor(state, 0);
|
||||
const json = JSON.stringify(view);
|
||||
for (const key of ['"seed"', '"rng"', '"deck"', '"log"', '"actions"']) assert.equal(json.includes(key), false, key);
|
||||
for (const c of [...state.players[1].hand, ...state.players[1].deck, ...state.players[0].deck])
|
||||
assert.equal(json.includes(`"${c.cardId}"`), false, c.cardId);
|
||||
assert.deepEqual(view.hand.map(c => c.cardId), state.players[0].hand.map(c => c.cardId));
|
||||
});
|
||||
|
||||
test('energy: energyByTurn + carry (max 1) of unspent energy', () => {
|
||||
let state = createMatch(DEFAULT_RULESET, [flatDeck(1, 'a'), flatDeck(1, 'b')], 3);
|
||||
const first = state.players[0].hand[0].cardId;
|
||||
state = applyAction(state, { type: 'play', player: 0, cardId: first, lane: 0 }); // p0 spends 1, p1 saves 1
|
||||
state = commitBoth(state);
|
||||
assert.deepEqual(state.players.map(p => p.energy), [2, 3]);
|
||||
state = commitBoth(state); // both save everything; carry is capped at 1
|
||||
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', () => {
|
||||
let state = createMatch(DEFAULT_RULESET, decks(), 17);
|
||||
state = commit(applyAction(state, { type: 'timeout', player: 0 }), 1);
|
||||
assert.equal(isOver(state), false);
|
||||
state = applyAction(state, { type: 'timeout', player: 0 });
|
||||
assert.deepEqual([result(state)?.winner, result(state)?.reason], [1, 'afk']);
|
||||
const conceded = applyAction(createMatch(DEFAULT_RULESET, decks(), 1), { type: 'concede', player: 1 });
|
||||
assert.equal(result(conceded)?.winner, 0);
|
||||
assert.deepEqual(legalActions(conceded, 0), []);
|
||||
});
|
||||
|
||||
test('two passing players draw after 6 turns', () => {
|
||||
let state = createMatch(DEFAULT_RULESET, decks(), 21);
|
||||
while (!isOver(state)) state = commitBoth(state);
|
||||
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', () => {
|
||||
for (let seed = 0; seed < 20; seed++) {
|
||||
const end = randomPlay(seed);
|
||||
assert.ok(result(end)!.turns <= DEFAULT_RULESET.turns);
|
||||
assert.deepEqual(randomPlay(seed), end);
|
||||
assert.deepEqual(replay(DEFAULT_RULESET, decks(String(seed)), seed, end.actions), end);
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user