forked from WikiDeck/wikideck
Merge remote-tracking branch 'origin/night2/duel-cards/profiles' into local/preview
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* Writes docs/game/duel-card-sample.json (card-sample.json → DuelCard[]) and prints the
|
||||
* type / Portal / cost / keyword distributions. Offline. Usage:
|
||||
* node --experimental-strip-types scripts/duel-card-sample.ts [--check]
|
||||
* --check exits non-zero if the committed fixture is out of date.
|
||||
*/
|
||||
import { readFileSync, writeFileSync } from 'node:fs';
|
||||
import { deriveSample, type SampleCard } from '../shared/duel/sample.ts';
|
||||
import { DERIVE_VERSION } from '../shared/duel/derive.ts';
|
||||
|
||||
const root = new URL('../', import.meta.url);
|
||||
const sample = JSON.parse(readFileSync(new URL('docs/game/card-sample.json', root), 'utf8')) as { cards: SampleCard[] };
|
||||
const cards = deriveSample(sample.cards);
|
||||
const out = JSON.stringify({ source: 'docs/game/card-sample.json', deriveVersion: DERIVE_VERSION, count: cards.length, cards }, null, 1) + '\n';
|
||||
const path = new URL('docs/game/duel-card-sample.json', root);
|
||||
|
||||
const tally = (f: (c: typeof cards[number]) => string | number) => {
|
||||
const m = new Map<string | number, number>();
|
||||
for (const c of cards) m.set(f(c), (m.get(f(c)) ?? 0) + 1);
|
||||
return [...m].sort((a, b) => String(a[0]).localeCompare(String(b[0]), 'en', { numeric: true }))
|
||||
.map(([k, v]) => `${k} ${v} (${(100 * v / cards.length).toFixed(1)}%)`).join(', ');
|
||||
};
|
||||
console.log('type:', tally(c => c.type));
|
||||
console.log('typedBy:', tally(c => c.typedBy));
|
||||
console.log('portal:', tally(c => c.portal));
|
||||
console.log('cost:', tally(c => c.cost));
|
||||
console.log('subtype:', tally(c => `${c.type}/${c.subtype ?? '-'}`));
|
||||
console.log('keywords:', tally(c => c.keywords.join('+') || 'none'));
|
||||
|
||||
if (process.argv.includes('--check')) {
|
||||
if (readFileSync(path, 'utf8') !== out) { console.error('duel-card-sample.json is stale'); process.exit(1); }
|
||||
} else writeFileSync(path, out);
|
||||
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* Card type classification (BRIEF "Card types", data review §1, designer review §3.1).
|
||||
* Pure and deterministic: everything comes from the frozen CardProfile, nothing is fetched here.
|
||||
* Order: exact Q-id anchors on P31, then P279 anchors, then P31 label regex (rule order is the
|
||||
* priority), then P279 label regex, then non-stub categories, then the description, then Doctrine.
|
||||
* Owner: duel-cards.
|
||||
*/
|
||||
|
||||
export type CardType = 'Figure' | 'Location' | 'Event' | 'Institution' | 'Doctrine';
|
||||
export const CARD_TYPES: readonly CardType[] = ['Figure', 'Location', 'Event', 'Institution', 'Doctrine'];
|
||||
|
||||
export interface WikidataClass { id: string; label: string }
|
||||
|
||||
/**
|
||||
* The off-chain card profile, frozen the first time a host sees the card (data §3) and logged
|
||||
* with the match so replays and recaps stay deterministic. Only what derivation reads.
|
||||
*/
|
||||
export interface CardProfile {
|
||||
wikidataId: string | null;
|
||||
/** Wikipedia short description. */
|
||||
description: string | null;
|
||||
/** Non-hidden category titles without the "Category:" prefix. */
|
||||
categories: readonly string[];
|
||||
/** P31 (instance of). */
|
||||
instanceOf: readonly WikidataClass[];
|
||||
/** P279 (subclass of) of the item itself, or the P31 classes' superclasses up to 4 hops, nearest first. */
|
||||
subclassOf?: readonly WikidataClass[];
|
||||
/** P17 / P27 country Q-ids (or labels when only text is known). */
|
||||
countries?: readonly string[];
|
||||
/** Years from P569/P570/P571/P580/P585 (negative = BCE). */
|
||||
years?: readonly number[];
|
||||
/** P570 (date of death) present. */
|
||||
died?: boolean;
|
||||
/** ns0 outlinks as pageIds (data §4), for the Linked tier of Connected. */
|
||||
links?: readonly number[];
|
||||
/** Item Q-ids cited by the frozen claims (P17, P27, P131, P361, P106, …), for the Linked tier. */
|
||||
cites?: readonly string[];
|
||||
/** The live revision the profile was fetched from (data §3). */
|
||||
fetchedRevisionId?: number;
|
||||
}
|
||||
|
||||
export type ClassifySource = 'qid' | 'p279-qid' | 'p31' | 'p279' | 'category' | 'description' | 'fallback';
|
||||
export interface Classification { type: CardType; source: ClassifySource; matched: string }
|
||||
|
||||
/** Exact anchors (designer §3.1 step 1, data §1 production table). Checked against P31, then P279. */
|
||||
export const QID_ANCHORS: Readonly<Record<string, CardType>> = {
|
||||
Q5: 'Figure', Q95074: 'Figure', Q16521: 'Figure', Q23038290: 'Figure', Q8436: 'Figure', Q178885: 'Figure',
|
||||
Q486972: 'Location', Q515: 'Location', Q532: 'Location', Q3957: 'Location', Q4022: 'Location', Q23397: 'Location',
|
||||
Q8502: 'Location', Q23442: 'Location', Q41176: 'Location',
|
||||
Q1656682: 'Event', Q40231: 'Event', Q178561: 'Event', Q198: 'Event', Q8065: 'Event',
|
||||
Q43229: 'Institution', Q4830453: 'Institution', Q783794: 'Institution', Q7278: 'Institution', Q215380: 'Institution',
|
||||
Q17537576: 'Institution', Q11424: 'Institution', Q482994: 'Institution', Q7366: 'Institution', Q571: 'Institution',
|
||||
Q12136: 'Doctrine', Q151885: 'Doctrine', Q7187: 'Doctrine', Q9143: 'Doctrine', Q315: 'Doctrine',
|
||||
};
|
||||
|
||||
type Rules = readonly (readonly [CardType, RegExp])[];
|
||||
|
||||
/** P31/P279 label rules (data §1 types.py, with `^human$` and the governing-body fix). Order is load-bearing. */
|
||||
export const LABEL_RULES: Rules = [
|
||||
['Doctrine', /aspect of|aspect in|disease|clinical sign|list article|chemical entity/],
|
||||
['Event', new RegExp('election|protest|battle|war\\b|storm|nor.easter|cyclone|tornado|earthquake|disaster|event|match|final\\b|'
|
||||
+ 'season|championship|tournament|\\brace\\b|grand prix|scandal|annexation|treaty|incident|festival|referendum|'
|
||||
+ 'conference|ceremony|time period|delegation|spaceflight|siege|riot|massacre|flood|pandemic|epidemic|straw poll')],
|
||||
['Institution', /artificial satellite|space station|space telescope|spacecraft|space probe|diocese|ecclesiastical|council\b|governing body|stele/],
|
||||
['Location', new RegExp('planet|natural satellite|\\bstar\\b|galaxy|nebula|planetary system|astronomical object|rainforest|reef|'
|
||||
+ 'civili[sz]ation|empire|historical country|archaeological site|'
|
||||
+ 'human settlement|settlement|village|town|city|commune|municipal|parish|county|district|region|province|'
|
||||
+ 'township|hamlet|townland|census area|local government|community of|island|river|lake|mountain|plateau|'
|
||||
+ 'waterfall|valley|bay|peak|geographical feature|historic district|park|state park|square|road|highway|'
|
||||
+ 'building|castle|mosque|church|temple|cathedral|house|home|museum|station|bridge|monument|historic site|'
|
||||
+ 'military base|battery|refinery|shopping|stadium|arch|tower|fort|palace|columbari|freguesia|country\\b|sovereign state')],
|
||||
['Figure', /^human$|fictional character|stock character|person|deity|orisha|loa\b|taxon|species|genus|breed|^family$|organism/],
|
||||
['Institution', new RegExp('company|business|organi[sz]ation|association|society|party|agency|studio|band|musical group|team|club|'
|
||||
+ 'university|college|school|institute|manufacturer|newspaper|magazine|film|album|'
|
||||
+ 'song|single|musical work|composition|television|series|book|novel|video game|painting|award|position|'
|
||||
+ 'aircraft|ship|steamship|vehicle|automobile|tram|railway line|route|typeface|software|product|brand|artifact|artefact')],
|
||||
['Doctrine', new RegExp('concept|theory|theorem|mathematical|programming language|language|gene|protein|chemical|compound|'
|
||||
+ 'ideology|religion|discipline|field|cuisine|food|dish|drink|aspect|'
|
||||
+ 'particle|process|genre|form\\b|game\\b|branch of|class of|type of|tabular|structure')],
|
||||
];
|
||||
|
||||
/** Category fallback (stub categories are skipped). */
|
||||
export const CATEGORY_RULES: Rules = [
|
||||
['Figure', /\bbirth|\bdeaths\b|living people|people from|\bspecies\b|described in \d|\bgenera\b|deities|characters/],
|
||||
['Event', /\belections\b|protests|\bbattles\b|disasters|\braces\b|\bseasons\b|\bevents\b|scandals|annexations|competitions/],
|
||||
['Location', new RegExp('villages|communes|parishes|local government|populated places|geography|rivers|islands|buildings and structures|bridges|'
|
||||
+ 'stations|parks|districts|townships|cities and towns|historic places|freguesias')],
|
||||
['Institution', new RegExp('companies|organi[sz]ations|\\bfilms\\b|albums|songs|novels|newspapers|television series|musical groups|'
|
||||
+ 'aircraft|ships|typefaces|software|awards|teams|clubs|establishments')],
|
||||
['Doctrine', new RegExp('theory|structures$|algebra|terminology|cuisine|drinks|desserts|ecology|languages|diseases|conditions|'
|
||||
+ 'concepts|ranks|etymology|maps|atlases')],
|
||||
];
|
||||
|
||||
/** Description fallback (present on ~90% of the sample). */
|
||||
export const DESCRIPTION_RULES: Rules = [
|
||||
['Figure', /^(species|genus) of|\b(painter|politician|actor|actress|writer|player|singer|born|species|genus)\b/],
|
||||
['Event', /\b(race|election|battle|match|protest|storm|war|competition)\b/],
|
||||
['Location', /^(commune|village|town|municipality|river) in|\b(village|town|city|river|island|building|church|columbarium|station|park)\b/],
|
||||
['Institution', /\b(company|band|film|album|organi[sz]ation|team|aircraft|ship|newspaper)\b/],
|
||||
['Doctrine', /\b(concept|theory|structure|dessert|drink|dish|technique|class of)\b/],
|
||||
];
|
||||
|
||||
function firstRule(rules: Rules, texts: readonly string[]): [CardType, string] | null {
|
||||
for (const [type, rx] of rules) for (const text of texts) if (rx.test(text)) return [type, text];
|
||||
return null;
|
||||
}
|
||||
|
||||
export function classify(profile: Pick<CardProfile, 'instanceOf' | 'subclassOf' | 'categories' | 'description'>): Classification {
|
||||
const p31 = profile.instanceOf ?? [];
|
||||
const p279 = profile.subclassOf ?? [];
|
||||
for (const c of p31) { const t = QID_ANCHORS[c.id]; if (t) return { type: t, source: 'qid', matched: c.id }; }
|
||||
const p31Labels = p31.map(c => c.label.toLowerCase());
|
||||
let hit = firstRule(LABEL_RULES, p31Labels);
|
||||
if (hit) return { type: hit[0], source: 'p31', matched: hit[1] };
|
||||
for (const c of p279) { const t = QID_ANCHORS[c.id]; if (t) return { type: t, source: 'p279-qid', matched: c.id }; }
|
||||
hit = firstRule(LABEL_RULES, p279.map(c => c.label.toLowerCase()));
|
||||
if (hit) return { type: hit[0], source: 'p279', matched: hit[1] };
|
||||
const cats = (profile.categories ?? []).map(c => c.toLowerCase()).filter(c => !c.includes('stubs'));
|
||||
hit = firstRule(CATEGORY_RULES, cats);
|
||||
if (hit) return { type: hit[0], source: 'category', matched: hit[1] };
|
||||
const desc = (profile.description ?? '').toLowerCase();
|
||||
hit = firstRule(DESCRIPTION_RULES, desc ? [desc] : []);
|
||||
if (hit) return { type: hit[0], source: 'description', matched: hit[1] };
|
||||
return { type: 'Doctrine', source: 'fallback', matched: '' };
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
/**
|
||||
* Duel card derivation: an on-chain card plus its frozen off-chain profile becomes a DuelCard
|
||||
* (BRIEF "Stats", "Keywords", "Factions", "Connected"; data review §2 and §4; designer review §3).
|
||||
* Pure and deterministic: no fetches, no clocks, no randomness. Every number is data in DERIVE_RULES.
|
||||
* Owner: duel-cards.
|
||||
*/
|
||||
import type { Article } from '../protocol.ts';
|
||||
import type { MintStatsSnapshot } from '../enrichment.ts';
|
||||
import { rarity as rarityOf } from '../protocol.ts';
|
||||
import { CARD_SAMPLE_PERCENTILES } from '../game/card-data.ts';
|
||||
import { percentile } from '../game/derive.ts';
|
||||
import { classify, type CardProfile, type CardType, type ClassifySource } from './classify.ts';
|
||||
import { effectsFor, subtypeFor, type EffectSpec } from './effects.ts';
|
||||
import { rulesTextFor } from './text.ts';
|
||||
|
||||
export type { CardProfile, CardType } from './classify.ts';
|
||||
export type { EffectSpec } from './effects.ts';
|
||||
|
||||
export const DERIVE_VERSION = 'duel-derive-1';
|
||||
|
||||
export type Portal = 'Arts' | 'Earth' | 'History' | 'Science' | 'Society' | 'Neutral';
|
||||
export const PORTALS: readonly Portal[] = ['Arts', 'Earth', 'History', 'Science', 'Society', 'Neutral'];
|
||||
export type Keyword = 'Protected' | 'Featured' | 'Translated' | 'Legacy' | 'Stub' | 'Well-sourced' | 'Multilingual' | 'Local';
|
||||
export type Rarity = 'Common' | 'Rare' | 'Epic' | 'Legendary';
|
||||
|
||||
/** What derive() reads from the chain: a minted block's article and stats snapshot. */
|
||||
export interface CardOnChain {
|
||||
tokenId: string;
|
||||
article: Pick<Article, 'pageId' | 'title' | 'extract' | 'revisionId'>;
|
||||
statsSnapshot: Pick<MintStatsSnapshot, 'pageBytes' | 'languageCount' | 'stats'>;
|
||||
}
|
||||
|
||||
export interface ConnectKeys {
|
||||
/** P17/P27 values, or normalised country names from text when Wikidata has none. */
|
||||
countries: string[];
|
||||
centuries: number[];
|
||||
/** Outlink pageIds. */
|
||||
links: number[];
|
||||
/** P31 Q-ids, excluding human and taxon (the Kin tier). */
|
||||
p31: string[];
|
||||
/** This card's Wikidata item, and the item Q-ids its claims cite (Linked tier). */
|
||||
qid: string | null;
|
||||
cites: string[];
|
||||
}
|
||||
|
||||
export interface DuelCard {
|
||||
cardId: string;
|
||||
pageId: number;
|
||||
revisionId: number;
|
||||
title: string;
|
||||
/** Wikidata short description, for log first mentions (omitted when absent). */
|
||||
description?: string;
|
||||
type: CardType;
|
||||
/** Template family within the type, e.g. 'conflict', 'election', 'organisation', 'pathology'. */
|
||||
subtype: string | null;
|
||||
portal: Portal;
|
||||
cost: number;
|
||||
/** Figures: power/toughness. Locations: 0 / Garrison. Others: null. */
|
||||
power: number | null;
|
||||
toughness: number | null;
|
||||
/** Locations: Citations income ramp (the engine caps the total). */
|
||||
territory: number;
|
||||
keywords: Keyword[];
|
||||
effects: EffectSpec[];
|
||||
rulesText: string;
|
||||
flavor: string;
|
||||
connect: ConnectKeys;
|
||||
rarity: Rarity;
|
||||
deriveVersion: string;
|
||||
/** Why the card got its type (for audit and the card's info panel). */
|
||||
typedBy: ClassifySource;
|
||||
/** The numbers behind cost and body, for the info panel and the simulator. */
|
||||
basis: { pctAttention: number | null; pctDepth: number; pctReach: number; fame: number; magnitude: number };
|
||||
}
|
||||
|
||||
export interface DeriveRules {
|
||||
percentiles: Record<'attention' | 'depth' | 'reach', readonly number[]>;
|
||||
/** fame → cost 1..6: 1 + number of thresholds ≤ fame. */
|
||||
costThresholds: readonly number[];
|
||||
/** P+T budget by cost (index = cost). MTG vanilla curve. */
|
||||
bodyBudget: readonly number[];
|
||||
maxKeywords: number;
|
||||
/** Keywords that cost 1 point of body (from the larger stat, min 1 each). */
|
||||
taxedKeywords: readonly Keyword[];
|
||||
keywordOrder: readonly Keyword[];
|
||||
featuredPct: number;
|
||||
wellSourcedPct: number;
|
||||
/** Translated: translatedPct ≤ pct_reach < multilingualPct. Multilingual: pct_reach ≥ multilingualPct. */
|
||||
translatedPct: number;
|
||||
multilingualPct: number;
|
||||
stubBytes: number;
|
||||
/** Garrison toughness = 1 + floor(pct_depth / garrisonStep). */
|
||||
garrisonStep: number;
|
||||
}
|
||||
|
||||
export const DERIVE_RULES: DeriveRules = {
|
||||
percentiles: CARD_SAMPLE_PERCENTILES,
|
||||
costThresholds: [26, 39, 51, 63, 78],
|
||||
bodyBudget: [0, 3, 4, 6, 8, 10, 12],
|
||||
maxKeywords: 2,
|
||||
taxedKeywords: ['Protected', 'Featured', 'Legacy', 'Multilingual', 'Well-sourced'],
|
||||
keywordOrder: ['Protected', 'Featured', 'Legacy', 'Multilingual', 'Translated', 'Well-sourced', 'Stub', 'Local'],
|
||||
featuredPct: 85,
|
||||
wellSourcedPct: 85,
|
||||
translatedPct: 75,
|
||||
multilingualPct: 90,
|
||||
stubBytes: 3000,
|
||||
garrisonStep: 25,
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- Portals (designer §3.2)
|
||||
|
||||
export const PORTAL_RULES: Readonly<Record<Exclude<Portal, 'Neutral'>, RegExp>> = {
|
||||
Arts: /\b(actor|actress|singer|musician|rapper|band|album|song|single|film|novel|novelist|writer|poet|painter|artist|composer|television|tv series|music|theatre|theater|dance|dancer|video game|studio|animation|anime|fiction|character|literature|book|magazine|typeface|sculpt\w*|architect\w*|comedian|opera|orchestra)\b/g,
|
||||
Earth: /\b(species|genus|genera|taxon|plant|plants|animal|bird|birds|fish|insect|moth|beetle|grasshopper|orchid|river|rivers|lake|mountain|island|islands|village|villages|commune|communes|geography|forest|park|ecology|breed|weather|storm|nor.easter|cyclone|earthquake|climate|flora|fauna|populated places|municipality|municipalities|county|township|parish|reef|valley|locality|oblast|freguesia|hamlet)\b/g,
|
||||
History: /(\b\d+(st|nd|rd|th)-century\b|\b\d+ deaths\b|\b(sultan\w*|empire|castle|castles|medieval|ancient|dynasty|war|battle|battles|monarch|monarchs|king|queen|historic|archaeolog\w*|former|disestablish\w*|colonial|kingdom|museum|nobility|pharaoh)\b)/g,
|
||||
Science: /\b(mathemat\w*|algebra\w*|programming|software|gene|genes|protein|chemi\w*|disease|diseases|scientist|physic\w*|astronom\w*|biolog\w*|medic\w*|engineer\w*|computer|computing|theorem|planet|galaxy|spacecraft|satellite|aircraft|technology|clinical|structure|structures|category theory|syndrome|virus|bacteri\w*)\b/g,
|
||||
Society: /\b(politic\w*|politician|election|elections|party|government|law|court|sport|sports|football|cricket|basketball|baseball|olympic\w*|team|club|league|church|religio\w*|diocese|mosque|temple|school|university|company|companies|business|corporation|protest|protests|scandal|corruption|people from|living people|police|crime|cuisine|association|council)\b/g,
|
||||
};
|
||||
const PORTAL_TIE_ORDER: readonly Exclude<Portal, 'Neutral'>[] = ['History', 'Science', 'Arts', 'Society', 'Earth'];
|
||||
export const TYPE_DEFAULT_PORTAL: Readonly<Record<CardType, Exclude<Portal, 'Neutral'>>> = {
|
||||
Figure: 'Society', Location: 'Earth', Event: 'History', Institution: 'Arts', Doctrine: 'Science',
|
||||
};
|
||||
|
||||
/** Count keyword hits over description + categories + P31 labels; ties go to the type default; no hits → Neutral. */
|
||||
export function portalFor(profile: CardProfile, type: CardType): Portal {
|
||||
const text = [profile.description ?? '', ...profile.categories, ...profile.instanceOf.map(c => c.label)]
|
||||
.join(' | ').toLowerCase();
|
||||
let best = 0; let tied: Exclude<Portal, 'Neutral'>[] = [];
|
||||
for (const portal of PORTAL_TIE_ORDER) {
|
||||
const hits = text.match(PORTAL_RULES[portal])?.length ?? 0;
|
||||
if (hits > best) { best = hits; tied = [portal]; } else if (hits === best && hits > 0) tied.push(portal);
|
||||
}
|
||||
if (best === 0) return 'Neutral';
|
||||
const fallback = TYPE_DEFAULT_PORTAL[type];
|
||||
return tied.includes(fallback) ? fallback : tied[0];
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Connected keys (data §4)
|
||||
|
||||
const COUNTRY_WORDS: readonly (readonly [RegExp, string])[] = ([
|
||||
['United States|American', 'United States'], ['United Kingdom|British|England|English|Scotland|Scottish|Wales|Welsh', 'United Kingdom'],
|
||||
['France|French', 'France'], ['Germany|German', 'Germany'], ['Japan|Japanese', 'Japan'], ['China|Chinese', 'China'],
|
||||
['India|Indian', 'India'], ['Brazil|Brazilian', 'Brazil'], ['Poland|Polish', 'Poland'], ['Italy|Italian', 'Italy'],
|
||||
['Spain|Spanish', 'Spain'], ['Austria|Austrian', 'Austria'], ['Canada|Canadian', 'Canada'], ['Australia|Australian', 'Australia'],
|
||||
['Russia|Russian', 'Russia'], ['Mexico|Mexican', 'Mexico'], ['Iran|Iranian', 'Iran'], ['Pakistan|Pakistani', 'Pakistan'],
|
||||
['Bangladesh|Bangladeshi', 'Bangladesh'], ['Sweden|Swedish', 'Sweden'], ['Norway|Norwegian', 'Norway'], ['Estonia|Estonian', 'Estonia'],
|
||||
['Ukraine|Ukrainian', 'Ukraine'], ['Croatia|Croatian', 'Croatia'], ['Philippines|Filipino', 'Philippines'], ['Cuba|Cuban', 'Cuba'],
|
||||
['Israel|Israeli', 'Israel'], ['Portugal|Portuguese', 'Portugal'], ['Ireland|Irish', 'Ireland'], ['Kazakhstan|Kazakh', 'Kazakhstan'],
|
||||
['Malaysia|Malaysian', 'Malaysia'], ['Argentina|Argentine', 'Argentina'], ['Belgium|Belgian', 'Belgium'], ['Iceland|Icelandic', 'Iceland'],
|
||||
['Thailand|Thai', 'Thailand'], ['Singapore', 'Singapore'], ['Sri Lanka|Sri Lankan', 'Sri Lanka'], ['Slovenia|Slovene|Slovenian', 'Slovenia'],
|
||||
['Moldova', 'Moldova'], ['Cyprus|Cypriot', 'Cyprus'], ['North Macedonia|Macedonian', 'North Macedonia'], ['Mauritania', 'Mauritania'],
|
||||
['Congo', 'Congo'], ['New Zealand', 'New Zealand'], ['Korea|Korean', 'Korea'], ['Indonesia|Indonesian|Aceh', 'Indonesia'],
|
||||
['Czech', 'Czechia'], ['Netherlands|Dutch', 'Netherlands'], ['Greece|Greek', 'Greece'], ['Turkey|Turkish', 'Turkey'],
|
||||
['Egypt|Egyptian', 'Egypt'], ['Nigeria|Nigerian', 'Nigeria'], ['Kenya|Kenyan', 'Kenya'], ['Ghana|Gold Coast', 'Ghana'],
|
||||
['Finland|Finnish', 'Finland'], ['Denmark|Danish', 'Denmark'], ['Switzerland|Swiss', 'Switzerland'], ['Hungary|Hungarian', 'Hungary'],
|
||||
['Romania|Romanian', 'Romania'], ['Serbia|Serbian', 'Serbia'], ['Bulgaria|Bulgarian', 'Bulgaria'], ['Vietnam|Vietnamese', 'Vietnam'],
|
||||
['Sri Lanka', 'Sri Lanka'], ['Chile|Chilean', 'Chile'], ['Colombia|Colombian', 'Colombia'], ['Peru|Peruvian', 'Peru'],
|
||||
] as const).map(([rx, name]) => [new RegExp(`\\b(${rx})\\b`), name] as const);
|
||||
|
||||
const YEAR = /\b(1[0-9]{3}|20[0-2][0-9])\b/g;
|
||||
const CENTURY = /\b(\d{1,2})(st|nd|rd|th)[- ]century\b/gi;
|
||||
|
||||
export function connectKeysFor(title: string, profile: CardProfile): ConnectKeys {
|
||||
const text = [profile.description ?? '', ...profile.categories].join(' | ');
|
||||
const countries = profile.countries?.length
|
||||
? [...new Set(profile.countries)]
|
||||
: [...new Set(COUNTRY_WORDS.filter(([rx]) => rx.test(text)).map(([, name]) => name))];
|
||||
const centuries = new Set<number>();
|
||||
if (profile.years?.length) for (const y of profile.years) centuries.add(y > 0 ? Math.floor((y - 1) / 100) + 1 : -(Math.floor(-y / 100) + 1));
|
||||
else {
|
||||
for (const m of `${title} | ${text}`.matchAll(YEAR)) centuries.add(Math.floor((Number(m[1]) - 1) / 100) + 1);
|
||||
for (const m of text.matchAll(CENTURY)) centuries.add(Number(m[1]));
|
||||
}
|
||||
return {
|
||||
countries: countries.sort(),
|
||||
centuries: [...centuries].sort((a, b) => a - b),
|
||||
links: [...new Set(profile.links ?? [])].sort((a, b) => a - b),
|
||||
p31: [...new Set(profile.instanceOf.map(c => c.id).filter(id => id !== 'Q5' && id !== 'Q16521'))].sort(),
|
||||
qid: profile.wikidataId,
|
||||
cites: [...new Set(profile.cites ?? [])].sort(),
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Flavour
|
||||
|
||||
/** First sentence of the on-chain extract (BRIEF "Flavour text"); the description if there is no extract. */
|
||||
export function flavorFor(extract: string, description: string | null): string {
|
||||
const text = extract.replace(/\s+/g, ' ').trim();
|
||||
if (!text) return (description ?? '').trim();
|
||||
// A sentence ends at . ! ? followed by a space and an uppercase letter or a quote, skipping
|
||||
// common abbreviations and initials ("U.S.", "St.", "J. R. R.") so names are not cut.
|
||||
const re = /[.!?](?=\s+["'“(\[]?[A-Z0-9])/g;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(text))) {
|
||||
const before = text.slice(0, m.index);
|
||||
const word = before.split(/\s/).pop() ?? '';
|
||||
if (/^([A-Z]|[A-Z][a-z]{0,2}|[A-Z]\.[A-Z]|U\.S|U\.K|c|ca|St|Dr|Mr|Mrs|Ms|Jr|Sr|No|vs|etc|Inc|Ltd|Co|Mt|Ft|Gen|Col|Lt|Sgt|Rev|Prof)$/.test(word.replace(/\.$/, ''))) continue;
|
||||
return text.slice(0, m.index + 1);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Stats and keywords (data §2, designer §3.3–3.4)
|
||||
|
||||
export interface Percentiles { attention: number | null; depth: number; reach: number }
|
||||
|
||||
export function percentilesFor(stats: MintStatsSnapshot['stats'], rules: DeriveRules = DERIVE_RULES): Percentiles {
|
||||
return {
|
||||
attention: stats.attention === null ? null : percentile(stats.attention, rules.percentiles.attention),
|
||||
depth: percentile(stats.depth, rules.percentiles.depth),
|
||||
reach: percentile(stats.reach, rules.percentiles.reach),
|
||||
};
|
||||
}
|
||||
|
||||
export function fameOf(p: Percentiles): number {
|
||||
const values = [p.attention, p.depth, p.reach].filter((v): v is number => v !== null);
|
||||
return Math.floor(values.reduce((a, b) => a + b, 0) / values.length + 0.5);
|
||||
}
|
||||
|
||||
export function costForFame(fame: number, rules: DeriveRules = DERIVE_RULES): number {
|
||||
return 1 + rules.costThresholds.filter(t => t <= fame).length;
|
||||
}
|
||||
|
||||
/** Every keyword the data triggers, in priority order (before the cap). */
|
||||
export function triggeredKeywords(chain: CardOnChain, profile: CardProfile, p: Percentiles, rules: DeriveRules = DERIVE_RULES): Keyword[] {
|
||||
const cats = profile.categories;
|
||||
const on: Record<Keyword, boolean> = {
|
||||
Protected: cats.includes('Living people'),
|
||||
Featured: p.attention !== null && p.attention >= rules.featuredPct,
|
||||
Legacy: profile.died === true || cats.some(c => /^\d+s? (BC )?deaths$/.test(c)),
|
||||
'Well-sourced': p.depth >= rules.wellSourcedPct,
|
||||
// Two bands of the same reach axis: a card never has both (DUEL_DESIGN §4).
|
||||
Multilingual: p.reach >= rules.multilingualPct,
|
||||
Translated: p.reach >= rules.translatedPct && p.reach < rules.multilingualPct,
|
||||
Stub: cats.some(c => c.toLowerCase().includes('stubs')) || chain.statsSnapshot.pageBytes < rules.stubBytes,
|
||||
Local: chain.statsSnapshot.stats.reach === 0,
|
||||
};
|
||||
return rules.keywordOrder.filter(k => on[k]);
|
||||
}
|
||||
|
||||
export interface Body { power: number; toughness: number; keywords: Keyword[] }
|
||||
|
||||
/**
|
||||
* Figure body (DUEL_DESIGN §3): take the first ≤2 triggered keywords in priority order, subtract 1
|
||||
* from the cost's P+T budget per taxed keyword, then split by attention vs depth, each stat ≥ 1.
|
||||
* A taxed keyword that would leave less than 2 points is skipped for the next one.
|
||||
*/
|
||||
export function figureBody(cost: number, p: Percentiles, keywords: readonly Keyword[], rules: DeriveRules = DERIVE_RULES): Body {
|
||||
let budget = rules.bodyBudget[cost];
|
||||
if (budget === undefined) throw new RangeError(`bodyBudget has no entry for cost ${cost}`);
|
||||
const kept: Keyword[] = [];
|
||||
for (const k of keywords) {
|
||||
if (kept.length >= rules.maxKeywords) break;
|
||||
if (rules.taxedKeywords.includes(k)) {
|
||||
if (budget <= 2) continue;
|
||||
budget--;
|
||||
}
|
||||
kept.push(k);
|
||||
}
|
||||
const a = p.attention ?? 50;
|
||||
const power = Math.min(budget - 1, Math.max(1, Math.round(budget * a / Math.max(1, a + p.depth))));
|
||||
return { power, toughness: budget - power, keywords: kept };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- derive
|
||||
|
||||
export function derive(chain: CardOnChain, profile: CardProfile, rules: DeriveRules = DERIVE_RULES): DuelCard {
|
||||
const { type, source } = classify(profile);
|
||||
const p = percentilesFor(chain.statsSnapshot.stats, rules);
|
||||
const fame = fameOf(p);
|
||||
const baseCost = costForFame(fame, rules);
|
||||
const magnitude = Math.ceil(baseCost / 2);
|
||||
const portal = portalFor(profile, type);
|
||||
const subtype = subtypeFor(type, profile);
|
||||
let cost = baseCost, power: number | null = null, toughness: number | null = null, territory = 0;
|
||||
let keywords: Keyword[] = [];
|
||||
if (type === 'Figure') {
|
||||
const body = figureBody(baseCost, p, triggeredKeywords(chain, profile, p, rules), rules);
|
||||
({ power, toughness, keywords } = body);
|
||||
} else if (type === 'Location') {
|
||||
cost = magnitude;
|
||||
power = 0;
|
||||
toughness = 1 + Math.floor(p.depth / rules.garrisonStep);
|
||||
territory = 1;
|
||||
}
|
||||
const effects = effectsFor(type, subtype, baseCost);
|
||||
const card: DuelCard = {
|
||||
cardId: chain.tokenId, pageId: chain.article.pageId, revisionId: chain.article.revisionId, title: chain.article.title,
|
||||
type, subtype, portal, cost, power, toughness, territory, keywords, effects, rulesText: '',
|
||||
flavor: flavorFor(chain.article.extract, profile.description),
|
||||
connect: connectKeysFor(chain.article.title, profile),
|
||||
rarity: rarityOf(chain.tokenId), deriveVersion: DERIVE_VERSION, typedBy: source,
|
||||
basis: { pctAttention: p.attention, pctDepth: p.depth, pctReach: p.reach, fame, magnitude },
|
||||
};
|
||||
if (profile.description) card.description = profile.description;
|
||||
card.rulesText = rulesTextFor(card);
|
||||
return card;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Connected (data §4)
|
||||
|
||||
/** DUEL_DESIGN §6: Contemporary counts only between different types. */
|
||||
export type ConnectedTier = 'Linked' | 'Compatriot' | 'Contemporary' | 'Kin';
|
||||
|
||||
/** The strongest Connected tier between two cards, or null. Linked gives +2/+2, the others +1/+1 (BRIEF). */
|
||||
export function connectedTier(a: DuelCard, b: DuelCard,
|
||||
tiers: readonly ConnectedTier[] = ['Linked', 'Compatriot', 'Contemporary', 'Kin']): ConnectedTier | null {
|
||||
if (a.cardId === b.cardId) return null;
|
||||
const meets = (x: readonly (string | number)[], y: readonly (string | number)[]) => x.some(v => y.includes(v));
|
||||
for (const tier of tiers) {
|
||||
if (tier === 'Linked' && (a.connect.links.includes(b.pageId) || b.connect.links.includes(a.pageId)
|
||||
|| (b.connect.qid !== null && a.connect.cites.includes(b.connect.qid))
|
||||
|| (a.connect.qid !== null && b.connect.cites.includes(a.connect.qid)))) return tier;
|
||||
if (tier === 'Compatriot' && meets(a.connect.countries, b.connect.countries)) return tier;
|
||||
if (tier === 'Contemporary' && a.type !== b.type && meets(a.connect.centuries, b.connect.centuries)) return tier;
|
||||
if (tier === 'Kin' && meets(a.connect.p31, b.connect.p31)) return tier;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* Effect templates by type and subtype (designer review §3.5; DUEL_DESIGN.md wins where they differ).
|
||||
* Effects are plain data for duel-core's interpreter. k = ceil(cost / 2), 1–3, from the derived (fame) cost.
|
||||
* Owner: duel-cards.
|
||||
*/
|
||||
import type { CardProfile, CardType } from './classify.ts';
|
||||
import type { Keyword, Portal } from './derive.ts';
|
||||
|
||||
export type EffectTrigger = 'onPlay' | 'onEnter' | 'startOfTurn' | 'onDestroyed' | 'static' | 'onCombatDamageToPlayer';
|
||||
export type EffectOp = 'damage' | 'damageEach' | 'createToken' | 'pump' | 'fight' | 'draw' | 'attach' | 'gainLife';
|
||||
export type EffectTarget = 'figure' | 'figureOrLocation' | 'ownFigure' | 'opponentFigure' | 'each' | 'self' | 'attached' | 'ownFigures';
|
||||
|
||||
export interface EffectSpec {
|
||||
trigger: EffectTrigger;
|
||||
op: EffectOp;
|
||||
target?: EffectTarget;
|
||||
amount?: number;
|
||||
power?: number;
|
||||
toughness?: number;
|
||||
duration?: 'turn' | 'permanent';
|
||||
token?: { name: string; power: number; toughness: number; portal: Portal };
|
||||
/** maxTokens: createToken only if the controller controls fewer than this many tokens (duel-core types.ts). */
|
||||
condition?: { maxPower?: number; samePortal?: boolean; connected?: boolean; maxTokens?: number };
|
||||
grant?: Keyword[];
|
||||
/** Template id (DUEL_DESIGN §5, T3–T12) for rules text and log wording. */
|
||||
template?: string;
|
||||
}
|
||||
|
||||
type Subtypes = readonly (readonly [string, RegExp])[];
|
||||
|
||||
/**
|
||||
* Subtype rules per type (DUEL_DESIGN §5), run over P31 labels, P279 labels, the description, then
|
||||
* categories. First match in list order wins; no match is the type's default template.
|
||||
* Additions beyond §5 (marked +): bands/associations count as organisations; 'flood' etc. as listed.
|
||||
*/
|
||||
export const SUBTYPE_RULES: Readonly<Record<CardType, Subtypes>> = {
|
||||
Event: [
|
||||
['conflict', /battle|war\b|siege|annexation|protest|riot|uprising|massacre|coup/],
|
||||
['disaster', /storm|nor.easter|cyclone|hurricane|earthquake|flood|tornado|wildfire|eruption|famine|epidemic/],
|
||||
['election', /election|referendum|straw poll/],
|
||||
['sport', /match|final\b|season|tournament|championship|grand prix|\brace\b/],
|
||||
],
|
||||
Institution: [
|
||||
['organisation', /company|organi[sz]ation|party|agency|studio|military|university|diocese|council|band\b|musical group|association|business|school|college|institute|manufacturer/],
|
||||
['work', /film|album|song|\bbook|novel|series|video game|painting|software|typeface|newspaper|magazine/],
|
||||
],
|
||||
Doctrine: [
|
||||
['pathology', /disease|clinical sign|pathogen|syndrome|disorder|toxin|poison/],
|
||||
['language', /language|software|programming/],
|
||||
['mathematics', /mathemat|theorem|algebra|geometr|polytope|polyhedron|equation|number theory|structure/],
|
||||
['ideology', /ideology|religion|belief|doctrine|philosophy|theology/],
|
||||
],
|
||||
Figure: [],
|
||||
Location: [],
|
||||
};
|
||||
|
||||
/** Default template names, for the info panel (null subtype). */
|
||||
export const DEFAULT_SUBTYPE: Readonly<Record<CardType, string | null>> = {
|
||||
Figure: null, Location: null, Event: 'other', Institution: 'other', Doctrine: 'adopt',
|
||||
};
|
||||
|
||||
export function subtypeFor(type: CardType, profile: Pick<CardProfile, 'instanceOf' | 'subclassOf' | 'description' | 'categories'>): string | null {
|
||||
const groups = [
|
||||
[...profile.instanceOf.map(c => c.label), ...(profile.subclassOf ?? []).map(c => c.label)],
|
||||
[profile.description ?? ''],
|
||||
[...(profile.categories ?? []).filter(c => !/stubs$/i.test(c))],
|
||||
].map(g => g.map(t => t.toLowerCase()).filter(Boolean));
|
||||
for (const texts of groups) for (const [name, rx] of SUBTYPE_RULES[type]) if (texts.some(t => rx.test(t))) return name;
|
||||
return DEFAULT_SUBTYPE[type];
|
||||
}
|
||||
|
||||
/** The effect list for a card (T1–T12). Figures and Locations have none beyond keywords and stats. */
|
||||
/** DUEL_DESIGN §5 template id by type and subtype. */
|
||||
export function templateFor(type: CardType, subtype: string | null): string | null {
|
||||
switch (type) {
|
||||
case 'Figure': return 'T1';
|
||||
case 'Location': return 'T2';
|
||||
case 'Event': return ({ conflict: 'T3', disaster: 'T4', election: 'T5', sport: 'T6' } as Record<string, string>)[subtype ?? ''] ?? 'T7';
|
||||
case 'Institution': return subtype === 'organisation' ? 'T8' : subtype === 'work' ? 'T9' : 'T10';
|
||||
case 'Doctrine': return subtype === 'pathology' ? 'T12' : 'T11';
|
||||
}
|
||||
}
|
||||
|
||||
export function effectsFor(type: CardType, subtype: string | null, cost: number): EffectSpec[] {
|
||||
const template = templateFor(type, subtype);
|
||||
return baseEffects(type, subtype, cost).map(e => (template ? { ...e, template } : e));
|
||||
}
|
||||
|
||||
function baseEffects(type: CardType, subtype: string | null, cost: number): EffectSpec[] {
|
||||
const k = Math.ceil(cost / 2);
|
||||
switch (type) {
|
||||
case 'Event':
|
||||
switch (subtype) {
|
||||
case 'conflict': return [{ trigger: 'onPlay', op: 'damage', target: 'figureOrLocation', amount: k + 1 }];
|
||||
case 'disaster': return [{ trigger: 'onPlay', op: 'damageEach', target: 'each', amount: Math.max(1, k - 1) }];
|
||||
case 'election': return [{ trigger: 'onPlay', op: 'createToken', amount: k,
|
||||
token: { name: 'Elected Member', power: 1, toughness: 1, portal: 'Society' } }];
|
||||
case 'sport': return [
|
||||
{ trigger: 'onPlay', op: 'pump', target: 'ownFigure', power: k, toughness: 0, duration: 'turn' },
|
||||
{ trigger: 'onPlay', op: 'fight', target: 'opponentFigure' },
|
||||
];
|
||||
default: return [{ trigger: 'onPlay', op: 'draw', amount: k }];
|
||||
}
|
||||
case 'Institution':
|
||||
switch (subtype) {
|
||||
case 'organisation': {
|
||||
const token = { name: 'Staff Member', power: 1, toughness: 1, portal: 'Neutral' as const };
|
||||
return cost >= 4
|
||||
? [{ trigger: 'startOfTurn', op: 'createToken', amount: 1, token, condition: { maxTokens: 3 } }]
|
||||
: [{ trigger: 'onEnter', op: 'createToken', amount: 1, token }];
|
||||
}
|
||||
case 'work': return [
|
||||
{ trigger: 'onEnter', op: 'draw', amount: 1 },
|
||||
{ trigger: 'static', op: 'pump', target: 'ownFigures', power: 1, toughness: 1, condition: { connected: true } },
|
||||
];
|
||||
default: return [{ trigger: 'static', op: 'pump', target: 'ownFigures', power: 1, toughness: 0, condition: { maxPower: 2 } }];
|
||||
}
|
||||
case 'Doctrine': {
|
||||
if (subtype === 'pathology') return [{ trigger: 'onPlay', op: 'attach', target: 'figure', power: -k, toughness: -k, duration: 'permanent' }];
|
||||
const attach: EffectSpec = { trigger: 'onPlay', op: 'attach', target: 'ownFigure', power: k, toughness: k, duration: 'permanent' };
|
||||
if (subtype === 'mathematics') return [{ ...attach, grant: ['Well-sourced'] }];
|
||||
if (subtype === 'language') return [attach, { trigger: 'onCombatDamageToPlayer', op: 'draw', target: 'attached', amount: 1 }];
|
||||
if (subtype === 'ideology') return [attach, { trigger: 'static', op: 'pump', target: 'ownFigures', power: 1, toughness: 0, condition: { samePortal: true } }];
|
||||
return [attach];
|
||||
}
|
||||
default: return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* Building the frozen CardProfile (data review §3) from data the host already has or fetches once
|
||||
* through the polite Wikimedia client. Pure: this file never fetches. The host:
|
||||
* 1. takes the cached PageEnrichment (description, wikidataId, categories),
|
||||
* 2. fetches the item once with wikidataEntityParams([qid, …]) (≤ 50 ids per request),
|
||||
* 3. fetches the labels of the P31/P279 classes it doesn't know with wikidataLabelParams(ids),
|
||||
* 4. optionally adds outlinks (prop=links, ns0) as pageIds,
|
||||
* 5. calls profileFromSources() and stores the result per tokenId forever.
|
||||
* Owner: duel-cards.
|
||||
*/
|
||||
import type { PageEnrichment } from '../enrichment.ts';
|
||||
import type { CardProfile, WikidataClass } from './classify.ts';
|
||||
|
||||
export const PROFILE_PROPERTIES = {
|
||||
instanceOf: 'P31', subclassOf: 'P279', country: 'P17', citizenship: 'P27',
|
||||
birth: 'P569', death: 'P570', inception: 'P571', start: 'P580', pointInTime: 'P585',
|
||||
} as const;
|
||||
|
||||
/** Properties whose item values count as "cited" for the Linked tier (DUEL_DESIGN §6). */
|
||||
export const CITE_PROPERTIES = ['P17', 'P27', 'P131', 'P361', 'P527', 'P463', 'P102', 'P108', 'P69', 'P19', 'P20', 'P710', 'P1344', 'P276'] as const;
|
||||
|
||||
/** Action API parameters for wbgetentities (claims only, so the payload stays small). */
|
||||
export function wikidataEntityParams(qids: readonly string[]): Record<string, string> {
|
||||
if (qids.length < 1 || qids.length > 50) throw new RangeError('wbgetentities takes 1 to 50 ids');
|
||||
return { action: 'wbgetentities', ids: [...qids].sort().join('|'), props: 'claims', format: 'json', formatversion: '2' };
|
||||
}
|
||||
|
||||
/** Action API parameters for class labels (English). */
|
||||
export function wikidataLabelParams(qids: readonly string[]): Record<string, string> {
|
||||
if (qids.length < 1 || qids.length > 50) throw new RangeError('wbgetentities takes 1 to 50 ids');
|
||||
return { action: 'wbgetentities', ids: [...qids].sort().join('|'), props: 'labels', languages: 'en', format: 'json', formatversion: '2' };
|
||||
}
|
||||
|
||||
/** The slice of a wbgetentities entity this module reads. Unknown shapes are ignored, never thrown on. */
|
||||
export interface WikidataEntity {
|
||||
id?: string;
|
||||
claims?: Record<string, readonly {
|
||||
rank?: string;
|
||||
mainsnak?: { snaktype?: string; datavalue?: { type?: string; value?: unknown } };
|
||||
}[]>;
|
||||
}
|
||||
|
||||
function claimValues(entity: WikidataEntity | null | undefined, property: string): unknown[] {
|
||||
const statements = entity?.claims?.[property];
|
||||
if (!Array.isArray(statements)) return [];
|
||||
return statements
|
||||
.filter(s => s?.rank !== 'deprecated' && s?.mainsnak?.snaktype === 'value')
|
||||
.map(s => s.mainsnak?.datavalue?.value)
|
||||
.filter(v => v !== undefined);
|
||||
}
|
||||
|
||||
function itemIds(entity: WikidataEntity | null | undefined, property: string): string[] {
|
||||
return claimValues(entity, property)
|
||||
.map(v => (v && typeof v === 'object' && 'id' in v && typeof (v as { id: unknown }).id === 'string') ? (v as { id: string }).id : null)
|
||||
.filter((id): id is string => id !== null && /^Q\d+$/.test(id));
|
||||
}
|
||||
|
||||
/** Years from Wikidata time values ("+1909-04-29T00:00:00Z", "-0044-03-15T…"). */
|
||||
function years(entity: WikidataEntity | null | undefined, property: string): number[] {
|
||||
return claimValues(entity, property)
|
||||
.map(v => (v && typeof v === 'object' && 'time' in v) ? String((v as { time: unknown }).time) : '')
|
||||
.map(t => /^([+-])0*(\d{1,6})-/.exec(t))
|
||||
.filter((m): m is RegExpExecArray => m !== null)
|
||||
.map(m => (m[1] === '-' ? -1 : 1) * Number(m[2]))
|
||||
.filter(y => y !== 0);
|
||||
}
|
||||
|
||||
/** Q-ids whose labels the host must look up to classify this entity. */
|
||||
export function classIdsOf(entity: WikidataEntity | null | undefined): string[] {
|
||||
return [...new Set([...itemIds(entity, 'P31'), ...itemIds(entity, 'P279')])].sort();
|
||||
}
|
||||
|
||||
export interface ProfileSources {
|
||||
enrichment: Pick<PageEnrichment, 'description' | 'wikidataId' | 'categories' | 'revisionId'>;
|
||||
/** The card's own wbgetentities entity, or null when it has no item or the fetch is pending. */
|
||||
entity?: WikidataEntity | null;
|
||||
/** English labels for class Q-ids; missing labels are kept as the bare Q-id. */
|
||||
labels?: Readonly<Record<string, string>>;
|
||||
/** Superclass chain for the P31 classes (P279, up to 4 hops), nearest first, if the host resolved it. */
|
||||
superclasses?: readonly WikidataClass[];
|
||||
/** ns0 outlinks resolved to pageIds. */
|
||||
links?: readonly number[];
|
||||
}
|
||||
|
||||
export function profileFromSources(src: ProfileSources): CardProfile {
|
||||
const { enrichment, entity, labels = {} } = src;
|
||||
const label = (id: string): WikidataClass => ({ id, label: labels[id] ?? id });
|
||||
const countries = [...new Set([...itemIds(entity, 'P17'), ...itemIds(entity, 'P27')])].sort();
|
||||
const yrs = [...new Set(['P569', 'P570', 'P571', 'P580', 'P585'].flatMap(p => years(entity, p)))].sort((a, b) => a - b);
|
||||
const cites = [...new Set(CITE_PROPERTIES.flatMap(p => itemIds(entity, p)))].sort();
|
||||
const subclassOf = [...itemIds(entity, 'P279').map(label), ...(src.superclasses ?? [])];
|
||||
const profile: CardProfile = {
|
||||
wikidataId: enrichment.wikidataId,
|
||||
description: enrichment.description,
|
||||
categories: [...enrichment.categories],
|
||||
instanceOf: itemIds(entity, 'P31').map(label),
|
||||
fetchedRevisionId: enrichment.revisionId,
|
||||
};
|
||||
if (subclassOf.length) profile.subclassOf = subclassOf;
|
||||
if (countries.length) profile.countries = countries;
|
||||
if (yrs.length) profile.years = yrs;
|
||||
if (claimValues(entity, 'P570').length) profile.died = true;
|
||||
if (cites.length) profile.cites = cites;
|
||||
if (src.links?.length) profile.links = [...new Set(src.links)].sort((a, b) => a - b);
|
||||
return profile;
|
||||
}
|
||||
|
||||
/** A canonical JSON string of a profile, for storing, hashing and logging in the match record. */
|
||||
export function canonicalProfile(profile: CardProfile): string {
|
||||
const sortKeys = (v: unknown): unknown => Array.isArray(v) ? v.map(sortKeys)
|
||||
: v && typeof v === 'object' ? Object.fromEntries(Object.keys(v).sort().map(k => [k, sortKeys((v as Record<string, unknown>)[k])]))
|
||||
: v;
|
||||
return JSON.stringify(sortKeys(profile));
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Fixture: docs/game/card-sample.json (236 real random cards) → DuelCard[], for sim-balance, the UI
|
||||
* and tests. The sample has no on-chain extract, so flavour falls back to the description, and its
|
||||
* tokenIds are synthetic (the pageId as 64 hex digits). Owner: duel-cards.
|
||||
*/
|
||||
import type { CardProfile } from './classify.ts';
|
||||
import { derive, DERIVE_RULES, type CardOnChain, type DeriveRules, type DuelCard } from './derive.ts';
|
||||
|
||||
/** The fields of a card-sample.json card that derivation reads. */
|
||||
export interface SampleCard {
|
||||
pageId: number; title: string; description: string | null; wikidataId: string | null; revisionId: number;
|
||||
pageBytes: number; languageCount: number; categories: string[];
|
||||
stats: { attention: number | null; depth: number; reach: number };
|
||||
instanceOf: { id: string; label: string }[];
|
||||
extract?: string;
|
||||
}
|
||||
|
||||
export function sampleTokenId(pageId: number): string {
|
||||
return pageId.toString(16).padStart(64, '0');
|
||||
}
|
||||
|
||||
export function sampleInputs(card: SampleCard): { chain: CardOnChain; profile: CardProfile } {
|
||||
return {
|
||||
chain: {
|
||||
tokenId: sampleTokenId(card.pageId),
|
||||
article: { pageId: card.pageId, title: card.title, extract: card.extract ?? '', revisionId: card.revisionId },
|
||||
statsSnapshot: { pageBytes: card.pageBytes, languageCount: card.languageCount, stats: card.stats },
|
||||
},
|
||||
profile: {
|
||||
wikidataId: card.wikidataId, description: card.description, categories: card.categories,
|
||||
instanceOf: card.instanceOf, fetchedRevisionId: card.revisionId,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function deriveSample(cards: readonly SampleCard[], rules: DeriveRules = DERIVE_RULES): DuelCard[] {
|
||||
return cards.map(card => { const { chain, profile } = sampleInputs(card); return derive(chain, profile, rules); });
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
/**
|
||||
* Rules text in MTG's terse register (designer review §3.4–3.5, critic S7, BRIEF decision 5).
|
||||
* Deterministic templates filled only with the card's own derived numbers and keyword names.
|
||||
* No prose about the subject, no invented facts: flavour text is the article's own first sentence.
|
||||
* Owner: duel-cards.
|
||||
*/
|
||||
import type { DuelCard, Keyword } from './derive.ts';
|
||||
import type { EffectSpec } from './effects.ts';
|
||||
|
||||
/** Reminder text per keyword (DUEL_DESIGN §4). */
|
||||
export const KEYWORD_REMINDER: Readonly<Record<Keyword, string>> = {
|
||||
Protected: 'Can\'t be the target of Events or Doctrines an opponent controls.',
|
||||
Featured: 'Can\'t be blocked except by Featured, Translated or Multilingual Figures.',
|
||||
Legacy: 'When this is destroyed, draw a card.',
|
||||
Multilingual: 'Can block Featured Figures. Can\'t be blocked by Local Figures.',
|
||||
Translated: 'Can block Featured Figures.',
|
||||
'Well-sourced': 'Prevent the first 1 damage that would be dealt to this each turn.',
|
||||
Stub: 'At the start of your turn, put a +1/+1 counter on this, to a maximum of 2.',
|
||||
Local: 'Gets +1/+1 while you control a Compatriot Location.',
|
||||
};
|
||||
|
||||
const NUMBER_WORDS = ['zero', 'one', 'two', 'three', 'four', 'five', 'six'];
|
||||
const word = (n: number) => NUMBER_WORDS[n] ?? String(n);
|
||||
const signed = (n: number) => (n >= 0 ? `+${n}` : `−${-n}`);
|
||||
const pt = (p = 0, t = 0) => `${signed(p)}/${signed(t)}`;
|
||||
|
||||
const TARGET_NOUN: Readonly<Record<string, string>> = {
|
||||
figure: 'target Figure', figureOrLocation: 'target Figure or Location', ownFigure: 'target Figure you control',
|
||||
opponentFigure: 'target Figure you don\'t control', each: 'each Figure and each Location', self: 'this',
|
||||
attached: 'enchanted Figure', ownFigures: 'Figures you control',
|
||||
};
|
||||
|
||||
function keywordsAsText(keywords: readonly Keyword[]): string {
|
||||
return keywords.join(', ');
|
||||
}
|
||||
|
||||
function staticText(e: EffectSpec): string {
|
||||
const c = e.condition ?? {};
|
||||
let who = 'Figures you control';
|
||||
if (c.maxPower !== undefined) who = `Figures you control with power ${c.maxPower} or less`;
|
||||
if (c.connected) who = 'Figures you control that are Connected to this';
|
||||
if (c.samePortal) who = 'Other Figures you control of its Portal';
|
||||
if (e.grant?.length && !e.power && !e.toughness) {
|
||||
return `${who} have ${keywordsAsText(e.grant)}.`;
|
||||
}
|
||||
return `${who} get ${pt(e.power, e.toughness)}.`;
|
||||
}
|
||||
|
||||
function tokenText(e: EffectSpec): string {
|
||||
const t = e.token!;
|
||||
const n = e.amount ?? 1;
|
||||
const portal = t.portal === 'Neutral' ? '' : `${t.portal} `;
|
||||
const body = `${t.power}/${t.toughness} ${portal}Figure token${n === 1 ? '' : 's'} named ${t.name}`;
|
||||
return n === 1 ? `create a ${body}` : `create ${word(n)} ${body}`;
|
||||
}
|
||||
|
||||
function actionText(e: EffectSpec): string {
|
||||
switch (e.op) {
|
||||
case 'damage': return `deal ${e.amount} damage to ${TARGET_NOUN[e.target ?? 'figure']}`;
|
||||
case 'damageEach': return `deal ${e.amount} damage to each Figure and each Location`;
|
||||
case 'createToken': return tokenText(e);
|
||||
case 'pump': return `${TARGET_NOUN[e.target ?? 'figure']} gets ${pt(e.power, e.toughness)}${e.duration === 'turn' ? ' until end of turn' : ''}`;
|
||||
case 'fight': return `it fights ${TARGET_NOUN[e.target ?? 'opponentFigure']}`;
|
||||
case 'draw': return e.amount === 1 ? 'draw a card' : `draw ${word(e.amount ?? 1)} cards`;
|
||||
case 'gainLife': return `you gain ${e.amount} Notability`;
|
||||
case 'attach': return '';
|
||||
}
|
||||
}
|
||||
|
||||
const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
|
||||
|
||||
/** One sentence per effect, in effect order. */
|
||||
export function effectText(effects: readonly EffectSpec[]): string[] {
|
||||
const lines: string[] = [];
|
||||
for (let i = 0; i < effects.length; i++) {
|
||||
const e = effects[i];
|
||||
if (e.op === 'attach') {
|
||||
const grant = e.grant?.length ? ` and has ${keywordsAsText(e.grant)}` : '';
|
||||
lines.push(`Attach to ${e.target === 'figure' ? 'target Figure' : 'target Figure you control'}. It gets ${pt(e.power, e.toughness)}${grant}.`);
|
||||
continue;
|
||||
}
|
||||
if (e.op === 'fight' && i > 0 && effects[i - 1].op === 'pump') {
|
||||
lines[lines.length - 1] = lines[lines.length - 1].replace(/\.$/, `, then ${actionText(e)}.`);
|
||||
continue;
|
||||
}
|
||||
switch (e.trigger) {
|
||||
case 'static': lines.push(staticText(e)); break;
|
||||
case 'onPlay': lines.push(`${cap(actionText(e))}.`); break;
|
||||
case 'onEnter': lines.push(`When this enters, ${actionText(e)}.`); break;
|
||||
case 'onDestroyed': lines.push(`When this is destroyed, ${actionText(e)}.`); break;
|
||||
case 'startOfTurn': {
|
||||
const max = e.condition?.maxTokens;
|
||||
const cond = max !== undefined ? `, if you control fewer than ${max} tokens` : '';
|
||||
lines.push(`At the start of your turn${cond}, ${actionText(e)}.`);
|
||||
break;
|
||||
}
|
||||
case 'onCombatDamageToPlayer':
|
||||
lines.push(`Whenever ${e.target === 'attached' ? 'it' : 'this'} deals combat damage to a player, ${actionText(e)}.`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
/** The type line, e.g. "Figure — Society" or "Event — History". */
|
||||
export function typeLine(card: Pick<DuelCard, 'type' | 'portal'>): string {
|
||||
return card.portal === 'Neutral' ? card.type : `${card.type} — ${card.portal}`;
|
||||
}
|
||||
|
||||
/** Full rules text: keyword line, Location lines, effect lines. Newline-separated. */
|
||||
export function rulesTextFor(card: Pick<DuelCard, 'type' | 'keywords' | 'effects' | 'territory' | 'toughness'>): string {
|
||||
const lines: string[] = [];
|
||||
if (card.keywords.length) lines.push(`${keywordsAsText(card.keywords)}.`);
|
||||
if (card.type === 'Location') {
|
||||
if (card.territory) lines.push('Territory.');
|
||||
lines.push(`Garrison 0/${card.toughness}.`);
|
||||
}
|
||||
lines.push(...effectText(card.effects));
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
export const RULE_WORD_REMINDER: Readonly<Record<'Territory' | 'Garrison', string>> = {
|
||||
Territory: 'Your Citation maximum is 1 higher while you control this, to at most +2 from Territory.',
|
||||
Garrison: 'This can block like a Figure with power 0. It can\'t attack.',
|
||||
};
|
||||
|
||||
/** Rules text with reminder text for keywords and rule words, for the tap-to-expand view. */
|
||||
export function rulesTextWithReminders(card: Pick<DuelCard, 'type' | 'keywords' | 'effects' | 'territory' | 'toughness'>): string {
|
||||
const lines = card.keywords.map(k => `${k}. (${KEYWORD_REMINDER[k]})`);
|
||||
for (const line of rulesTextFor({ ...card, keywords: [] }).split('\n').filter(Boolean)) {
|
||||
const word = line.match(/^(Territory|Garrison)\b/)?.[1] as keyof typeof RULE_WORD_REMINDER | undefined;
|
||||
lines.push(word ? `${line} (${RULE_WORD_REMINDER[word]})` : line);
|
||||
}
|
||||
return lines.join('\n');
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { classify } from '../shared/duel/classify.ts';
|
||||
import {
|
||||
derive, connectedTier, figureBody, flavorFor, portalFor, DERIVE_RULES, DERIVE_VERSION,
|
||||
type DuelCard, type CardProfile,
|
||||
} from '../shared/duel/derive.ts';
|
||||
import { deriveSample, sampleInputs, type SampleCard } from '../shared/duel/sample.ts';
|
||||
import { rulesTextFor, rulesTextWithReminders, typeLine } from '../shared/duel/text.ts';
|
||||
|
||||
const root = new URL('../', import.meta.url);
|
||||
const SAMPLE = (JSON.parse(readFileSync(new URL('docs/game/card-sample.json', root), 'utf8')) as { cards: SampleCard[] }).cards;
|
||||
const FIXTURE = JSON.parse(readFileSync(new URL('docs/game/duel-card-sample.json', root), 'utf8')) as { deriveVersion: string; cards: DuelCard[] };
|
||||
const CARDS = deriveSample(SAMPLE);
|
||||
const byTitle = (title: string) => {
|
||||
const card = CARDS.find(c => c.title === title);
|
||||
assert.ok(card, `missing sample card ${title}`);
|
||||
return card;
|
||||
};
|
||||
const profile = (overrides: Partial<CardProfile>): CardProfile =>
|
||||
({ wikidataId: null, description: null, categories: [], instanceOf: [], ...overrides });
|
||||
|
||||
test('every sample card gets a type, and nothing falls through to the Doctrine residual', () => {
|
||||
assert.equal(CARDS.length, 236);
|
||||
const fallback = CARDS.filter(c => c.typedBy === 'fallback');
|
||||
assert.deepEqual(fallback.map(c => c.title), []);
|
||||
const share = (t: string) => CARDS.filter(c => c.type === t).length / CARDS.length;
|
||||
// data §1 distribution, ±4 points
|
||||
assert.ok(Math.abs(share('Figure') - 0.364) < 0.04);
|
||||
assert.ok(Math.abs(share('Location') - 0.331) < 0.04);
|
||||
assert.ok(share('Event') > 0.05 && share('Doctrine') > 0.05 && share('Institution') > 0.1);
|
||||
});
|
||||
|
||||
test('"human settlement" villages are Locations, not Figures (the \\bhuman\\b bug)', () => {
|
||||
for (const title of ['Buky', 'Lunugala', 'Žižki', 'Laukhella']) assert.equal(byTitle(title).type, 'Location', title);
|
||||
assert.equal(classify(profile({ instanceOf: [{ id: 'Q999', label: 'human settlement' }] })).type, 'Location');
|
||||
assert.equal(classify(profile({ instanceOf: [{ id: 'Q999', label: 'human' }] })).type, 'Figure');
|
||||
});
|
||||
|
||||
test('rule order: elections beat "municipal", aspects beat "region", governing bodies are Institutions', () => {
|
||||
assert.equal(byTitle('2023 Seville municipal election').type, 'Event');
|
||||
assert.equal(byTitle('Corruption in Kazakhstan').type, 'Doctrine');
|
||||
assert.equal(byTitle('Diocese of Mindelo').type, 'Institution');
|
||||
assert.equal(byTitle('Region Östergötland').type, 'Institution');
|
||||
assert.equal(byTitle('Lewis and Elizabeth Bolton House').type, 'Location');
|
||||
});
|
||||
|
||||
test('P279 anchors and labels classify items without P31; categories then description are fallbacks', () => {
|
||||
assert.deepEqual(classify(profile({ subclassOf: [{ id: 'Q1', label: 'algebraic structure' }] })),
|
||||
{ type: 'Doctrine', source: 'p279', matched: 'algebraic structure' });
|
||||
assert.equal(classify(profile({ subclassOf: [{ id: 'Q43229', label: 'x' }] })).source, 'p279-qid');
|
||||
assert.equal(classify(profile({ categories: ['Villages in Somewhere', 'Somewhere geography stubs'] })).type, 'Location');
|
||||
assert.equal(classify(profile({ description: 'Species of beetle' })).type, 'Figure');
|
||||
assert.deepEqual(classify(profile({})), { type: 'Doctrine', source: 'fallback', matched: '' });
|
||||
});
|
||||
|
||||
test('derive is deterministic and the committed fixture is current', () => {
|
||||
assert.deepEqual(deriveSample(SAMPLE), CARDS);
|
||||
assert.equal(FIXTURE.deriveVersion, DERIVE_VERSION);
|
||||
assert.deepEqual(FIXTURE.cards, CARDS, 'run: node --experimental-strip-types scripts/duel-card-sample.ts');
|
||||
const { chain, profile: p } = sampleInputs(SAMPLE[0]);
|
||||
const frozen = structuredClone(p);
|
||||
derive(chain, p);
|
||||
assert.deepEqual(p, frozen, 'derive must not mutate the profile');
|
||||
});
|
||||
|
||||
test('costs, bodies and keyword caps stay in range', () => {
|
||||
for (const c of CARDS) {
|
||||
assert.ok(c.keywords.length <= 2, c.title);
|
||||
if (c.type === 'Figure') {
|
||||
assert.ok(c.cost >= 1 && c.cost <= 6, c.title);
|
||||
const taxed = c.keywords.filter(k => DERIVE_RULES.taxedKeywords.includes(k)).length;
|
||||
assert.ok(c.connect.qid === null || /^Q\d+$/.test(c.connect.qid));
|
||||
assert.equal(c.power! + c.toughness!, DERIVE_RULES.bodyBudget[c.cost] - taxed, c.title);
|
||||
assert.ok(c.power! >= 1 && c.toughness! >= 1, c.title);
|
||||
} else if (c.type === 'Location') {
|
||||
assert.ok(c.cost >= 1 && c.cost <= 3, c.title);
|
||||
assert.equal(c.power, 0);
|
||||
assert.ok(c.toughness! >= 1 && c.toughness! <= 4);
|
||||
assert.deepEqual(c.keywords, []);
|
||||
} else {
|
||||
assert.equal(c.power, null);
|
||||
assert.ok(c.effects.length > 0, c.title);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('no famous Figure is strictly better than another Figure of no lower cost with the same keywords (data §2)', () => {
|
||||
const figures = CARDS.filter(c => c.type === 'Figure');
|
||||
const dominated: string[] = [];
|
||||
for (const x of figures) for (const y of figures) {
|
||||
if (x === y || x.keywords.join() !== y.keywords.join()) continue;
|
||||
if (x.cost <= y.cost && x.power! >= y.power! && x.toughness! >= y.toughness!
|
||||
&& (x.cost < y.cost || x.power! > y.power! || x.toughness! > y.toughness!)) dominated.push(`${x.title} > ${y.title}`);
|
||||
}
|
||||
assert.deepEqual(dominated, []);
|
||||
// Fame buys size, not efficiency: (P+T)/cost does not rise with cost.
|
||||
const eff = (cost: number) => { const g = figures.filter(c => c.cost === cost); return g.reduce((s, c) => s + (c.power! + c.toughness!) / cost, 0) / g.length; };
|
||||
for (let cost = 2; cost <= 6; cost++) assert.ok(eff(cost) < eff(1) && eff(cost) <= 2, `cost ${cost}: ${eff(cost)}`);
|
||||
});
|
||||
|
||||
test('figureBody: keyword tax comes off the budget first, then attention vs depth splits it', () => {
|
||||
assert.deepEqual(figureBody(4, { attention: 90, depth: 10, reach: 0 }, []), { power: 7, toughness: 1, keywords: [] });
|
||||
assert.deepEqual(figureBody(4, { attention: 10, depth: 90, reach: 0 }, ['Featured']), { power: 1, toughness: 6, keywords: ['Featured'] });
|
||||
assert.deepEqual(figureBody(1, { attention: 50, depth: 50, reach: 0 }, ['Legacy', 'Stub', 'Local']),
|
||||
{ power: 1, toughness: 1, keywords: ['Legacy', 'Stub'] });
|
||||
assert.deepEqual(figureBody(1, { attention: 50, depth: 50, reach: 0 }, ['Protected', 'Legacy', 'Stub']),
|
||||
{ power: 1, toughness: 1, keywords: ['Protected', 'Stub'] });
|
||||
assert.deepEqual(figureBody(3, { attention: null, depth: 50, reach: 0 }, ['Translated', 'Stub', 'Local']),
|
||||
{ power: 3, toughness: 3, keywords: ['Translated', 'Stub'] });
|
||||
});
|
||||
|
||||
test('keyword bands: Multilingual and Translated never both; Figures only', () => {
|
||||
for (const c of CARDS) {
|
||||
assert.ok(!(c.keywords.includes('Multilingual') && c.keywords.includes('Translated')), c.title);
|
||||
if (c.type !== 'Figure') assert.deepEqual(c.keywords, [], c.title);
|
||||
}
|
||||
});
|
||||
|
||||
test('DUEL_DESIGN §9 worked examples (golden)', () => {
|
||||
const show = (title: string) => {
|
||||
const c = byTitle(title);
|
||||
const body = c.type === 'Figure' || c.type === 'Location' ? ` · ${c.power}/${c.toughness}` : '';
|
||||
return `${c.cost} · ${typeLine(c)}${body} · ${c.rulesText.replace(/\n/g, ' ')} · ${c.flavor}`;
|
||||
};
|
||||
const golden: Record<string, string> = {
|
||||
'Marc Fesneau': '5 · Figure — Society · 5/4 · Protected. · French politician (born 1971)',
|
||||
'Tom Ewell': '6 · Figure — Arts · 5/5 · Featured, Legacy. · American actor (1909–1994)',
|
||||
'Zbyszek Godlewski': '5 · Figure — History · 6/3 · Legacy, Translated. · Polish protester (1952–1970)',
|
||||
"Pallas's cat": '6 · Figure — Earth · 5/5 · Featured, Multilingual. · Species of small wild cat',
|
||||
'Dichromorpha viridis': '2 · Figure — Earth · 3/1 · Stub. · Species of grasshopper',
|
||||
Monoid: '6 · Doctrine — Science · Attach to target Figure you control. It gets +3/+3 and has Well-sourced. · '
|
||||
+ 'Algebraic structure with an associative operation and an identity element',
|
||||
'Heart rot': '5 · Doctrine — Science · Attach to target Figure. It gets −3/−3. · Fungal disease of trees',
|
||||
"April 2021 nor'easter": "3 · Event — Earth · Deal 1 damage to each Figure and each Location. · Slow-moving nor'easter in April 2021",
|
||||
// §9 says History; the Portal score is Society (protest/riot categories outnumber "war").
|
||||
'2025 Tehreek-e-Labbaik Pakistan protests': '5 · Event — Society · Deal 4 damage to target Figure or Location. · Gaza war protests in Pakistan',
|
||||
'1954 Gold Coast general election': '3 · Event — Society · Create two 1/1 Society Figure tokens named Elected Member. · ',
|
||||
// §9 says History; "mosque" hits (P31, description, 2 categories) outscore 15th-century + Sultanate.
|
||||
'Pathrail Mosque': '2 · Location — Society · 0/3 · Territory. Garrison 0/3. · Mosque in Faridpur, Bangladesh',
|
||||
'Tatsunoko Production': '6 · Institution — Arts · At the start of your turn, if you control fewer than 3 tokens, '
|
||||
+ 'create a 1/1 Figure token named Staff Member. · Japanese animation studio',
|
||||
'Agda (programming language)': '6 · Doctrine — Science · Attach to target Figure you control. It gets +3/+3. '
|
||||
+ 'Whenever it deals combat damage to a player, draw a card. · Functional programming language',
|
||||
};
|
||||
for (const [title, want] of Object.entries(golden)) assert.equal(show(title), want, title);
|
||||
assert.equal(rulesTextWithReminders(byTitle('Tom Ewell')),
|
||||
'Featured. (Can\'t be blocked except by Featured, Translated or Multilingual Figures.)\nLegacy. (When this is destroyed, draw a card.)');
|
||||
assert.equal(rulesTextWithReminders(byTitle('Pathrail Mosque')),
|
||||
'Territory. (Your Citation maximum is 1 higher while you control this, to at most +2 from Territory.)\n'
|
||||
+ 'Garrison 0/3. (This can block like a Figure with power 0. It can\'t attack.)');
|
||||
});
|
||||
|
||||
test('rules text uses only card numbers and fixed words: no title, description or category text leaks in', () => {
|
||||
for (const c of CARDS) {
|
||||
const stripped = c.rulesText.replace(/Protected|Featured|Translated|Legacy|Stub|Well-sourced|Multilingual|Local/g, '');
|
||||
assert.ok(!stripped.includes(c.title), c.title);
|
||||
assert.match(c.rulesText, /^[A-Za-z0-9 ,.;:'()+−/\n—-]*$/, c.title);
|
||||
assert.equal(rulesTextFor(c), c.rulesText);
|
||||
}
|
||||
});
|
||||
|
||||
test('flavour is the first sentence of the extract, else the description', () => {
|
||||
assert.equal(flavorFor('Tom Ewell (born Samuel Yewell Tompkins; April 29, 1909 – September 12, 1994) was an American actor. He won a Tony.', null),
|
||||
'Tom Ewell (born Samuel Yewell Tompkins; April 29, 1909 – September 12, 1994) was an American actor.');
|
||||
assert.equal(flavorFor('J. R. R. Tolkien was an English writer. He wrote.', null), 'J. R. R. Tolkien was an English writer.');
|
||||
assert.equal(flavorFor('The U.S. Route 66 is a road in the U.S. state of Arizona. More.', null), 'The U.S. Route 66 is a road in the U.S. state of Arizona.');
|
||||
assert.equal(flavorFor('No terminal punctuation', 'desc'), 'No terminal punctuation');
|
||||
assert.equal(flavorFor(' ', 'Species of grasshopper'), 'Species of grasshopper');
|
||||
assert.equal(byTitle('Dichromorpha viridis').flavor, 'Species of grasshopper');
|
||||
});
|
||||
|
||||
test('Portals: keyword hits decide, ties go to the type default, no hits is Neutral', () => {
|
||||
assert.equal(portalFor(profile({ description: 'Sultan of Aceh', categories: ['16th-century monarchs in Asia'] }), 'Figure'), 'History');
|
||||
assert.equal(portalFor(profile({ description: 'mathematician and politician' }), 'Figure'), 'Society');
|
||||
assert.equal(portalFor(profile({ description: 'zzz' }), 'Figure'), 'Neutral');
|
||||
const portals = new Set(CARDS.map(c => c.portal));
|
||||
for (const p of ['Arts', 'Earth', 'History', 'Science', 'Society']) assert.ok(portals.has(p as DuelCard['portal']), p);
|
||||
});
|
||||
|
||||
test('Connected: Linked beats Compatriot beats Contemporary beats Kin; a card is never connected to itself', () => {
|
||||
const base = (id: string, pageId: number, connect: Partial<DuelCard['connect']>, type: DuelCard['type'] = 'Event'): DuelCard =>
|
||||
({ ...byTitle('Tom Ewell'), cardId: id, pageId, type, connect: { countries: [], centuries: [], links: [], p31: [], qid: null, cites: [], ...connect } });
|
||||
const a = base('a', 1, { links: [2], countries: ['France'], centuries: [20], p31: ['Q1'], qid: 'Q100' }, 'Figure');
|
||||
assert.equal(connectedTier(a, base('g', 7, { cites: ['Q100'] })), 'Linked');
|
||||
assert.equal(connectedTier(a, base('h', 8, { centuries: [20] }, 'Figure')), null, 'Contemporary needs different types');
|
||||
assert.equal(connectedTier(a, base('b', 2, { countries: ['France'] })), 'Linked');
|
||||
assert.equal(connectedTier(base('b', 2, { links: [1] }), a), 'Linked');
|
||||
assert.equal(connectedTier(a, base('c', 3, { countries: ['France'], centuries: [20] })), 'Compatriot');
|
||||
assert.equal(connectedTier(a, base('d', 4, { centuries: [20] })), 'Contemporary');
|
||||
assert.equal(connectedTier(a, base('e', 5, { p31: ['Q1'] })), 'Kin');
|
||||
assert.equal(connectedTier(a, base('f', 6, {})), null);
|
||||
assert.equal(connectedTier(a, a), null);
|
||||
assert.equal(connectedTier(a, base('c', 3, { centuries: [20] }), ['Linked', 'Compatriot']), null);
|
||||
});
|
||||
|
||||
test('Connected fires in a plausible share of sample pairs (BRIEF target 15–30%, tuned in the sim)', () => {
|
||||
let hits = 0, pairs = 0;
|
||||
for (let i = 0; i < CARDS.length; i++) for (let j = i + 1; j < CARDS.length; j++) {
|
||||
pairs++; if (connectedTier(CARDS[i], CARDS[j])) hits++;
|
||||
}
|
||||
const rate = hits / pairs;
|
||||
assert.ok(rate > 0.1 && rate < 0.4, `rate ${rate}`);
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
canonicalProfile, classIdsOf, profileFromSources, wikidataEntityParams, wikidataLabelParams, type WikidataEntity,
|
||||
} from '../shared/duel/profile.ts';
|
||||
import { classify } from '../shared/duel/classify.ts';
|
||||
import { derive } from '../shared/duel/derive.ts';
|
||||
|
||||
const item = (id: string) => ({ rank: 'normal', mainsnak: { snaktype: 'value', datavalue: { type: 'wikibase-entityid', value: { id } } } });
|
||||
const time = (t: string) => ({ rank: 'normal', mainsnak: { snaktype: 'value', datavalue: { type: 'time', value: { time: t } } } });
|
||||
|
||||
const EWELL: WikidataEntity = {
|
||||
id: 'Q1351340',
|
||||
claims: {
|
||||
P31: [item('Q5')],
|
||||
P27: [item('Q30')],
|
||||
P569: [time('+1909-04-29T00:00:00Z')],
|
||||
P570: [time('+1994-09-12T00:00:00Z')],
|
||||
P19: [item('Q1018580')],
|
||||
P106: [item('Q33999')],
|
||||
P17: [{ rank: 'deprecated', mainsnak: { snaktype: 'value', datavalue: { value: { id: 'Q999' } } } }],
|
||||
},
|
||||
};
|
||||
const ENRICH = { description: 'American actor (1909–1994)', wikidataId: 'Q1351340', categories: ['1994 deaths', 'American male actors'], revisionId: 42 };
|
||||
|
||||
test('profileFromSources reads P31, countries, years, death and cited items; ignores deprecated claims', () => {
|
||||
const p = profileFromSources({ enrichment: ENRICH, entity: EWELL, labels: { Q5: 'human' }, links: [9, 3, 9] });
|
||||
assert.deepEqual(p, {
|
||||
wikidataId: 'Q1351340', description: 'American actor (1909–1994)', categories: ['1994 deaths', 'American male actors'],
|
||||
instanceOf: [{ id: 'Q5', label: 'human' }], fetchedRevisionId: 42,
|
||||
countries: ['Q30'], years: [1909, 1994], died: true, cites: ['Q1018580', 'Q30'], links: [3, 9],
|
||||
});
|
||||
assert.equal(classify(p).type, 'Figure');
|
||||
});
|
||||
|
||||
test('BCE years are negative; malformed and novalue claims are skipped without throwing', () => {
|
||||
const entity: WikidataEntity = { claims: {
|
||||
P571: [time('-0753-04-21T00:00:00Z'), { mainsnak: { snaktype: 'novalue' } }, { mainsnak: { snaktype: 'value', datavalue: { value: 'junk' } } }],
|
||||
P31: [item('not-a-qid'), item('Q515')],
|
||||
} };
|
||||
const p = profileFromSources({ enrichment: { ...ENRICH, categories: [] }, entity });
|
||||
assert.deepEqual(p.years, [-753]);
|
||||
assert.deepEqual(p.instanceOf, [{ id: 'Q515', label: 'Q515' }]);
|
||||
assert.equal(classify(p).type, 'Location', 'Q-id anchors classify even without labels');
|
||||
assert.equal(profileFromSources({ enrichment: ENRICH, entity: null }).instanceOf.length, 0);
|
||||
});
|
||||
|
||||
test('without a Wikidata item the profile still classifies from categories and description', () => {
|
||||
const p = profileFromSources({ enrichment: { description: 'Village in Poland', wikidataId: null, categories: ['Villages in Gmina X'], revisionId: 1 } });
|
||||
assert.equal(classify(p).type, 'Location');
|
||||
});
|
||||
|
||||
test('request parameters: claims-only entities, English labels, ≤ 50 sorted ids', () => {
|
||||
assert.deepEqual(wikidataEntityParams(['Q5', 'Q1']), { action: 'wbgetentities', ids: 'Q1|Q5', props: 'claims', format: 'json', formatversion: '2' });
|
||||
assert.equal(wikidataLabelParams(['Q5']).props, 'labels');
|
||||
assert.throws(() => wikidataEntityParams([]), RangeError);
|
||||
assert.throws(() => wikidataLabelParams(Array.from({ length: 51 }, (_, i) => `Q${i + 1}`)), RangeError);
|
||||
assert.deepEqual(classIdsOf({ claims: { P31: [item('Q5')], P279: [item('Q2'), item('Q5')] } }), ['Q2', 'Q5']);
|
||||
});
|
||||
|
||||
test('canonicalProfile is key-order independent, and the frozen profile derives the same card twice', () => {
|
||||
const p = profileFromSources({ enrichment: ENRICH, entity: EWELL, labels: { Q5: 'human' } });
|
||||
const shuffled = Object.fromEntries(Object.entries(p).reverse()) as typeof p;
|
||||
assert.equal(canonicalProfile(shuffled), canonicalProfile(p));
|
||||
const chain = { tokenId: 'ab'.repeat(32), article: { pageId: 1, title: 'Tom Ewell', extract: 'Tom Ewell was an American actor. More.', revisionId: 42 },
|
||||
statsSnapshot: { pageBytes: 9000, languageCount: 30, stats: { attention: 60, depth: 70, reach: 50 } } };
|
||||
const thawed = JSON.parse(canonicalProfile(p));
|
||||
assert.deepEqual(derive(chain, thawed), derive(chain, p));
|
||||
assert.equal(derive(chain, p).flavor, 'Tom Ewell was an American actor.');
|
||||
assert.ok(derive(chain, p).keywords.includes('Legacy'));
|
||||
});
|
||||
Reference in New Issue
Block a user