forked from WikiDeck/wikideck
Merge remote-tracking branch 'origin/night/2026-11-16' into night/modes/hosting
This commit is contained in:
+107
-56
@@ -1,67 +1,119 @@
|
||||
# Card data: real stat distributions (council-data)
|
||||
|
||||
Status: **interim**, generated 2026-11-16 23:06 EST. The full 330-card run is still fetching pageviews politely; this file and `card-sample.json` will be regenerated.
|
||||
Status: **final for tonight**, 236 fully enriched cards, generated 2026-11-16 23:20 EST. Sampling stopped early on night-lead's request because Wikimedia was rate-limiting (429) our shared egress IP. 330 cards were picked; the first 236 finished enrichment.
|
||||
|
||||
Method: `scripts/night/card_sample.py` draws random ns0 articles in batches of 20 and keeps those passing the `server/wiki.ts` filter (thumbnail from upload/thumb.wikimedia.org, intro extract of at least 40 characters). It enriches them with the same API parameters as `server/enrichment.ts`: six completed months Jun–Oct 2026; attention uses October. It adds Wikidata P31 and 30-day drift (views 10-17..11-15 vs 09-17..10-16). `scripts/night/card_analyze.py` produces the tables below.
|
||||
**Method:** `scripts/night/card_sample.py` draws random ns0 articles in batches of 20 and keeps those that pass the `server/wiki.ts` filter: a thumbnail from upload/thumb.wikimedia.org and an intro extract of at least 40 characters. About 44% of random pages pass. Each card is enriched with the same API parameters as `server/enrichment.ts`:
|
||||
- six completed months, Jun–Oct 2026; attention uses October
|
||||
- monthly views summed from the daily REST pageviews
|
||||
|
||||
## Headline findings (INTERIM: 100 fully enriched random illustrated cards; 330 sampled, rest still fetching under Wikimedia 429 rate limits)
|
||||
On top of that it adds Wikidata P31 and a 30-day drift (views 10-17..11-15 vs 09-17..10-16).
|
||||
|
||||
1. **Raw stats are compressed and skewed.** Median card: attention 33, depth 63, reach 24 (p10–p90: attention 23–53, depth 54–71, reach 9–48). No card above 81 on anything; 100 is unreachable honestly. **Use the 1–10 tier tables below (sample deciles), not 0–100.**
|
||||
2. **Correlation is weaker than feared, except attention↔depth (Spearman 0.59).** Reach is nearly independent of both (0.10 / 0.02): stub villages get many bot-made language editions. So reach is a real separate axis; attention+depth partly double-count fame.
|
||||
3. **Underlying raw values are very long-tailed:** monthly views median 94 (p90 1,438, max 14k); pageBytes median 6 KB; languageCount median 4, and **10% have 0 other languages** (reach 0).
|
||||
4. **Trend is mostly negative:** 69% of cards have trendPercent < 0 (median −10%), 31% positive, 14% swing by more than 50%. Null is rare (1%). A "Trending" keyword fires for about a third of cards: fine as a small ±1.
|
||||
5. **Live values are fairly stable in score terms:** 30-day pageview drift median |18%| (p90 55%), but that moves the attention score by only a median of **1.4 points** (p90 5.6). So "live vs. mint" differences are small for random cards; big swings only come from deliberate inflation (see the critic's point A4).
|
||||
6. **The legacy `category()` buckets are unusable as factions:** Culture 53%, People 30%, Nature 9%, History 5%, Science 3%, **Space 0%**.
|
||||
7. **Candidate factions from Wikidata P31 (instance of), clean and readable:** People 31%, Places 25%, Nature 10%, Structures 6%, Works 5%, Events 5%, Sport 3%, Ideas & Tech 3%, Organisations 2%, unclassified 10%. Suggest **6 factions**: People, Places, Nature, Works & Culture (Works + Organisations + Sport), Structures, Events & Ideas (Events + Ideas & Tech), plus a neutral fallback. People and Places are big, so faction bonuses should scale with *share in deck*, not raw count, or the small factions need their own perks.
|
||||
8. **Starter/loaner list:** frozen stats for up to 4 cards per legacy category, spread across tiers, in `docs/game/starter-cards.json` (Space has no sample cards: hand-pick e.g. the Moon from `shared/catalog.ts`).
|
||||
**Politeness:** the sampler runs serially at 1 request a second or slower, honours Retry-After, and caches every response to disk. `scripts/night/card_analyze.py` produces everything below, plus the `percentiles` (99 cut points each, for DESIGN §1.1) in `card-sample.json`.
|
||||
|
||||
## Files
|
||||
- `card-sample.json`: `cards[]` with the `PageEnrichment` shape, plus `category` (legacy `category()`), `instanceOf` (P31), `faction` (the P31 rules below), `tiers` and `drift30`. Top level: `percentiles`, `tierBreakpoints`, `factionRules` and `note`.
|
||||
- `starter-cards.json`: the loaner **pool**, 20 real frozen snapshots (a `MintStatsSnapshot` in `snapshot`). It also holds `starterDeckPageIds`: the 48 DESIGN §2.1 starter titles with their real pageIds and `cardId`s.
|
||||
|
||||
## Headline findings (236 cards)
|
||||
1. **Raw scores are compressed.**
|
||||
|
||||
| score | median | p10–p90 | max |
|
||||
|---|---|---|---|
|
||||
| attention | 32 | 20–53 | 77 |
|
||||
| depth | 63 | 54–73 | 87 |
|
||||
| reach | 20 | 0–45 | 70 |
|
||||
|
||||
No honest card reaches 100. Use `percentiles` (§1.1) or the 1–10 tiers, never the raw 0–100 values.
|
||||
2. **Correlations (Spearman):**
|
||||
- attention and depth: 0.61, so these two double-count fame
|
||||
- reach is nearly independent of both (0.17 with attention, 0.02 with depth)
|
||||
3. **Reach has a hard floor:** 18% of cards (42) have 0 other languages, so reach is 0. Under the §1.1 counting, all of them get pct_reach of about 8.
|
||||
4. **Raw values are long-tailed:**
|
||||
|
||||
| value | median | p90 | max |
|
||||
|---|---|---|---|
|
||||
| monthly views | 82 | 1,576 | 42k |
|
||||
| pageBytes | 6.1 KB | 24 KB | |
|
||||
| languageCount | 3 | 22 | |
|
||||
5. **Trend is mostly down:**
|
||||
- 65% of cards have a negative trendPercent, 34% positive; median −9.5%
|
||||
- 16% swing by more than 50% either way
|
||||
- null: 1%
|
||||
6. **Live drift is small in score terms.** The 30-day median |pageview drift| is 22% (p90 60%). That moves attention by only **1.7 points** (p90 6.3), so at-mint and live values differ little unless someone inflates them.
|
||||
7. **The legacy `category()` split is very skewed:**
|
||||
|
||||
| category | share |
|
||||
|---|---|
|
||||
| Culture | 56% |
|
||||
| People | 26% |
|
||||
| Nature | 8% |
|
||||
| History | 8% |
|
||||
| Science | 1% |
|
||||
| Space | 0.4% |
|
||||
8. **Candidate factions from P31:**
|
||||
|
||||
| faction | share |
|
||||
|---|---|
|
||||
| People | 29% |
|
||||
| Places | 20% |
|
||||
| Nature | 8% |
|
||||
| Structures | 7% |
|
||||
| Works | 5% |
|
||||
| Events | 5% |
|
||||
| Organisations | 4% |
|
||||
| Ideas & Tech | 3% |
|
||||
| Sport | 3% |
|
||||
| unclassified | 14% |
|
||||
|
||||
Suggested 6 for v2: People, Places, Nature, Works & Culture (Works + Organisations + Sport), Structures, Events & Ideas, plus a neutral fallback.
|
||||
|
||||
## Full tables
|
||||
|
||||
Sample: **100 cards**; ~44% (149/340 logged during sampling) of random pages pass the illustrated filter. Pageviews available for 100.
|
||||
Sample: **236 cards**; ~44% (149/340 logged during sampling) of random pages pass the illustrated filter. Pageviews available for 236.
|
||||
|
||||
| stat | n | min | p10 | p25 | median | p75 | p90 | max | mean | skew |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| attention | 100 | 13 | 23 | 27 | 33 | 41 | 53 | 69 | 35 | 0.75 |
|
||||
| depth | 100 | 50 | 54 | 59 | 63 | 68 | 71 | 81 | 63 | 0.24 |
|
||||
| reach | 100 | 0 | 9 | 16 | 24 | 36 | 48 | 59 | 26 | 0.11 |
|
||||
| pageBytes | 100 | 998 | 1804 | 3407 | 6018 | 12512 | 19161 | 74169 | 9885 | 3.20 |
|
||||
| languageCount | 100 | 0 | 1 | 2 | 4 | 11 | 27 | 56 | 9 | 1.83 |
|
||||
| monthlyViews | 100 | 5 | 22 | 43 | 94 | 277 | 1438 | 14374 | 611 | 5.76 |
|
||||
| dailyAverage | 100 | 0.2 | 0.7 | 1.4 | 3.0 | 8.9 | 46.4 | 463.7 | 19.7 | 5.76 |
|
||||
| trendPercent | 99 | -86.6 | -45.1 | -26.4 | -10.4 | 4.5 | 21.1 | 187.1 | -9.5 | 1.83 |
|
||||
| drift30Percent | 99 | -94.7 | -45.9 | -30.7 | -12.7 | -1.7 | 14.8 | 72.1 | -16.1 | -0.20 |
|
||||
| attention | 236 | 13 | 20 | 25 | 32 | 41 | 53 | 77 | 35 | 0.78 |
|
||||
| depth | 236 | 48 | 54 | 58 | 63 | 68 | 73 | 87 | 64 | 0.42 |
|
||||
| reach | 236 | 0 | 0 | 10 | 20 | 33 | 45 | 70 | 23 | 0.36 |
|
||||
| pageBytes | 236 | 772 | 1847 | 3084 | 6110 | 12805 | 24412 | 168332 | 11691 | 4.61 |
|
||||
| languageCount | 236 | 0 | 0 | 1 | 3 | 9 | 22 | 124 | 8 | 4.14 |
|
||||
| monthlyViews | 236 | 5 | 16 | 30 | 82 | 300 | 1576 | 42025 | 812 | 9.82 |
|
||||
| dailyAverage | 236 | 0.2 | 0.5 | 1.0 | 2.6 | 9.7 | 50.8 | 1355.6 | 26.2 | 9.82 |
|
||||
| trendPercent | 234 | -86.6 | -49.3 | -26.3 | -9.5 | 5.3 | 31.2 | 388.9 | -3.6 | 4.11 |
|
||||
| drift30Percent | 235 | -94.7 | -58.2 | -33.8 | -12.9 | 1.0 | 27.7 | 2268.7 | -4.2 | 14.07 |
|
||||
|
||||
**Spearman rank correlations** (cards with pageviews):
|
||||
|
||||
| | attention | depth | reach | trendPercent | drift30Percent |
|
||||
|---|---|---|---|---|---|
|
||||
| attention | 1.00 | 0.59 | 0.10 | 0.24 | 0.25 |
|
||||
| depth | 0.59 | 1.00 | 0.02 | 0.07 | 0.05 |
|
||||
| reach | 0.10 | 0.02 | 1.00 | -0.10 | 0.24 |
|
||||
| trendPercent | 0.24 | 0.07 | -0.10 | 1.00 | 0.53 |
|
||||
| drift30Percent | 0.25 | 0.05 | 0.24 | 0.53 | 1.00 |
|
||||
| attention | 1.00 | 0.61 | 0.17 | 0.35 | 0.33 |
|
||||
| depth | 0.61 | 1.00 | 0.02 | 0.15 | 0.14 |
|
||||
| reach | 0.17 | 0.02 | 1.00 | 0.00 | 0.09 |
|
||||
| trendPercent | 0.35 | 0.15 | 0.00 | 1.00 | 0.31 |
|
||||
| drift30Percent | 0.33 | 0.14 | 0.09 | 0.31 | 1.00 |
|
||||
|
||||
(n=99; attention~monthlyViews, depth~pageBytes, reach~languageCount are monotonic so their rank correlations are identical.)
|
||||
(n=234; attention~monthlyViews, depth~pageBytes, reach~languageCount are monotonic so their rank correlations are identical.)
|
||||
|
||||
**trendPercent sign:** positive 31 (31%), negative 68 (69%), zero 0; null (prior month 0 or no views) 1. |trend| > 50%: 14; > 100%: 1.
|
||||
**trendPercent sign:** positive 79 (34%), negative 153 (65%), zero 2; null (prior month 0 or no views) 2. |trend| > 50%: 38; > 100%: 7.
|
||||
|
||||
**30-day drift** (views 10-17..11-15 vs 09-17..10-16): median |drift| 18%, p90 |drift| 55%. Attention score change implied: median 1.4 points, p90 5.6 points.
|
||||
**30-day drift** (views 10-17..11-15 vs 09-17..10-16): median |drift| 22%, p90 |drift| 60%. Attention score change implied: median 1.7 points, p90 6.3 points.
|
||||
|
||||
**attention histogram (deciles 0-9,10-19..90-100):** 0 4 30 39 12 11 4 0 0 0
|
||||
**depth histogram (deciles 0-9,10-19..90-100):** 0 0 0 0 0 30 53 15 2 0
|
||||
**reach histogram (deciles 0-9,10-19..90-100):** 10 25 23 23 10 9 0 0 0 0
|
||||
**attention histogram (deciles 0-9,10-19..90-100):** 0 19 74 74 36 20 12 1 0 0
|
||||
**depth histogram (deciles 0-9,10-19..90-100):** 0 0 0 0 2 72 117 38 7 0
|
||||
**reach histogram (deciles 0-9,10-19..90-100):** 42 60 53 43 21 15 1 1 0 0
|
||||
|
||||
Reach = 0 (no other languages): 10; reach 100 (>=999 langs) impossible in practice, max langs 56. Attention null: 0; attention 0: 0.
|
||||
Reach = 0 (no other languages): 42; reach 100 (>=999 langs) impossible in practice, max langs 124. Attention null: 0; attention 0: 0.
|
||||
|
||||
**Sum of three stats:** min 84, p10 97, p25 107, median 120, p75 140, p90 155, max 193
|
||||
**Sum of three stats:** min 73, p10 89, p25 102, median 116, p75 135, p90 156, max 222
|
||||
|
||||
**Legacy `category()` (server/wiki.ts):** Culture 53, People 30, Nature 9, History 5, Science 3
|
||||
**Legacy `category()` (server/wiki.ts):** Culture 133, People 62, Nature 19, History 18, Science 3, Space 1
|
||||
|
||||
**Top Wikidata P31 classes:** human 30, taxon 8, river 4, village 4, commune of France 3, musical group 2, building 2, castle 2, rural municipality of Austria 1, municipality of Austria 1, municipality of Brazil 1, television film 1, nor'easter 1, rail company (Japan) 1, village of Poland 1, municipality 1, civil parish 1, association football match 1, final 1, local government area of Victoria 1, plant disease 1, basketball team season 1, mosque 1, functional programming language 1, purely functional programming language 1, dependently typed programming language 1, programming language 1, free software 1, proof assistant 1, municipality of Croatia 1, municipality of Bangladesh 1, town 1, town in the United States 1, municipality of Georgia 1, epiphyte 1, protest 1, region of Mauritania 1, legislative election 1, musical work/composition 1, plateau 1
|
||||
**Top Wikidata P31 classes:** human 64, taxon 16, village 7, commune of France 6, river 5, human settlement 4, musical group 3, building 3, gene 3, village of Poland 2, civil parish 2, protest 2, legislative election 2, castle 2, events in a specific year or time period 2, township of Pennsylvania 2, film 2, company 2, island 2, rural municipality of Austria 1, municipality of Austria 1, municipality of Brazil 1, television film 1, nor'easter 1, rail company (Japan) 1, municipality 1, association football match 1, final 1, local government area of Victoria 1, plant disease 1, basketball team season 1, mosque 1, functional programming language 1, purely functional programming language 1, dependently typed programming language 1, programming language 1, free software 1, proof assistant 1, municipality of Croatia 1, municipality of Bangladesh 1
|
||||
|
||||
No Wikidata item: 0; no P31: 6
|
||||
No Wikidata item: 0; no P31: 13
|
||||
|
||||
**Most frequent category words (cards containing):** stubs 35, births 27, people 26, from 24, century 22, living 16, geography 15, deaths 14, american 13, county 9, university 8, male 7, united 7, film 7, players 7, district 6, states 6, sports 6, biography 6, television 5, alumni 5, genera 5, established 5, villages 5, football 5, city 5, buildings 5, expatriate 5, sportspeople 5, sportsmen 5, towns 4, municipalities 4, writers 4, women 4, faculty 4, communes 4, rivers 4, places 4, establishments 4, actors 4, california 4, russian 4, association 4, structures 4, described 3, british 3, french 3, ohio 3, academics 3, based 3, japanese 3, pennsylvania 3, argentine 3, australia 3, populated 3, directors 3, rock 3, musical 3, conference 3, division 3
|
||||
**Most frequent category words (cards containing):** stubs 81, births 55, people 50, from 50, century 46, living 33, geography 30, american 29, deaths 28, united 27, county 27, states 23, established 21, establishments 20, alumni 18, places 17, university 16, buildings 16, state 15, national 14, structures 14, male 13, players 12, district 11, villages 11, sportsmen 11, members 11, described 10, football 10, sports 10, city 10, film 10, british 9, companies 9, populated 9, sportspeople 9, biography 9, york 9, women 8, taxa 8, germany 8, politicians 8, television 7, writers 7, french 7, genera 7, based 7, communes 7, language 7, expatriate 7, named 7, olympics 7, completed 7, historic 7, register 7, faculty 6, pennsylvania 6, civil 6, history 6, california 6
|
||||
|
||||
|
||||
## Rank-normalised tiers (1–10)
|
||||
@@ -70,29 +122,28 @@ Tier = 1 + number of breakpoints the score is **>=**. Breakpoints are the sample
|
||||
|
||||
| stat | p10 | p20 | p30 | p40 | p50 | p60 | p70 | p80 | p90 |
|
||||
|---|---|---|---|---|---|---|---|---|---|
|
||||
| attention | 23 | 25 | 28 | 31 | 33 | 36 | 38 | 45 | 53 |
|
||||
| depth | 54 | 57 | 60 | 61 | 63 | 65 | 67 | 69 | 72 |
|
||||
| reach | 10 | 10 | 16 | 20 | 26 | 30 | 36 | 39 | 49 |
|
||||
| attention | 20 | 24 | 27 | 30 | 32 | 35 | 39 | 44 | 53 |
|
||||
| depth | 54 | 57 | 59 | 61 | 63 | 65 | 67 | 69 | 73 |
|
||||
| reach | 0 | 10 | 10 | 16 | 20 | 26 | 30 | 36 | 45 |
|
||||
|
||||
Resulting tier counts — attention: None:0 1:10 2:9 3:7 4:14 5:8 6:12 7:7 8:12 9:10 10:11
|
||||
; depth: 1:7 2:11 3:12 4:6 5:11 6:11 7:9 8:9 9:14 10:10
|
||||
; reach: 1:10 2:0 3:13 4:12 5:15 6:8 7:11 8:10 9:11 10:10
|
||||
Resulting tier counts — attention: None:0 1:19 2:27 3:24 4:23 5:23 6:17 7:28 8:25 9:22 10:28
|
||||
; depth: 1:14 2:23 3:26 4:21 5:25 6:26 7:22 8:21 9:30 10:28
|
||||
; reach: 1:0 2:42 3:0 4:30 5:30 6:32 7:21 8:27 9:27 10:27
|
||||
|
||||
Starter candidates: 19 written to /tmp/claude-1000/-home-eric-worker-jobs-night-council-data/d4e31987-ce7f-4f28-8262-8f0225215102/scratchpad/starter.json: Counter({'Nature': 4, 'People': 4, 'History': 4, 'Culture': 4, 'Science': 3})
|
||||
|
||||
## Candidate factions (Wikidata P31 rules)
|
||||
|
||||
| faction | n | share | median attention | median depth | median reach | example |
|
||||
|---|---|---|---|---|---|---|
|
||||
| People | 31 | 31% | 33 | 65 | 26 | Salahuddin of Aceh |
|
||||
| Places | 25 | 25% | 28 | 61 | 36 | St. Georgen am Längsee |
|
||||
| Nature | 10 | 10% | 30 | 56 | 31 | Dichromorpha viridis |
|
||||
| Other | 10 | 10% | 52 | 64 | 22 | Village (Pennsylvania) |
|
||||
| Structures | 6 | 6% | 32 | 58 | 16 | Pathrail Mosque |
|
||||
| Works | 5 | 5% | 40 | 64 | 16 | The Best of Men |
|
||||
| Events | 5 | 5% | 38 | 72 | 10 | April 2021 nor'easter |
|
||||
| Sport | 3 | 3% | 25 | 71 | 0 | 1912 Argentine Primera División final |
|
||||
| Ideas & Tech | 3 | 3% | 37 | 62 | 20 | Agda (programming language) |
|
||||
| Organisations | 2 | 2% | 50 | 62 | 24 | Hiroshima Electric Railway |
|
||||
| People | 68 | 29% | 31 | 65 | 22 | Salahuddin of Aceh |
|
||||
| Places | 48 | 20% | 28 | 61 | 32 | St. Georgen am Längsee |
|
||||
| Other | 34 | 14% | 40 | 65 | 16 | Village (Pennsylvania) |
|
||||
| Nature | 20 | 8% | 30 | 56 | 29 | Dichromorpha viridis |
|
||||
| Structures | 17 | 7% | 26 | 57 | 10 | Pathrail Mosque |
|
||||
| Works | 12 | 5% | 36 | 63 | 13 | The Best of Men |
|
||||
| Events | 12 | 5% | 40 | 72 | 13 | April 2021 nor'easter |
|
||||
| Organisations | 10 | 4% | 48 | 68 | 10 | Hiroshima Electric Railway |
|
||||
| Ideas & Tech | 8 | 3% | 30 | 63 | 16 | Agda (programming language) |
|
||||
| Sport | 7 | 3% | 27 | 70 | 16 | 1912 Argentine Primera División final |
|
||||
|
||||
Unclassified P31 labels: typeface 1, annexation 1, position 1, family 1
|
||||
Unclassified P31 labels: typeface 1, annexation 1, position 1, family 1, historic site 1, automobile manufacturer 1, historical society 1, stock character 1, pigeon breed 1, shopping center 1, Wikimedia list article 1, clinical sign 1, tram route 1, rubber-tyred tram 1, oil refinery 1, waterfall 1, orisha 1, water deity 1, Loa 1, arch 1, award 1, sex scandal 1, military base 1, artillery battery 1
|
||||
|
||||
+3
-1
@@ -160,7 +160,9 @@ These are the default `starterDecks`: four 12-card loaner decks.
|
||||
Everything after them still applies: `powerByCost`, `onTopicBonus`, `vanillaBonus`, the §10.1 keyword choice and `keywordParams`.
|
||||
A mode that changes those numbers changes loaners exactly as it changes owned cards.
|
||||
- **Pinned cost isn't fame.** Cost was set by hand to fit the curve, not from the article's fame. Rarity is `Common` (frame only) and trend is 0.
|
||||
- **Loaner ids:** `cardId` = `loaner:<kebab-title>`, and `pageId` = the article's real pageId if the UI has it, otherwise `null`. Copies are counted per `cardId`.
|
||||
- **Loaner ids:** `cardId` = `loaner:<kebab-title>`, and `pageId` = the article's real pageId (v1 pins the 4 `shared/catalog.ts` ones: Moon 19331, Periodic table 23053, Octopus 22780,
|
||||
Albert Einstein 736; the rest are filled in from one batched API call in v1.1, `null` until then). The copy limit counts per `pageId`
|
||||
together with owned copies (§2); a loaner with `pageId: null` counts per `cardId`.
|
||||
- **Relation to `docs/game/starter-cards.json`** (council-data, real frozen snapshots of random articles): that file is the
|
||||
**loaner pool** for the sim and for "fill a slot with a loaner" in the deck builder. It is **not** the default starter decks.
|
||||
The decks below pin their values on purpose, for two reasons. Famous, recognisable articles would all derive to cost 5–6.
|
||||
|
||||
+11703
-104
File diff suppressed because it is too large
Load Diff
+1678
-302
File diff suppressed because it is too large
Load Diff
@@ -137,3 +137,20 @@ for name, cs in sorted(by.items(), key=lambda kv: -len(kv[1])):
|
||||
other = collections.Counter(x['label'] for c in by.get('Other', []) for x in c['instanceOf'])
|
||||
print('\nUnclassified P31 labels: ' + ', '.join(f'{k} {v}' for k, v in other.most_common(25)))
|
||||
if len(sys.argv) > 4: json.dump({c['pageId']: c['faction'] for c in C}, open(sys.argv[4], 'w'))
|
||||
if len(sys.argv) > 3:
|
||||
s = json.load(open(sys.argv[3])); fmap = {c['pageId']: c['faction'] for c in C}
|
||||
for p in s['cards']: p['faction'] = fmap[p['pageId']]
|
||||
json.dump(s, open(sys.argv[3], 'w'), indent=1, ensure_ascii=False)
|
||||
if len(sys.argv) > 5:
|
||||
d['factionRules'] = [[n, rx] for n, rx in FAC]; d['tierBreakpoints'] = T
|
||||
def cuts(k):
|
||||
v = sorted(c['stats'][k] for c in C if c['stats'][k] is not None); n = len(v)
|
||||
return [v[max(0, math.ceil(i * n / 100) - 1)] for i in range(1, 100)]
|
||||
d['percentiles'] = {k: cuts(k) for k in ('attention', 'depth', 'reach')}
|
||||
d['percentilesMethod'] = 'cut point i (1..99) = nearest-rank i-th percentile of the sample snapshot score (sorted ascending, index ceil(i*n/100)-1). Use with DESIGN.md §1.1 counting.'
|
||||
if not d['rawPagesSeen']:
|
||||
d['randomBatches'], d['rawPagesSeen'] = 17, 340
|
||||
d['randomBatchesNote'] = 'Sampling was resumed from a saved state, so full batch counts were lost. These are the counts logged at batch 17 (149 illustrated of 340 raw pages, 44% pass rate). The 330 picked cards came from about 38 batches; this sample holds the first N of those that finished enrichment before sampling stopped (Wikimedia 429s).'
|
||||
d['note'] = 'docs/game/starter-cards.json is the loaner POOL (real frozen snapshots of random articles), used by the sim and the deck builder to fill slots. The default starter decks are defined in DESIGN.md §2.1; their real pageIds are in starter-cards.json under starterDeckPageIds.'
|
||||
for c in d['cards']: c['category'] = c['legacyCategory']
|
||||
json.dump(d, open(sys.argv[5], 'w'), indent=1, ensure_ascii=False)
|
||||
|
||||
@@ -17,7 +17,7 @@ def get(url, cache=True):
|
||||
if os.environ.get('CACHE_ONLY') and 'wikidata.org' not in url:
|
||||
return {'__missing': True}
|
||||
for attempt in range(6):
|
||||
wait = (1.0 if 'en.wikipedia.org' in url else 0.25) - (time.time() - _last[0])
|
||||
wait = 1.0 - (time.time() - _last[0])
|
||||
if wait > 0: time.sleep(wait)
|
||||
_last[0] = time.time()
|
||||
req = urllib.request.Request(url, headers={'User-Agent': UA, 'Accept': 'application/json'})
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* Card derivation (DESIGN §1 and §10.1): a host-frozen CardInput becomes a GameCard.
|
||||
* Pure and deterministic. The engine itself never reads raw 0–100 stats; hosts call
|
||||
* deriveCard() before createMatch. Owner: engine-b.
|
||||
*/
|
||||
import { FACTION_KEYWORD, V1_KEYWORDS } from './keywords.ts';
|
||||
import { STATS, type Faction, type GameCard, type Rarity, type Stat } from './types.ts';
|
||||
|
||||
/** §1.4 tie-break order: depth and reach are the hardest to inflate. */
|
||||
export const HOME_TIE_ORDER: readonly Stat[] = ['depth', 'reach', 'attention'];
|
||||
|
||||
export interface CardInput {
|
||||
cardId: string;
|
||||
/** null for loaners without a known article (§2.1). */
|
||||
pageId: number | null;
|
||||
title: string;
|
||||
category: Faction;
|
||||
rarity: Rarity;
|
||||
/** Only the derived scores are read (MintStatsSnapshot.stats). */
|
||||
snapshot: { stats: { attention: number | null; depth: number; reach: number } };
|
||||
/** Frozen by the host at match start. */
|
||||
live: { trendPercent: number | null; dailyAverage: number | null };
|
||||
/** §1.10, set by the host. Only 'unchecked' changes derivation (cost cap). */
|
||||
check: 'verified' | 'unverified' | 'unchecked' | 'loaner';
|
||||
/** Loaners only (§2.1): replaces §1.1–1.5. Ignored unless check === 'loaner'. */
|
||||
pinned?: { cost: number; home: Stat; faction: Faction };
|
||||
}
|
||||
|
||||
/** 99 ascending cut points per stat (§1.1). */
|
||||
export type PercentileTable = Record<Stat, readonly number[]>;
|
||||
|
||||
/** The rules config keys derivation reads (§9). */
|
||||
export interface DerivationRules {
|
||||
costThresholds: readonly number[];
|
||||
powerByCost: readonly number[];
|
||||
vanillaBonus: number;
|
||||
keywordsEnabled: readonly string[];
|
||||
keywordParams: Record<string, Record<string, number>>;
|
||||
trendUp: number;
|
||||
trendDown: number;
|
||||
trendMinDaily: number;
|
||||
uncheckedCostCap: number;
|
||||
}
|
||||
|
||||
export const DEFAULT_DERIVATION: DerivationRules = {
|
||||
costThresholds: [15, 35, 55, 75, 90],
|
||||
powerByCost: [0, 1, 2, 4, 6, 8, 10],
|
||||
vanillaBonus: 1,
|
||||
keywordsEnabled: V1_KEYWORDS,
|
||||
keywordParams: {},
|
||||
trendUp: 25, trendDown: -200, trendMinDaily: 20, // −200: no down arrow in v1 (§1.6)
|
||||
uncheckedCostCap: 4,
|
||||
};
|
||||
|
||||
/** §1.1: cut points strictly below, plus half of those equal, rounded down. */
|
||||
export function percentile(score: number, cuts: readonly number[]): number {
|
||||
let below = 0, equal = 0;
|
||||
for (const cut of cuts) {
|
||||
if (cut < score) below++;
|
||||
else if (cut === score) equal++;
|
||||
}
|
||||
return Math.floor(below + equal / 2);
|
||||
}
|
||||
|
||||
export function percentiles(stats: CardInput['snapshot']['stats'], table: PercentileTable): Record<Stat, number | null> {
|
||||
return {
|
||||
attention: stats.attention === null ? null : percentile(stats.attention, table.attention),
|
||||
depth: percentile(stats.depth, table.depth),
|
||||
reach: percentile(stats.reach, table.reach),
|
||||
};
|
||||
}
|
||||
|
||||
/** §1.2: integer mean of the non-null percentiles, rounded half up. */
|
||||
export function fame(pct: Record<Stat, number | null>): number {
|
||||
const values = STATS.map(stat => pct[stat]).filter((value): value is number => value !== null);
|
||||
if (!values.length) return 0;
|
||||
return Math.floor(values.reduce((total, value) => total + value, 0) / values.length + 0.5);
|
||||
}
|
||||
|
||||
/** §1.2: 1 + the number of thresholds ≤ fame. */
|
||||
export function costFor(fameValue: number, thresholds: readonly number[]): number {
|
||||
return 1 + thresholds.filter(threshold => threshold <= fameValue).length;
|
||||
}
|
||||
|
||||
/** §1.4: highest percentile, ties by depth > reach > attention; null never wins. */
|
||||
export function homeStat(pct: Record<Stat, number | null>): Stat {
|
||||
let best: Stat = HOME_TIE_ORDER[0];
|
||||
for (const stat of HOME_TIE_ORDER) {
|
||||
const value = pct[stat], current = pct[best];
|
||||
if (value !== null && (current === null || value > current)) best = stat;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** §1.6: ±1 past the thresholds; 0 for null or for articles under trendMinDaily views a day. */
|
||||
export function trendFor(live: CardInput['live'], rules: Pick<DerivationRules, 'trendUp' | 'trendDown' | 'trendMinDaily'>): -1 | 0 | 1 {
|
||||
const { trendPercent, dailyAverage } = live;
|
||||
if (trendPercent === null || !Number.isFinite(trendPercent)) return 0;
|
||||
if (dailyAverage === null || !(dailyAverage >= rules.trendMinDaily)) return 0;
|
||||
if (trendPercent >= rules.trendUp) return 1;
|
||||
if (trendPercent <= rules.trendDown) return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* §10.1: cost 1 → vanilla (+vanillaBonus); edition if enabled and the deck has another
|
||||
* copy; else the faction keyword if enabled; else vanilla without the bonus.
|
||||
*/
|
||||
export function keywordFor(faction: Faction, cost: number, hasCopyInDeck: boolean, rules: Pick<DerivationRules, 'keywordsEnabled'>):
|
||||
{ keyword: string | null; vanilla: boolean } {
|
||||
if (cost === 1) return { keyword: null, vanilla: true };
|
||||
if (hasCopyInDeck && rules.keywordsEnabled.includes('edition')) return { keyword: 'edition', vanilla: false };
|
||||
const keyword = FACTION_KEYWORD[faction];
|
||||
return rules.keywordsEnabled.includes(keyword) ? { keyword, vanilla: false } : { keyword: null, vanilla: false };
|
||||
}
|
||||
|
||||
export function deriveCard(input: CardInput, table: PercentileTable, rules: DerivationRules = DEFAULT_DERIVATION,
|
||||
hasCopyInDeck = false): GameCard {
|
||||
const pinned = input.check === 'loaner' ? input.pinned : undefined;
|
||||
const pct = percentiles(input.snapshot.stats, table);
|
||||
let cost = pinned ? pinned.cost : costFor(fame(pct), rules.costThresholds);
|
||||
if (input.check === 'unchecked') cost = Math.min(cost, rules.uncheckedCostCap);
|
||||
const faction = pinned ? pinned.faction : input.category;
|
||||
const base = rules.powerByCost[cost];
|
||||
if (base === undefined) throw new RangeError(`powerByCost has no entry for cost ${cost}`);
|
||||
const { keyword, vanilla } = keywordFor(faction, cost, hasCopyInDeck, rules);
|
||||
const delta = keyword ? Math.max(-3, Math.min(0, rules.keywordParams[keyword]?.powerDelta ?? 0)) : 0;
|
||||
return {
|
||||
cardId: input.cardId, pageId: input.pageId, title: input.title, faction, rarity: pinned ? 'Common' : input.rarity,
|
||||
cost, power: Math.max(0, base + (vanilla ? rules.vanillaBonus : 0) + delta),
|
||||
home: pinned ? pinned.home : homeStat(pct), trend: pinned ? 0 : trendFor(input.live, rules), keyword,
|
||||
source: input.check === 'loaner' ? 'loaner' : 'owned', check: input.check,
|
||||
};
|
||||
}
|
||||
|
||||
/** Derive a whole deck; Edition (if enabled) needs to know about copies of the same pageId. */
|
||||
export function deriveDeck(inputs: readonly CardInput[], table: PercentileTable, rules: DerivationRules = DEFAULT_DERIVATION): GameCard[] {
|
||||
const key = (input: CardInput) => input.pageId ?? `card:${input.cardId}`;
|
||||
const counts = new Map<number | string, number>();
|
||||
for (const input of inputs) counts.set(key(input), (counts.get(key(input)) ?? 0) + 1);
|
||||
return inputs.map(input => deriveCard(input, table, rules, (counts.get(key(input)) ?? 0) > 1));
|
||||
}
|
||||
+11
-2
@@ -6,5 +6,14 @@ 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';
|
||||
export {
|
||||
KEYWORDS, PORTALS, KEYWORD_IDS, PORTAL_IDS, FACTION_KEYWORD, V1_KEYWORDS, OPTIONAL_KEYWORDS, allies, activePortal, isOnTopic, hiddenFrom,
|
||||
type KeywordDef, type PortalDef, type EffectContext,
|
||||
} from './keywords.ts';
|
||||
export {
|
||||
DEFAULT_DERIVATION, HOME_TIE_ORDER, percentile, percentiles, fame, costFor, homeStat, trendFor, keywordFor, deriveCard, deriveDeck,
|
||||
type CardInput, type PercentileTable, type DerivationRules,
|
||||
} from './derive.ts';
|
||||
export {
|
||||
STARTER_POOL, STARTER_DECKS, loanerCard, loanerInput, previewPool, starterDeck, starterDeckById, type StarterDeckDef,
|
||||
} from './starter.ts';
|
||||
|
||||
+149
-5
@@ -23,7 +23,7 @@
|
||||
* - 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';
|
||||
import type { CardInPlay, GameCard, MatchState, PlayerId, Stat } 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;
|
||||
@@ -88,8 +88,152 @@ export function isOnTopic(state: MatchState, card: CardInPlay): boolean {
|
||||
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> = {};
|
||||
/** §10.1 v1 faction keywords. */
|
||||
export const FACTION_KEYWORD = {
|
||||
Culture: 'viral', Nature: 'rising', People: 'local', Science: 'encyclopedic', History: 'nostalgic', Space: 'translated',
|
||||
} as const;
|
||||
export const V1_KEYWORDS: readonly string[] = Object.values(FACTION_KEYWORD);
|
||||
/** Implemented but off by default (modes only). */
|
||||
export const OPTIONAL_KEYWORDS: readonly string[] = ['edition', 'obscure', 'wildcard'];
|
||||
|
||||
/** True when `card` should be shown face down to `viewer` (Obscure). viewFor should use this. */
|
||||
export function hiddenFrom(state: MatchState, card: CardInPlay, viewer: PlayerId): boolean {
|
||||
return card.owner !== viewer && state.phase !== 'over' && card.card.keyword === 'obscure' && state.ruleset.keywordsEnabled.includes('obscure');
|
||||
}
|
||||
|
||||
const amount = (ctx: EffectContext, fallback: number) => ctx.params.amount ?? fallback;
|
||||
|
||||
/**
|
||||
* DESIGN §10.2 (PR #17 @ cf2fceb). All keywords only add power, use no RNG, and
|
||||
* the largest single swing is +2. Every number comes from Ruleset.keywordParams.
|
||||
* `powerDelta` params are applied at derivation (derive.ts), not here.
|
||||
*/
|
||||
export const KEYWORDS: Record<string, KeywordDef> = {
|
||||
viral: {
|
||||
id: 'viral', name: 'Viral', text: '+{amount} power for each other card you revealed earlier this turn (max +{cap}).',
|
||||
onReveal(ctx, self) {
|
||||
let earlier = 0;
|
||||
for (const lane of ctx.state.lanes) for (const card of lane.cards[self.owner])
|
||||
if (card !== self && card.turn === ctx.state.turn) earlier++;
|
||||
const gain = Math.min(earlier * amount(ctx, 1), ctx.params.cap ?? 2);
|
||||
if (gain > 0) { self.bonus += gain; ctx.log(`${self.card.title}: Viral +${gain}`); }
|
||||
},
|
||||
},
|
||||
rising: {
|
||||
id: 'rising', name: 'Rising', text: 'End of turn: +{amount} power (max +{cap} in total).',
|
||||
// Stateless: the gain so far is a function of how many ends of turn it has seen.
|
||||
endOfTurn(ctx, self) {
|
||||
const step = amount(ctx, 1), cap = ctx.params.cap ?? 2;
|
||||
const seen = ctx.state.turn - self.turn; // ends of turn before this one
|
||||
const gain = Math.min(cap, (seen + 1) * step) - Math.min(cap, seen * step);
|
||||
if (gain > 0) { self.bonus += gain; ctx.log(`${self.card.title}: Rising +${gain}`); }
|
||||
},
|
||||
},
|
||||
local: {
|
||||
id: 'local', name: 'Local', text: '+{amount} power while on-topic.',
|
||||
ongoing(ctx, self, target) {
|
||||
return target === self && isOnTopic(ctx.state, self) ? amount(ctx, 1) : 0;
|
||||
},
|
||||
},
|
||||
encyclopedic: {
|
||||
id: 'encyclopedic', name: 'Encyclopedic', text: '+{amount} power if there are no other cards here.',
|
||||
onReveal(ctx, self) {
|
||||
const [mine, theirs] = ctx.state.lanes[self.lane].cards;
|
||||
if (mine.every(card => card === self) && theirs.length === 0) {
|
||||
self.bonus += amount(ctx, 2);
|
||||
ctx.log(`${self.card.title}: Encyclopedic +${amount(ctx, 2)}`);
|
||||
}
|
||||
},
|
||||
},
|
||||
nostalgic: {
|
||||
id: 'nostalgic', name: 'Nostalgic', text: '+{amount} power if you are losing here.',
|
||||
onReveal(ctx, self) {
|
||||
// Topic power just before this card was added (§10.2): take it out, measure, put it back.
|
||||
const side = ctx.state.lanes[self.lane].cards[self.owner];
|
||||
const index = side.indexOf(self);
|
||||
side.splice(index, 1);
|
||||
const [mine, theirs] = [self.owner, self.owner === 0 ? 1 : 0]
|
||||
.map(seat => ctx.state.lanes[self.lane].cards[seat].reduce((sum, card) => sum + ctx.power(card), 0));
|
||||
side.splice(index, 0, self);
|
||||
if (theirs > mine) {
|
||||
self.bonus += amount(ctx, 2);
|
||||
ctx.log(`${self.card.title}: Nostalgic +${amount(ctx, 2)}`);
|
||||
}
|
||||
},
|
||||
},
|
||||
translated: {
|
||||
id: 'translated', name: 'Translated', text: '+{amount} power to your most recently revealed card in each other Topic.',
|
||||
onReveal(ctx, self) {
|
||||
ctx.state.lanes.forEach((lane, index) => {
|
||||
if (index === self.lane) return;
|
||||
// Highest global reveal sequence number among your cards there (§10.2).
|
||||
const latest = lane.cards[self.owner].reduce<CardInPlay | undefined>((best, card) => (!best || card.seq > best.seq ? card : best), undefined);
|
||||
if (!latest) return;
|
||||
latest.bonus += amount(ctx, 1);
|
||||
ctx.log(`${self.card.title}: Translated +${amount(ctx, 1)} to ${latest.card.title}`);
|
||||
});
|
||||
},
|
||||
},
|
||||
|
||||
// Implemented, disabled by default (not in keywordsEnabled): modes only.
|
||||
edition: {
|
||||
id: 'edition', name: 'Edition', text: '+{amount} power for each other copy of this article on your side.',
|
||||
ongoing(ctx, self, target) {
|
||||
if (target !== self) return 0;
|
||||
let copies = 0;
|
||||
for (const lane of ctx.state.lanes) for (const card of lane.cards[self.owner])
|
||||
if (card !== self && self.card.pageId !== null && card.card.pageId === self.card.pageId) copies++;
|
||||
return copies * amount(ctx, 2);
|
||||
},
|
||||
},
|
||||
obscure: {
|
||||
id: 'obscure', name: 'Obscure', text: 'Your opponent sees this card face down until the match ends.',
|
||||
},
|
||||
wildcard: {
|
||||
id: 'wildcard', name: 'Wildcard', text: "On reveal: its home stat becomes this Topic's stat.",
|
||||
onReveal(ctx, self) {
|
||||
const stat: Stat = ctx.state.lanes[self.lane].topic.stat;
|
||||
if (self.card.home !== stat) { self.card.home = stat; ctx.log(`${self.card.title}: Wildcard → ${stat}`); }
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
/** DESIGN §10.3 Portals, keyed by portal id (= Topic id). Numbers from Ruleset.portalParams. */
|
||||
export const PORTALS: Record<string, PortalDef> = {
|
||||
'main-page': {
|
||||
id: 'main-page', name: 'Main Page', text: 'At scoring, each card here gets +{amount} power.',
|
||||
atScoring(ctx) {
|
||||
const [a, b] = ctx.state.lanes[ctx.lane].cards;
|
||||
return [a.length * amount(ctx, 1), b.length * amount(ctx, 1)];
|
||||
},
|
||||
},
|
||||
trending: {
|
||||
id: 'trending', name: 'Trending', text: 'Trend arrows count ×{factor} here.',
|
||||
ongoing(ctx, target) { return target.card.trend * ((ctx.params.factor ?? 2) - 1); },
|
||||
},
|
||||
'featured-article': {
|
||||
id: 'featured-article', name: 'Featured Article',
|
||||
text: 'At scoring, the player with the single highest-power card here gets +{amount}.',
|
||||
atScoring(ctx) {
|
||||
const best = ctx.state.lanes[ctx.lane].cards.map(side => Math.max(-1, ...side.map(card => ctx.power(card))));
|
||||
if (best[0] === best[1] || Math.max(best[0], best[1]) < 0) return [0, 0];
|
||||
return best[0] > best[1] ? [amount(ctx, 2), 0] : [0, amount(ctx, 2)];
|
||||
},
|
||||
},
|
||||
stub: {
|
||||
id: 'stub', name: 'Stub', text: 'Lane capacity here is {value} per player.',
|
||||
capacity(ctx) { return ctx.params.value ?? 2; },
|
||||
},
|
||||
interwiki: {
|
||||
id: 'interwiki', name: 'Interwiki', text: '+{amount} Topic power here if you have a card in every Topic.',
|
||||
// Judged at scoring: in v1 Topic leads only matter at scoring (initiative alternates, underdog off).
|
||||
atScoring(ctx) {
|
||||
const lanes = ctx.state.lanes;
|
||||
return [0, 1].map(seat => lanes.every(lane => lane.cards[seat].length > 0) ? amount(ctx, 1) : 0) as [number, number];
|
||||
},
|
||||
},
|
||||
disambiguation: {
|
||||
id: 'disambiguation', name: 'Disambiguation', text: 'Every card here counts as on-topic.', allOnTopic: true,
|
||||
},
|
||||
};
|
||||
|
||||
/** Filled in by engine-b (§10.3). Ids must be in PORTAL_IDS. */
|
||||
export const PORTALS: Record<string, PortalDef> = {};
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
* 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 { DEFAULT_DERIVATION, deriveCard, type CardInput, type DerivationRules } from './derive.ts';
|
||||
import { Rng } from './rng.ts';
|
||||
import type { Faction, GameCard, Stat } from './types.ts';
|
||||
|
||||
@@ -64,3 +65,63 @@ export function starterDeck(seed: number | string): GameCard[] {
|
||||
}
|
||||
return deck;
|
||||
}
|
||||
|
||||
// ---------- DESIGN §2.1 starter decks v1 (PR #18) ----------
|
||||
|
||||
type Pin = [cost: number, title: string, faction: Faction, home: Stat];
|
||||
|
||||
/** Real pageIds for the shared/catalog.ts cards; the others have none yet (§2.1), see loanerPageId. */
|
||||
const CATALOG_PAGE_IDS: Record<string, number> = { Moon: 19331, 'Periodic table': 23053, Octopus: 22780, 'Albert Einstein': 736 };
|
||||
|
||||
export interface StarterDeckDef { id: string; name: string; cards: readonly Pin[] }
|
||||
|
||||
/** Four 12-card loaner decks, each with the curve 1,1,2,2,3,3,3,4,4,5,5,6, 6+6 factions and 4 cards per home stat. */
|
||||
export const STARTER_DECKS: readonly StarterDeckDef[] = [
|
||||
{ id: 'stargazers', name: 'Stargazers', cards: [
|
||||
[1, 'Moon', 'Space', 'reach'], [1, 'Electron', 'Science', 'depth'], [2, 'Mars', 'Space', 'attention'],
|
||||
[2, 'Periodic table', 'Science', 'depth'], [3, 'Saturn', 'Space', 'reach'], [3, 'Photosynthesis', 'Science', 'attention'],
|
||||
[3, 'Black hole', 'Space', 'depth'], [4, 'Quantum mechanics', 'Science', 'reach'], [4, 'Milky Way', 'Space', 'attention'],
|
||||
[5, 'DNA', 'Science', 'attention'], [5, 'Sun', 'Space', 'reach'], [6, 'Theory of relativity', 'Science', 'depth'],
|
||||
] },
|
||||
{ id: 'field-guide', name: 'Field Guide', cards: [
|
||||
[1, 'Octopus', 'Nature', 'depth'], [1, 'Stonehenge', 'History', 'attention'], [2, 'Axolotl', 'Nature', 'attention'],
|
||||
[2, 'Rosetta Stone', 'History', 'reach'], [3, 'Coral reef', 'Nature', 'depth'], [3, 'Roman Empire', 'History', 'reach'],
|
||||
[3, 'Honey bee', 'Nature', 'attention'], [4, 'Ancient Egypt', 'History', 'depth'], [4, 'Amazon rainforest', 'Nature', 'reach'],
|
||||
[5, 'Blue whale', 'Nature', 'attention'], [5, 'Great Wall of China', 'History', 'reach'], [6, 'World War II', 'History', 'depth'],
|
||||
] },
|
||||
{ id: 'headliners', name: 'Headliners', cards: [
|
||||
[1, 'Haiku', 'Culture', 'attention'], [1, 'Ada Lovelace', 'People', 'depth'], [2, 'Jazz', 'Culture', 'attention'],
|
||||
[2, 'Marie Curie', 'People', 'reach'], [3, 'Mona Lisa', 'Culture', 'reach'], [3, 'Frida Kahlo', 'People', 'attention'],
|
||||
[3, 'Chess', 'Culture', 'depth'], [4, 'Leonardo da Vinci', 'People', 'reach'], [4, 'The Beatles', 'Culture', 'attention'],
|
||||
[5, 'William Shakespeare', 'People', 'depth'], [5, 'Olympic Games', 'Culture', 'reach'], [6, 'Wolfgang Amadeus Mozart', 'People', 'depth'],
|
||||
] },
|
||||
{ id: 'pioneers', name: 'Pioneers', cards: [
|
||||
[1, 'Sputnik 1', 'Space', 'reach'], [1, 'Nikola Tesla', 'People', 'attention'], [2, 'Hubble Space Telescope', 'Space', 'depth'],
|
||||
[2, 'Isaac Newton', 'People', 'reach'], [3, 'Neil Armstrong', 'People', 'attention'], [3, 'Jupiter', 'Space', 'reach'],
|
||||
[3, 'Galileo Galilei', 'People', 'depth'], [4, 'Albert Einstein', 'People', 'attention'], [4, 'International Space Station', 'Space', 'depth'],
|
||||
[5, 'Apollo 11', 'Space', 'attention'], [5, 'Charles Darwin', 'People', 'reach'], [6, 'Solar System', 'Space', 'depth'],
|
||||
] },
|
||||
];
|
||||
|
||||
const kebab = (title: string) => title.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
|
||||
|
||||
/** §2.1: the real pageId for the shared/catalog.ts cards, null for the rest (copies then count per cardId). */
|
||||
export function loanerPageId(title: string): number | null {
|
||||
return Object.hasOwn(CATALOG_PAGE_IDS, title) ? CATALOG_PAGE_IDS[title] : null;
|
||||
}
|
||||
|
||||
/** The §1 CardInput for a pinned loaner. Snapshot stats are unused (pinned replaces §1.1–1.5). */
|
||||
export function loanerInput([cost, title, faction, home]: Pin): CardInput {
|
||||
return { cardId: `loaner:${kebab(title)}`, pageId: loanerPageId(title), title, category: faction, rarity: 'Common',
|
||||
snapshot: { stats: { attention: null, depth: 0, reach: 0 } }, live: { trendPercent: null, dailyAverage: null },
|
||||
check: 'loaner', pinned: { cost, home, faction } };
|
||||
}
|
||||
|
||||
const NO_TABLE = { attention: [], depth: [], reach: [] };
|
||||
|
||||
/** A §2.1 starter deck by id, derived with the given rules (modes that change the curve change loaners too). */
|
||||
export function starterDeckById(id: string, rules: DerivationRules = DEFAULT_DERIVATION): GameCard[] {
|
||||
const def = STARTER_DECKS.find(deck => deck.id === id);
|
||||
if (!def) throw new RangeError(`Unknown starter deck: ${id}`);
|
||||
return def.cards.map(pin => deriveCard(loanerInput(pin), NO_TABLE, rules));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
DEFAULT_DERIVATION, percentile, percentiles, fame, costFor, homeStat, trendFor, keywordFor, deriveCard, deriveDeck,
|
||||
type CardInput, type PercentileTable, type DerivationRules, type Faction,
|
||||
} from '../shared/game/index.ts';
|
||||
import { forAll } from './game/property.ts';
|
||||
|
||||
/** Cut points 1..99: score s sits at percentile ~s, which makes examples readable. */
|
||||
const LINEAR = Array.from({ length: 99 }, (_, i) => i + 1);
|
||||
const TABLE: PercentileTable = { attention: LINEAR, depth: LINEAR, reach: LINEAR };
|
||||
const RULES = DEFAULT_DERIVATION;
|
||||
const LIVE = { trendPercent: null, dailyAverage: null };
|
||||
|
||||
function input(stats: CardInput['snapshot']['stats'], overrides: Partial<CardInput> = {}): CardInput {
|
||||
return { cardId: 'c1', pageId: 1, title: 'T', category: 'Science', rarity: 'Common',
|
||||
snapshot: { stats }, live: LIVE, check: 'verified', ...overrides };
|
||||
}
|
||||
|
||||
test('percentile counts cuts strictly below plus half of equal ones, rounded down (§1.1)', () => {
|
||||
assert.equal(percentile(0, LINEAR), 0);
|
||||
assert.equal(percentile(50, LINEAR), 49);
|
||||
assert.equal(percentile(50.5, LINEAR), 50);
|
||||
assert.equal(percentile(1000, LINEAR), 99);
|
||||
assert.equal(percentile(5, [5, 5, 5, 5]), 2);
|
||||
assert.equal(percentile(5, [1, 5, 5, 9]), 2);
|
||||
});
|
||||
|
||||
test('null attention gives a null percentile and is ignored by fame (§1.1, §1.2)', () => {
|
||||
const pct = percentiles({ attention: null, depth: 61, reach: 31 }, TABLE);
|
||||
assert.deepEqual(pct, { attention: null, depth: 60, reach: 30 });
|
||||
assert.equal(fame(pct), 45);
|
||||
});
|
||||
|
||||
test('fame rounds half up', () => {
|
||||
assert.equal(fame({ attention: 10, depth: 11, reach: null }), 11);
|
||||
assert.equal(fame({ attention: 10, depth: 10, reach: 11 }), 10);
|
||||
assert.equal(fame({ attention: 10, depth: 11, reach: 11 }), 11);
|
||||
});
|
||||
|
||||
test('cost is 1 + thresholds ≤ fame, spanning 1–6 (§1.2)', () => {
|
||||
const t = RULES.costThresholds;
|
||||
assert.deepEqual([0, 14, 15, 54, 55, 89, 90, 100].map(f => costFor(f, t)), [1, 1, 2, 3, 4, 5, 6, 6]);
|
||||
});
|
||||
|
||||
test('home stat: highest percentile, ties depth > reach > attention, never null (§1.4)', () => {
|
||||
assert.equal(homeStat({ attention: 90, depth: 10, reach: 10 }), 'attention');
|
||||
assert.equal(homeStat({ attention: 50, depth: 50, reach: 50 }), 'depth');
|
||||
assert.equal(homeStat({ attention: 50, depth: 40, reach: 50 }), 'reach');
|
||||
assert.equal(homeStat({ attention: null, depth: 0, reach: 0 }), 'depth');
|
||||
assert.equal(homeStat({ attention: null, depth: 0, reach: 1 }), 'reach');
|
||||
});
|
||||
|
||||
test('trend: ±1 at inclusive thresholds, 0 for null, 0 under trendMinDaily (§1.6)', () => {
|
||||
const modeRules = { ...RULES, trendDown: -25 }; // a mode that turns the down arrow back on
|
||||
const t = (trendPercent: number | null, dailyAverage: number | null = 100) => trendFor({ trendPercent, dailyAverage }, modeRules);
|
||||
assert.deepEqual([t(25), t(24.9), t(-25), t(-24.9), t(null), t(Number.NaN), t(1e9)], [1, 0, -1, 0, 0, 0, 1]);
|
||||
assert.equal(trendFor({ trendPercent: -99, dailyAverage: 1000 }, RULES), 0, 'v1 default: no down arrow');
|
||||
assert.equal(t(80, 19.9), 0);
|
||||
assert.equal(t(80, 20), 1);
|
||||
assert.equal(t(80, null), 0);
|
||||
});
|
||||
|
||||
test('keyword choice: cost 1 vanilla, faction keyword otherwise, disabled → plain vanilla (§10.1)', () => {
|
||||
const expected: Record<Faction, string> = { Culture: 'viral', Nature: 'rising', People: 'local',
|
||||
Science: 'encyclopedic', History: 'nostalgic', Space: 'translated' };
|
||||
for (const [faction, keyword] of Object.entries(expected) as [Faction, string][]) {
|
||||
assert.deepEqual(keywordFor(faction, 1, false, RULES), { keyword: null, vanilla: true });
|
||||
assert.deepEqual(keywordFor(faction, 3, false, RULES), { keyword, vanilla: false });
|
||||
assert.deepEqual(keywordFor(faction, 3, false, { keywordsEnabled: [] }), { keyword: null, vanilla: false });
|
||||
}
|
||||
assert.equal(keywordFor('Culture', 3, true, RULES).keyword, 'viral', 'edition is off by default');
|
||||
assert.equal(keywordFor('Culture', 3, true, { keywordsEnabled: ['edition', 'viral'] }).keyword, 'edition');
|
||||
assert.equal(keywordFor('Culture', 1, true, { keywordsEnabled: ['edition'] }).keyword, null, 'cost 1 stays vanilla');
|
||||
});
|
||||
|
||||
test('deriveCard: cost, power, vanillaBonus, home, trend and source', () => {
|
||||
// pct 80/70/60 → fame 70 → cost 4 → power 6, Science → encyclopedic
|
||||
const card = deriveCard(input({ attention: 81, depth: 71, reach: 61 }, { live: { trendPercent: 40, dailyAverage: 50 } }), TABLE);
|
||||
assert.deepEqual(card, { cardId: 'c1', pageId: 1, title: 'T', faction: 'Science', rarity: 'Common',
|
||||
cost: 4, power: 6, home: 'attention', trend: 1, keyword: 'encyclopedic', source: 'owned', check: 'verified' });
|
||||
const cheap = deriveCard(input({ attention: 5, depth: 5, reach: 5 }, { check: 'loaner' }), TABLE);
|
||||
assert.deepEqual([cheap.cost, cheap.power, cheap.keyword, cheap.source], [1, 2, null, 'loaner']);
|
||||
const disabled = deriveCard(input({ attention: 81, depth: 71, reach: 61 }), TABLE, { ...RULES, keywordsEnabled: [] });
|
||||
assert.deepEqual([disabled.power, disabled.keyword], [6, null]);
|
||||
});
|
||||
|
||||
test('rarity is cosmetic: it never changes cost, power or keyword (§1.7)', () => {
|
||||
const stats = { attention: 40, depth: 60, reach: 20 };
|
||||
const cards = (['Common', 'Rare', 'Epic', 'Legendary'] as const).map(rarity => deriveCard(input(stats, { rarity }), TABLE));
|
||||
for (const card of cards) assert.deepEqual({ ...card, rarity: 'Common' }, { ...cards[0], rarity: 'Common' });
|
||||
});
|
||||
|
||||
test('unchecked cards are capped at uncheckedCostCap and keep their home stat (§1.10)', () => {
|
||||
const stats = { attention: 100, depth: 100, reach: 99 };
|
||||
const checked = deriveCard(input(stats), TABLE);
|
||||
const unchecked = deriveCard(input(stats, { check: 'unchecked' }), TABLE);
|
||||
assert.equal(checked.cost, 6);
|
||||
assert.equal(unchecked.cost, 4);
|
||||
assert.equal(unchecked.power, RULES.powerByCost[4]);
|
||||
assert.equal(unchecked.home, checked.home);
|
||||
});
|
||||
|
||||
test('powerDelta from keywordParams lowers keyword cards only, clamped to −3..0', () => {
|
||||
const rules: DerivationRules = { ...RULES, keywordParams: { encyclopedic: { powerDelta: -2 }, viral: { powerDelta: -9 } } };
|
||||
assert.equal(deriveCard(input({ attention: 81, depth: 71, reach: 61 }), TABLE, rules).power, 4);
|
||||
assert.equal(deriveCard(input({ attention: 81, depth: 71, reach: 61 }, { category: 'Culture' }), TABLE, rules).power, 3);
|
||||
assert.equal(deriveCard(input({ attention: 5, depth: 5, reach: 5 }), TABLE, rules).power, 2);
|
||||
});
|
||||
|
||||
test('deriveDeck marks copies for Edition when it is enabled', () => {
|
||||
const a = input({ attention: 50, depth: 50, reach: 50 }, { cardId: 'a', pageId: 7, category: 'Culture' });
|
||||
const b = { ...a, cardId: 'b' };
|
||||
const c = { ...a, cardId: 'c', pageId: 8 };
|
||||
const rules = { ...RULES, keywordsEnabled: [...RULES.keywordsEnabled, 'edition'] };
|
||||
assert.deepEqual(deriveDeck([a, b, c], TABLE, rules).map(card => card.keyword), ['edition', 'edition', 'viral']);
|
||||
assert.deepEqual(deriveDeck([a, b, c], TABLE).map(card => card.keyword), ['viral', 'viral', 'viral']);
|
||||
});
|
||||
|
||||
test('power depends only on cost: forged stats only move a card up the curve (§1.3)', () => {
|
||||
forAll(300, g => {
|
||||
const stats = { attention: g.bool(0.1) ? null : g.int(0, 100), depth: g.int(0, 100), reach: g.int(0, 100) };
|
||||
const card = deriveCard(input(stats, { category: g.pick(['Space', 'Nature', 'People', 'Science', 'History', 'Culture'] as const) }), TABLE);
|
||||
assert.ok(card.cost >= 1 && card.cost <= 6);
|
||||
assert.equal(card.power, RULES.powerByCost[card.cost] + (card.cost === 1 ? RULES.vanillaBonus : 0));
|
||||
assert.ok(stats[card.home] !== null, 'home is never a null stat');
|
||||
const bumped = { ...stats, depth: Math.min(100, stats.depth + g.int(1, 30)) };
|
||||
assert.ok(deriveCard(input(bumped), TABLE).cost >= card.cost, 'raising a stat never lowers cost');
|
||||
});
|
||||
});
|
||||
|
||||
test('deriveCard rejects a rules config with no power for the derived cost', () => {
|
||||
assert.throws(() => deriveCard(input({ attention: 100, depth: 100, reach: 100 }), TABLE, { ...RULES, powerByCost: [0, 1, 2] }), RangeError);
|
||||
});
|
||||
|
||||
test('pinned values replace §1.1–1.5 for loaners only (§2.1)', () => {
|
||||
const pinned = { cost: 5, home: 'reach' as const, faction: 'History' as const };
|
||||
const stats = { attention: 5, depth: 5, reach: 5 };
|
||||
const loaner = deriveCard(input(stats, { check: 'loaner', pinned, rarity: 'Epic', live: { trendPercent: 99, dailyAverage: 999 } }), TABLE);
|
||||
assert.deepEqual([loaner.cost, loaner.power, loaner.home, loaner.faction, loaner.keyword, loaner.rarity, loaner.trend, loaner.source],
|
||||
[5, 8, 'reach', 'History', 'nostalgic', 'Common', 0, 'loaner']);
|
||||
const owned = deriveCard(input(stats, { pinned }), TABLE);
|
||||
assert.deepEqual([owned.cost, owned.faction], [1, 'Science'], 'pinned is ignored when check !== loaner');
|
||||
const cheap = deriveCard(input(stats, { check: 'loaner', pinned: { ...pinned, cost: 1 } }), TABLE);
|
||||
assert.deepEqual([cheap.power, cheap.keyword], [2, null], 'vanillaBonus still applies to pinned cost-1');
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* Golden test: DESIGN.md §12 worked example (PR #17 @ cf2fceb), encoded exactly.
|
||||
* The Topic order, hands and initiative are injected; each player's per-turn
|
||||
* commit list is the table's, in the listed queue order. Owner: engine-b.
|
||||
*
|
||||
* Passes against night/engine/core e0ac157 (frozen §3–§7 rules).
|
||||
*/
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
DEFAULT_RULESET, applyAction, createMatch, isOver, lanePower, result, starterDeck, topicsLed,
|
||||
type Action, type GameCard, type MatchState, type PlayerId, type Ruleset, type Stat, type Faction,
|
||||
} from '../shared/game/index.ts';
|
||||
|
||||
const opts = {};
|
||||
|
||||
/** §9 defaults the example depends on. */
|
||||
const FROZEN = {
|
||||
laneCapacity: 3, powerByCost: [0, 1, 2, 4, 6, 8, 10], onTopicBonus: [0, 1, 1, 2, 2, 3, 3],
|
||||
vanillaBonus: 1, energyCarryMax: 1, underdog: false, portalReveal: [2, 3, 4],
|
||||
};
|
||||
|
||||
const c = (owner: string, title: string, faction: Faction, cost: number, power: number, home: Stat, keyword: string | null): GameCard =>
|
||||
({ cardId: `${owner}:${title}`, pageId: title.length * 1000 + cost, title, faction, rarity: 'Common',
|
||||
cost, power, home, trend: 0, keyword, source: 'loaner' });
|
||||
|
||||
const ANA = [
|
||||
c('ana', 'Octopus', 'Nature', 1, 2, 'depth', null),
|
||||
c('ana', 'Moon', 'Space', 2, 2, 'reach', 'translated'),
|
||||
c('ana', 'Coral reef', 'Nature', 2, 2, 'depth', 'rising'),
|
||||
c('ana', 'Albert Einstein', 'People', 4, 6, 'attention', 'local'),
|
||||
c('ana', 'Ancient Rome', 'History', 5, 8, 'depth', 'nostalgic'),
|
||||
c('ana', 'Library of Alexandria', 'History', 4, 6, 'depth', 'nostalgic'),
|
||||
c('ana', 'Periodic table', 'Science', 3, 4, 'depth', 'encyclopedic'),
|
||||
];
|
||||
const BO = [
|
||||
c('bo', 'Haiku', 'Culture', 1, 2, 'attention', null),
|
||||
c('bo', 'Mars', 'Space', 2, 2, 'reach', 'translated'),
|
||||
c('bo', 'Jazz', 'Culture', 2, 2, 'attention', 'viral'),
|
||||
c('bo', 'Pop music', 'Culture', 4, 6, 'attention', 'viral'),
|
||||
c('bo', 'Jupiter', 'Space', 5, 8, 'reach', 'translated'),
|
||||
c('bo', 'Fern', 'Nature', 3, 4, 'depth', 'rising'),
|
||||
c('bo', 'Mona Lisa', 'Culture', 3, 4, 'attention', 'viral'),
|
||||
];
|
||||
|
||||
const T1 = 0, T2 = 1, T3 = 2;
|
||||
/** [player, title, lane] in queue order, per turn (§12 table). */
|
||||
const PLAN: [PlayerId, string, number][][] = [
|
||||
[[0, 'Octopus', T1], [1, 'Haiku', T2]],
|
||||
[[0, 'Moon', T3]], // Bo passes to carry 1
|
||||
[[0, 'Coral reef', T1], [1, 'Mars', T3], [1, 'Jazz', T2]],
|
||||
[[1, 'Pop music', T3], [0, 'Albert Einstein', T2]],
|
||||
[[0, 'Ancient Rome', T3], [1, 'Jupiter', T1]],
|
||||
[[1, 'Fern', T1], [0, 'Library of Alexandria', T1], [1, 'Mona Lisa', T2], [0, 'Periodic table', T2]],
|
||||
];
|
||||
|
||||
function setup(): MatchState {
|
||||
const rules: Ruleset = { ...DEFAULT_RULESET };
|
||||
const state = createMatch(rules, [starterDeck('golden-a'), starterDeck('golden-b')], 1);
|
||||
const pool = state.ruleset.topicPool;
|
||||
const find = (id: string) => pool.find(t => t.id === id) ?? assert.fail(`topic ${id} missing from the default pool`);
|
||||
const topics = [find('archive'), find('main-page'), find('translations')];
|
||||
state.lanes = topics.map(topic => ({ topic, portalRevealed: false, cards: [[], []] }));
|
||||
// Inject: every card the example plays starts in hand, nothing left to draw.
|
||||
state.players[0].hand = structuredClone(ANA);
|
||||
state.players[1].hand = structuredClone(BO);
|
||||
for (const p of state.players) p.deck = [];
|
||||
state.initiative = 0; // Ana has initiative on odd turns
|
||||
return state;
|
||||
}
|
||||
|
||||
const id = (player: PlayerId, title: string) => `${player === 0 ? 'ana' : 'bo'}:${title}`;
|
||||
|
||||
function playTurn(state: MatchState, plays: [PlayerId, string, number][]): MatchState {
|
||||
for (const [player, title, lane] of plays) state = applyAction(state, { type: 'play', player, cardId: id(player, title), lane } as Action);
|
||||
state = applyAction(state, { type: 'commit', player: 0 });
|
||||
return applyAction(state, { type: 'commit', player: 1 });
|
||||
}
|
||||
|
||||
test('§12 golden: rules defaults match the frozen §9 values', opts, () => {
|
||||
for (const [key, value] of Object.entries(FROZEN)) assert.deepEqual((DEFAULT_RULESET as unknown as Record<string, unknown>)[key], value, key);
|
||||
});
|
||||
|
||||
test('§12 golden: final Topic powers 19–15, 15–19, 13–10; Ana (p0) wins 2–1', opts, () => {
|
||||
let state = setup();
|
||||
const energyAtStart: [number, number][] = [];
|
||||
const snapshots: MatchState[] = [];
|
||||
for (const plays of PLAN) {
|
||||
energyAtStart.push([state.players[0].energy, state.players[1].energy]);
|
||||
state = playTurn(state, plays);
|
||||
snapshots.push(state);
|
||||
}
|
||||
assert.ok(isOver(state));
|
||||
const r = result(state)!;
|
||||
assert.deepEqual(r.lanePower, [[19, 15], [15, 19], [13, 10]]);
|
||||
assert.equal(r.winner, 0);
|
||||
assert.deepEqual(r.topicsLed, [2, 1]);
|
||||
|
||||
// Carry-over: Bo 4 at the start of turn 3; Ana 5, 6, 7 at the start of turns 4, 5, 6.
|
||||
assert.equal(energyAtStart[2][1], 4);
|
||||
assert.deepEqual(energyAtStart.slice(3).map(e => e[0]), [5, 6, 7]);
|
||||
|
||||
// After turn 5: T2 is 9–9 and Bo leads it by consensus (2 on-topic cards to 1).
|
||||
const afterFive = snapshots[4];
|
||||
assert.deepEqual(lanePower(afterFive, T2), [9, 9]);
|
||||
assert.deepEqual(lanePower(afterFive, T1), [9, 8]);
|
||||
assert.deepEqual(lanePower(afterFive, T3), [13, 10]);
|
||||
assert.deepEqual(topicsLed(afterFive), [2, 1]);
|
||||
});
|
||||
|
||||
test('§12 golden: per-turn Topic powers match the table', opts, () => {
|
||||
const expected = [
|
||||
[[3, 0], [0, 3], [0, 0]],
|
||||
[[4, 0], [0, 3], [3, 0]],
|
||||
[[8, 0], [0, 8], [3, 3]],
|
||||
[[9, 0], [9, 8], [3, 9]],
|
||||
[[9, 8], [9, 9], [13, 10]],
|
||||
];
|
||||
let state = setup();
|
||||
PLAN.slice(0, 5).forEach((plays, turn) => {
|
||||
state = playTurn(state, plays);
|
||||
assert.deepEqual(state.lanes.map((_, lane) => lanePower(state, lane)), expected[turn], `after turn ${turn + 1}`);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,229 @@
|
||||
// Keyword and Portal unit tests (DESIGN §10.2, §10.3 — PR #17 @ cf2fceb). Owner: engine-b.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
DEFAULT_RULESET, FACTION_KEYWORD, KEYWORDS, OPTIONAL_KEYWORDS, PORTALS, V1_KEYWORDS, hiddenFrom, isOnTopic, parseRuleset,
|
||||
} from '../shared/game/index.ts';
|
||||
import { board, card, cardPower, ctxFor, endOfTurn, place, reveal, topic, atScoring } from './game/build.ts';
|
||||
|
||||
|
||||
test('registry: ids match keys, every entry has name and text, v1 set is one keyword per faction', () => {
|
||||
for (const [id, def] of [...Object.entries(KEYWORDS), ...Object.entries(PORTALS)]) {
|
||||
assert.equal(def.id, id);
|
||||
assert.ok(def.name && def.text, `${id} needs name and text`);
|
||||
}
|
||||
assert.deepEqual([...V1_KEYWORDS].sort(), ['encyclopedic', 'local', 'nostalgic', 'rising', 'translated', 'viral']);
|
||||
assert.equal(new Set(Object.values(FACTION_KEYWORD)).size, 6);
|
||||
for (const id of [...V1_KEYWORDS, ...OPTIONAL_KEYWORDS]) assert.ok(KEYWORDS[id], `${id} implemented`);
|
||||
});
|
||||
|
||||
test('the default ruleset (topic pool and params) validates', () => {
|
||||
assert.doesNotThrow(() => parseRuleset(DEFAULT_RULESET));
|
||||
for (const t of DEFAULT_RULESET.topicPool) if (t.portal) assert.equal(t.portal, t.id, 'portal id = topic id');
|
||||
assert.equal(DEFAULT_RULESET.topicPool.length, 9);
|
||||
});
|
||||
|
||||
// ---- viral ----
|
||||
test('viral: +1 per other own card revealed earlier this turn, any Topic, capped at +2', () => {
|
||||
const s = board();
|
||||
place(s, 0, 0, card(), s.turn - 1); // an older card does not count
|
||||
place(s, 1, 1, card()); // nor do the opponent's
|
||||
assert.equal(reveal(s, 0, 1, card({ keyword: 'viral' })).bonus, 0);
|
||||
place(s, 0, 2, card());
|
||||
// two earlier this turn now (the first viral card and this one) → +2
|
||||
assert.equal(reveal(s, 0, 2, card({ keyword: 'viral' })).bonus, 2);
|
||||
for (let i = 0; i < 3; i++) place(s, 0, 0, card());
|
||||
assert.equal(reveal(s, 0, 0, card({ keyword: 'viral' })).bonus, 2, 'cap');
|
||||
});
|
||||
|
||||
test('viral: the §12 example (Mars then Jazz → +1)', () => {
|
||||
const s = board();
|
||||
place(s, 1, 2, card({ title: 'Mars' }));
|
||||
assert.equal(reveal(s, 1, 1, card({ title: 'Jazz', keyword: 'viral' })).bonus, 1);
|
||||
});
|
||||
|
||||
// ---- rising ----
|
||||
test('rising: +1 at each end of turn, stopping after +2 in total', () => {
|
||||
const s = board();
|
||||
const r = place(s, 0, 0, card({ power: 2, keyword: 'rising' }));
|
||||
const seen: number[] = [];
|
||||
for (let i = 0; i < 4; i++) { endOfTurn(s, r); seen.push(r.bonus); s.turn++; }
|
||||
assert.deepEqual(seen, [1, 2, 2, 2]);
|
||||
});
|
||||
|
||||
test('rising: other bonuses do not count toward its cap', () => {
|
||||
const s = board();
|
||||
const r = place(s, 0, 0, card({ keyword: 'rising' }));
|
||||
r.bonus = 5;
|
||||
endOfTurn(s, r); s.turn++; endOfTurn(s, r); s.turn++; endOfTurn(s, r);
|
||||
assert.equal(r.bonus, 7);
|
||||
});
|
||||
|
||||
test('rising: respects keywordParams amount and cap', () => {
|
||||
const s = board();
|
||||
s.ruleset.keywordParams.rising = { amount: 2, cap: 3 };
|
||||
const r = place(s, 0, 0, card({ keyword: 'rising' }));
|
||||
endOfTurn(s, r); s.turn++; endOfTurn(s, r); s.turn++; endOfTurn(s, r);
|
||||
assert.equal(r.bonus, 3);
|
||||
});
|
||||
|
||||
// ---- local ----
|
||||
test('local: +1 only while on-topic, on top of the on-topic bonus', () => {
|
||||
const s = board();
|
||||
const on = place(s, 0, 1, card({ cost: 4, power: 6, home: 'attention', keyword: 'local' }));
|
||||
const off = place(s, 0, 0, card({ cost: 4, power: 6, home: 'attention', keyword: 'local' }));
|
||||
const plain = place(s, 1, 1, card({ cost: 4, power: 6, home: 'attention' }));
|
||||
assert.equal(cardPower(s, on) - cardPower(s, plain), 1);
|
||||
assert.equal(cardPower(s, off), 6);
|
||||
assert.equal(KEYWORDS.local.ongoing!(ctxFor(s, {}, 1), on, plain), 0, 'only buffs itself');
|
||||
});
|
||||
|
||||
// ---- encyclopedic ----
|
||||
test('encyclopedic: +2 only into a completely empty Topic (either side)', () => {
|
||||
const s = board();
|
||||
assert.equal(reveal(s, 0, 0, card({ keyword: 'encyclopedic' })).bonus, 2);
|
||||
place(s, 1, 1, card());
|
||||
assert.equal(reveal(s, 0, 1, card({ keyword: 'encyclopedic' })).bonus, 0, 'opponent card here');
|
||||
place(s, 0, 2, card());
|
||||
assert.equal(reveal(s, 0, 2, card({ keyword: 'encyclopedic' })).bonus, 0, 'own card here');
|
||||
});
|
||||
|
||||
// ---- nostalgic ----
|
||||
test('nostalgic: +2 when strictly losing, counted before this card is added', () => {
|
||||
const s = board();
|
||||
place(s, 0, 2, card({ power: 3, home: 'attention' }));
|
||||
place(s, 1, 2, card({ power: 9, home: 'attention' }));
|
||||
const n = reveal(s, 0, 2, card({ power: 8, home: 'depth', keyword: 'nostalgic' }));
|
||||
assert.equal(n.bonus, 2);
|
||||
assert.equal(s.lanes[2].cards[0].indexOf(n), 1, 'card is back in place, in reveal order');
|
||||
});
|
||||
|
||||
test('nostalgic: a tie is not losing, and neither is an empty Topic', () => {
|
||||
const s = board();
|
||||
place(s, 0, 2, card({ power: 4 }));
|
||||
place(s, 1, 2, card({ power: 4 }));
|
||||
assert.equal(reveal(s, 0, 2, card({ keyword: 'nostalgic' })).bonus, 0);
|
||||
assert.equal(reveal(s, 1, 0, card({ keyword: 'nostalgic' })).bonus, 0);
|
||||
});
|
||||
|
||||
// ---- translated ----
|
||||
test('translated: +1 to your most recently revealed card in each other Topic', () => {
|
||||
const s = board();
|
||||
const first = place(s, 0, 0, card());
|
||||
const latest = place(s, 0, 0, card());
|
||||
const enemy = place(s, 1, 2, card());
|
||||
const t = reveal(s, 0, 1, card({ keyword: 'translated' }));
|
||||
assert.deepEqual([first.bonus, latest.bonus, enemy.bonus, t.bonus], [0, 1, 0, 0]);
|
||||
});
|
||||
|
||||
test('translated: the §12 example (Jupiter → Jazz in T2 and Pop music in T3)', () => {
|
||||
const s = board();
|
||||
const haiku = place(s, 1, 1, card({ title: 'Haiku' }));
|
||||
const jazz = place(s, 1, 1, card({ title: 'Jazz' }));
|
||||
const mars = place(s, 1, 2, card({ title: 'Mars' }));
|
||||
const pop = place(s, 1, 2, card({ title: 'Pop music' }));
|
||||
reveal(s, 1, 0, card({ title: 'Jupiter', keyword: 'translated' }));
|
||||
assert.deepEqual([haiku.bonus, jazz.bonus, mars.bonus, pop.bonus], [0, 1, 0, 1]);
|
||||
});
|
||||
|
||||
// ---- optional keywords ----
|
||||
test('edition: +2 per other copy of the same pageId on your side (when enabled)', () => {
|
||||
const s = board();
|
||||
const a0 = place(s, 0, 1, card({ pageId: 41, power: 5, home: 'reach', keyword: 'edition' }));
|
||||
place(s, 0, 2, card({ pageId: 41, power: 5, home: 'depth', keyword: 'edition' }));
|
||||
assert.equal(cardPower(s, a0), 5, 'disabled by default');
|
||||
s.ruleset.keywordsEnabled = [...s.ruleset.keywordsEnabled, 'edition'];
|
||||
assert.equal(cardPower(s, a0), 7);
|
||||
s.lanes[1].cards[0] = []; s.lanes[2].cards[0] = [];
|
||||
const a = place(s, 0, 0, card({ pageId: 42, power: 5, home: 'reach', keyword: 'edition' }));
|
||||
assert.equal(cardPower(s, a), 5);
|
||||
place(s, 0, 2, card({ pageId: 42, power: 5, home: 'depth', keyword: 'edition' }));
|
||||
place(s, 1, 0, card({ pageId: 42 }));
|
||||
assert.equal(cardPower(s, a), 7);
|
||||
});
|
||||
|
||||
test('wildcard: its home stat becomes the Topic stat on reveal', () => {
|
||||
const s = board();
|
||||
s.ruleset.keywordsEnabled = [...s.ruleset.keywordsEnabled, 'wildcard'];
|
||||
const w = reveal(s, 0, 2, card({ home: 'attention', keyword: 'wildcard' }));
|
||||
assert.equal(w.card.home, 'reach');
|
||||
assert.ok(isOnTopic(s, w));
|
||||
});
|
||||
|
||||
test('obscure: hidden only from the opponent, only while running, only when enabled', () => {
|
||||
const s = board();
|
||||
const o = place(s, 0, 1, card({ keyword: 'obscure' }));
|
||||
(s.ruleset as unknown as { keywordsEnabled: string[] }).keywordsEnabled = ['obscure'];
|
||||
assert.equal(hiddenFrom(s, o, 1), true);
|
||||
assert.equal(hiddenFrom(s, o, 0), false);
|
||||
(s.ruleset as unknown as { keywordsEnabled: string[] }).keywordsEnabled = [...V1_KEYWORDS];
|
||||
assert.equal(hiddenFrom(s, o, 1), false, 'disabled by default');
|
||||
(s.ruleset as unknown as { keywordsEnabled: string[] }).keywordsEnabled = ['obscure'];
|
||||
s.phase = 'over';
|
||||
assert.equal(hiddenFrom(s, o, 1), false);
|
||||
});
|
||||
|
||||
// ---- Portals (§10.3) ----
|
||||
test('isOnTopic: home stat matches the Topic stat; Disambiguation makes everything on-topic once revealed', () => {
|
||||
const s = board([topic('depth'), topic('reach', 'disambiguation'), topic('reach')]);
|
||||
assert.ok(isOnTopic(s, place(s, 0, 0, card({ home: 'depth' }))));
|
||||
assert.ok(!isOnTopic(s, place(s, 0, 2, card({ home: 'depth' }))));
|
||||
const d = place(s, 0, 1, card({ home: 'attention' }));
|
||||
assert.ok(isOnTopic(s, d));
|
||||
s.lanes[1].portalRevealed = false;
|
||||
assert.ok(!isOnTopic(s, d), 'Portal not active while face down');
|
||||
});
|
||||
|
||||
test('Main Page: +1 per card at scoring', () => {
|
||||
const s = board([topic('depth'), topic('attention', 'main-page'), topic('reach')]);
|
||||
place(s, 0, 1, card()); place(s, 0, 1, card()); place(s, 1, 1, card());
|
||||
assert.deepEqual(atScoring(s, 1), [2, 1]);
|
||||
});
|
||||
|
||||
test('Trending: trend arrows count double', () => {
|
||||
const s = board([topic('depth'), topic('attention', 'trending'), topic('reach')]);
|
||||
const up = place(s, 0, 1, card({ trend: 1 }));
|
||||
const down = place(s, 1, 1, card({ trend: -1 }));
|
||||
const flat = place(s, 1, 1, card({ trend: 0 }));
|
||||
const portal = PORTALS.trending;
|
||||
const ctx = ctxFor(s, s.ruleset.portalParams.trending, 1);
|
||||
assert.deepEqual([portal.ongoing!(ctx, up), portal.ongoing!(ctx, down), portal.ongoing!(ctx, flat)], [1, -1, 0]);
|
||||
});
|
||||
|
||||
test('Featured Article: +2 to the owner of the single highest card at scoring; tie → nobody', () => {
|
||||
const s = board([topic('depth', 'featured-article'), topic('attention'), topic('reach')]);
|
||||
place(s, 0, 0, card({ power: 6, home: 'reach' }));
|
||||
const bo = place(s, 1, 0, card({ power: 5, home: 'reach' }));
|
||||
assert.deepEqual(atScoring(s, 0), [2, 0]);
|
||||
bo.bonus = 1;
|
||||
assert.deepEqual(atScoring(s, 0), [0, 0], 'tied highest');
|
||||
bo.bonus = 3;
|
||||
assert.deepEqual(atScoring(s, 0), [0, 2]);
|
||||
assert.deepEqual(atScoring(board([topic('depth', 'featured-article')]), 0), [0, 0], 'empty');
|
||||
});
|
||||
|
||||
test('Stub: lane capacity 2', () => {
|
||||
const s = board([topic('depth', 'stub'), topic('attention'), topic('reach')]);
|
||||
assert.equal(PORTALS.stub.capacity!(ctxFor(s, s.ruleset.portalParams.stub, 0)), 2);
|
||||
});
|
||||
|
||||
test('Interwiki: +1 Topic power to a player with a card in every Topic', () => {
|
||||
const s = board([topic('depth'), topic('attention'), topic('reach', 'interwiki')]);
|
||||
for (const lane of [0, 1, 2]) place(s, 0, lane, card());
|
||||
place(s, 1, 2, card());
|
||||
assert.deepEqual(atScoring(s, 2), [1, 0]);
|
||||
assert.deepEqual(atScoring(s, 2), [1, 0]);
|
||||
});
|
||||
|
||||
test('no keyword or Portal hook moves or removes cards (§10 v1 constraint)', () => {
|
||||
const s = board([topic('depth', 'featured-article'), topic('attention', 'main-page'), topic('reach', 'interwiki')]);
|
||||
for (const lane of [0, 1, 2]) { place(s, 0, lane, card()); place(s, 1, lane, card()); }
|
||||
const count = () => s.lanes.map(l => l.cards.map(side => side.map(c => c.card.cardId)));
|
||||
for (const id of [...V1_KEYWORDS, ...OPTIONAL_KEYWORDS]) {
|
||||
const before = count();
|
||||
const c = reveal(s, 0, 1, card({ keyword: id }));
|
||||
endOfTurn(s, c);
|
||||
s.lanes[1].cards[0].pop();
|
||||
assert.deepEqual(count(), before, id);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
// Property tests over random legal play (engine-b). Failures print a seed: rerun with PROP_SEED=<seed>.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
DEFAULT_RULESET, FACTION_KEYWORD, PLAYERS, applyAction, createMatch, deserialize, isOver, legalActions, replay, result,
|
||||
serialize, starterDeck, viewFor, type Action, type Faction, type GameCard, type MatchState,
|
||||
} from '../shared/game/index.ts';
|
||||
import { forAll, type Gen } from './game/property.ts';
|
||||
|
||||
const MAX_ACTIONS = 2000;
|
||||
const FACTIONS = Object.keys(FACTION_KEYWORD) as Faction[];
|
||||
const STATS = ['attention', 'depth', 'reach'] as const;
|
||||
|
||||
/** A starter deck with random factions, homes and trend, keywords per §10.1, so every keyword and Portal gets exercised. */
|
||||
function randomDeck(g: Gen, tag: string): GameCard[] {
|
||||
return starterDeck(tag).map(card => {
|
||||
const faction = g.pick(FACTIONS);
|
||||
return { ...card, cardId: `${tag}:${card.cardId}`, faction, home: g.pick(STATS), trend: g.pick([-1, 0, 0, 1] as const),
|
||||
keyword: card.cost === 1 ? null : FACTION_KEYWORD[faction] };
|
||||
});
|
||||
}
|
||||
|
||||
function decksFor(g: Gen, seed: number): [GameCard[], GameCard[]] {
|
||||
return [randomDeck(g, `a-${seed}`), randomDeck(g, `b-${seed}`)];
|
||||
}
|
||||
|
||||
/** Random legal play; commits come out at random so queues of every length happen. Concede is rare. */
|
||||
function playOut(g: Gen, state: MatchState, check?: (s: MatchState) => void) {
|
||||
const log: Action[] = [];
|
||||
for (let steps = 0; !isOver(state); steps++) {
|
||||
assert.ok(steps <= MAX_ACTIONS, `match did not terminate within ${MAX_ACTIONS} actions`);
|
||||
const options = PLAYERS.flatMap(player => legalActions(state, player));
|
||||
assert.ok(options.length > 0, `no legal actions in a live match (turn ${state.turn})`);
|
||||
const action: Action = g.bool(0.002) ? { type: 'concede', player: g.pick(PLAYERS) } : g.pick(options);
|
||||
log.push(action);
|
||||
state = applyAction(state, action);
|
||||
check?.(state);
|
||||
}
|
||||
return { state, log };
|
||||
}
|
||||
|
||||
test('random legal play never crashes, always terminates within the turn cap, and has a result', () => {
|
||||
forAll(200, (g, seed) => {
|
||||
const { state } = playOut(g, createMatch(DEFAULT_RULESET, decksFor(g, seed), seed));
|
||||
const r = result(state);
|
||||
assert.ok(r, 'finished match has a result');
|
||||
assert.ok(r.turns <= DEFAULT_RULESET.turns);
|
||||
if (r.reason !== 'concede' && r.reason !== 'afk') {
|
||||
const led = r.topicsLed;
|
||||
if (r.winner === null) assert.equal(led[0], led[1]);
|
||||
else assert.ok(led[r.winner] > led[1 - r.winner] || r.reason === 'totalPower');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test('same seed, decks and actions give the same match (replay)', () => {
|
||||
forAll(50, (g, seed) => {
|
||||
const decks = decksFor(g, seed);
|
||||
const first = playOut(g, createMatch(DEFAULT_RULESET, decks, seed));
|
||||
const again = replay(DEFAULT_RULESET, decks, seed, first.log);
|
||||
assert.deepEqual(again, first.state);
|
||||
});
|
||||
});
|
||||
|
||||
test('createMatch is deterministic per seed and varies across seeds', () => {
|
||||
const decks = (): [GameCard[], GameCard[]] => [starterDeck('x'), starterDeck('y')];
|
||||
assert.deepEqual(createMatch(DEFAULT_RULESET, decks(), 7), createMatch(DEFAULT_RULESET, decks(), 7));
|
||||
const distinct = new Set(Array.from({ length: 20 }, (_, i) => JSON.stringify(createMatch(DEFAULT_RULESET, decks(), i))));
|
||||
assert.ok(distinct.size > 1);
|
||||
});
|
||||
|
||||
test('serialize/deserialize round-trips after every action', () => {
|
||||
forAll(30, (g, seed) => {
|
||||
playOut(g, createMatch(DEFAULT_RULESET, decksFor(g, seed), seed), s => assert.deepEqual(deserialize(serialize(s)), s));
|
||||
});
|
||||
});
|
||||
|
||||
test('applyAction never mutates its input', () => {
|
||||
forAll(30, (g, seed) => {
|
||||
let state = createMatch(DEFAULT_RULESET, decksFor(g, seed), seed);
|
||||
for (let steps = 0; !isOver(state) && steps < MAX_ACTIONS; steps++) {
|
||||
const before = serialize(state);
|
||||
const next = applyAction(state, g.pick(PLAYERS.flatMap(player => legalActions(state, player))));
|
||||
assert.equal(serialize(state), before);
|
||||
state = next;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test('every listed legal action is accepted; a finished match lists none', () => {
|
||||
forAll(30, (g, seed) => {
|
||||
const { state } = playOut(g, createMatch(DEFAULT_RULESET, decksFor(g, seed), seed), s => {
|
||||
for (const player of PLAYERS) for (const action of legalActions(s, player)) assert.doesNotThrow(() => applyAction(s, action));
|
||||
});
|
||||
for (const player of PLAYERS) assert.deepEqual(legalActions(state, player), []);
|
||||
});
|
||||
});
|
||||
|
||||
test('lane power is never negative and lanes never exceed capacity', () => {
|
||||
forAll(50, (g, seed) => {
|
||||
playOut(g, createMatch(DEFAULT_RULESET, decksFor(g, seed), seed), s => {
|
||||
for (const player of PLAYERS) {
|
||||
const view = viewFor(s, player);
|
||||
for (const lane of view.lanes) {
|
||||
assert.ok(lane.power[0] >= 0 && lane.power[1] >= 0);
|
||||
for (const side of lane.cardPower) for (const p of side) assert.ok(p >= 0);
|
||||
}
|
||||
}
|
||||
for (const lane of s.lanes) for (const side of lane.cards) assert.ok(side.length <= s.ruleset.laneCapacity);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('a view never shows the opponent hand or queue', () => {
|
||||
forAll(30, (g, seed) => {
|
||||
playOut(g, createMatch(DEFAULT_RULESET, decksFor(g, seed), seed), s => {
|
||||
for (const player of PLAYERS) {
|
||||
const text = JSON.stringify(viewFor(s, player));
|
||||
for (const card of s.players[1 - player].hand) assert.ok(!text.includes(`"${card.cardId}"`), `p${player} sees ${card.cardId}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
// DESIGN §2.1 starter decks (PR #18). Owner: engine-b.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
DEFAULT_DERIVATION, DEFAULT_RULESET, FACTION_KEYWORD, STARTER_DECKS, createMatch, starterDeckById, validateDeck,
|
||||
} from '../shared/game/index.ts';
|
||||
|
||||
const countBy = (keys: string[]) => keys.reduce<Record<string, number>>((m, k) => ({ ...m, [k]: (m[k] ?? 0) + 1 }), {});
|
||||
|
||||
test('four starter decks, each with the frozen curve, 6+6 factions and 4 cards per home stat', () => {
|
||||
assert.deepEqual(STARTER_DECKS.map(d => d.id), ['stargazers', 'field-guide', 'headliners', 'pioneers']);
|
||||
for (const def of STARTER_DECKS) {
|
||||
const deck = starterDeckById(def.id);
|
||||
assert.deepEqual(deck.map(c => c.cost), [1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6], def.id);
|
||||
const factions = Object.values(countBy(deck.map(c => c.faction)));
|
||||
assert.deepEqual(factions, [6, 6], `${def.id} factions`);
|
||||
const homes = Object.values(countBy(deck.map(c => c.home)));
|
||||
assert.deepEqual(homes, [4, 4, 4], `${def.id} homes`);
|
||||
}
|
||||
});
|
||||
|
||||
test('starter cards follow §10.1 and the power curve like owned cards', () => {
|
||||
for (const def of STARTER_DECKS) for (const card of starterDeckById(def.id)) {
|
||||
assert.equal(card.source, 'loaner');
|
||||
assert.equal(card.rarity, 'Common');
|
||||
assert.equal(card.trend, 0);
|
||||
assert.match(card.cardId, /^loaner:[a-z0-9-]+$/);
|
||||
if (card.cost === 1) assert.deepEqual([card.keyword, card.power], [null, 2]);
|
||||
else assert.deepEqual([card.keyword, card.power], [FACTION_KEYWORD[card.faction], DEFAULT_DERIVATION.powerByCost[card.cost]]);
|
||||
}
|
||||
});
|
||||
|
||||
test('all 6 factions and all 4 shared/catalog.ts cards (with real pageIds) are covered', () => {
|
||||
const all = STARTER_DECKS.flatMap(d => starterDeckById(d.id));
|
||||
assert.equal(new Set(all.map(c => c.faction)).size, 6);
|
||||
const ids = Object.fromEntries(all.map(c => [c.title, c.pageId]));
|
||||
assert.deepEqual([ids.Moon, ids['Periodic table'], ids.Octopus, ids['Albert Einstein']], [19331, 23053, 22780, 736]);
|
||||
for (const c of all) if (!['Moon', 'Periodic table', 'Octopus', 'Albert Einstein'].includes(c.title)) assert.equal(c.pageId, null, c.title);
|
||||
});
|
||||
|
||||
test('every starter deck passes engine deck validation and starts a match against every other', () => {
|
||||
for (const a of STARTER_DECKS) {
|
||||
assert.deepEqual(validateDeck(DEFAULT_RULESET, starterDeckById(a.id)), [], a.id);
|
||||
for (const b of STARTER_DECKS) assert.doesNotThrow(() => createMatch(DEFAULT_RULESET, [starterDeckById(a.id), starterDeckById(b.id)], 1));
|
||||
}
|
||||
});
|
||||
|
||||
test('modes changing the curve change loaners too; unknown ids are rejected', () => {
|
||||
const flat = starterDeckById('pioneers', { ...DEFAULT_DERIVATION, powerByCost: [0, 3, 3, 3, 3, 3, 3], vanillaBonus: 0 });
|
||||
assert.ok(flat.every(c => c.power === 3));
|
||||
assert.throws(() => starterDeckById('nope'), RangeError);
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
/** Hand-built boards for keyword and Portal unit tests (engine-b). */
|
||||
import {
|
||||
DEFAULT_RULESET, KEYWORDS, PORTALS, Rng, cardPower, createMatch, lanePower, starterDeck,
|
||||
type CardInPlay, type EffectContext, type GameCard, type MatchState, type PlayerId, type Stat, type TopicDef,
|
||||
} from '../../shared/game/index.ts';
|
||||
|
||||
export const topic = (stat: Stat, portal: string | null = null, id = portal ?? `plain-${stat}`): TopicDef =>
|
||||
({ id, name: id, stat, portal });
|
||||
|
||||
/** Empty board, turn 1; lanes are depth / attention / reach plain Topics unless given. */
|
||||
export function board(topics: TopicDef[] = [topic('depth'), topic('attention'), topic('reach')], revealed = true): MatchState {
|
||||
const state = createMatch(DEFAULT_RULESET, [starterDeck('a'), starterDeck('b')], 'keyword-test');
|
||||
state.lanes = topics.map(t => ({ topic: t, portalRevealed: revealed, cards: [[], []] as [CardInPlay[], CardInPlay[]] }));
|
||||
return state;
|
||||
}
|
||||
|
||||
let serial = 0;
|
||||
export function card(overrides: Partial<GameCard> = {}): GameCard {
|
||||
serial++;
|
||||
return { cardId: `t${serial}`, pageId: 1000 + serial, title: `Card ${serial}`, faction: 'Culture', rarity: 'Common',
|
||||
cost: 2, power: 2, home: 'attention', trend: 0, keyword: null, source: 'loaner', ...overrides };
|
||||
}
|
||||
|
||||
/** Put a card in a lane with no effects (mutates). */
|
||||
export function place(state: MatchState, owner: PlayerId, lane: number, c: GameCard, turn = state.turn): CardInPlay {
|
||||
state.revealSeq += 1;
|
||||
const inPlay: CardInPlay = { card: c, owner, lane, turn, seq: state.revealSeq, bonus: 0 };
|
||||
state.lanes[lane].cards[owner].push(inPlay);
|
||||
return inPlay;
|
||||
}
|
||||
|
||||
export function ctxFor(state: MatchState, params: Record<string, number> | undefined, lane: number): EffectContext {
|
||||
return { state, rng: new Rng(1), params: params ?? {}, lane, log: () => {}, power: c => cardPower(state, c) };
|
||||
}
|
||||
|
||||
/** Place a card and fire its keyword's onReveal, as the engine does at reveal (mutates). */
|
||||
export function reveal(state: MatchState, owner: PlayerId, lane: number, c: GameCard): CardInPlay {
|
||||
const inPlay = place(state, owner, lane, c);
|
||||
const keyword = c.keyword ? KEYWORDS[c.keyword] : undefined;
|
||||
keyword?.onReveal?.(ctxFor(state, state.ruleset.keywordParams[keyword.id], lane), inPlay);
|
||||
return inPlay;
|
||||
}
|
||||
|
||||
export function endOfTurn(state: MatchState, self: CardInPlay): void {
|
||||
const keyword = self.card.keyword ? KEYWORDS[self.card.keyword] : undefined;
|
||||
keyword?.endOfTurn?.(ctxFor(state, state.ruleset.keywordParams[keyword.id], self.lane), self);
|
||||
}
|
||||
|
||||
/** A Portal's at-scoring Topic power for [seat 0, seat 1] (DESIGN §7). */
|
||||
export function atScoring(state: MatchState, lane: number): [number, number] {
|
||||
const id = state.lanes[lane].topic.portal;
|
||||
const portal = id ? PORTALS[id] : undefined;
|
||||
const params = state.ruleset.portalParams[state.lanes[lane].topic.id] ?? state.ruleset.portalParams[id!];
|
||||
return portal?.atScoring?.(ctxFor(state, params, lane)) ?? [0, 0];
|
||||
}
|
||||
|
||||
export { cardPower, lanePower };
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Tiny dependency-free property-testing helper. Each case gets its own seed
|
||||
* so a failure reports a reproducible seed: rerun with PROP_SEED=<seed>.
|
||||
*/
|
||||
export function mulberry32(seed: number): () => number {
|
||||
let a = seed >>> 0;
|
||||
return () => {
|
||||
a = (a + 0x6d2b79f5) >>> 0;
|
||||
let t = a;
|
||||
t = Math.imul(t ^ (t >>> 15), t | 1);
|
||||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
export interface Gen {
|
||||
rand: () => number;
|
||||
int(min: number, max: number): number;
|
||||
pick<T>(items: readonly T[]): T;
|
||||
bool(p?: number): boolean;
|
||||
}
|
||||
|
||||
export function gen(seed: number): Gen {
|
||||
const rand = mulberry32(seed);
|
||||
return {
|
||||
rand,
|
||||
int: (min, max) => min + Math.floor(rand() * (max - min + 1)),
|
||||
pick: items => {
|
||||
if (!items.length) throw new Error('pick from empty list');
|
||||
return items[Math.floor(rand() * items.length)];
|
||||
},
|
||||
bool: (p = 0.5) => rand() < p,
|
||||
};
|
||||
}
|
||||
|
||||
export function forAll(runs: number, property: (g: Gen, seed: number) => void, baseSeed = 0x5eed): void {
|
||||
const fixed = process.env.PROP_SEED;
|
||||
const seeds = fixed ? [Number(fixed)] : Array.from({ length: runs }, (_, i) => (baseSeed + i * 2654435761) >>> 0);
|
||||
for (const seed of seeds) {
|
||||
try {
|
||||
property(gen(seed), seed);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
throw new Error(`Property failed for seed ${seed} (rerun with PROP_SEED=${seed}): ${message}`, { cause: error });
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user