diff --git a/docs/game/duel-card-sample.json b/docs/game/duel-card-sample.json index ef983ed..a82bd43 100644 --- a/docs/game/duel-card-sample.json +++ b/docs/game/duel-card-sample.json @@ -851,9 +851,14 @@ "trigger": "onPlay", "op": "attach", "target": "figure", + "template": "T12" + }, + { + "trigger": "static", + "op": "pump", + "target": "attached", "power": -3, "toughness": -3, - "duration": "permanent", "template": "T12" } ], @@ -943,15 +948,19 @@ "trigger": "onPlay", "op": "attach", "target": "ownFigure", + "template": "T11" + }, + { + "trigger": "static", + "op": "pump", + "target": "attached", "power": 3, "toughness": 3, - "duration": "permanent", "template": "T11" }, { "trigger": "onCombatDamageToPlayer", "op": "draw", - "target": "attached", "amount": 1, "template": "T11" } @@ -1272,15 +1281,19 @@ "trigger": "onPlay", "op": "attach", "target": "ownFigure", + "template": "T11" + }, + { + "trigger": "static", + "op": "pump", + "target": "attached", "power": 3, "toughness": 3, - "duration": "permanent", "template": "T11" }, { "trigger": "onCombatDamageToPlayer", "op": "draw", - "target": "attached", "amount": 1, "template": "T11" } @@ -3753,9 +3766,14 @@ "trigger": "onPlay", "op": "attach", "target": "ownFigure", + "template": "T11" + }, + { + "trigger": "static", + "op": "pump", + "target": "attached", "power": 3, "toughness": 3, - "duration": "permanent", "template": "T11" } ], @@ -4189,9 +4207,14 @@ "trigger": "onPlay", "op": "attach", "target": "ownFigure", + "template": "T11" + }, + { + "trigger": "static", + "op": "pump", + "target": "attached", "power": 2, "toughness": 2, - "duration": "permanent", "template": "T11" } ], @@ -4325,9 +4348,14 @@ "trigger": "onPlay", "op": "attach", "target": "ownFigure", + "template": "T11" + }, + { + "trigger": "static", + "op": "pump", + "target": "attached", "power": 3, "toughness": 3, - "duration": "permanent", "template": "T11" } ], @@ -4787,9 +4815,14 @@ "trigger": "onPlay", "op": "attach", "target": "ownFigure", + "template": "T11" + }, + { + "trigger": "static", + "op": "pump", + "target": "attached", "power": 2, "toughness": 2, - "duration": "permanent", "template": "T11" } ], @@ -5010,9 +5043,14 @@ "trigger": "onPlay", "op": "attach", "target": "ownFigure", + "template": "T11" + }, + { + "trigger": "static", + "op": "pump", + "target": "attached", "power": 3, "toughness": 3, - "duration": "permanent", "grant": [ "Well-sourced" ], @@ -5059,9 +5097,14 @@ "trigger": "onPlay", "op": "attach", "target": "ownFigure", + "template": "T11" + }, + { + "trigger": "static", + "op": "pump", + "target": "attached", "power": 3, "toughness": 3, - "duration": "permanent", "template": "T11" } ], @@ -5196,9 +5239,14 @@ "trigger": "onPlay", "op": "attach", "target": "ownFigure", + "template": "T11" + }, + { + "trigger": "static", + "op": "pump", + "target": "attached", "power": 3, "toughness": 3, - "duration": "permanent", "grant": [ "Well-sourced" ], @@ -6030,9 +6078,14 @@ "trigger": "onPlay", "op": "attach", "target": "ownFigure", + "template": "T11" + }, + { + "trigger": "static", + "op": "pump", + "target": "attached", "power": 2, "toughness": 2, - "duration": "permanent", "template": "T11" } ], @@ -7070,9 +7123,14 @@ "trigger": "onPlay", "op": "attach", "target": "ownFigure", + "template": "T11" + }, + { + "trigger": "static", + "op": "pump", + "target": "attached", "power": 2, "toughness": 2, - "duration": "permanent", "grant": [ "Well-sourced" ], @@ -7120,9 +7178,14 @@ "trigger": "onPlay", "op": "attach", "target": "figure", + "template": "T12" + }, + { + "trigger": "static", + "op": "pump", + "target": "attached", "power": -2, "toughness": -2, - "duration": "permanent", "template": "T12" } ], @@ -7830,9 +7893,14 @@ "trigger": "onPlay", "op": "attach", "target": "figure", + "template": "T12" + }, + { + "trigger": "static", + "op": "pump", + "target": "attached", "power": -2, "toughness": -2, - "duration": "permanent", "template": "T12" } ], @@ -8132,9 +8200,14 @@ "trigger": "onPlay", "op": "attach", "target": "ownFigure", + "template": "T11" + }, + { + "trigger": "static", + "op": "pump", + "target": "attached", "power": 1, "toughness": 1, - "duration": "permanent", "template": "T11" } ], @@ -8552,9 +8625,14 @@ "trigger": "onPlay", "op": "attach", "target": "ownFigure", + "template": "T11" + }, + { + "trigger": "static", + "op": "pump", + "target": "attached", "power": 2, "toughness": 2, - "duration": "permanent", "grant": [ "Well-sourced" ], @@ -9028,9 +9106,14 @@ "trigger": "onPlay", "op": "attach", "target": "ownFigure", + "template": "T11" + }, + { + "trigger": "static", + "op": "pump", + "target": "attached", "power": 2, "toughness": 2, - "duration": "permanent", "template": "T11" } ], @@ -9074,9 +9157,14 @@ "trigger": "onPlay", "op": "attach", "target": "ownFigure", + "template": "T11" + }, + { + "trigger": "static", + "op": "pump", + "target": "attached", "power": 3, "toughness": 3, - "duration": "permanent", "template": "T11" } ], @@ -9384,9 +9472,14 @@ "trigger": "onPlay", "op": "attach", "target": "ownFigure", + "template": "T11" + }, + { + "trigger": "static", + "op": "pump", + "target": "attached", "power": 3, "toughness": 3, - "duration": "permanent", "template": "T11" } ], @@ -9559,9 +9652,14 @@ "trigger": "onPlay", "op": "attach", "target": "ownFigure", + "template": "T11" + }, + { + "trigger": "static", + "op": "pump", + "target": "attached", "power": 1, "toughness": 1, - "duration": "permanent", "template": "T11" } ], diff --git a/shared/duel/classify.ts b/shared/duel/classify.ts index 52fce1f..e8e74d4 100644 --- a/shared/duel/classify.ts +++ b/shared/duel/classify.ts @@ -40,7 +40,8 @@ export interface CardProfile { fetchedRevisionId?: number; } -export type ClassifySource = 'qid' | 'p279-qid' | 'p31' | 'p279' | 'category' | 'description' | 'fallback'; +export type ClassifySource = 'qid' | 'p279-qid' | 'p31' | 'p279' | 'category' | 'description' + | 'extract' | 'title' | 'chain-category' | '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. */ @@ -101,12 +102,58 @@ export const DESCRIPTION_RULES: Rules = [ ['Doctrine', /\b(concept|theory|structure|dessert|drink|dish|technique|class of)\b/], ]; +/** + * On-chain data every block carries (protocol Article), used when the frozen profile is empty or + * missing: the mint-time `category` (server/wiki.ts buckets), the title and the extract. + */ +export interface ChainHints { title: string; extract?: string; category?: string } + +/** + * Rules for an extract's definitional phrase ("is a village in …"). Broader than the short-description + * rules because lead sentences use more varied nouns. Order: Doctrine overrides, then as for labels. + */ +export const EXTRACT_RULES: Rules = [ + ['Doctrine', /\b(gene|protein|enzyme|disease|syndrome|disorder|theorem|conjecture|concept|theory|language|cuisine|dish|algebraic|mathematical|list of)\b/], + ['Event', /\b(election|referendum|battle|war|siege|protest|riot|massacre|annexation|storm|hurricane|cyclone|tornado|tornadoes|earthquake|flood|season|tournament|championship|race|grand prix|match|festival|ceremony)\b/], + ['Figure', /\b(actor|actress|politician|writer|author|poet|painter|artist|singer|musician|composer|director|producer|player|footballer|cricketer|athlete|boxer|scientist|engineer|bishop|priest|monarch|king|queen|sultan|businessman|businesswoman|family|dynasty|species|genus|breed|character|deity|god|goddess)\b/], + ['Institution', /\b(company|corporation|business|manufacturer|organi[sz]ation|association|society|party|coalition|band|team|club|university|college|school|studio|newspaper|magazine|film|album|song|single|novel|book|series|video game|aircraft|airliner|ship|automobile|car|locomotive|tramway|railway line|bus route|typeface|software|position|office|award|diocese|council)\b/], + ['Location', /\b(village|town|city|municipality|commune|parish|county|district|region|province|state|locality|hamlet|suburb|neighbourhood|neighborhood|settlement|community|census area|river|lake|island|mountain|plateau|valley|bay|peak|building|house|church|cathedral|mosque|temple|castle|ch[aâ]teau|palace|museum|pavilion|stadium|bridge|station|park|mall|shopping (centre|center)|road|street|square|monument)\b/], +]; + +/** Title patterns (checked after the extract's definitional phrase). */ +export const TITLE_RULES: Rules = [ + ['Event', /\b(election|elections|referendum|straw poll|battle of|siege of|war|protests?|riots?|massacre|earthquake|hurricane|cyclone|typhoon|nor'easter|storm|flood|season|championship|tournament|grand prix|olympics|world cup|final)\b/i], + ['Institution', /\((film|album|song|single|novel|book|band|tv series|television series|video game|magazine|newspaper|company|ship|aircraft|typeface|software)\)|\b(f\.?c\.?|company|corporation|university|college|school|party|club|association|society|records|airlines?)\b/i], + ['Doctrine', /\((programming language|mathematics|disease|gene|chemistry|philosophy|religion)\)|\b(disease|syndrome|theorem|conjecture|cuisine)\b/i], + ['Figure', /\((actor|actress|politician|footballer|cricketer|singer|musician|writer|author|painter|artist|boxer|wrestler|bishop|priest|judge|businessman|athlete|rugby union|rugby league|baseball|basketball)\)|\((plant|animal|bird|fish|moth|beetle|spider|fungus|genus)\)/i], + ['Location', /\b(river|lake|mount|mountain|island|islands|county|village|township|parish|district|province|church|cathedral|chapel|castle|mosque|temple|abbey|bridge|station|house|park|street|road|square|tower|palace|fort|airport|dam|valley|bay)\b/i], +]; + +/** Mint-time category buckets that carry a type signal (History and Culture don't). */ +export const CHAIN_CATEGORY_TYPE: Readonly> = { + People: 'Figure', Nature: 'Figure', Space: 'Location', Science: 'Doctrine', +}; + +/** + * The definitional phrase of an extract's first sentence: what follows "is a / was an / are the …", + * up to the next clause break. "Tom Ewell (1909–1994) was an American actor." → "american actor". + */ +export function definitionOf(extract: string | undefined): string { + const text = (extract ?? '').replace(/\s+/g, ' ').trim(); + const m = /\b(?:is|was|are|were)\s+(?:an?|the|one of the)\s+([^.;:]{1,120})/i.exec(text); + return m ? m[1].toLowerCase() : ''; +} + +/** Lead-sentence life dates: "Name (born 1971)", "Name (1909–1994)", "Name (c. 1530 – 1548)". */ +const LIFE_DATES = /^[^.(]{1,80}\((?:[^)]*;\s*)?(?:born\s+(?:[A-Z][a-z]+\s+)?(?:\d{1,2}\s+)?(?:[A-Z][a-z]+\s+)?\d{3,4}|(?:c\.\s*)?\d{3,4}\s*[–-]\s*(?:c\.\s*)?\d{3,4})/; + 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): Classification { +export function classify(profile: Pick, + chain?: ChainHints): 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 }; } @@ -122,5 +169,16 @@ export function classify(profile: Pick; /** What derive() reads from the chain: a minted block's article and stats snapshot. */ export interface CardOnChain { tokenId: string; - article: Pick; + /** `category` is the mint-time bucket (server/wiki.ts); only used when the profile is empty. */ + article: Pick & { category?: string }; statsSnapshot: Pick; } @@ -270,13 +271,13 @@ export function figureBody(cost: number, p: Percentiles, keywords: readonly Keyw // ---------------------------------------------------------------- derive export function derive(chain: CardOnChain, profile: CardProfile, rules: DeriveRules = DERIVE_RULES): DuelCard { - const { type, source } = classify(profile); + const { type, source } = classify(profile, chain.article); 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); + const subtype = subtypeFor(type, profile, chain.article); let cost = baseCost, power: number | null = null, toughness: number | null = null, territory = 0; let keywords: Keyword[] = []; if (type === 'Figure') { diff --git a/shared/duel/effects.ts b/shared/duel/effects.ts index 4f4f5be..d774b62 100644 --- a/shared/duel/effects.ts +++ b/shared/duel/effects.ts @@ -3,7 +3,7 @@ * 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 { definitionOf, type CardProfile, type CardType, type ChainHints } from './classify.ts'; import type { EffectSpec } from './types.ts'; export type { EffectOp, EffectSpec, EffectTrigger, TargetSpec as EffectTarget } from './types.ts'; @@ -41,11 +41,14 @@ export const DEFAULT_SUBTYPE: Readonly> = { Figure: null, Location: null, Event: 'other', Institution: 'other', Doctrine: 'adopt', }; -export function subtypeFor(type: CardType, profile: Pick): string | null { +export function subtypeFor(type: CardType, profile: Pick, + chain?: ChainHints): 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))], + // On-chain fallbacks, last: the extract's definitional phrase, then the title. + [definitionOf(chain?.extract), chain?.title ?? ''], ].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]; @@ -98,12 +101,15 @@ function baseEffects(type: CardType, subtype: string | null, cost: number): Effe 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]; + // DUEL_API "Doctrine": `attach` picks the Figure; the buff is a static pump on `attached`. + const pathology = subtype === 'pathology'; + const attach: EffectSpec = { trigger: 'onPlay', op: 'attach', target: pathology ? 'figure' : 'ownFigure' }; + const buff: EffectSpec = { trigger: 'static', op: 'pump', target: 'attached', power: pathology ? -k : k, toughness: pathology ? -k : k }; + if (pathology) return [attach, buff]; + if (subtype === 'mathematics') return [attach, { ...buff, grant: ['Well-sourced'] }]; + if (subtype === 'language') return [attach, buff, { trigger: 'onCombatDamageToPlayer', op: 'draw', amount: 1 }]; + if (subtype === 'ideology') return [attach, buff, { trigger: 'static', op: 'pump', target: 'ownFigures', power: 1, toughness: 0, condition: { samePortal: true } }]; + return [attach, buff]; } default: return []; } diff --git a/shared/duel/sample.ts b/shared/duel/sample.ts index 05df0a9..dcb22d7 100644 --- a/shared/duel/sample.ts +++ b/shared/duel/sample.ts @@ -13,6 +13,8 @@ export interface SampleCard { stats: { attention: number | null; depth: number; reach: number }; instanceOf: { id: string; label: string }[]; extract?: string; + /** The on-chain mint-time category (server/wiki.ts bucket). */ + legacyCategory?: string; } export function sampleTokenId(pageId: number): string { @@ -23,7 +25,8 @@ export function sampleInputs(card: SampleCard): { chain: CardOnChain; profile: C return { chain: { tokenId: sampleTokenId(card.pageId), - article: { pageId: card.pageId, title: card.title, extract: card.extract ?? '', revisionId: card.revisionId }, + article: { pageId: card.pageId, title: card.title, extract: card.extract ?? '', revisionId: card.revisionId, + ...(card.legacyCategory ? { category: card.legacyCategory } : {}) }, statsSnapshot: { pageBytes: card.pageBytes, languageCount: card.languageCount, stats: card.stats }, }, profile: { diff --git a/shared/duel/text.ts b/shared/duel/text.ts index ce44397..c1576dc 100644 --- a/shared/duel/text.ts +++ b/shared/duel/text.ts @@ -80,8 +80,16 @@ export function effectText(effects: readonly EffectSpec[]): 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}.`); + // The Doctrine's buff is the static pump on `attached` that follows (DUEL_API "Doctrine"). + const next = effects[i + 1]; + const buff = next && next.trigger === 'static' && next.op === 'pump' && next.target === 'attached' ? next : null; + let line = `Attach to ${e.target === 'figure' ? 'target Figure' : 'target Figure you control'}.`; + if (buff) { + const grant = buff.grant?.length ? ` and has ${keywordsAsText(buff.grant)}` : ''; + line += ` It gets ${pt(buff.power, buff.toughness)}${grant}.`; + i++; + } + lines.push(line); continue; } if (e.op === 'fight' && i > 0 && effects[i - 1].op === 'pump') { @@ -100,7 +108,8 @@ export function effectText(effects: readonly EffectSpec[]): string[] { break; } case 'onCombatDamageToPlayer': - lines.push(`Whenever ${e.target === 'attached' ? 'it' : 'this'} deals combat damage to a player, ${actionText(e)}.`); + // On a Doctrine the trigger belongs to the attached Figure ("it"); on a Figure, to "this". + lines.push(`Whenever ${effects.some(x => x.op === 'attach') ? 'it' : 'this'} deals combat damage to a player, ${actionText(e)}.`); break; } } diff --git a/tests/duel-cards-derive.test.ts b/tests/duel-cards-derive.test.ts index 473ebbb..62142f8 100644 --- a/tests/duel-cards-derive.test.ts +++ b/tests/duel-cards-derive.test.ts @@ -203,3 +203,53 @@ test('Connected fires in a plausible share of sample pairs (BRIEF target 15–30 const rate = hits / pairs; assert.ok(rate > 0.1 && rate < 0.4, `rate ${rate}`); }); + +test('Doctrines use the engine encoding: attach picks the Figure, a static pump on `attached` carries ±k (DUEL_API)', () => { + for (const c of CARDS.filter(x => x.type === 'Doctrine')) { + assert.equal(c.effects[0].op, 'attach', c.title); + const buff = c.effects[1]; + assert.equal(buff.trigger, 'static', c.title); + assert.equal(buff.op, 'pump'); + assert.equal(buff.target, 'attached'); + const magnitude = c.basis.magnitude; + const sign = c.subtype === 'pathology' ? -1 : 1; + assert.deepEqual([buff.power, buff.toughness], [sign * magnitude, sign * magnitude], c.title); + assert.equal(c.effects[0].target, c.subtype === 'pathology' ? 'figure' : 'ownFigure'); + } + assert.deepEqual(byTitle('Heart rot').effects.map(e => [e.trigger, e.op, e.target, e.power ?? null]), + [['onPlay', 'attach', 'figure', null], ['static', 'pump', 'attached', -3]]); +}); + +test('chain-only fallback: an empty profile still types from the on-chain title, category and extract', () => { + const empty = profile({}); + const chain = (title: string, extract = '', category?: string) => ({ title, extract, ...(category ? { category } : {}) }); + assert.equal(classify(empty, chain('Tom Ewell', 'Tom Ewell (born Samuel Yewell Tompkins; April 29, 1909 – September 12, 1994) was an American actor.')).type, 'Figure'); + assert.equal(classify(empty, chain('Buky', 'Buky is a village in Cherkasy Oblast, Ukraine.')).type, 'Location'); + assert.equal(classify(empty, chain('Heart rot', 'Heart rot is a fungal disease of trees.')).type, 'Doctrine'); + assert.equal(classify(empty, chain('1954 Gold Coast general election')).source, 'title'); + assert.equal(classify(empty, chain('1954 Gold Coast general election')).type, 'Event'); + assert.equal(classify(empty, chain('Zzyzx', '', 'People')).type, 'Figure'); + assert.equal(classify(empty, chain('Zzyzx', '', 'Culture')).source, 'fallback'); + assert.equal(classify(empty).source, 'fallback', 'no chain hints: unchanged'); + // derive() passes chain.article through, so hosts need no extra argument. + const { chain: c } = sampleInputs(SAMPLE.find(s => s.title === '1954 Gold Coast general election')!); + const card = derive(c, empty); + assert.deepEqual([card.type, card.typedBy, card.subtype], ['Event', 'title', 'election']); +}); + +test('chain-only typing over the sample agrees with the full classifier on most cards', () => { + // The sample has no extracts and tests can't fetch, so this uses a lead-sentence proxy: + // " is a <description>." (Wikipedia leads usually open this way). Labelled as a proxy. + const empty = profile({}); + let agree = 0; const types: Record<string, number> = {}; + for (const s of SAMPLE) { + const extract = s.description ? `${s.title} is a ${s.description[0].toLowerCase()}${s.description.slice(1)}.` : ''; + const t = classify(empty, { title: s.title, extract, ...(s.legacyCategory ? { category: s.legacyCategory } : {}) }).type; + types[t] = (types[t] ?? 0) + 1; + if (t === classify(s).type) agree++; + } + assert.ok(agree / SAMPLE.length >= 0.8, `agree ${agree}/${SAMPLE.length}`); + assert.ok(types.Figure / SAMPLE.length > 0.3 && types.Figure / SAMPLE.length < 0.42, JSON.stringify(types)); + assert.ok(types.Location / SAMPLE.length > 0.22 && types.Location / SAMPLE.length < 0.38, JSON.stringify(types)); + assert.ok(types.Doctrine / SAMPLE.length < 0.25, JSON.stringify(types)); +});