forked from WikiDeck/wikideck
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3bbbb49048 | ||
|
|
7c86ed35f5 |
@@ -1,98 +0,0 @@
|
||||
# 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.
|
||||
|
||||
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.
|
||||
|
||||
## Headline findings (INTERIM: 100 fully enriched random illustrated cards; 330 sampled, rest still fetching under Wikimedia 429 rate limits)
|
||||
|
||||
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`).
|
||||
|
||||
## Full tables
|
||||
|
||||
Sample: **100 cards**; ~44% (149/340 logged during sampling) of random pages pass the illustrated filter. Pageviews available for 100.
|
||||
|
||||
| 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 |
|
||||
|
||||
**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 |
|
||||
|
||||
(n=99; 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.
|
||||
|
||||
**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.
|
||||
|
||||
**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
|
||||
|
||||
Reach = 0 (no other languages): 10; reach 100 (>=999 langs) impossible in practice, max langs 56. Attention null: 0; attention 0: 0.
|
||||
|
||||
**Sum of three stats:** min 84, p10 97, p25 107, median 120, p75 140, p90 155, max 193
|
||||
|
||||
**Legacy `category()` (server/wiki.ts):** Culture 53, People 30, Nature 9, History 5, Science 3
|
||||
|
||||
**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
|
||||
|
||||
No Wikidata item: 0; no P31: 6
|
||||
|
||||
**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
|
||||
|
||||
|
||||
## Rank-normalised tiers (1–10)
|
||||
|
||||
Tier = 1 + number of breakpoints the score is **>=**. Breakpoints are the sample deciles p10..p90 of the 0–100 score. Ties make some tiers thin (scores are integers).
|
||||
|
||||
| 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 |
|
||||
|
||||
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
|
||||
|
||||
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 |
|
||||
|
||||
Unclassified P31 labels: typeface 1, annexation 1, position 1, family 1
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,424 +0,0 @@
|
||||
{
|
||||
"frozenAt": "2026-11-17",
|
||||
"note": "Frozen loaner/starter stats from the council-data random sample. Do not fetch live.",
|
||||
"cards": [
|
||||
{
|
||||
"pageId": 49830722,
|
||||
"title": "Dicroidium odontopteroides",
|
||||
"category": "Nature",
|
||||
"wikidataId": "Q25095289",
|
||||
"revisionId": 1116073630,
|
||||
"pageBytes": 1943,
|
||||
"languageCount": 0,
|
||||
"monthlyViews": 59,
|
||||
"latestMonth": "2026-10",
|
||||
"trendPercent": 5.4,
|
||||
"stats": {
|
||||
"attention": 30,
|
||||
"depth": 55,
|
||||
"reach": 0
|
||||
},
|
||||
"tiers": {
|
||||
"attention": 4,
|
||||
"depth": 2,
|
||||
"reach": 1
|
||||
}
|
||||
},
|
||||
{
|
||||
"pageId": 25856905,
|
||||
"title": "Dichromorpha viridis",
|
||||
"category": "Nature",
|
||||
"wikidataId": "Q5272562",
|
||||
"revisionId": 1367363150,
|
||||
"pageBytes": 1347,
|
||||
"languageCount": 4,
|
||||
"monthlyViews": 133,
|
||||
"latestMonth": "2026-10",
|
||||
"trendPercent": -43.6,
|
||||
"stats": {
|
||||
"attention": 35,
|
||||
"depth": 52,
|
||||
"reach": 23
|
||||
},
|
||||
"tiers": {
|
||||
"attention": 6,
|
||||
"depth": 1,
|
||||
"reach": 5
|
||||
}
|
||||
},
|
||||
{
|
||||
"pageId": 66508497,
|
||||
"title": "Amanita mairei",
|
||||
"category": "Nature",
|
||||
"wikidataId": "Q15651951",
|
||||
"revisionId": 1323515500,
|
||||
"pageBytes": 998,
|
||||
"languageCount": 8,
|
||||
"monthlyViews": 61,
|
||||
"latestMonth": "2026-10",
|
||||
"trendPercent": -21.8,
|
||||
"stats": {
|
||||
"attention": 30,
|
||||
"depth": 50,
|
||||
"reach": 32
|
||||
},
|
||||
"tiers": {
|
||||
"attention": 4,
|
||||
"depth": 1,
|
||||
"reach": 7
|
||||
}
|
||||
},
|
||||
{
|
||||
"pageId": 4289899,
|
||||
"title": "Anthodon (reptile)",
|
||||
"category": "Nature",
|
||||
"wikidataId": "Q2505064",
|
||||
"revisionId": 1384682008,
|
||||
"pageBytes": 9037,
|
||||
"languageCount": 12,
|
||||
"monthlyViews": 233,
|
||||
"latestMonth": "2026-10",
|
||||
"trendPercent": -8.3,
|
||||
"stats": {
|
||||
"attention": 39,
|
||||
"depth": 66,
|
||||
"reach": 37
|
||||
},
|
||||
"tiers": {
|
||||
"attention": 8,
|
||||
"depth": 7,
|
||||
"reach": 8
|
||||
}
|
||||
},
|
||||
{
|
||||
"pageId": 47519878,
|
||||
"title": "Jeanne Madden",
|
||||
"category": "People",
|
||||
"wikidataId": "Q20974011",
|
||||
"revisionId": 1382761423,
|
||||
"pageBytes": 1817,
|
||||
"languageCount": 4,
|
||||
"monthlyViews": 26,
|
||||
"latestMonth": "2026-10",
|
||||
"trendPercent": -40.9,
|
||||
"stats": {
|
||||
"attention": 24,
|
||||
"depth": 54,
|
||||
"reach": 23
|
||||
},
|
||||
"tiers": {
|
||||
"attention": 2,
|
||||
"depth": 2,
|
||||
"reach": 5
|
||||
}
|
||||
},
|
||||
{
|
||||
"pageId": 46263191,
|
||||
"title": "Max Touloute",
|
||||
"category": "People",
|
||||
"wikidataId": "Q20641573",
|
||||
"revisionId": 1384441370,
|
||||
"pageBytes": 10140,
|
||||
"languageCount": 2,
|
||||
"monthlyViews": 47,
|
||||
"latestMonth": "2026-10",
|
||||
"trendPercent": 95.8,
|
||||
"stats": {
|
||||
"attention": 28,
|
||||
"depth": 67,
|
||||
"reach": 16
|
||||
},
|
||||
"tiers": {
|
||||
"attention": 4,
|
||||
"depth": 8,
|
||||
"reach": 4
|
||||
}
|
||||
},
|
||||
{
|
||||
"pageId": 3372934,
|
||||
"title": "Hermes Ramírez",
|
||||
"category": "People",
|
||||
"wikidataId": "Q522855",
|
||||
"revisionId": 1364063954,
|
||||
"pageBytes": 8264,
|
||||
"languageCount": 13,
|
||||
"monthlyViews": 59,
|
||||
"latestMonth": "2026-10",
|
||||
"trendPercent": -9.2,
|
||||
"stats": {
|
||||
"attention": 30,
|
||||
"depth": 65,
|
||||
"reach": 38
|
||||
},
|
||||
"tiers": {
|
||||
"attention": 4,
|
||||
"depth": 7,
|
||||
"reach": 8
|
||||
}
|
||||
},
|
||||
{
|
||||
"pageId": 1374812,
|
||||
"title": "Tom Ewell",
|
||||
"category": "People",
|
||||
"wikidataId": "Q427388",
|
||||
"revisionId": 1381663979,
|
||||
"pageBytes": 17965,
|
||||
"languageCount": 30,
|
||||
"monthlyViews": 4548,
|
||||
"latestMonth": "2026-10",
|
||||
"trendPercent": -19.8,
|
||||
"stats": {
|
||||
"attention": 61,
|
||||
"depth": 71,
|
||||
"reach": 50
|
||||
},
|
||||
"tiers": {
|
||||
"attention": 10,
|
||||
"depth": 9,
|
||||
"reach": 10
|
||||
}
|
||||
},
|
||||
{
|
||||
"pageId": 13799810,
|
||||
"title": "Levophacetoperane",
|
||||
"category": "Science",
|
||||
"wikidataId": "Q6535818",
|
||||
"revisionId": 1374230485,
|
||||
"pageBytes": 4639,
|
||||
"languageCount": 2,
|
||||
"monthlyViews": 165,
|
||||
"latestMonth": "2026-10",
|
||||
"trendPercent": -1.8,
|
||||
"stats": {
|
||||
"attention": 37,
|
||||
"depth": 61,
|
||||
"reach": 16
|
||||
},
|
||||
"tiers": {
|
||||
"attention": 7,
|
||||
"depth": 5,
|
||||
"reach": 4
|
||||
}
|
||||
},
|
||||
{
|
||||
"pageId": 36740675,
|
||||
"title": "The Best of Men",
|
||||
"category": "Science",
|
||||
"wikidataId": "Q7717125",
|
||||
"revisionId": 1372732350,
|
||||
"pageBytes": 6002,
|
||||
"languageCount": 4,
|
||||
"monthlyViews": 476,
|
||||
"latestMonth": "2026-10",
|
||||
"trendPercent": -3.4,
|
||||
"stats": {
|
||||
"attention": 45,
|
||||
"depth": 63,
|
||||
"reach": 23
|
||||
},
|
||||
"tiers": {
|
||||
"attention": 9,
|
||||
"depth": 6,
|
||||
"reach": 5
|
||||
}
|
||||
},
|
||||
{
|
||||
"pageId": 4426773,
|
||||
"title": "Agda (programming language)",
|
||||
"category": "Science",
|
||||
"wikidataId": "Q20479",
|
||||
"revisionId": 1384528612,
|
||||
"pageBytes": 14254,
|
||||
"languageCount": 11,
|
||||
"monthlyViews": 2439,
|
||||
"latestMonth": "2026-10",
|
||||
"trendPercent": 7.8,
|
||||
"stats": {
|
||||
"attention": 56,
|
||||
"depth": 69,
|
||||
"reach": 36
|
||||
},
|
||||
"tiers": {
|
||||
"attention": 10,
|
||||
"depth": 9,
|
||||
"reach": 8
|
||||
}
|
||||
},
|
||||
{
|
||||
"pageId": 42770753,
|
||||
"title": "Château de la Faye (Villexavier)",
|
||||
"category": "History",
|
||||
"wikidataId": "Q2971223",
|
||||
"revisionId": 1375492681,
|
||||
"pageBytes": 1851,
|
||||
"languageCount": 1,
|
||||
"monthlyViews": 14,
|
||||
"latestMonth": "2026-10",
|
||||
"trendPercent": 7.7,
|
||||
"stats": {
|
||||
"attention": 20,
|
||||
"depth": 54,
|
||||
"reach": 10
|
||||
},
|
||||
"tiers": {
|
||||
"attention": 1,
|
||||
"depth": 2,
|
||||
"reach": 3
|
||||
}
|
||||
},
|
||||
{
|
||||
"pageId": 15362336,
|
||||
"title": "1954 Gold Coast general election",
|
||||
"category": "History",
|
||||
"wikidataId": "Q2539674",
|
||||
"revisionId": 1351181171,
|
||||
"pageBytes": 4141,
|
||||
"languageCount": 2,
|
||||
"monthlyViews": 181,
|
||||
"latestMonth": "2026-10",
|
||||
"trendPercent": -10.4,
|
||||
"stats": {
|
||||
"attention": 38,
|
||||
"depth": 60,
|
||||
"reach": 16
|
||||
},
|
||||
"tiers": {
|
||||
"attention": 8,
|
||||
"depth": 4,
|
||||
"reach": 4
|
||||
}
|
||||
},
|
||||
{
|
||||
"pageId": 9026000,
|
||||
"title": "Names of Poland",
|
||||
"category": "History",
|
||||
"wikidataId": "Q6961536",
|
||||
"revisionId": 1351068420,
|
||||
"pageBytes": 18966,
|
||||
"languageCount": 4,
|
||||
"monthlyViews": 1431,
|
||||
"latestMonth": "2026-10",
|
||||
"trendPercent": -0.9,
|
||||
"stats": {
|
||||
"attention": 53,
|
||||
"depth": 71,
|
||||
"reach": 23
|
||||
},
|
||||
"tiers": {
|
||||
"attention": 10,
|
||||
"depth": 9,
|
||||
"reach": 5
|
||||
}
|
||||
},
|
||||
{
|
||||
"pageId": 25275009,
|
||||
"title": "Amur Annexation",
|
||||
"category": "History",
|
||||
"wikidataId": "Q4379152",
|
||||
"revisionId": 1381503728,
|
||||
"pageBytes": 15490,
|
||||
"languageCount": 9,
|
||||
"monthlyViews": 3238,
|
||||
"latestMonth": "2026-10",
|
||||
"trendPercent": -6.7,
|
||||
"stats": {
|
||||
"attention": 59,
|
||||
"depth": 70,
|
||||
"reach": 33
|
||||
},
|
||||
"tiers": {
|
||||
"attention": 10,
|
||||
"depth": 9,
|
||||
"reach": 7
|
||||
}
|
||||
},
|
||||
{
|
||||
"pageId": 7674700,
|
||||
"title": "Shipley Plateau",
|
||||
"category": "Culture",
|
||||
"wikidataId": "Q7498025",
|
||||
"revisionId": 1384061257,
|
||||
"pageBytes": 1745,
|
||||
"languageCount": 1,
|
||||
"monthlyViews": 22,
|
||||
"latestMonth": "2026-10",
|
||||
"trendPercent": -55.1,
|
||||
"stats": {
|
||||
"attention": 23,
|
||||
"depth": 54,
|
||||
"reach": 10
|
||||
},
|
||||
"tiers": {
|
||||
"attention": 2,
|
||||
"depth": 2,
|
||||
"reach": 3
|
||||
}
|
||||
},
|
||||
{
|
||||
"pageId": 15810707,
|
||||
"title": "Charmont-en-Beauce",
|
||||
"category": "Culture",
|
||||
"wikidataId": "Q667131",
|
||||
"revisionId": 1381828954,
|
||||
"pageBytes": 1811,
|
||||
"languageCount": 32,
|
||||
"monthlyViews": 23,
|
||||
"latestMonth": "2026-10",
|
||||
"trendPercent": 27.8,
|
||||
"stats": {
|
||||
"attention": 23,
|
||||
"depth": 54,
|
||||
"reach": 51
|
||||
},
|
||||
"tiers": {
|
||||
"attention": 2,
|
||||
"depth": 2,
|
||||
"reach": 10
|
||||
}
|
||||
},
|
||||
{
|
||||
"pageId": 48653101,
|
||||
"title": "Tornadoes of 1978",
|
||||
"category": "Culture",
|
||||
"wikidataId": "Q22093730",
|
||||
"revisionId": 1381828221,
|
||||
"pageBytes": 16373,
|
||||
"languageCount": 0,
|
||||
"monthlyViews": 511,
|
||||
"latestMonth": "2026-10",
|
||||
"trendPercent": 3.2,
|
||||
"stats": {
|
||||
"attention": 45,
|
||||
"depth": 70,
|
||||
"reach": 0
|
||||
},
|
||||
"tiers": {
|
||||
"attention": 9,
|
||||
"depth": 9,
|
||||
"reach": 1
|
||||
}
|
||||
},
|
||||
{
|
||||
"pageId": 981340,
|
||||
"title": "Tatsunoko Production",
|
||||
"category": "Culture",
|
||||
"wikidataId": "Q1323459",
|
||||
"revisionId": 1384823392,
|
||||
"pageBytes": 74169,
|
||||
"languageCount": 19,
|
||||
"monthlyViews": 4738,
|
||||
"latestMonth": "2026-10",
|
||||
"trendPercent": -9.4,
|
||||
"stats": {
|
||||
"attention": 61,
|
||||
"depth": 81,
|
||||
"reach": 43
|
||||
},
|
||||
"tiers": {
|
||||
"attention": 10,
|
||||
"depth": 10,
|
||||
"reach": 9
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Summarise card-sample.json into markdown stats. Usage: python3 -I card_analyze.py sample.json > out.md"""
|
||||
import json, sys, math, statistics as st, collections, re
|
||||
d = json.load(open(sys.argv[1])); C = d['cards']
|
||||
def q(v):
|
||||
v = sorted(v); n = len(v)
|
||||
def p(x):
|
||||
k = (n - 1) * x; f = math.floor(k); c = min(f + 1, n - 1); return v[f] + (v[c] - v[f]) * (k - f)
|
||||
return [v[0], p(.1), p(.25), p(.5), p(.75), p(.9), v[-1]]
|
||||
def skew(v):
|
||||
m, s = st.mean(v), st.pstdev(v); return sum((x - m) ** 3 for x in v) / len(v) / s ** 3 if s else 0
|
||||
def rank(v):
|
||||
o = sorted(range(len(v)), key=lambda i: v[i]); r = [0] * len(v); i = 0
|
||||
while i < len(o):
|
||||
j = i
|
||||
while j + 1 < len(o) and v[o[j + 1]] == v[o[i]]: j += 1
|
||||
for k in range(i, j + 1): r[o[k]] = (i + j) / 2
|
||||
i = j + 1
|
||||
return r
|
||||
def pearson(a, b):
|
||||
ma, mb = st.mean(a), st.mean(b); sa = math.sqrt(sum((x - ma) ** 2 for x in a)); sb = math.sqrt(sum((y - mb) ** 2 for y in b))
|
||||
return sum((x - ma) * (y - mb) for x, y in zip(a, b)) / (sa * sb) if sa and sb else float('nan')
|
||||
pv = [c for c in C if c['pageviews']['status'] == 'available']
|
||||
F = {'attention': lambda c: c['stats']['attention'], 'depth': lambda c: c['stats']['depth'], 'reach': lambda c: c['stats']['reach'],
|
||||
'pageBytes': lambda c: c['pageBytes'], 'languageCount': lambda c: c['languageCount'],
|
||||
'monthlyViews': lambda c: c['pageviews']['months'][5]['views'] if c['pageviews']['status'] == 'available' else None,
|
||||
'dailyAverage': lambda c: c['pageviews']['dailyAverage'], 'trendPercent': lambda c: c['pageviews']['trendPercent'],
|
||||
'drift30Percent': lambda c: c['drift30']['pct']}
|
||||
out = []
|
||||
P = out.append
|
||||
rate = f"{len(C)/d['rawPagesSeen']*100:.0f}%" if d['rawPagesSeen'] else '~44% (149/340 logged during sampling)'
|
||||
P(f"Sample: **{len(C)} cards**; {rate} of random pages pass the illustrated filter. Pageviews available for {len(pv)}.\n")
|
||||
P('| stat | n | min | p10 | p25 | median | p75 | p90 | max | mean | skew |'); P('|---|---|---|---|---|---|---|---|---|---|---|')
|
||||
for k, f in F.items():
|
||||
v = [f(c) for c in C if f(c) is not None]
|
||||
qs = q(v); fmt = (lambda x: f'{x:.0f}') if k not in ('trendPercent', 'drift30Percent', 'dailyAverage') else (lambda x: f'{x:.1f}')
|
||||
P(f"| {k} | {len(v)} | " + ' | '.join(fmt(x) for x in qs) + f" | {fmt(st.mean(v))} | {skew(v):.2f} |")
|
||||
P('\n**Spearman rank correlations** (cards with pageviews):\n')
|
||||
keys = ['attention', 'depth', 'reach', 'trendPercent', 'drift30Percent']
|
||||
rows = [c for c in pv if c['pageviews']['trendPercent'] is not None and c['drift30']['pct'] is not None]
|
||||
R = {k: rank([F[k](c) for c in rows]) for k in keys}
|
||||
P('| | ' + ' | '.join(keys) + ' |'); P('|---' * (len(keys) + 1) + '|')
|
||||
for a in keys: P(f'| {a} | ' + ' | '.join(f'{pearson(R[a], R[b]):.2f}' for b in keys) + ' |')
|
||||
P(f'\n(n={len(rows)}; attention~monthlyViews, depth~pageBytes, reach~languageCount are monotonic so their rank correlations are identical.)\n')
|
||||
tp = [c['pageviews']['trendPercent'] for c in pv if c['pageviews']['trendPercent'] is not None]
|
||||
P(f"**trendPercent sign:** positive {sum(t>0 for t in tp)} ({sum(t>0 for t in tp)/len(tp)*100:.0f}%), negative {sum(t<0 for t in tp)} ({sum(t<0 for t in tp)/len(tp)*100:.0f}%), zero {sum(t==0 for t in tp)}; null (prior month 0 or no views) {len(C)-len(tp)}. "
|
||||
f"|trend| > 50%: {sum(abs(t)>50 for t in tp)}; > 100%: {sum(abs(t)>100 for t in tp)}.\n")
|
||||
dr = [c['drift30']['pct'] for c in C if c['drift30']['pct'] is not None]
|
||||
P(f"**30-day drift** (views 10-17..11-15 vs 09-17..10-16): median |drift| {st.median([abs(x) for x in dr]):.0f}%, "
|
||||
f"p90 |drift| {q([abs(x) for x in dr])[5]:.0f}%. Attention score change implied: "
|
||||
f"median {st.median([abs(100*math.log10((c['drift30']['last30']+1)/(c['drift30']['prev30']+1))/6) for c in C]):.1f} points, "
|
||||
f"p90 {q([abs(100*math.log10((c['drift30']['last30']+1)/(c['drift30']['prev30']+1))/6) for c in C])[5]:.1f} points.\n")
|
||||
for name, f in [('attention', F['attention']), ('depth', F['depth']), ('reach', F['reach'])]:
|
||||
v = [f(c) for c in C if f(c) is not None]; h = collections.Counter(min(x // 10, 9) for x in v)
|
||||
P(f"**{name} histogram (deciles 0-9,10-19..90-100):** " + ' '.join(str(h.get(i, 0)) for i in range(10)))
|
||||
P(f"\nReach = 0 (no other languages): {sum(c['languageCount']==0 for c in C)}; reach 100 (>=999 langs) impossible in practice, max langs {max(c['languageCount'] for c in C)}. "
|
||||
f"Attention null: {sum(c['stats']['attention'] is None for c in C)}; attention 0: {sum(c['stats']['attention']==0 for c in C)}.\n")
|
||||
s3 = [sum(F[k](c) or 0 for k in ('attention', 'depth', 'reach')) for c in C]
|
||||
P(f"**Sum of three stats:** " + ', '.join(f'{n} {x:.0f}' for n, x in zip(['min', 'p10', 'p25', 'median', 'p75', 'p90', 'max'], q(s3))) + '\n')
|
||||
P('**Legacy `category()` (server/wiki.ts):** ' + ', '.join(f'{k} {v}' for k, v in collections.Counter(c['legacyCategory'] for c in C).most_common()) + '\n')
|
||||
io = collections.Counter(x['label'] for c in C for x in c['instanceOf'])
|
||||
P('**Top Wikidata P31 classes:** ' + ', '.join(f'{k} {v}' for k, v in io.most_common(40)) + '\n')
|
||||
P(f"No Wikidata item: {sum(not c['wikidataId'] for c in C)}; no P31: {sum(not c['instanceOf'] for c in C)}\n")
|
||||
words = collections.Counter()
|
||||
for c in C:
|
||||
for cat in set(w for t in c['categories'] for w in re.findall(r'[a-z]+', t.lower()) if len(w) > 3): words[cat] += 1
|
||||
P('**Most frequent category words (cards containing):** ' + ', '.join(f'{k} {v}' for k, v in words.most_common(60)) + '\n')
|
||||
print('\n'.join(out))
|
||||
|
||||
# ---- rank normalisation table (critic request): score -> 1..10 tier by sample decile
|
||||
def tiers(name):
|
||||
v = sorted(F[name](c) for c in C if F[name](c) is not None)
|
||||
return [v[min(len(v) - 1, int(len(v) * k / 10))] for k in range(1, 10)]
|
||||
T = {k: tiers(k) for k in ('attention', 'depth', 'reach')}
|
||||
print('\n## Rank-normalised tiers (1–10)\n')
|
||||
print('Tier = 1 + number of breakpoints the score is **>=**. Breakpoints are the sample deciles p10..p90 of the 0–100 score. '
|
||||
'Ties make some tiers thin (scores are integers).\n')
|
||||
print('| stat | p10 | p20 | p30 | p40 | p50 | p60 | p70 | p80 | p90 |'); print('|---' * 10 + '|')
|
||||
for k, b in T.items(): print(f'| {k} | ' + ' | '.join(str(x) for x in b) + ' |')
|
||||
def tier(k, s): return None if s is None else 1 + sum(s >= x for x in T[k])
|
||||
for c in C: c['tiers'] = {k: tier(k, c['stats'][k]) for k in T}
|
||||
tc = collections.Counter(c['tiers']['attention'] for c in C)
|
||||
print('\nResulting tier counts — attention: ' + ' '.join(f'{t}:{tc.get(t,0)}' for t in [None] + list(range(1, 11))))
|
||||
for k in ('depth', 'reach'):
|
||||
tc = collections.Counter(c['tiers'][k] for c in C); print(f'; {k}: ' + ' '.join(f'{t}:{tc.get(t,0)}' for t in range(1, 11)))
|
||||
json.dump({'breakpoints': T, 'rule': 'tier = 1 + count(breakpoints <= score); attention null -> no tier'},
|
||||
open(sys.argv[2] if len(sys.argv) > 2 else '/dev/null', 'w'), indent=1)
|
||||
|
||||
# ---- starter loaner candidates: 4 per legacy category, spread over combined tier
|
||||
if len(sys.argv) > 3:
|
||||
pick = []
|
||||
for cat in ['Space', 'Nature', 'People', 'Science', 'History', 'Culture']:
|
||||
pool = sorted((c for c in C if c['legacyCategory'] == cat and c['stats']['attention'] is not None),
|
||||
key=lambda c: sum(c['tiers'].values()))
|
||||
if not pool: continue
|
||||
n = min(4, len(pool)); idx = sorted({round(i * (len(pool) - 1) / max(1, n - 1)) for i in range(n)})
|
||||
for i in idx:
|
||||
c = pool[i]
|
||||
pick.append({'pageId': c['pageId'], 'title': c['title'], 'category': cat, 'wikidataId': c['wikidataId'],
|
||||
'revisionId': c['revisionId'], 'pageBytes': c['pageBytes'], 'languageCount': c['languageCount'],
|
||||
'monthlyViews': c['pageviews']['months'][5]['views'], 'latestMonth': c['pageviews']['latestMonth'],
|
||||
'trendPercent': None if c['pageviews']['trendPercent'] is None else round(c['pageviews']['trendPercent'], 1),
|
||||
'stats': c['stats'], 'tiers': c['tiers']})
|
||||
json.dump({'frozenAt': d['generatedAt'][:10], 'note': 'Frozen loaner/starter stats from the council-data random sample. Do not fetch live.',
|
||||
'cards': pick}, open(sys.argv[3], 'w'), indent=1, ensure_ascii=False)
|
||||
print(f'\nStarter candidates: {len(pick)} written to {sys.argv[3]}: ' + collections.Counter(p['category'] for p in pick).__repr__())
|
||||
|
||||
# ---- candidate factions from Wikidata P31 (+ categories fallback)
|
||||
FAC = [
|
||||
('People', r'\bhuman\b|fictional character|person'),
|
||||
('Sport', r'season|sports team|football|match|tournament|championship|final\b|club|league|olympic|race\b'),
|
||||
('Nature', r'taxon|species|genus|plant|fungus|disease|epiphyte|mineral|bird|fish|insect'),
|
||||
('Places', r'village|town|city|commune|municipality|river|lake|mountain|county|district|parish|region|plateau|island|settlement|neighbo|locality|census|hamlet|valley|bay|area|province|state of|capital|suburb|stream|peak|unincorporated|human settlement|local government'),
|
||||
('Structures', r'building|castle|mosque|church|cathedral|temple|bridge|station|railway line|road|highway|museum|structure|stadium|dam|tower|house|school|hospital|airport|monument|fort|palace|lighthouse|park'),
|
||||
('Works', r'film|album|single|song|musical|television|book|novel|video game|painting|literary|composition|series|episode|magazine|newspaper|poem|opera|play\b|artwork|sculpture'),
|
||||
('Organisations', r'company|group|band|organi[sz]ation|university|college|party|business|enterprise|agency|institute|association|brand|union|ministry|military unit'),
|
||||
('Events', r'election|protest|battle|war\b|storm|nor.easter|cyclone|event|disaster|treaty|conflict|earthquake|incident|festival|referendum|conference|ceremony'),
|
||||
('Ideas & Tech', r'programming|software|language|chemical|compound|gene|protein|theorem|concept|technology|vehicle|aircraft|ship|weapon|class|model|device|algorithm|religion|discipline|theory|food|dish'),
|
||||
]
|
||||
def faction(c):
|
||||
text = ' | '.join(x['label'].lower() for x in c['instanceOf'])
|
||||
for name, rx in FAC:
|
||||
if text and re.search(rx, text): return name
|
||||
cats = ' | '.join(c['categories']).lower()
|
||||
if re.search(r'births|deaths|people', cats): return 'People'
|
||||
if re.search(r'populated|villages|towns|geography|rivers', cats): return 'Places'
|
||||
if re.search(r'films|albums|songs|novels|television|video games', cats): return 'Works'
|
||||
return 'Other'
|
||||
for c in C: c['faction'] = faction(c)
|
||||
print('\n## Candidate factions (Wikidata P31 rules)\n')
|
||||
print('| faction | n | share | median attention | median depth | median reach | example |'); print('|---|---|---|---|---|---|---|')
|
||||
by = collections.defaultdict(list)
|
||||
for c in C: by[c['faction']].append(c)
|
||||
for name, cs in sorted(by.items(), key=lambda kv: -len(kv[1])):
|
||||
med = lambda k: st.median([x['stats'][k] for x in cs if x['stats'][k] is not None] or [0])
|
||||
print(f"| {name} | {len(cs)} | {len(cs)/len(C)*100:.0f}% | {med('attention'):.0f} | {med('depth'):.0f} | {med('reach'):.0f} | {cs[0]['title']} |")
|
||||
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'))
|
||||
@@ -1,158 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Sample random illustrated en.wikipedia articles the way server/wiki.ts selects them and
|
||||
enrich them the way server/enrichment.ts does. Polite: ~4 req/s, sequential, disk cache.
|
||||
Usage: python3 -I card_sample.py <cache_dir> <out.json> [target=320]"""
|
||||
import hashlib, json, os, re, sys, time, urllib.parse, urllib.request, calendar, datetime as dt
|
||||
|
||||
UA = 'WikiDeckCardDataSampler/0.1 (experimental card-game stat research; python-urllib)'
|
||||
CACHE, OUT = sys.argv[1], sys.argv[2]
|
||||
TARGET = int(sys.argv[3]) if len(sys.argv) > 3 else 320
|
||||
os.makedirs(CACHE, exist_ok=True)
|
||||
_last = [0.0]
|
||||
|
||||
def get(url, cache=True):
|
||||
key = os.path.join(CACHE, hashlib.sha1(url.encode()).hexdigest() + '.json')
|
||||
if cache and os.path.exists(key):
|
||||
return json.load(open(key))
|
||||
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])
|
||||
if wait > 0: time.sleep(wait)
|
||||
_last[0] = time.time()
|
||||
req = urllib.request.Request(url, headers={'User-Agent': UA, 'Accept': 'application/json'})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=20) as r:
|
||||
data = json.loads(r.read().decode())
|
||||
break
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code == 404: data = {'__404': True}; break
|
||||
if e.code == 429 or e.code >= 500:
|
||||
ra = e.headers.get('retry-after'); w = int(ra) + 1 if ra and ra.isdigit() else 5 * (attempt + 1)
|
||||
print('http', e.code, 'sleep', w, file=sys.stderr); time.sleep(min(w, 60)); continue
|
||||
raise
|
||||
except Exception as e:
|
||||
print('retry', attempt, type(e).__name__, e, file=sys.stderr); time.sleep(2 * (attempt + 1))
|
||||
else:
|
||||
raise RuntimeError('failed ' + url)
|
||||
if cache: json.dump(data, open(key, 'w'))
|
||||
return data
|
||||
|
||||
def api(params, cache=True):
|
||||
return get('https://en.wikipedia.org/w/api.php?' + urllib.parse.urlencode({'format': 'json', 'formatversion': '2', **params}), cache)
|
||||
|
||||
def legacy_category(title, cats):
|
||||
t = (title + ' ' + ' '.join(cats)).lower()
|
||||
if re.search(r'astronom|planet|space|galax|moon|star\b', t): return 'Space'
|
||||
if re.search(r'animal|plant|species|ocean|biolog|mollusc', t): return 'Nature'
|
||||
if re.search(r'births|deaths|people|scientist', t): return 'People'
|
||||
if re.search(r'physic|chem|math|science|technolog', t): return 'Science'
|
||||
if re.search(r'histor|ancient|archaeolog|empire', t): return 'History'
|
||||
return 'Culture'
|
||||
|
||||
def score(v, scale):
|
||||
import math
|
||||
return min(100, round(math.log10(v + 1) / scale * 100))
|
||||
|
||||
# 1. random illustrated articles (same filter as wiki.ts: thumbnail + extract >= 40 chars)
|
||||
picked, seen, batches, raw_pages = [], set(), 0, 0
|
||||
state_file = os.path.join(CACHE, '_random_state.json')
|
||||
if os.path.exists(state_file):
|
||||
picked = json.load(open(state_file)); seen = {p['pageId'] for p in picked}
|
||||
while len(picked) < TARGET:
|
||||
try: d = api({'action': 'query', 'generator': 'random', 'grnnamespace': '0', 'grnlimit': '20',
|
||||
'prop': 'extracts|pageimages|info|categories', 'exintro': '1', 'explaintext': '1', 'exchars': '900',
|
||||
'exlimit': '20', 'piprop': 'thumbnail', 'pithumbsize': '800', 'cllimit': '500'}, cache=False)
|
||||
except RuntimeError as e: print(e, file=sys.stderr); time.sleep(5); continue
|
||||
batches += 1
|
||||
for p in d.get('query', {}).get('pages', []):
|
||||
raw_pages += 1
|
||||
thumb = (p.get('thumbnail') or {}).get('source', '')
|
||||
ext = (p.get('extract') or '').strip()
|
||||
if not re.match(r'https://(upload|thumb)\.wikimedia\.org/', thumb) or len(ext) < 40 or p['pageid'] in seen: continue
|
||||
seen.add(p['pageid'])
|
||||
picked.append({'pageId': p['pageid'], 'title': p['title'],
|
||||
'legacyCategory': legacy_category(p['title'], [c['title'] for c in p.get('categories', [])])})
|
||||
json.dump(picked, open(state_file, 'w'))
|
||||
print(f'random batch {batches}: {len(picked)} illustrated / {raw_pages} raw', file=sys.stderr)
|
||||
picked = picked[:TARGET]
|
||||
|
||||
# 2. enrichment per article (same params as enrichment.ts) + daily views for drift
|
||||
now = dt.datetime(2026, 11, 16, tzinfo=dt.timezone.utc)
|
||||
months = []
|
||||
for i in range(6):
|
||||
m = now.month - 6 + i; y = now.year + (m - 1) // 12; m = (m - 1) % 12 + 1
|
||||
months.append(f'{y:04d}-{m:02d}')
|
||||
# batched metadata (same props as enrichment.ts; per-page cllimit 50 is emulated by truncating)
|
||||
meta = {}
|
||||
ids = [p['pageId'] for p in picked]
|
||||
for i in range(0, len(ids), 50):
|
||||
chunk = ids[i:i + 50]; cont = {}; pages = {}
|
||||
while True:
|
||||
md = api({'action': 'query', 'pageids': '|'.join(map(str, chunk)), 'prop': 'info|categories|pageprops|description|langlinks',
|
||||
'clshow': '!hidden', 'cllimit': '500', 'lllimit': '500', 'ppprop': 'wikibase_item', **cont})
|
||||
for pg in md['query']['pages']:
|
||||
cur = pages.setdefault(pg['pageid'], {**pg, 'categories': [], 'langlinks': []})
|
||||
cur['categories'] += pg.get('categories', []); cur['langlinks'] += pg.get('langlinks', [])
|
||||
if 'continue' not in md: break
|
||||
cont = md['continue']
|
||||
meta.update(pages)
|
||||
print(f'metadata {len(meta)}/{len(ids)}', file=sys.stderr)
|
||||
cards = []
|
||||
for n, pk in enumerate(picked):
|
||||
page = meta[pk['pageId']]
|
||||
cont = {'clcontinue': 1} if len(page['categories']) > 50 else {}
|
||||
page['categories'] = page['categories'][:50]
|
||||
langs = len(page.get('langlinks', []))
|
||||
t = urllib.parse.quote(page['title'].replace(' ', '_'), safe='')
|
||||
daily = get(f'https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org/all-access/user/{t}/daily/{months[0].replace("-", "")}01/20261115')
|
||||
if daily.get('__missing'): continue
|
||||
dmap = {it['timestamp'][:8]: it['views'] for it in daily.get('items', [])}
|
||||
pv = {'status': 'unavailable', 'months': [], 'latestMonth': months[5], 'total': None, 'dailyAverage': None, 'trendPercent': None}
|
||||
if dmap:
|
||||
ordered = []
|
||||
for m in months:
|
||||
y, mo = map(int, m.split('-')); nd = calendar.monthrange(y, mo)[1]
|
||||
ordered.append({'month': m, 'views': sum(dmap.get(f'{y:04d}{mo:02d}{d:02d}', 0) for d in range(1, nd + 1))})
|
||||
latest, prior = ordered[5]['views'], ordered[4]['views']
|
||||
nd = calendar.monthrange(*map(int, months[5].split('-')))[1]
|
||||
pv = {'status': 'available', 'months': ordered, 'latestMonth': months[5], 'total': sum(o['views'] for o in ordered),
|
||||
'dailyAverage': latest / nd, 'trendPercent': (latest - prior) / prior * 100 if prior > 0 else None}
|
||||
# 30-day drift: views 2026-10-17..11-15 vs 2026-09-17..10-16
|
||||
def window(start, days):
|
||||
s = dt.date.fromisoformat(start)
|
||||
return sum(dmap.get((s + dt.timedelta(d)).strftime('%Y%m%d'), 0) for d in range(days))
|
||||
last30, prev30 = window('2026-10-17', 30), window('2026-09-17', 30)
|
||||
pb = page['length']
|
||||
cards.append({'pageId': page['pageid'], 'title': page['title'], 'description': page.get('description'),
|
||||
'wikidataId': (page.get('pageprops') or {}).get('wikibase_item'), 'revisionId': page['lastrevid'], 'pageBytes': pb,
|
||||
'languageCount': langs, 'languagesTruncated': 'llcontinue' in cont,
|
||||
'categories': [c['title'].removeprefix('Category:') for c in page.get('categories', [])],
|
||||
'categoriesTruncated': 'clcontinue' in cont, 'fetchedAt': now.isoformat(), 'pageviews': pv,
|
||||
'stats': {'attention': score(pv['months'][5]['views'], 6) if pv['status'] == 'available' else None,
|
||||
'depth': score(pb, 6), 'reach': score(langs, 3)},
|
||||
'legacyCategory': pk['legacyCategory'],
|
||||
'drift30': {'last30': last30, 'prev30': prev30, 'pct': (last30 - prev30) / prev30 * 100 if prev30 else None}})
|
||||
if n % 25 == 0: print(f'enriched {n + 1}/{len(picked)}', file=sys.stderr)
|
||||
|
||||
# 3. Wikidata P31 (instance of) + labels
|
||||
qids = [c['wikidataId'] for c in cards if c['wikidataId']]
|
||||
p31 = {}
|
||||
for i in range(0, len(qids), 50):
|
||||
d = get('https://www.wikidata.org/w/api.php?' + urllib.parse.urlencode({'action': 'wbgetentities', 'format': 'json',
|
||||
'ids': '|'.join(qids[i:i + 50]), 'props': 'claims'}))
|
||||
for q, ent in d.get('entities', {}).items():
|
||||
p31[q] = [c['mainsnak']['datavalue']['value']['id'] for c in ent.get('claims', {}).get('P31', [])
|
||||
if c['mainsnak'].get('datavalue')]
|
||||
classes = sorted({c for v in p31.values() for c in v})
|
||||
labels = {}
|
||||
for i in range(0, len(classes), 50):
|
||||
d = get('https://www.wikidata.org/w/api.php?' + urllib.parse.urlencode({'action': 'wbgetentities', 'format': 'json',
|
||||
'ids': '|'.join(classes[i:i + 50]), 'props': 'labels', 'languages': 'en'}))
|
||||
for q, ent in d.get('entities', {}).items():
|
||||
labels[q] = ent.get('labels', {}).get('en', {}).get('value', q)
|
||||
for c in cards:
|
||||
c['instanceOf'] = [{'id': q, 'label': labels.get(q, q)} for q in p31.get(c['wikidataId'], [])]
|
||||
json.dump({'generatedAt': dt.datetime.now(dt.timezone.utc).isoformat(), 'method': 'random ns0 batches of 20, filter as server/wiki.ts (thumbnail + extract>=40); enrichment as server/enrichment.ts; monthly views summed from daily REST pageviews; P31 from Wikidata',
|
||||
'randomBatches': batches, 'rawPagesSeen': raw_pages, 'cards': cards}, open(OUT, 'w'), indent=1, ensure_ascii=False)
|
||||
print('done', len(cards), file=sys.stderr)
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* Turning WikiDeck data into GameCards, and starter decks for players with no NFTs.
|
||||
* PLACEHOLDER numbers until docs/game/DESIGN.md v1; engine-b tunes the mapping.
|
||||
* Starter cards are offline preview cards: not NFTs, never minted or moved.
|
||||
*/
|
||||
import { Rng } from './rng.ts';
|
||||
import { DEFAULT_RULESET } from './ruleset.ts';
|
||||
import type { Category, GameCard, Ruleset } from './types.ts';
|
||||
|
||||
type StarterSpec = [pageId: number, name: string, category: Category, cost: number, power: number, keyword: string | null];
|
||||
|
||||
/** 24 curated preview cards, 4 per cost 1–6. pageIds outside shared/catalog.ts are unverified (display only). */
|
||||
export const STARTER_POOL: readonly StarterSpec[] = [
|
||||
[22780, 'Octopus', 'Nature', 1, 2, null],
|
||||
[19331, 'Moon', 'Space', 1, 1, 'anchor'],
|
||||
[23053, 'Periodic table', 'Science', 1, 2, null],
|
||||
[3383, 'Bronze Age', 'History', 1, 1, 'rally'],
|
||||
[5843419, 'Chess', 'Culture', 2, 3, null],
|
||||
[9228, 'Earth', 'Space', 2, 2, 'rally'],
|
||||
[2008, 'Ada Lovelace', 'People', 2, 4, null],
|
||||
[21830, 'Honey bee', 'Nature', 2, 3, 'anchor'],
|
||||
[736, 'Albert Einstein', 'People', 3, 5, null],
|
||||
[10979, 'Fungus', 'Nature', 3, 4, 'rally'],
|
||||
[26903, 'Solar System', 'Space', 3, 6, null],
|
||||
[30758, 'Roman Empire', 'History', 3, 4, 'anchor'],
|
||||
[9649, 'Evolution', 'Science', 4, 7, null],
|
||||
[8424, 'Jazz', 'Culture', 4, 6, 'rally'],
|
||||
[12898, 'Marie Curie', 'People', 4, 8, null],
|
||||
[14533, 'Silk Road', 'History', 4, 6, 'anchor'],
|
||||
[19468, 'Mount Everest', 'Nature', 5, 9, null],
|
||||
[22936, 'Photosynthesis', 'Science', 5, 8, 'rally'],
|
||||
[18110, 'Leonardo da Vinci', 'People', 5, 10, null],
|
||||
[14627, 'Ancient Egypt', 'History', 5, 8, 'anchor'],
|
||||
[4177, 'Black hole', 'Space', 6, 12, null],
|
||||
[25443, 'Quantum mechanics', 'Science', 6, 11, 'rally'],
|
||||
[17867, 'Library of Alexandria', 'History', 6, 11, 'anchor'],
|
||||
[20217, 'Music', 'Culture', 6, 12, null],
|
||||
];
|
||||
|
||||
export function starterCard(spec: StarterSpec, copy = 0): GameCard {
|
||||
const [pageId, name, category, cost, power, keyword] = spec;
|
||||
return { id: `starter:${pageId}:${copy}`, name, pageId, category, cost, power, keyword, source: 'starter' };
|
||||
}
|
||||
|
||||
/**
|
||||
* A deterministic starter deck: 2 cards of each cost 1–6 (for a 12-card deck),
|
||||
* drawn from STARTER_POOL by `seed`. Cards whose keyword the ruleset doesn't
|
||||
* enable still play (as vanilla). Fills to ruleset.deck.min.
|
||||
*/
|
||||
export function starterDeck(seed: string, rules: Ruleset = DEFAULT_RULESET): GameCard[] {
|
||||
const rng = Rng.fromSeed(`starter:${seed}`);
|
||||
const byCost = new Map<number, StarterSpec[]>();
|
||||
for (const spec of STARTER_POOL) byCost.set(spec[3], [...(byCost.get(spec[3]) ?? []), spec]);
|
||||
const picks: StarterSpec[] = [];
|
||||
const costs = [...byCost.keys()].sort((a, b) => a - b);
|
||||
for (const cost of costs) picks.push(...rng.shuffle(byCost.get(cost)!).slice(0, 2));
|
||||
const deck = rng.shuffle(picks).slice(0, rules.deck.max).map(spec => starterCard(spec));
|
||||
// Pad for modes with bigger decks, respecting maxCopiesPerPage.
|
||||
let copy = 1;
|
||||
while (deck.length < rules.deck.min && copy < rules.deck.maxCopiesPerPage) {
|
||||
for (const spec of rng.shuffle(STARTER_POOL)) {
|
||||
if (deck.length >= rules.deck.min) break;
|
||||
deck.push(starterCard(spec, copy));
|
||||
}
|
||||
copy++;
|
||||
}
|
||||
return deck;
|
||||
}
|
||||
|
||||
/** Input for an owned card; matches PageEnrichment / MintStatsSnapshot fields (shared/enrichment.ts). */
|
||||
export interface CardSource {
|
||||
id: string;
|
||||
title: string;
|
||||
pageId: number;
|
||||
category: Category;
|
||||
stats: { attention: number | null; depth: number; reach: number };
|
||||
}
|
||||
|
||||
/**
|
||||
* PLACEHOLDER stat → card mapping (DESIGN.md will replace it). Famous cards cost
|
||||
* more (sidegrade): cost from the mean score, power = 2·cost (+1 if no keyword).
|
||||
*/
|
||||
export function cardFromStats(source: CardSource): GameCard {
|
||||
const { attention, depth, reach } = source.stats;
|
||||
const mean = ((attention ?? 0) + depth + reach) / 3;
|
||||
const cost = Math.max(1, Math.min(6, Math.ceil(mean / (100 / 6))));
|
||||
const keyword = depth >= reach && depth >= (attention ?? 0) ? 'anchor' : reach >= (attention ?? 0) ? 'rally' : null;
|
||||
return {
|
||||
id: source.id, name: source.title, pageId: source.pageId, category: source.category,
|
||||
cost, power: 2 * cost + (keyword ? 0 : 1), keyword, source: 'owned',
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* Card derivation (DESIGN.md §1): a frozen CardInput becomes a GameCard.
|
||||
* Pure and deterministic. The engine never reads raw 0–100 stats as power.
|
||||
*/
|
||||
export type Stat = 'attention' | 'depth' | 'reach';
|
||||
export type Faction = 'Space' | 'Nature' | 'People' | 'Science' | 'History' | 'Culture';
|
||||
export type Rarity = 'Legendary' | 'Epic' | 'Rare' | 'Common';
|
||||
|
||||
export const STATS: readonly Stat[] = ['attention', 'depth', 'reach'];
|
||||
export const FACTIONS: readonly Faction[] = ['Space', 'Nature', 'People', 'Science', 'History', 'Culture'];
|
||||
/** §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;
|
||||
pageId: number;
|
||||
title: string;
|
||||
category: Faction;
|
||||
rarity: Rarity;
|
||||
snapshot: { stats: { attention: number | null; depth: number; reach: number } };
|
||||
/** Frozen by the host at match start. */
|
||||
live: { trendPercent: number | null };
|
||||
}
|
||||
|
||||
export interface GameCard {
|
||||
cardId: string;
|
||||
pageId: number;
|
||||
title: string;
|
||||
faction: Faction;
|
||||
rarity: Rarity;
|
||||
cost: number;
|
||||
power: number;
|
||||
home: Stat;
|
||||
trend: -1 | 0 | 1;
|
||||
keyword: string | null;
|
||||
}
|
||||
|
||||
/** 99 ascending cut points per stat (§1.1). */
|
||||
export type PercentileTable = Record<Stat, readonly number[]>;
|
||||
|
||||
/** The subset of the rules config that card derivation reads. */
|
||||
export interface DerivationRules {
|
||||
costThresholds: readonly number[];
|
||||
powerByCost: readonly number[];
|
||||
trendUp: number;
|
||||
trendDown: number;
|
||||
}
|
||||
|
||||
export type KeywordPicker = (card: Omit<GameCard, 'keyword'>) => string | null;
|
||||
|
||||
/** §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);
|
||||
const sum = values.reduce((total, value) => total + value, 0);
|
||||
return Math.floor(sum / 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];
|
||||
const current = pct[best];
|
||||
if (value !== null && (current === null || value > current)) best = stat;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** §1.6: ±1 past the thresholds, null → 0. */
|
||||
export function trendFor(trendPercent: number | null, rules: Pick<DerivationRules, 'trendUp' | 'trendDown'>): -1 | 0 | 1 {
|
||||
if (trendPercent === null || !Number.isFinite(trendPercent)) return 0;
|
||||
if (trendPercent >= rules.trendUp) return 1;
|
||||
if (trendPercent <= rules.trendDown) return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
export function deriveCard(input: CardInput, rules: DerivationRules, table: PercentileTable,
|
||||
pickKeyword: KeywordPicker = () => null): GameCard {
|
||||
const pct = percentiles(input.snapshot.stats, table);
|
||||
const cost = costFor(fame(pct), rules.costThresholds);
|
||||
const power = rules.powerByCost[cost];
|
||||
if (power === undefined) throw new RangeError(`powerByCost has no entry for cost ${cost}`);
|
||||
const base = {
|
||||
cardId: input.cardId, pageId: input.pageId, title: input.title,
|
||||
faction: input.category, rarity: input.rarity,
|
||||
cost, power, home: homeStat(pct), trend: trendFor(input.live.trendPercent, rules),
|
||||
};
|
||||
return { ...base, keyword: pickKeyword(base) };
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
/**
|
||||
* WikiDeck game engine core: pure, deterministic, off-chain.
|
||||
* Every exported function treats its inputs as immutable and returns new data.
|
||||
* All randomness comes from the match seed via state.rng.
|
||||
* Contract: docs/game/ENGINE_API.md.
|
||||
*/
|
||||
import { KEYWORDS, LANE_MODIFIERS, type EffectContext } from './keywords.ts';
|
||||
import { Rng, seedRng } from './rng.ts';
|
||||
import { energyForTurn, parseRuleset } from './ruleset.ts';
|
||||
import {
|
||||
IllegalActionError, PLAYERS,
|
||||
type Action, type CardInPlay, type GameCard, type MatchResult, type MatchState,
|
||||
type PlayerId, type PlayerState, type PlayerView, type Ruleset,
|
||||
} from './types.ts';
|
||||
|
||||
export const ENGINE_VERSION = 1;
|
||||
|
||||
const other = (player: PlayerId): PlayerId => (player === 0 ? 1 : 0);
|
||||
const clone = <T>(value: T): T => structuredClone(value);
|
||||
|
||||
// ---------- validation ----------
|
||||
|
||||
export function validateDeck(rules: Ruleset, deck: readonly GameCard[]): string[] {
|
||||
const problems: string[] = [];
|
||||
if (deck.length < rules.deck.min || deck.length > rules.deck.max)
|
||||
problems.push(`Deck must have ${rules.deck.min === rules.deck.max ? rules.deck.min : `${rules.deck.min}–${rules.deck.max}`} cards (has ${deck.length})`);
|
||||
const ids = new Set<string>();
|
||||
const copies = new Map<number, number>();
|
||||
for (const card of deck) {
|
||||
if (typeof card?.id !== 'string' || !card.id || card.id.length > 128) { problems.push('Card id must be a non-empty string'); continue; }
|
||||
if (ids.has(card.id)) problems.push(`Duplicate card id ${card.id}`);
|
||||
ids.add(card.id);
|
||||
if (!Number.isInteger(card.cost) || card.cost < 0 || card.cost > 20) problems.push(`Card ${card.id}: bad cost`);
|
||||
if (!Number.isInteger(card.power) || card.power < -100 || card.power > 100) problems.push(`Card ${card.id}: bad power`);
|
||||
if (card.pageId !== null) {
|
||||
const n = (copies.get(card.pageId) ?? 0) + 1;
|
||||
copies.set(card.pageId, n);
|
||||
if (n === rules.deck.maxCopiesPerPage + 1) problems.push(`More than ${rules.deck.maxCopiesPerPage} copies of page ${card.pageId}`);
|
||||
}
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
// ---------- match setup ----------
|
||||
|
||||
/**
|
||||
* Start a match. `decks[0]` belongs to player 0. Throws IllegalActionError for an
|
||||
* invalid deck and ZodError for an invalid ruleset.
|
||||
*/
|
||||
export function createMatch(ruleset: Ruleset, decks: readonly [readonly GameCard[], readonly GameCard[]], seed: string): MatchState {
|
||||
const rules = parseRuleset(clone(ruleset));
|
||||
if (typeof seed !== 'string' || !seed) throw new IllegalActionError('Seed must be a non-empty string');
|
||||
for (const player of PLAYERS) {
|
||||
const problems = validateDeck(rules, decks[player] ?? []);
|
||||
if (problems.length) throw new IllegalActionError(`Player ${player} deck: ${problems.join('; ')}`);
|
||||
}
|
||||
const rng = new Rng(seedRng(seed));
|
||||
const modifiers = rules.laneModifiers.pool.length ? rng.shuffle(rules.laneModifiers.pool).slice(0, rules.lanes) : [];
|
||||
const newPlayer = (player: PlayerId): PlayerState => ({
|
||||
deck: rng.shuffle(clone(decks[player])), hand: [], energy: 0, staged: [], ended: false, discard: [],
|
||||
});
|
||||
const players: [PlayerState, PlayerState] = [newPlayer(0), newPlayer(1)];
|
||||
const state: MatchState = {
|
||||
schema: 'wikideck-match/1', ruleset: rules, seed, rng: rng.state, turn: 0, phase: 'planning',
|
||||
firstToReveal: rng.int(2) as PlayerId, players,
|
||||
lanes: Array.from({ length: rules.lanes }, (_, lane) => ({ modifier: modifiers[lane] ?? null, cards: [[], []] as [CardInPlay[], CardInPlay[]] })),
|
||||
log: [], actions: [], result: null,
|
||||
};
|
||||
for (const player of PLAYERS) for (let i = 0; i < rules.hand.start; 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.hand.max) return;
|
||||
const card = p.deck.shift()!;
|
||||
p.hand.push(card);
|
||||
state.log.push({ t: 'draw', player, cardId: card.id });
|
||||
}
|
||||
|
||||
function startTurn(state: MatchState, rng: Rng): void {
|
||||
state.turn += 1;
|
||||
const energy = energyForTurn(state.ruleset, state.turn);
|
||||
if (state.turn > 1) state.firstToReveal = leader(state, rng);
|
||||
for (const player of PLAYERS) Object.assign(state.players[player], { energy, staged: [], ended: false });
|
||||
state.log.push({ t: 'turnStart', turn: state.turn, energy: [energy, energy] });
|
||||
state.ruleset.laneModifiers.revealTurns.forEach((turn, lane) => {
|
||||
if (turn === state.turn) state.log.push({ t: 'laneRevealed', lane, modifier: state.lanes[lane].modifier });
|
||||
});
|
||||
for (const player of PLAYERS) for (let i = 0; i < state.ruleset.hand.drawPerTurn; i++) draw(state, player);
|
||||
}
|
||||
|
||||
/** Player winning more lanes reveals first; then higher total power; then a seeded coin flip. */
|
||||
function leader(state: MatchState, rng: Rng): PlayerId {
|
||||
const { lanesWon, totalPower } = score(state);
|
||||
if (lanesWon[0] !== lanesWon[1]) return lanesWon[0] > lanesWon[1] ? 0 : 1;
|
||||
if (totalPower[0] !== totalPower[1]) return totalPower[0] > totalPower[1] ? 0 : 1;
|
||||
return rng.int(2) as PlayerId;
|
||||
}
|
||||
|
||||
// ---------- power ----------
|
||||
|
||||
export function modifierActive(state: MatchState, lane: number): boolean {
|
||||
const revealTurn = state.ruleset.laneModifiers.revealTurns[lane] ?? 1;
|
||||
return state.lanes[lane]?.modifier != null && state.turn >= revealTurn;
|
||||
}
|
||||
|
||||
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 }) };
|
||||
}
|
||||
|
||||
function keywordOf(state: MatchState, card: GameCard) {
|
||||
return card.keyword && Object.hasOwn(state.ruleset.keywords, card.keyword) ? KEYWORDS[card.keyword] : undefined;
|
||||
}
|
||||
|
||||
/** Current power of one card in play, including ongoing keyword and lane effects. */
|
||||
export function cardPower(state: MatchState, target: CardInPlay): number {
|
||||
const scratch = new Rng(state.rng); // ongoing effects must not consume real randomness
|
||||
let power = target.card.power + target.bonus;
|
||||
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(context(state, scratch, state.ruleset.keywords[keyword.id], source.lane, keyword.id, source.owner), source, target);
|
||||
}
|
||||
const lane = state.lanes[target.lane];
|
||||
if (modifierActive(state, target.lane)) {
|
||||
const modifier = LANE_MODIFIERS[lane.modifier!];
|
||||
if (modifier?.ongoing) power += modifier.ongoing(context(state, scratch, state.ruleset.laneModifiers.params[modifier.id], target.lane, modifier.id, target.owner), target);
|
||||
}
|
||||
return power;
|
||||
}
|
||||
|
||||
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];
|
||||
}
|
||||
|
||||
function score(state: MatchState): Omit<MatchResult, 'winner' | 'reason' | 'turns'> {
|
||||
const powers = state.lanes.map((_, lane) => lanePower(state, lane));
|
||||
const lanesWon: [number, number] = [0, 0];
|
||||
const totalPower: [number, number] = [0, 0];
|
||||
for (const [a, b] of powers) {
|
||||
if (a > b) lanesWon[0]++; else if (b > a) lanesWon[1]++;
|
||||
totalPower[0] += a; totalPower[1] += b;
|
||||
}
|
||||
return { lanesWon, lanePower: powers, totalPower };
|
||||
}
|
||||
|
||||
// ---------- actions ----------
|
||||
|
||||
function stagedInLane(p: PlayerState, lane: number): number {
|
||||
return p.staged.filter(play => play.lane === lane).length;
|
||||
}
|
||||
|
||||
function playProblem(state: MatchState, action: Extract<Action, { type: 'play' }>): string | null {
|
||||
const p = state.players[action.player];
|
||||
if (p.ended) return 'You already ended your turn';
|
||||
const card = p.hand.find(c => c.id === action.cardId);
|
||||
if (!card) return 'Card is not in your hand';
|
||||
if (p.staged.some(play => play.cardId === action.cardId)) return 'Card is already staged';
|
||||
if (!Number.isInteger(action.lane) || action.lane < 0 || action.lane >= state.lanes.length) return 'No such lane';
|
||||
if (card.cost > p.energy) return 'Not enough energy';
|
||||
if (state.lanes[action.lane].cards[action.player].length + stagedInLane(p, action.lane) >= state.ruleset.laneCapacity) return 'Lane is full';
|
||||
if (modifierActive(state, action.lane)) {
|
||||
const modifier = LANE_MODIFIERS[state.lanes[action.lane].modifier!];
|
||||
const ctx = context(state, new Rng(state.rng), state.ruleset.laneModifiers.params[modifier?.id ?? ''], action.lane, modifier?.id ?? '', action.player);
|
||||
if (modifier?.canPlay && !modifier.canPlay(ctx, card, action.player)) return `${modifier.name} lane rejects this card`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 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';
|
||||
switch (action.type) {
|
||||
case 'play': return playProblem(state, action);
|
||||
case 'unstage': {
|
||||
const p = state.players[action.player];
|
||||
if (p.ended) return 'You already ended your turn';
|
||||
return p.staged.some(play => play.cardId === action.cardId) ? null : 'Card is not staged';
|
||||
}
|
||||
case 'endTurn': return state.players[action.player].ended ? 'You already ended your turn' : null;
|
||||
case 'concede': return null;
|
||||
default: return 'Unknown action';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Every legal action for `player` except `concede` (always legal while the match
|
||||
* is running). `endTurn` is always included while the player hasn't ended.
|
||||
*/
|
||||
export function legalActions(state: MatchState, player: PlayerId): Action[] {
|
||||
if (state.phase === 'over') return [];
|
||||
const p = state.players[player];
|
||||
if (p.ended) return [];
|
||||
const actions: Action[] = [];
|
||||
for (const card of p.hand) {
|
||||
if (p.staged.some(play => play.cardId === card.id)) continue;
|
||||
for (let lane = 0; lane < state.lanes.length; lane++) {
|
||||
const action: Action = { type: 'play', player, cardId: card.id, lane };
|
||||
if (!playProblem(state, action)) actions.push(action);
|
||||
}
|
||||
}
|
||||
for (const play of p.staged) actions.push({ type: 'unstage', player, cardId: play.cardId });
|
||||
actions.push({ type: 'endTurn', 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.staged.push({ cardId: action.cardId, lane: action.lane });
|
||||
p.energy -= p.hand.find(c => c.id === action.cardId)!.cost;
|
||||
break;
|
||||
}
|
||||
case 'unstage': {
|
||||
const index = p.staged.findIndex(play => play.cardId === action.cardId);
|
||||
p.staged.splice(index, 1);
|
||||
p.energy += p.hand.find(c => c.id === action.cardId)!.cost;
|
||||
break;
|
||||
}
|
||||
case 'endTurn': {
|
||||
p.ended = true;
|
||||
if (next.players.every(player => player.ended)) resolveTurn(next, rng);
|
||||
break;
|
||||
}
|
||||
case 'concede': {
|
||||
next.log.push({ t: 'concede', player: action.player });
|
||||
finish(next, other(action.player), 'concede');
|
||||
break;
|
||||
}
|
||||
}
|
||||
next.rng = rng.state;
|
||||
return next;
|
||||
}
|
||||
|
||||
function resolveTurn(state: MatchState, rng: Rng): void {
|
||||
for (const player of [state.firstToReveal, other(state.firstToReveal)]) {
|
||||
const p = state.players[player];
|
||||
for (const play of p.staged) {
|
||||
const index = p.hand.findIndex(c => c.id === play.cardId);
|
||||
const [card] = p.hand.splice(index, 1);
|
||||
const inPlay: CardInPlay = { card, owner: player, lane: play.lane, turn: state.turn, bonus: 0 };
|
||||
state.lanes[play.lane].cards[player].push(inPlay);
|
||||
state.log.push({ t: 'reveal', player, cardId: card.id, lane: play.lane });
|
||||
const keyword = keywordOf(state, card);
|
||||
keyword?.onReveal?.(context(state, rng, state.ruleset.keywords[keyword.id], play.lane, keyword.id, player), inPlay);
|
||||
if (modifierActive(state, play.lane)) {
|
||||
const modifier = LANE_MODIFIERS[state.lanes[play.lane].modifier!];
|
||||
modifier?.onReveal?.(context(state, rng, state.ruleset.laneModifiers.params[modifier.id], play.lane, modifier.id, player), inPlay);
|
||||
}
|
||||
}
|
||||
p.staged = [];
|
||||
}
|
||||
if (state.turn >= state.ruleset.maxTurns) finish(state, null, 'lanes');
|
||||
else startTurn(state, rng);
|
||||
}
|
||||
|
||||
function finish(state: MatchState, concedeWinner: PlayerId | null, reason: 'lanes' | 'concede'): void {
|
||||
const s = score(state);
|
||||
let winner: PlayerId | null = concedeWinner;
|
||||
let why: MatchResult['reason'] = reason;
|
||||
if (reason !== 'concede') {
|
||||
if (s.lanesWon[0] !== s.lanesWon[1]) winner = s.lanesWon[0] > s.lanesWon[1] ? 0 : 1;
|
||||
else if (state.ruleset.tieBreak === 'totalPower' && s.totalPower[0] !== s.totalPower[1]) {
|
||||
winner = s.totalPower[0] > s.totalPower[1] ? 0 : 1; why = 'totalPower';
|
||||
} else why = 'draw';
|
||||
}
|
||||
state.result = { winner, reason: why, ...s, turns: state.turn };
|
||||
state.phase = 'over';
|
||||
state.log.push({ t: 'matchOver', result: 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 player. UI and AI should only ever read this. */
|
||||
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, firstToReveal: state.firstToReveal,
|
||||
energy: me.energy, hand: me.hand, staged: me.staged, ended: me.ended, deckCount: me.deck.length,
|
||||
opponent: { handCount: opp.hand.length - opp.staged.length, deckCount: opp.deck.length, stagedCount: opp.staged.length, ended: opp.ended },
|
||||
lanes: state.lanes.map((lane, index) => {
|
||||
const revealed = modifierActive(state, index);
|
||||
const power = lanePower(state, index);
|
||||
return {
|
||||
modifier: revealed ? lane.modifier : null, modifierRevealed: revealed,
|
||||
cards: [lane.cards[you], lane.cards[them]] as [CardInPlay[], CardInPlay[]],
|
||||
power: [power[you], power[them]] as [number, number],
|
||||
};
|
||||
}),
|
||||
result: state.result,
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- serialisation / replay ----------
|
||||
|
||||
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: string, actions: readonly Action[]): MatchState {
|
||||
return actions.reduce(applyAction, createMatch(ruleset, decks, seed));
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/** Public entry point of the WikiDeck game engine. See docs/game/ENGINE_API.md. */
|
||||
export * from './types.ts';
|
||||
export { Rng, seedRng, type RngState } from './rng.ts';
|
||||
export { DEFAULT_RULESET, RulesetSchema, parseRuleset, energyForTurn } from './ruleset.ts';
|
||||
export {
|
||||
ENGINE_VERSION, createMatch, legalActions, applyAction, actionProblem, isOver, result, viewFor,
|
||||
serialize, deserialize, replay, validateDeck, cardPower, lanePower, modifierActive,
|
||||
} from './engine.ts';
|
||||
export { KEYWORDS, LANE_MODIFIERS, CATEGORY_ORDER, MENTION_TOKEN_PREFIX, hiddenFrom, laneFaction, type KeywordDef, type LaneModifierDef, type EffectContext } from './keywords.ts';
|
||||
export { STARTER_POOL, starterCard, starterDeck, cardFromStats, type CardSource } from './cards.ts';
|
||||
@@ -0,0 +1,208 @@
|
||||
/**
|
||||
* Keyword and lane-modifier registry. Effects are code here, but which ones a
|
||||
* mode uses and their numbers are data (Ruleset.keywords / laneModifiers.params).
|
||||
* Owner: engine-b (claude/wikideck#3). engine-a owns the hook contract below.
|
||||
*
|
||||
* Hook contract:
|
||||
* - onReveal: runs once when the card is revealed, after it is placed in its lane.
|
||||
* May mutate ctx.state (e.g. add `bonus` to cards, draw cards) but must use ctx.rng
|
||||
* for any randomness and must not throw.
|
||||
* - ongoing: pure; returns a power delta for `target` while `source` is in play.
|
||||
* Called for every (source, target) pair in play, including source === target.
|
||||
* - Lane modifiers have the same shape; `source` is null and `lane` is the modifier's lane.
|
||||
* canPlay lets a lane reject a card (checked when staging).
|
||||
*/
|
||||
import type { Rng } from './rng.ts';
|
||||
import type { CardInPlay, Category, GameCard, MatchState, PlayerId } from './types.ts';
|
||||
|
||||
export interface EffectContext {
|
||||
state: MatchState;
|
||||
rng: Rng;
|
||||
/** Tunable numbers for this keyword/modifier from the ruleset. */
|
||||
params: Record<string, number>;
|
||||
lane: number;
|
||||
log(text: string): void;
|
||||
/** Current power of a card in play (engine's cardPower). Optional so tests can build contexts by hand. */
|
||||
power?(card: CardInPlay): number;
|
||||
}
|
||||
|
||||
export interface KeywordDef {
|
||||
id: string;
|
||||
name: string;
|
||||
/** Short rules text with {param} placeholders, for card faces/tooltips. */
|
||||
text: string;
|
||||
onReveal?(ctx: EffectContext, self: CardInPlay): void;
|
||||
ongoing?(ctx: EffectContext, self: CardInPlay, target: CardInPlay): number;
|
||||
/** Runs at the end of each turn while in play (after all reveals). May mutate ctx.state. */
|
||||
endOfTurn?(ctx: EffectContext, self: CardInPlay): void;
|
||||
}
|
||||
|
||||
export interface LaneModifierDef {
|
||||
id: string;
|
||||
name: string;
|
||||
text: string;
|
||||
/** Runs when any card is revealed in this lane (after its own onReveal). */
|
||||
onReveal?(ctx: EffectContext, card: CardInPlay): void;
|
||||
ongoing?(ctx: EffectContext, target: CardInPlay): number;
|
||||
canPlay?(ctx: EffectContext, card: GameCard, player: PlayerId): boolean;
|
||||
}
|
||||
|
||||
/** 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);
|
||||
}
|
||||
|
||||
/** Faction of a lane (its Topic), or null. v1: an active `portal` lane modifier names one. */
|
||||
export function laneFaction(state: MatchState, lane: number): Category | null {
|
||||
const l = state.lanes[lane];
|
||||
if (!l || l.modifier !== 'portal') return null;
|
||||
const revealTurn = state.ruleset.laneModifiers.revealTurns[lane] ?? 1;
|
||||
if (state.turn < revealTurn) return null;
|
||||
return CATEGORY_ORDER[state.ruleset.laneModifiers.params.portal?.categoryIndex ?? 0] ?? null;
|
||||
}
|
||||
|
||||
/** Ongoing power of a card, excluding effects that need the full engine (base + bonus + ongoing keywords here). */
|
||||
function sidePower(ctx: EffectContext, lane: number, owner: PlayerId, exclude?: CardInPlay): number {
|
||||
return ctx.state.lanes[lane].cards[owner].filter(card => card !== exclude)
|
||||
.reduce((sum, card) => sum + (ctx.power ? ctx.power(card) : card.card.power + card.bonus), 0);
|
||||
}
|
||||
|
||||
/** True when `card` should be shown face down to `viewer` (Obscure). viewFor uses this. */
|
||||
export function hiddenFrom(state: MatchState, card: CardInPlay, viewer: PlayerId): boolean {
|
||||
return card.owner !== viewer && state.phase !== 'over' && card.card.keyword === 'obscure'
|
||||
&& Object.hasOwn(state.ruleset.keywords, 'obscure');
|
||||
}
|
||||
|
||||
export const MENTION_TOKEN_PREFIX = 'token:mention:';
|
||||
|
||||
export const KEYWORDS: Record<string, KeywordDef> = {
|
||||
// engine-a's original examples, kept for the placeholder starter pool and modes.
|
||||
rally: {
|
||||
id: 'rally', name: 'Rally', text: 'On reveal: +{amount} power to your other cards here.',
|
||||
onReveal(ctx, self) {
|
||||
const amount = ctx.params.amount ?? 1;
|
||||
for (const ally of allies(ctx.state, self)) ally.bonus += amount;
|
||||
ctx.log(`Rally +${amount}`);
|
||||
},
|
||||
},
|
||||
anchor: {
|
||||
id: 'anchor', name: 'Anchor', text: 'Ongoing: +{amount} power if this is your only card here.',
|
||||
ongoing(ctx, self, target) {
|
||||
return target === self && allies(ctx.state, self).length === 0 ? ctx.params.amount ?? 2 : 0;
|
||||
},
|
||||
},
|
||||
|
||||
// DESIGN.md (designer-b draft) §7.
|
||||
edition: {
|
||||
id: 'edition', name: 'Edition', text: 'Ongoing: +{amount} power for each other copy of this article on your side.',
|
||||
ongoing(ctx, self, target) {
|
||||
if (target !== self || self.card.pageId === null) return 0;
|
||||
let copies = 0;
|
||||
for (const lane of ctx.state.lanes) for (const card of lane.cards[self.owner])
|
||||
if (card !== self && card.card.pageId === self.card.pageId) copies++;
|
||||
return copies * (ctx.params.amount ?? 2);
|
||||
},
|
||||
},
|
||||
translated: {
|
||||
id: 'translated', name: 'Translated', text: 'On reveal: +{amount} power to your first card in each other Topic.',
|
||||
onReveal(ctx, self) {
|
||||
const amount = ctx.params.amount ?? 1;
|
||||
ctx.state.lanes.forEach((lane, index) => {
|
||||
const first = lane.cards[self.owner][0];
|
||||
if (index !== self.lane && first) {
|
||||
first.bonus += amount;
|
||||
ctx.log(`Translated +${amount} to ${first.card.name}`);
|
||||
}
|
||||
});
|
||||
},
|
||||
},
|
||||
viral: {
|
||||
id: 'viral', name: 'Viral', text: 'On reveal: add a {amount}-power Mention to a random other Topic with space.',
|
||||
onReveal(ctx, self) {
|
||||
const cap = ctx.state.ruleset.laneCapacity;
|
||||
const open = ctx.state.lanes.map((lane, index) => ({ lane, index }))
|
||||
.filter(({ lane, index }) => index !== self.lane && lane.cards[self.owner].length < cap)
|
||||
.map(({ index }) => index);
|
||||
if (!open.length) return;
|
||||
const lane = open[ctx.rng.int(open.length)];
|
||||
const token: GameCard = {
|
||||
id: `${MENTION_TOKEN_PREFIX}${self.card.id}:${ctx.state.turn}`, name: 'Mention', pageId: null,
|
||||
category: self.card.category, cost: 0, power: ctx.params.amount ?? 1, keyword: null, source: 'loaner',
|
||||
meta: { token: true },
|
||||
};
|
||||
ctx.state.lanes[lane].cards[self.owner].push({ card: token, owner: self.owner, lane, turn: ctx.state.turn, bonus: 0 });
|
||||
ctx.log(`Viral: Mention in lane ${lane + 1}`);
|
||||
},
|
||||
},
|
||||
rising: {
|
||||
id: 'rising', name: 'Rising', text: 'End of turn: +{amount} power (up to +{max}).',
|
||||
endOfTurn(ctx, self) {
|
||||
const amount = ctx.params.amount ?? 1, max = ctx.params.max ?? 3;
|
||||
const risen = Number(self.card.meta?.risen ?? 0);
|
||||
const gain = Math.max(0, Math.min(amount, max - risen));
|
||||
if (!gain) return;
|
||||
self.bonus += gain;
|
||||
self.card.meta = { ...self.card.meta, risen: risen + gain };
|
||||
ctx.log(`Rising +${gain}`);
|
||||
},
|
||||
},
|
||||
nostalgic: {
|
||||
id: 'nostalgic', name: 'Nostalgic', text: "On reveal: if you're losing here, +{amount} power.",
|
||||
onReveal(ctx, self) {
|
||||
const mine = sidePower(ctx, self.lane, self.owner, self);
|
||||
const theirs = sidePower(ctx, self.lane, self.owner === 0 ? 1 : 0);
|
||||
if (mine < theirs) {
|
||||
self.bonus += ctx.params.amount ?? 3;
|
||||
ctx.log(`Nostalgic +${ctx.params.amount ?? 3}`);
|
||||
}
|
||||
},
|
||||
},
|
||||
encyclopedic: {
|
||||
id: 'encyclopedic', name: 'Encyclopedic', text: "Can't have its power reduced. On reveal: if it's your only card here, +{amount} power.",
|
||||
onReveal(ctx, self) {
|
||||
if (allies(ctx.state, self).length === 0) {
|
||||
self.bonus += ctx.params.amount ?? 2;
|
||||
ctx.log(`Encyclopedic +${ctx.params.amount ?? 2}`);
|
||||
}
|
||||
},
|
||||
// Floor: cancel any negative bonus on itself (v1 has no negative effects; kept for modes).
|
||||
ongoing(_ctx, self, target) { return target === self && self.bonus < 0 ? -self.bonus : 0; },
|
||||
},
|
||||
obscure: {
|
||||
id: 'obscure', name: 'Obscure', text: 'The opponent sees this card face down until the match ends.',
|
||||
},
|
||||
local: {
|
||||
id: 'local', name: 'Local', text: "Ongoing: +{amount} power in a Topic of this card's faction.",
|
||||
ongoing(ctx, self, target) {
|
||||
return target === self && laneFaction(ctx.state, self.lane) === self.card.category ? ctx.params.amount ?? 2 : 0;
|
||||
},
|
||||
},
|
||||
wildcard: {
|
||||
id: 'wildcard', name: 'Wildcard', text: "On reveal: this card's faction becomes its Topic's faction.",
|
||||
onReveal(ctx, self) {
|
||||
const faction = laneFaction(ctx.state, self.lane);
|
||||
if (faction && faction !== self.card.category) {
|
||||
self.card.category = faction;
|
||||
ctx.log(`Wildcard becomes ${faction}`);
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const LANE_MODIFIERS: Record<string, LaneModifierDef> = {
|
||||
plain: { id: 'plain', name: 'Plain', text: 'No effect.' },
|
||||
portal: {
|
||||
id: 'portal', name: 'Portal', text: 'Cards of category {category} get +{amount} power here.',
|
||||
// params.categoryIndex picks from CATEGORY_ORDER so params stay numeric.
|
||||
ongoing(ctx, target) {
|
||||
const category = CATEGORY_ORDER[ctx.params.categoryIndex ?? 0];
|
||||
return target.card.category === category ? ctx.params.amount ?? 2 : 0;
|
||||
},
|
||||
},
|
||||
narrow: {
|
||||
id: 'narrow', name: 'Narrow', text: 'Only cards costing {maxCost} or less can be played here.',
|
||||
canPlay(ctx, card) { return card.cost <= (ctx.params.maxCost ?? 3); },
|
||||
},
|
||||
};
|
||||
|
||||
export const CATEGORY_ORDER = ['Space', 'Nature', 'People', 'Science', 'History', 'Culture'] as const;
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* Seeded, serialisable PRNG for the game engine (off-chain only).
|
||||
* sfc32 seeded by cyrb128 of a string. The state is four uint32 numbers so it
|
||||
* round-trips through JSON and a match can be resumed or replayed exactly.
|
||||
*/
|
||||
export type RngState = [number, number, number, number];
|
||||
|
||||
function cyrb128(text: string): RngState {
|
||||
let h1 = 1779033703, h2 = 3144134277, h3 = 1013904242, h4 = 2773480762;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const k = text.charCodeAt(i);
|
||||
h1 = h2 ^ Math.imul(h1 ^ k, 597399067);
|
||||
h2 = h3 ^ Math.imul(h2 ^ k, 2869860233);
|
||||
h3 = h4 ^ Math.imul(h3 ^ k, 951274213);
|
||||
h4 = h1 ^ Math.imul(h4 ^ k, 2716044179);
|
||||
}
|
||||
h1 = Math.imul(h3 ^ (h1 >>> 18), 597399067);
|
||||
h2 = Math.imul(h4 ^ (h2 >>> 22), 2869860233);
|
||||
h3 = Math.imul(h1 ^ (h3 >>> 17), 951274213);
|
||||
h4 = Math.imul(h2 ^ (h4 >>> 19), 2716044179);
|
||||
h1 ^= h2 ^ h3 ^ h4; h2 ^= h1; h3 ^= h1; h4 ^= h1;
|
||||
return [h1 >>> 0, h2 >>> 0, h3 >>> 0, h4 >>> 0];
|
||||
}
|
||||
|
||||
export function seedRng(seed: string): RngState {
|
||||
const state = cyrb128(seed);
|
||||
// Warm up so similar seeds diverge.
|
||||
const rng = new Rng(state);
|
||||
for (let i = 0; i < 12; i++) rng.nextUint32();
|
||||
return rng.state;
|
||||
}
|
||||
|
||||
/** Mutable wrapper over an RngState. The engine keeps `state` inside MatchState. */
|
||||
export class Rng {
|
||||
state: RngState;
|
||||
constructor(state: RngState) { this.state = [state[0] >>> 0, state[1] >>> 0, state[2] >>> 0, state[3] >>> 0]; }
|
||||
static fromSeed(seed: string): Rng { return new Rng(seedRng(seed)); }
|
||||
|
||||
nextUint32(): number {
|
||||
let [a, b, c, d] = this.state;
|
||||
const t = (((a + b) | 0) + d) | 0;
|
||||
d = (d + 1) | 0;
|
||||
a = b ^ (b >>> 9);
|
||||
b = (c + (c << 3)) | 0;
|
||||
c = (c << 21) | (c >>> 11);
|
||||
c = (c + t) | 0;
|
||||
this.state = [a >>> 0, b >>> 0, c >>> 0, d >>> 0];
|
||||
return t >>> 0;
|
||||
}
|
||||
/** Float in [0, 1). */
|
||||
next(): number { return this.nextUint32() / 4294967296; }
|
||||
/** Integer in [0, n). Unbiased via rejection sampling. */
|
||||
int(n: number): number {
|
||||
if (!Number.isInteger(n) || n <= 0 || n > 4294967296) throw new RangeError('Rng.int needs a positive integer bound');
|
||||
const limit = 4294967296 - (4294967296 % n);
|
||||
let x: number;
|
||||
do x = this.nextUint32(); while (x >= limit);
|
||||
return x % 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; 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,70 @@
|
||||
/**
|
||||
* Ruleset: 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; it enforces bounds that keep matches short and terminating.
|
||||
*/
|
||||
import { z } from 'zod';
|
||||
import { KEYWORDS, LANE_MODIFIERS } from './keywords.ts';
|
||||
import type { Ruleset } from './types.ts';
|
||||
|
||||
const int = (min: number, max: number) => z.number().int().min(min).max(max);
|
||||
const params = z.record(z.string().max(32), z.number().finite().min(-100).max(100))
|
||||
.refine(value => Object.keys(value).length <= 8, 'Too many params');
|
||||
|
||||
export const RulesetSchema = z.object({
|
||||
id: z.string().regex(/^[a-z0-9][a-z0-9-]{0,47}$/),
|
||||
name: z.string().min(1).max(64),
|
||||
version: int(1, 1_000_000),
|
||||
lanes: int(1, 5),
|
||||
laneCapacity: int(1, 8),
|
||||
maxTurns: int(1, 12),
|
||||
deck: z.object({ min: int(1, 40), max: int(1, 40), maxCopiesPerPage: int(1, 40) }).strict(),
|
||||
hand: z.object({ start: int(0, 10), max: int(1, 12), drawPerTurn: int(0, 3) }).strict(),
|
||||
energy: z.object({ start: int(0, 20), perTurn: int(0, 5), max: int(1, 20) }).strict(),
|
||||
keywords: z.record(z.string(), params).refine(value => Object.keys(value).length <= 32, 'Too many keywords'),
|
||||
laneModifiers: z.object({
|
||||
pool: z.array(z.string()).max(32),
|
||||
revealTurns: z.array(int(1, 12)).max(5),
|
||||
params: z.record(z.string(), params),
|
||||
}).strict(),
|
||||
tieBreak: z.enum(['totalPower', 'draw']),
|
||||
}).strict().superRefine((rules, ctx) => {
|
||||
const issue = (message: string) => ctx.addIssue({ code: 'custom', message });
|
||||
if (rules.deck.min > rules.deck.max) issue('deck.min > deck.max');
|
||||
if (rules.hand.start > rules.hand.max) issue('hand.start > hand.max');
|
||||
if (rules.energy.start > rules.energy.max) issue('energy.start > energy.max');
|
||||
if (rules.laneModifiers.revealTurns.length !== rules.lanes) issue('laneModifiers.revealTurns must have one entry per lane');
|
||||
if (rules.laneModifiers.pool.length && rules.laneModifiers.pool.length < rules.lanes) issue('laneModifiers.pool needs at least one modifier per lane (or be empty)');
|
||||
for (const id of Object.keys(rules.keywords)) if (!Object.hasOwn(KEYWORDS, id)) issue(`Unknown keyword: ${id}`);
|
||||
for (const id of [...rules.laneModifiers.pool, ...Object.keys(rules.laneModifiers.params)])
|
||||
if (!Object.hasOwn(LANE_MODIFIERS, id)) issue(`Unknown lane modifier: ${id}`);
|
||||
});
|
||||
|
||||
/** Validate untrusted ruleset JSON. Throws a ZodError with readable issues. */
|
||||
export function parseRuleset(input: unknown): Ruleset {
|
||||
return RulesetSchema.parse(input) as Ruleset;
|
||||
}
|
||||
|
||||
/** Placeholder base rules (Snap-style lanes) until DESIGN.md v1 lands. */
|
||||
export const DEFAULT_RULESET: Ruleset = {
|
||||
id: 'wikideck-standard',
|
||||
name: 'WikiDeck Standard',
|
||||
version: 1,
|
||||
lanes: 3,
|
||||
laneCapacity: 4,
|
||||
maxTurns: 6,
|
||||
deck: { min: 12, max: 12, maxCopiesPerPage: 2 },
|
||||
hand: { start: 3, max: 7, drawPerTurn: 1 },
|
||||
energy: { start: 1, perTurn: 1, max: 6 },
|
||||
keywords: { rally: { amount: 1 }, anchor: { amount: 2 } },
|
||||
laneModifiers: {
|
||||
pool: ['plain', 'portal', 'narrow'],
|
||||
revealTurns: [1, 2, 3],
|
||||
params: { portal: { categoryIndex: 0, amount: 2 }, narrow: { maxCost: 3 } },
|
||||
},
|
||||
tieBreak: 'totalPower',
|
||||
};
|
||||
|
||||
export function energyForTurn(rules: Ruleset, turn: number): number {
|
||||
return Math.min(rules.energy.max, rules.energy.start + (turn - 1) * rules.energy.perTurn);
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
/**
|
||||
* WikiDeck game engine types (off-chain). Everything here is plain JSON data:
|
||||
* MatchState round-trips through JSON.stringify/parse with no loss.
|
||||
* 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. */
|
||||
export type Category = 'Space' | 'Nature' | 'People' | 'Science' | 'History' | 'Culture';
|
||||
|
||||
/** A card as the engine sees it. Built from enrichment data by cards.ts, or a starter/loaner card. */
|
||||
export interface GameCard {
|
||||
/** Unique within one deck (e.g. the NFT card hash, or `starter:<pageId>:<n>`). */
|
||||
id: string;
|
||||
name: string;
|
||||
pageId: number | null;
|
||||
category: Category;
|
||||
cost: number;
|
||||
power: number;
|
||||
/** Keyword id from the ruleset's keyword list, or null. */
|
||||
keyword: string | null;
|
||||
/** 'owned' = an NFT the player holds (never moved or burned by a match). */
|
||||
source: 'owned' | 'starter' | 'loaner';
|
||||
/** Optional display/tie-break data; never used for rules unless a keyword says so. */
|
||||
meta?: Record<string, string | number | boolean | null>;
|
||||
}
|
||||
|
||||
/** All rule numbers. Peer-hosted modes override these as data (see ruleset.ts). */
|
||||
export interface Ruleset {
|
||||
id: string;
|
||||
name: string;
|
||||
version: number;
|
||||
lanes: number;
|
||||
/** Cards that may sit on one side of one lane. */
|
||||
laneCapacity: number;
|
||||
maxTurns: number;
|
||||
deck: { min: number; max: number; maxCopiesPerPage: number };
|
||||
hand: { start: number; max: number; drawPerTurn: number };
|
||||
/** Energy available on turn t (1-based) = min(max, start + (t - 1) * perTurn). Unspent energy is lost. */
|
||||
energy: { start: number; perTurn: number; max: number };
|
||||
/** Keyword ids that cards may carry in this mode, with tunable numbers per keyword. */
|
||||
keywords: Record<string, Record<string, number>>;
|
||||
laneModifiers: {
|
||||
/** Pool of lane modifier ids; one is drawn (without replacement) per lane at match start. */
|
||||
pool: string[];
|
||||
/** Turn on which lane i's modifier becomes visible and active (length = lanes). */
|
||||
revealTurns: number[];
|
||||
params: Record<string, Record<string, number>>;
|
||||
};
|
||||
/** How the match ends when lanes tie on count. */
|
||||
tieBreak: 'totalPower' | 'draw';
|
||||
}
|
||||
|
||||
export interface CardInPlay {
|
||||
card: GameCard;
|
||||
owner: PlayerId;
|
||||
lane: number;
|
||||
/** Turn the card was revealed. */
|
||||
turn: number;
|
||||
/** Permanent power changes from effects (onReveal buffs etc.). */
|
||||
bonus: number;
|
||||
}
|
||||
|
||||
export interface StagedPlay { cardId: string; lane: number }
|
||||
|
||||
export interface PlayerState {
|
||||
deck: GameCard[];
|
||||
hand: GameCard[];
|
||||
/** Energy left this turn (after staging). */
|
||||
energy: number;
|
||||
/** Plays chosen this turn, hidden from the opponent until reveal. Order matters. */
|
||||
staged: StagedPlay[];
|
||||
ended: boolean;
|
||||
discard: GameCard[];
|
||||
}
|
||||
|
||||
export interface LaneState {
|
||||
modifier: string | null;
|
||||
cards: [CardInPlay[], CardInPlay[]];
|
||||
}
|
||||
|
||||
export type MatchPhase = 'planning' | 'over';
|
||||
|
||||
export type LogEvent =
|
||||
| { t: 'turnStart'; turn: number; energy: [number, number] }
|
||||
| { t: 'draw'; player: PlayerId; cardId: string }
|
||||
| { t: 'reveal'; player: PlayerId; cardId: string; lane: number }
|
||||
| { t: 'laneRevealed'; lane: number; modifier: string | null }
|
||||
| { t: 'effect'; source: string; player: PlayerId; text: string }
|
||||
| { t: 'concede'; player: PlayerId }
|
||||
| { t: 'matchOver'; result: MatchResult };
|
||||
|
||||
export interface MatchState {
|
||||
schema: 'wikideck-match/1';
|
||||
ruleset: Ruleset;
|
||||
seed: string;
|
||||
rng: RngState;
|
||||
turn: number;
|
||||
phase: MatchPhase;
|
||||
/** Player who reveals first this turn. */
|
||||
firstToReveal: PlayerId;
|
||||
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 =
|
||||
| { type: 'play'; player: PlayerId; cardId: string; lane: number }
|
||||
/** Take back a staged (unrevealed) play this turn; refunds its energy. */
|
||||
| { type: 'unstage'; player: PlayerId; cardId: string }
|
||||
| { type: 'endTurn'; player: PlayerId }
|
||||
| { type: 'concede'; player: PlayerId };
|
||||
|
||||
export interface MatchResult {
|
||||
/** null = draw. */
|
||||
winner: PlayerId | null;
|
||||
reason: 'lanes' | 'totalPower' | 'draw' | 'concede';
|
||||
lanesWon: [number, number];
|
||||
/** lanePower[lane][player] at the end. */
|
||||
lanePower: [number, number][];
|
||||
totalPower: [number, number];
|
||||
turns: number;
|
||||
}
|
||||
|
||||
/** What one player is allowed to see. Use this for UI and AI, never raw MatchState. */
|
||||
export interface PlayerView {
|
||||
you: PlayerId;
|
||||
ruleset: Ruleset;
|
||||
turn: number;
|
||||
phase: MatchPhase;
|
||||
firstToReveal: PlayerId;
|
||||
energy: number;
|
||||
hand: GameCard[];
|
||||
staged: StagedPlay[];
|
||||
ended: boolean;
|
||||
deckCount: number;
|
||||
opponent: { handCount: number; deckCount: number; stagedCount: number; ended: boolean };
|
||||
lanes: {
|
||||
/** null when not yet revealed. */
|
||||
modifier: string | null;
|
||||
modifierRevealed: boolean;
|
||||
/** cards[0] = yours, cards[1] = opponent's (revealed only). */
|
||||
cards: [CardInPlay[], CardInPlay[]];
|
||||
/** power[0] = yours, power[1] = opponent's. */
|
||||
power: [number, number];
|
||||
}[];
|
||||
result: MatchResult | null;
|
||||
}
|
||||
|
||||
export class IllegalActionError extends Error {
|
||||
constructor(message: string) { super(message); this.name = 'IllegalActionError'; }
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
percentile, percentiles, fame, costFor, homeStat, trendFor, deriveCard,
|
||||
type CardInput, type PercentileTable, type DerivationRules,
|
||||
} from '../shared/game/derive.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: DerivationRules = {
|
||||
costThresholds: [15, 35, 55, 75, 90], powerByCost: [0, 1, 2, 4, 5, 7, 9], trendUp: 25, trendDown: -25,
|
||||
};
|
||||
|
||||
function input(stats: CardInput['snapshot']['stats'], trendPercent: number | null = null): CardInput {
|
||||
return { cardId: 'c1', pageId: 1, title: 'T', category: 'Science', rarity: 'Common',
|
||||
snapshot: { stats }, live: { trendPercent } };
|
||||
}
|
||||
|
||||
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); // 49 below + 0.5 equal → 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); // 1 + 2/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); // 10.5 → 11
|
||||
assert.equal(fame({ attention: 10, depth: 10, reach: 11 }), 10); // 10.33 → 10
|
||||
assert.equal(fame({ attention: 10, depth: 11, reach: 11 }), 11); // 10.67 → 11
|
||||
});
|
||||
|
||||
test('cost is 1 + thresholds ≤ fame, spanning 1–6 (§1.2)', () => {
|
||||
const t = RULES.costThresholds;
|
||||
assert.equal(costFor(0, t), 1);
|
||||
assert.equal(costFor(14, t), 1);
|
||||
assert.equal(costFor(15, t), 2);
|
||||
assert.equal(costFor(54, t), 3);
|
||||
assert.equal(costFor(55, t), 4);
|
||||
assert.equal(costFor(89, t), 5);
|
||||
assert.equal(costFor(90, t), 6);
|
||||
assert.equal(costFor(100, t), 6);
|
||||
});
|
||||
|
||||
test('home stat is the highest percentile, ties broken depth > reach > attention (§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: 60, depth: 40, reach: 60 }), 'reach');
|
||||
assert.equal(homeStat({ attention: null, depth: 0, reach: 0 }), 'depth');
|
||||
assert.equal(homeStat({ attention: null, depth: 0, reach: 1 }), 'reach');
|
||||
});
|
||||
|
||||
test('trend is ±1 at the inclusive thresholds and 0 for null (§1.6)', () => {
|
||||
assert.equal(trendFor(25, RULES), 1);
|
||||
assert.equal(trendFor(24.9, RULES), 0);
|
||||
assert.equal(trendFor(-25, RULES), -1);
|
||||
assert.equal(trendFor(-24.9, RULES), 0);
|
||||
assert.equal(trendFor(null, RULES), 0);
|
||||
assert.equal(trendFor(Number.NaN, RULES), 0);
|
||||
assert.equal(trendFor(1e9, RULES), 1); // inflated live views are still worth only +1
|
||||
});
|
||||
|
||||
test('deriveCard assembles cost, power, home, faction and trend', () => {
|
||||
const card = deriveCard(input({ attention: 81, depth: 71, reach: 61 }, 40), RULES, TABLE);
|
||||
// pct 80/70/60 → fame 70 → cost 4 → power 5
|
||||
assert.deepEqual(card, { cardId: 'c1', pageId: 1, title: 'T', faction: 'Science', rarity: 'Common',
|
||||
cost: 4, power: 5, home: 'attention', trend: 1, keyword: null });
|
||||
});
|
||||
|
||||
test('deriveCard passes the keyword picker the derived card', () => {
|
||||
const card = deriveCard(input({ attention: 10, depth: 20, reach: 30 }), RULES, TABLE,
|
||||
base => `${base.faction}:${base.home}:${base.cost}`);
|
||||
assert.equal(card.keyword, 'Science:reach:2');
|
||||
});
|
||||
|
||||
test('power depends only on cost: forged 100/100/100 stats only move a card up the curve (§1.3)', () => {
|
||||
const forged = deriveCard(input({ attention: 100, depth: 100, reach: 100 }), RULES, TABLE);
|
||||
assert.equal(forged.cost, 6);
|
||||
assert.equal(forged.power, RULES.powerByCost[6]);
|
||||
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, g.bool(0.2) ? null : g.int(-100, 100)), RULES, TABLE);
|
||||
assert.ok(card.cost >= 1 && card.cost <= 6);
|
||||
assert.equal(card.power, RULES.powerByCost[card.cost]);
|
||||
assert.ok(stats[card.home] !== null, 'home is never a null stat');
|
||||
// Raising any single stat never lowers cost.
|
||||
const bumped = { ...stats, depth: Math.min(100, stats.depth + g.int(1, 30)) };
|
||||
assert.ok(deriveCard(input(bumped), RULES, TABLE).cost >= card.cost);
|
||||
});
|
||||
});
|
||||
|
||||
test('deriveCard rejects a rules config without a power for the derived cost', () => {
|
||||
assert.throws(() => deriveCard(input({ attention: 100, depth: 100, reach: 100 }),
|
||||
{ ...RULES, powerByCost: [0, 1, 2] }, TABLE), RangeError);
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
DEFAULT_RULESET, IllegalActionError, Rng, applyAction, createMatch, deserialize, isOver, legalActions,
|
||||
parseRuleset, replay, result, serialize, starterDeck, viewFor, type Action, type GameCard, type MatchState, type PlayerId,
|
||||
} from '../shared/game/index.ts';
|
||||
|
||||
const decks = (seed = 'd'): [GameCard[], GameCard[]] => [starterDeck(`${seed}-a`), starterDeck(`${seed}-b`)];
|
||||
|
||||
function randomPlay(seed: string, ruleset = DEFAULT_RULESET): MatchState {
|
||||
let state = createMatch(ruleset, decks(seed), seed);
|
||||
const chooser = Rng.fromSeed(`bot:${seed}`);
|
||||
for (let steps = 0; !isOver(state); steps++) {
|
||||
assert.ok(steps < 1000, 'match must terminate');
|
||||
const player = chooser.int(2) as PlayerId;
|
||||
const actions = legalActions(state, player);
|
||||
if (!actions.length) continue;
|
||||
state = applyAction(state, chooser.pick(actions));
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
test('rng is deterministic and seed-sensitive', () => {
|
||||
const a = Rng.fromSeed('x'), b = Rng.fromSeed('x'), c = Rng.fromSeed('y');
|
||||
const seq = (r: Rng) => Array.from({ length: 8 }, () => r.nextUint32());
|
||||
assert.deepEqual(seq(a), seq(b));
|
||||
assert.notDeepEqual(seq(Rng.fromSeed('x')), seq(c));
|
||||
const r = Rng.fromSeed('bounds');
|
||||
for (let i = 0; i < 1000; i++) { const n = r.int(7); assert.ok(n >= 0 && n < 7); }
|
||||
});
|
||||
|
||||
test('default ruleset validates; bad rulesets are rejected', () => {
|
||||
assert.deepEqual(parseRuleset(DEFAULT_RULESET), DEFAULT_RULESET);
|
||||
assert.throws(() => parseRuleset({ ...DEFAULT_RULESET, maxTurns: 99 }));
|
||||
assert.throws(() => parseRuleset({ ...DEFAULT_RULESET, keywords: { nope: {} } }));
|
||||
assert.throws(() => parseRuleset({ ...DEFAULT_RULESET, extra: 1 }));
|
||||
});
|
||||
|
||||
test('starter decks are legal, deterministic and non-NFT', () => {
|
||||
const deck = starterDeck('s');
|
||||
assert.equal(deck.length, 12);
|
||||
assert.deepEqual(deck, starterDeck('s'));
|
||||
assert.ok(deck.every(card => card.source === 'starter'));
|
||||
assert.deepEqual(deck.map(c => c.cost).sort().join(''), '112233445566');
|
||||
});
|
||||
|
||||
test('match setup: hands, energy, turn 1', () => {
|
||||
const state = createMatch(DEFAULT_RULESET, decks(), 'setup');
|
||||
assert.equal(state.turn, 1);
|
||||
for (const p of state.players) { assert.equal(p.hand.length, 4); assert.equal(p.deck.length, 8); assert.equal(p.energy, 1); }
|
||||
assert.throws(() => createMatch(DEFAULT_RULESET, [decks()[0].slice(0, 5), decks()[1]], 's'), IllegalActionError);
|
||||
});
|
||||
|
||||
test('staging is hidden from the opponent until reveal', () => {
|
||||
let state = createMatch(DEFAULT_RULESET, decks(), 'hidden');
|
||||
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, 1).opponent.stagedCount, 1);
|
||||
assert.equal(viewFor(state, 1).lanes[play.lane].cards[1].length, 0);
|
||||
assert.equal(JSON.stringify(viewFor(state, 1)).includes(`"${play.cardId}"`), false);
|
||||
state = applyAction(state, { type: 'endTurn', player: 0 });
|
||||
state = applyAction(state, { type: 'endTurn', player: 1 });
|
||||
assert.equal(state.turn, 2);
|
||||
assert.equal(viewFor(state, 1).lanes[play.lane].cards[1][0].card.id, play.cardId);
|
||||
assert.throws(() => applyAction(state, { type: 'play', player: 0, cardId: play.cardId, lane: 0 }), IllegalActionError);
|
||||
});
|
||||
|
||||
test('unstage refunds energy', () => {
|
||||
let state = createMatch(DEFAULT_RULESET, decks(), 'unstage');
|
||||
const play = legalActions(state, 0).find(a => a.type === 'play') as Extract<Action, { type: 'play' }>;
|
||||
state = applyAction(state, play);
|
||||
state = applyAction(state, { type: 'unstage', player: 0, cardId: play.cardId });
|
||||
assert.equal(state.players[0].energy, 1);
|
||||
assert.equal(state.players[0].staged.length, 0);
|
||||
});
|
||||
|
||||
test('concede ends the match for the other player', () => {
|
||||
const state = applyAction(createMatch(DEFAULT_RULESET, decks(), 'c'), { type: 'concede', player: 1 });
|
||||
assert.equal(isOver(state), true);
|
||||
assert.equal(result(state)?.winner, 0);
|
||||
assert.deepEqual(legalActions(state, 0), []);
|
||||
});
|
||||
|
||||
test('random legal play terminates within maxTurns, and replays and serialises exactly', () => {
|
||||
for (let i = 0; i < 40; i++) {
|
||||
const seed = `prop-${i}`;
|
||||
const end = randomPlay(seed);
|
||||
const r = result(end)!;
|
||||
assert.ok(r.turns <= DEFAULT_RULESET.maxTurns);
|
||||
assert.deepEqual(randomPlay(seed), end);
|
||||
assert.deepEqual(replay(DEFAULT_RULESET, decks(seed), seed, end.actions), end);
|
||||
assert.deepEqual(deserialize(serialize(end)), end);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,147 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { KEYWORDS, Rng, hiddenFrom, laneFaction, parseRuleset } from '../shared/game/index.ts';
|
||||
import { card, cardPower, emptyBoard, endOfTurn, lanePower, place, reveal, testRules } from './game/build.ts';
|
||||
|
||||
test('every keyword has an id matching its key, a name and rules text', () => {
|
||||
for (const [id, def] of Object.entries(KEYWORDS)) {
|
||||
assert.equal(def.id, id);
|
||||
assert.ok(def.name && def.text, `${id} needs name and text`);
|
||||
}
|
||||
});
|
||||
|
||||
test('the all-keywords test ruleset validates', () => {
|
||||
assert.doesNotThrow(() => parseRuleset(testRules()));
|
||||
});
|
||||
|
||||
test('Edition: +2 for each other copy of the same article on your side, any lane', () => {
|
||||
const s = emptyBoard();
|
||||
const a = place(s, 0, 0, card({ pageId: 42, power: 5, keyword: 'edition' }));
|
||||
assert.equal(cardPower(s, a), 5);
|
||||
const b = place(s, 0, 2, card({ pageId: 42, power: 5, keyword: 'edition' }));
|
||||
assert.equal(cardPower(s, a), 7);
|
||||
assert.equal(cardPower(s, b), 7);
|
||||
place(s, 1, 0, card({ pageId: 42, power: 5 })); // the opponent's copy doesn't count
|
||||
assert.equal(cardPower(s, a), 7);
|
||||
});
|
||||
|
||||
test('Translated: +1 to your first card in each other lane that has one', () => {
|
||||
const s = emptyBoard();
|
||||
const left = place(s, 0, 0, card({ power: 2 }));
|
||||
const leftSecond = place(s, 0, 0, card({ power: 2 }));
|
||||
const enemy = place(s, 1, 2, card({ power: 2 }));
|
||||
const t = reveal(s, 0, 1, card({ power: 4, keyword: 'translated' }));
|
||||
assert.equal(left.bonus, 1);
|
||||
assert.equal(leftSecond.bonus, 0);
|
||||
assert.equal(enemy.bonus, 0);
|
||||
assert.equal(t.bonus, 0);
|
||||
});
|
||||
|
||||
test('Viral: adds a 1-power Mention token to a random other lane with space', () => {
|
||||
const s = emptyBoard();
|
||||
reveal(s, 0, 1, card({ keyword: 'viral' }), new Rng([9, 9, 9, 9]));
|
||||
const tokens = s.lanes.flatMap((lane, index) => lane.cards[0].filter(c => c.card.meta?.token).map(c => ({ c, index })));
|
||||
assert.equal(tokens.length, 1);
|
||||
assert.notEqual(tokens[0].index, 1);
|
||||
assert.equal(tokens[0].c.lane, tokens[0].index);
|
||||
assert.equal(cardPower(s, tokens[0].c), 1);
|
||||
});
|
||||
|
||||
test('Viral: deterministic for the same rng, and a no-op when no other lane has space', () => {
|
||||
const run = () => { const s = emptyBoard(); reveal(s, 0, 1, card({ id: 'v', name: 'V', pageId: 1, keyword: 'viral' }), new Rng([5, 6, 7, 8])); return s.lanes; };
|
||||
assert.deepEqual(run(), run());
|
||||
const s = emptyBoard();
|
||||
for (const lane of [0, 2]) for (let i = 0; i < s.ruleset.laneCapacity; i++) place(s, 0, lane, card());
|
||||
const before = JSON.stringify(s.lanes);
|
||||
reveal(s, 0, 1, card({ id: 'viral-full', keyword: 'viral' }));
|
||||
s.lanes[1].cards[0].pop();
|
||||
assert.equal(JSON.stringify(s.lanes), before);
|
||||
});
|
||||
|
||||
test('Rising: +1 at each end of turn, capped at +3', () => {
|
||||
const s = emptyBoard();
|
||||
const r = place(s, 0, 1, card({ power: 3, keyword: 'rising' }));
|
||||
const seen = [];
|
||||
for (let i = 0; i < 5; i++) { endOfTurn(s, r); seen.push(cardPower(s, r)); }
|
||||
assert.deepEqual(seen, [4, 5, 6, 6, 6]);
|
||||
});
|
||||
|
||||
test('Rising: the cap counts only Rising gains, not other bonuses', () => {
|
||||
const s = emptyBoard();
|
||||
const r = place(s, 0, 1, card({ power: 3, keyword: 'rising' }));
|
||||
r.bonus += 5; // e.g. Translated/Rally
|
||||
for (let i = 0; i < 4; i++) endOfTurn(s, r);
|
||||
assert.equal(cardPower(s, r), 11);
|
||||
});
|
||||
|
||||
test('Nostalgic: +3 only when losing the lane, judged without itself (DESIGN example: 2 vs 8)', () => {
|
||||
const s = emptyBoard();
|
||||
place(s, 0, 1, card({ power: 2 }));
|
||||
place(s, 1, 1, card({ power: 8 }));
|
||||
const n = reveal(s, 0, 1, card({ power: 3, keyword: 'nostalgic' }));
|
||||
assert.equal(cardPower(s, n), 6);
|
||||
assert.deepEqual(lanePower(s, 1), [8, 8]);
|
||||
});
|
||||
|
||||
test('Nostalgic: no bonus when tied or winning', () => {
|
||||
const s = emptyBoard();
|
||||
place(s, 0, 1, card({ power: 4 }));
|
||||
place(s, 1, 1, card({ power: 4 }));
|
||||
assert.equal(reveal(s, 0, 1, card({ power: 3, keyword: 'nostalgic' })).bonus, 0);
|
||||
const t = emptyBoard();
|
||||
assert.equal(reveal(t, 0, 1, card({ power: 3, keyword: 'nostalgic' })).bonus, 0); // 0 vs 0 is not losing
|
||||
});
|
||||
|
||||
test('Encyclopedic: +2 when alone here; floors its own negative bonus', () => {
|
||||
const s = emptyBoard();
|
||||
const e = reveal(s, 0, 1, card({ power: 7, keyword: 'encyclopedic' }));
|
||||
assert.equal(cardPower(s, e), 9);
|
||||
place(s, 0, 2, card());
|
||||
const f = (() => { place(s, 0, 2, card()); return reveal(s, 0, 2, card({ power: 7, keyword: 'encyclopedic' })); })();
|
||||
assert.equal(cardPower(s, f), 7);
|
||||
f.bonus = -4;
|
||||
assert.equal(cardPower(s, f), 7);
|
||||
});
|
||||
|
||||
test('Local: +2 only in a lane whose faction matches', () => {
|
||||
const s = emptyBoard();
|
||||
assert.equal(laneFaction(s, 0), 'Science');
|
||||
assert.equal(laneFaction(s, 1), null);
|
||||
const home = place(s, 0, 0, card({ power: 2, category: 'Science', keyword: 'local' }));
|
||||
const away = place(s, 0, 1, card({ power: 2, category: 'Science', keyword: 'local' }));
|
||||
const wrong = place(s, 0, 0, card({ power: 2, category: 'History', keyword: 'local' }));
|
||||
assert.deepEqual([cardPower(s, home), cardPower(s, away), cardPower(s, wrong)], [4, 2, 2]);
|
||||
});
|
||||
|
||||
test('laneFaction is null until the portal lane is revealed', () => {
|
||||
const s = emptyBoard(testRules({ laneModifiers: { pool: [], revealTurns: [3, 1, 1], params: { portal: { categoryIndex: 3, amount: 0 } } } }));
|
||||
assert.equal(laneFaction(s, 0), null);
|
||||
s.turn = 3;
|
||||
assert.equal(laneFaction(s, 0), 'Science');
|
||||
});
|
||||
|
||||
test('Wildcard: takes the lane faction on reveal, and then counts for Local', () => {
|
||||
const s = emptyBoard();
|
||||
const w = reveal(s, 0, 0, card({ category: 'Culture', keyword: 'wildcard' }));
|
||||
assert.equal(w.card.category, 'Science');
|
||||
const plain = reveal(s, 0, 1, card({ category: 'Culture', keyword: 'wildcard' }));
|
||||
assert.equal(plain.card.category, 'Culture');
|
||||
});
|
||||
|
||||
test('Obscure: hidden from the opponent only, and only while the match runs', () => {
|
||||
const s = emptyBoard();
|
||||
const o = place(s, 0, 1, card({ keyword: 'obscure' }));
|
||||
assert.equal(hiddenFrom(s, o, 1), true);
|
||||
assert.equal(hiddenFrom(s, o, 0), false);
|
||||
s.phase = 'over';
|
||||
assert.equal(hiddenFrom(s, o, 1), false);
|
||||
});
|
||||
|
||||
test('a keyword the ruleset does not enable has no effect', () => {
|
||||
const s = emptyBoard(testRules({ keywords: {} }));
|
||||
place(s, 0, 0, card({ pageId: 7, power: 5, keyword: 'edition' }));
|
||||
const b = place(s, 0, 1, card({ pageId: 7, power: 5, keyword: 'edition' }));
|
||||
assert.equal(cardPower(s, b), 5);
|
||||
const o = place(s, 0, 2, card({ keyword: 'obscure' }));
|
||||
assert.equal(hiddenFrom(s, o, 1), false);
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
createMatch, legalActions, applyAction, isOver, result, serialize, deserialize, starterDeck, PLAYERS,
|
||||
type Action, type GameCard, type MatchState,
|
||||
} from '../shared/game/index.ts';
|
||||
import { forAll, type Gen } from './game/property.ts';
|
||||
import { testRules } from './game/build.ts';
|
||||
|
||||
type State = MatchState;
|
||||
/** Every keyword enabled, so property runs exercise all effects. */
|
||||
const RULES = testRules({ laneModifiers: { pool: ['plain', 'portal', 'narrow'], revealTurns: [1, 2, 3],
|
||||
params: { portal: { categoryIndex: 3, amount: 1 }, narrow: { maxCost: 3 } } } });
|
||||
const KEYWORD_IDS = Object.keys(RULES.keywords);
|
||||
/** Generous bound: a match must finish well within this many actions. */
|
||||
const MAX_ACTIONS = 2000;
|
||||
|
||||
/** Starter deck with random keywords sprinkled in (shared pageIds so Edition can fire). */
|
||||
function randomDeck(g: Gen, tag: string): GameCard[] {
|
||||
return starterDeck(tag, RULES).map(c => ({ ...c, keyword: g.bool(0.6) ? g.pick(KEYWORD_IDS) : null,
|
||||
category: g.pick(['Space', 'Nature', 'People', 'Science', 'History', 'Culture'] as const) }));
|
||||
}
|
||||
|
||||
function randomMatch(g: Gen, seed: number) {
|
||||
return createMatch(RULES, [randomDeck(g, `a-${seed}`), randomDeck(g, `b-${seed}`)], `match-${seed}`);
|
||||
}
|
||||
|
||||
/** Plays random legal actions until the match ends; returns the final state and the action log. */
|
||||
function playOut(g: Gen, state: State, check?: (s: State) => void) {
|
||||
const log: unknown[] = [];
|
||||
let steps = 0;
|
||||
while (!isOver(state)) {
|
||||
const options = PLAYERS.flatMap(player => legalActions(state, player));
|
||||
assert.ok(options.length > 0, `no legal actions in a live match at step ${steps}`);
|
||||
const action = g.pick(options);
|
||||
log.push(action);
|
||||
state = applyAction(state, action);
|
||||
check?.(state);
|
||||
assert.ok(++steps <= MAX_ACTIONS, `match did not terminate within ${MAX_ACTIONS} actions`);
|
||||
}
|
||||
return { state, log };
|
||||
}
|
||||
|
||||
test('random legal play never crashes and always terminates with a result', () => {
|
||||
forAll(200, (g, seed) => {
|
||||
const { state } = playOut(g, randomMatch(g, seed));
|
||||
const outcome = result(state);
|
||||
assert.ok(outcome, 'finished match has a result');
|
||||
});
|
||||
});
|
||||
|
||||
test('same seed and same actions give the same result', () => {
|
||||
forAll(50, (g, seed) => {
|
||||
const decks: [GameCard[], GameCard[]] = [randomDeck(g, `a-${seed}`), randomDeck(g, `b-${seed}`)];
|
||||
const first = playOut(g, createMatch(RULES, decks, `m-${seed}`));
|
||||
// Replay the exact action log on a fresh match from the same seed.
|
||||
let replay = createMatch(RULES, decks, `m-${seed}`);
|
||||
for (const action of first.log) replay = applyAction(replay, action as Action);
|
||||
assert.deepEqual(replay, first.state);
|
||||
assert.deepEqual(result(replay), result(first.state));
|
||||
});
|
||||
});
|
||||
|
||||
test('createMatch is deterministic for a seed and varies across seeds', () => {
|
||||
const a = createMatch(RULES, [starterDeck('x'), starterDeck('y')], 'same');
|
||||
const b = createMatch(RULES, [starterDeck('x'), starterDeck('y')], 'same');
|
||||
assert.deepEqual(a, b);
|
||||
const distinct = new Set(Array.from({ length: 20 }, (_, i) =>
|
||||
JSON.stringify(createMatch(RULES, [starterDeck('x'), starterDeck('y')], `seed-${i}`))));
|
||||
assert.ok(distinct.size > 1, 'different seeds should shuffle differently');
|
||||
});
|
||||
|
||||
test('serialize/deserialize round-trips after every action', () => {
|
||||
forAll(30, (g, seed) => {
|
||||
playOut(g, randomMatch(g, seed), s => {
|
||||
assert.deepEqual(deserialize(serialize(s)), s);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('applyAction never mutates its input state', () => {
|
||||
forAll(30, (g, seed) => {
|
||||
let state = randomMatch(g, seed);
|
||||
let steps = 0;
|
||||
while (!isOver(state) && steps++ < MAX_ACTIONS) {
|
||||
const before = JSON.stringify(state);
|
||||
const action = g.pick(PLAYERS.flatMap(player => legalActions(state, player)));
|
||||
const next = applyAction(state, action);
|
||||
assert.equal(JSON.stringify(state), before);
|
||||
state = next;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test('a finished match offers no legal actions', () => {
|
||||
forAll(30, (g, seed) => {
|
||||
const { state } = playOut(g, randomMatch(g, seed));
|
||||
for (const player of PLAYERS) assert.deepEqual(legalActions(state, player), []);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
/** Hand-built match states for keyword unit tests. */
|
||||
import {
|
||||
DEFAULT_RULESET, Rng, createMatch, starterDeck, KEYWORDS, cardPower, lanePower,
|
||||
type CardInPlay, type Category, type EffectContext, type GameCard, type MatchState, type PlayerId, type Ruleset,
|
||||
} from '../../shared/game/index.ts';
|
||||
|
||||
export const ALL_KEYWORDS: Ruleset['keywords'] = {
|
||||
rally: { amount: 1 }, anchor: { amount: 2 }, edition: { amount: 2 }, translated: { amount: 1 },
|
||||
viral: { amount: 1 }, rising: { amount: 1, max: 3 }, nostalgic: { amount: 3 }, encyclopedic: { amount: 2 },
|
||||
obscure: {}, local: { amount: 2 }, wildcard: {},
|
||||
};
|
||||
|
||||
/** A ruleset with every keyword on and lane 0 a revealed Science portal (lanes 1–2 plain). */
|
||||
export function testRules(overrides: Partial<Ruleset> = {}): Ruleset {
|
||||
return {
|
||||
...DEFAULT_RULESET, keywords: ALL_KEYWORDS,
|
||||
laneModifiers: { pool: [], revealTurns: [1, 1, 1], params: { portal: { categoryIndex: 3, amount: 0 } } },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
/** An empty board on turn 1 with lane 0 set to the Science portal. */
|
||||
export function emptyBoard(rules = testRules()): MatchState {
|
||||
const state = createMatch(rules, [starterDeck('a', rules), starterDeck('b', rules)], 'keyword-test');
|
||||
for (const lane of state.lanes) lane.cards = [[], []];
|
||||
state.lanes[0].modifier = 'portal';
|
||||
state.lanes[1].modifier = 'plain';
|
||||
state.lanes[2].modifier = 'plain';
|
||||
return state;
|
||||
}
|
||||
|
||||
let serial = 0;
|
||||
export function card(overrides: Partial<GameCard> = {}): GameCard {
|
||||
serial++;
|
||||
return { id: `t${serial}`, name: `Card ${serial}`, pageId: 1000 + serial, category: 'Culture' as Category,
|
||||
cost: 1, power: 2, keyword: null, source: 'loaner', ...overrides };
|
||||
}
|
||||
|
||||
export function place(state: MatchState, owner: PlayerId, lane: number, c: GameCard): CardInPlay {
|
||||
const inPlay: CardInPlay = { card: c, owner, lane, turn: state.turn, bonus: 0 };
|
||||
state.lanes[lane].cards[owner].push(inPlay);
|
||||
return inPlay;
|
||||
}
|
||||
|
||||
export function ctxFor(state: MatchState, keyword: string, lane: number, rng = new Rng([1, 2, 3, 4])): EffectContext {
|
||||
return { state, rng, params: state.ruleset.keywords[keyword] ?? {}, lane, log: () => {}, power: c => cardPower(state, c) };
|
||||
}
|
||||
|
||||
/** Place a card and fire its onReveal, as the engine does at reveal. */
|
||||
export function reveal(state: MatchState, owner: PlayerId, lane: number, c: GameCard, rng?: Rng): CardInPlay {
|
||||
const inPlay = place(state, owner, lane, c);
|
||||
if (c.keyword) KEYWORDS[c.keyword]?.onReveal?.(ctxFor(state, c.keyword, lane, rng), inPlay);
|
||||
return inPlay;
|
||||
}
|
||||
|
||||
export function endOfTurn(state: MatchState, self: CardInPlay): void {
|
||||
const keyword = self.card.keyword;
|
||||
if (keyword) KEYWORDS[keyword]?.endOfTurn?.(ctxFor(state, keyword, self.lane), self);
|
||||
}
|
||||
|
||||
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