forked from WikiDeck/wikideck
Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3e4dd72ca8 | ||
|
|
067de837a8 | ||
|
|
c0dd5b2e38 | ||
|
|
bf929e2575 | ||
|
|
ff6c93c808 | ||
|
|
0f924b7732 | ||
|
|
848cfbbaf1 | ||
|
|
ae14bc7b89 | ||
|
|
9c26b8d560 | ||
|
|
a57698a7e2 | ||
|
|
57d2fc2fc7 | ||
|
|
75ce8f5ba5 | ||
|
|
a7e46583fb | ||
|
|
4160086d16 | ||
|
|
0fcf0b0a73 | ||
|
|
0666b08829 | ||
|
|
a8468dd96c | ||
|
|
2fe16a66c8 | ||
|
|
5a7cfba124 | ||
|
|
3c70f643f2 |
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 (omitted when it has none), and the item Q-ids its claims cite (Linked tier). */
|
||||
qid?: string;
|
||||
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(),
|
||||
...(profile.wikidataId ? { 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 !== undefined && a.connect.cites.includes(b.connect.qid))
|
||||
|| (a.connect.qid !== undefined && 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,131 @@
|
||||
/**
|
||||
* 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': {
|
||||
// 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 [];
|
||||
}
|
||||
}
|
||||
@@ -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,144 @@
|
||||
/**
|
||||
* 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') {
|
||||
// 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') {
|
||||
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':
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
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,39 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import type { DuelAction, LogEvent, PlayerView } from './contract.ts';
|
||||
import { boardFromView, expand, legalFromActions, plainLog, type Articles } from './adapter.ts';
|
||||
import { DuelTable } from './DuelTable.tsx';
|
||||
import type { DuelUIAction } from './model.ts';
|
||||
|
||||
/**
|
||||
* The duel board on duel-core's types, for any controller (ui-pvp's OnlinePlay, the local bot match).
|
||||
* One board intent can be several atomic actions (toggleAttacker × N, confirmAttack): they go out
|
||||
* through `onAct` in order, each awaited, each an element of `legal` or legal once the previous ones apply.
|
||||
*/
|
||||
export function DuelBoard({ view, legal, onAct, opponentName, playerName = 'You', error, busy, log, logEvents, articles, clock, onExit, onRecap }: {
|
||||
view: PlayerView; legal: DuelAction[]; onAct: (a: DuelAction) => void | Promise<void>;
|
||||
opponentName: string; playerName?: string; error?: string; busy?: boolean;
|
||||
/** Rendered log lines (duel-design's story renderer). If absent, `logEvents` are shown with plain templates. */
|
||||
log?: string[]; logEvents?: LogEvent[];
|
||||
/** cardId → article image/url, from the chain. */
|
||||
articles?: Articles;
|
||||
clock?: { turn: number; bank: number };
|
||||
onExit?: () => void; onRecap?: () => void;
|
||||
}) {
|
||||
const [sending, setSending] = useState(false);
|
||||
const [sendError, setSendError] = useState<string>();
|
||||
const names = useMemo<[string, string]>(() => (view.seat === 0 ? [playerName, opponentName] : [opponentName, playerName]), [view.seat, playerName, opponentName]);
|
||||
const lines = useMemo(() => log ?? plainLog(logEvents ?? [], names), [log, logEvents, names]);
|
||||
const board = useMemo(() => boardFromView(view, names, lines, articles, clock), [view, names, lines, articles, clock]);
|
||||
const boardLegal = useMemo(() => legalFromActions(legal), [legal]);
|
||||
|
||||
const act = async (ui: DuelUIAction) => {
|
||||
const seq = expand(ui, legal);
|
||||
setSending(true); setSendError(undefined);
|
||||
try { for (const a of seq) await onAct(a); }
|
||||
catch (e) { setSendError(e instanceof Error ? e.message : 'That move was not accepted.'); }
|
||||
finally { setSending(false); }
|
||||
};
|
||||
|
||||
return <DuelTable view={board} legal={boardLegal} onAct={ui => { void act(ui); }} busy={busy || sending}
|
||||
error={error ?? sendError} onExit={onExit} onRecap={onRecap} />;
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import type { DuelAction, DuelCard, DuelEngineLike, DuelRulesetLike, Seat } from './contract.ts';
|
||||
import type { Articles } from './adapter.ts';
|
||||
import { DuelBoard } from './DuelBoard.tsx';
|
||||
import { DuelGate } from './DuelGate.tsx';
|
||||
import { botDeck, hash, mulberry, playerDeck, type BotMatchCard, type DuelBot } from './decks.ts';
|
||||
|
||||
export type { BotMatchCard, DuelBot };
|
||||
|
||||
const HUMAN: Seat = 0, BOT: Seat = 1;
|
||||
const BOT_STEP_MS = 300;
|
||||
|
||||
/**
|
||||
* A bot match in the browser, for eligible players only (BRIEF decisions 2–3): the deck must be
|
||||
* exactly `deckSize` cards the player owns. Off-chain; nothing moves or burns.
|
||||
*/
|
||||
export function DuelBotMatch<S, R extends DuelRulesetLike>({ deck, cards, onExit, onFinish, engine, bot, botPool, rules, playerName = 'You', onMine }: {
|
||||
deck: string[]; cards: BotMatchCard[]; onExit: () => void; onFinish: (matchId?: string) => void;
|
||||
engine: DuelEngineLike<S, R>; bot: DuelBot; botPool: readonly DuelCard[]; rules: R; playerName?: string; onMine?: () => void;
|
||||
}) {
|
||||
const mine = useMemo(() => playerDeck(deck, cards, rules.deckSize), [deck, cards, rules.deckSize]);
|
||||
const [seed] = useState(() => `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`);
|
||||
const [state, setState] = useState<S | null>(null);
|
||||
const [error, setError] = useState<string>();
|
||||
const rng = useRef(mulberry(hash(seed)));
|
||||
const current = useRef<S | null>(null);
|
||||
current.current = state;
|
||||
|
||||
useEffect(() => {
|
||||
if (!mine.cards.length) return;
|
||||
try { setState(engine.createDuel(rules, [mine.cards, botDeck(botPool, rules.deckSize, seed)], seed)); }
|
||||
catch (e) { setError(e instanceof Error ? e.message : 'This deck can’t be played.'); }
|
||||
}, [engine, rules, mine.cards, botPool, seed]);
|
||||
|
||||
// The bot moves one atomic action at a time, so the board shows its plays and declarations.
|
||||
useEffect(() => {
|
||||
if (!state || engine.toAct(state) !== BOT) return;
|
||||
const t = setTimeout(() => {
|
||||
const legal = engine.legalActions(state, BOT);
|
||||
if (!legal.length) return;
|
||||
let a: DuelAction;
|
||||
try { a = bot.choose(engine.viewFor(state, BOT), legal, rng.current); } catch { a = legal[0]; }
|
||||
if (!legal.some(l => JSON.stringify(l) === JSON.stringify(a))) a = legal[0];
|
||||
if (current.current !== state) return;
|
||||
const next = engine.applyAction(state, BOT, a);
|
||||
current.current = next;
|
||||
setState(next);
|
||||
}, BOT_STEP_MS);
|
||||
return () => clearTimeout(t);
|
||||
}, [state, engine, bot]);
|
||||
|
||||
// Applied synchronously through a ref, so a confirmed declaration (toggleAttacker × N, confirmAttack)
|
||||
// sees each previous action, and an illegal action throws back to DuelBoard, which shows the error.
|
||||
const onAct = useCallback((a: DuelAction) => {
|
||||
const s = current.current;
|
||||
if (!s) return;
|
||||
const next = engine.applyAction(s, HUMAN, a);
|
||||
current.current = next;
|
||||
setError(undefined);
|
||||
setState(next);
|
||||
}, [engine]);
|
||||
|
||||
const articles = useMemo<Articles>(() => Object.fromEntries(cards.map(c => [c.tokenId, { image: c.imageUrl, url: c.url, extract: c.extract }])), [cards]);
|
||||
|
||||
if (!mine.cards.length) {
|
||||
if (deck.length < rules.deckSize || mine.missing.length) return <DuelGate owned={deck.length - mine.missing.length} deckSize={rules.deckSize} onExit={onExit} onMine={onMine} />;
|
||||
return <section className="duel-gate"><h2>Card profiles pending</h2>
|
||||
<p className="muted">These cards don’t have a duel profile yet, so they can’t be played: {mine.pending.join(', ')}. Pick other cards for your deck, or try again shortly.</p>
|
||||
<div className="play-actions"><button className="button outline" onClick={onExit}>Back</button></div></section>;
|
||||
}
|
||||
if (!state) return error ? <section className="duel-gate"><h2>Can’t start this match</h2><p className="muted">{error}</p>
|
||||
<div className="play-actions"><button className="button outline" onClick={onExit}>Back</button></div></section> : null;
|
||||
|
||||
const view = engine.viewFor(state, HUMAN);
|
||||
return <DuelBoard view={view} legal={engine.legalActions(state, HUMAN)} onAct={onAct} opponentName={`Bot (${bot.name})`} playerName={playerName}
|
||||
logEvents={engine.logFor(state, HUMAN)} articles={articles} busy={engine.toAct(state) === BOT} error={error}
|
||||
onExit={engine.isOver(state) ? () => onFinish() : onExit} />;
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { BookMarked, BookOpen, Building2, CalendarClock, Globe2, Home, Hourglass, Languages, Link2, MapPin, Shield, ShieldCheck, Sparkles, Sprout, Star, Swords, TrendingUp, UserRound } from 'lucide-react';
|
||||
import type { BoardCard, DuelCardType } from './model.ts';
|
||||
import { cardSummary, typeLine } from './model.ts';
|
||||
|
||||
const TYPE_ICONS: Record<DuelCardType, typeof UserRound> = {
|
||||
Figure: UserRound, Location: MapPin, Event: CalendarClock, Institution: Building2, Doctrine: BookOpen,
|
||||
};
|
||||
export const TypeIcon = ({ type, size = 12 }: { type: DuelCardType; size?: number }) => {
|
||||
const Icon = TYPE_ICONS[type] ?? BookOpen;
|
||||
return <Icon size={size} aria-hidden="true" />;
|
||||
};
|
||||
|
||||
/** Keyword icons for the board face, where a word doesn't fit 62 px. The words are in the label and the zoom face. */
|
||||
const KEYWORD_ICONS: Record<string, typeof Star> = {
|
||||
protected: ShieldCheck, featured: Star, translated: Languages, legacy: Hourglass, stub: Sprout,
|
||||
'well-sourced': BookMarked, multilingual: Globe2, local: Home, trending: TrendingUp, connected: Link2,
|
||||
};
|
||||
export const KeywordIcon = ({ keyword, size = 11 }: { keyword: string; size?: number }) => {
|
||||
const Icon = KEYWORD_ICONS[keyword.toLowerCase()] ?? Sparkles;
|
||||
return <Icon size={size} aria-hidden="true" />;
|
||||
};
|
||||
|
||||
export type FaceSize = 'board' | 'hand' | 'zoom';
|
||||
export type FaceState = { selected?: boolean; attacking?: boolean; blocking?: boolean; target?: boolean; dim?: boolean; fresh?: boolean };
|
||||
|
||||
const statClass = (now?: number, base?: number) => (now === undefined || base === undefined ? '' : now > base ? 'up' : now < base ? 'down' : '');
|
||||
|
||||
function Stats({ card }: { card: BoardCard }) {
|
||||
if (card.power === undefined) return null;
|
||||
const tough = (card.toughness ?? 0) - (card.damage ?? 0);
|
||||
return <span className="dface-pt" aria-hidden="true">
|
||||
<b className={statClass(card.power, card.basePower)}>{card.power}</b>/<b className={card.damage ? 'down' : statClass(card.toughness, card.baseToughness)}>{tough}</b>
|
||||
</span>;
|
||||
}
|
||||
|
||||
function Art({ card, iconSize }: { card: BoardCard; iconSize: number }) {
|
||||
return <span className="dface-art" aria-hidden="true">
|
||||
{card.image ? <img src={card.image} alt="" loading="lazy" decoding="async" referrerPolicy="no-referrer"
|
||||
onError={e => { e.currentTarget.style.display = 'none'; }} /> : null}
|
||||
<TypeIcon type={card.type} size={iconSize} />
|
||||
</span>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The duel card face (MTG layout). Board and hand faces show only what fits a phone: title (2-line
|
||||
* clamp), cost, type icon, P/T and keyword chips. Rules text and flavour live in the zoom face,
|
||||
* which the tap-to-zoom sheet shows (critic S4).
|
||||
*/
|
||||
export function DuelCardFace({ card, size = 'hand', state = {}, onClick, label, refNumber }: {
|
||||
card: BoardCard; size?: FaceSize; state?: FaceState; onClick?: () => void; label?: string; refNumber?: number;
|
||||
}) {
|
||||
const cls = ['dface', `dface-${size}`, `portal-${card.portal.toLowerCase()}`,
|
||||
card.tapped && 'is-tapped', card.pending && 'is-pending', state.selected && 'is-selected', state.attacking && 'is-attacking',
|
||||
state.blocking && 'is-blocking', state.target && 'is-target', state.dim && 'is-dim', state.fresh && 'is-fresh', card.token && 'is-token']
|
||||
.filter(Boolean).join(' ');
|
||||
|
||||
if (size === 'zoom') return <article className={cls} aria-label={cardSummary(card)}>
|
||||
<div className="dface-namebar"><h3 className="dface-name">{card.title}</h3><span className="dface-cost" aria-label={`Cost ${card.cost} Citations`}>{card.cost}</span></div>
|
||||
<Art card={card} iconSize={34} />
|
||||
<p className="dface-typeline"><TypeIcon type={card.type} size={13} /> {typeLine(card)}<span className="dface-portal">{card.portal}</span></p>
|
||||
<div className="dface-textbox">
|
||||
{card.keywords.length > 0 && !card.keywords.every(k => card.rulesText.includes(k)) && <p className="dface-keywords">{card.keywords.join('. ')}.</p>}
|
||||
{card.rulesText && <p className="dface-rules">{card.rulesText}</p>}
|
||||
{card.flavour && <p className="dface-flavour">{card.flavour}{card.url
|
||||
? <sup><a href={card.url} target="_blank" rel="noopener noreferrer" aria-label={`Wikipedia article: ${card.title}`}>[{refNumber ?? 1}]</a></sup>
|
||||
: null}</p>}
|
||||
</div>
|
||||
<div className="dface-footer">
|
||||
<span className="dface-rev">{card.revisionId ? `rev. ${card.revisionId}` : card.token ? 'Token' : ''}</span>
|
||||
<Stats card={card} />
|
||||
</div>
|
||||
</article>;
|
||||
|
||||
const kwShown = card.keywords.slice(0, 2);
|
||||
const Tag = onClick ? 'button' : 'div';
|
||||
return <Tag {...(onClick ? { type: 'button' as const, onClick, 'aria-pressed': state.selected || state.attacking || state.blocking || undefined } : { role: 'img' })}
|
||||
className={cls} aria-label={label ?? cardSummary(card)}>
|
||||
<Art card={card} iconSize={size === 'board' ? 14 : 18} />
|
||||
<span className="dface-cost" aria-hidden="true">{card.cost}</span>
|
||||
{state.attacking && <span className="dface-flag attack" aria-hidden="true"><Swords size={11} /></span>}
|
||||
{state.blocking && <span className="dface-flag block" aria-hidden="true"><Shield size={11} /></span>}
|
||||
<span className="dface-title">{card.title}</span>
|
||||
<span className="dface-bottom">
|
||||
{size === 'board' || kwShown.length > 1
|
||||
? kwShown.map(k => <span key={k} className="dface-kwicon" title={k}><KeywordIcon keyword={k} size={10} /></span>)
|
||||
: kwShown.map(k => <span key={k} className="dface-chip">{k}</span>)}
|
||||
<Stats card={card} />
|
||||
</span>
|
||||
</Tag>;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { Pickaxe } from 'lucide-react';
|
||||
import { eligibility } from './model.ts';
|
||||
import './duel.css';
|
||||
|
||||
/**
|
||||
* Shown instead of a board when the player doesn't own a full deck (BRIEF decisions 1–2). There is
|
||||
* no practice with borrowed cards: the only way forward is mining (or trading) for real cards.
|
||||
*/
|
||||
export function DuelGate({ owned, deckSize, onMine, onExit }: { owned: number; deckSize: number; onMine?: () => void; onExit?: () => void }) {
|
||||
const e = eligibility(owned, deckSize);
|
||||
const pct = Math.round((Math.min(owned, deckSize) / deckSize) * 100);
|
||||
return <section className="duel-gate" aria-labelledby="duel-gate-title">
|
||||
<div className="section-eyebrow">DUEL · {deckSize}-CARD DECKS</div>
|
||||
<h2 id="duel-gate-title">{e.label}</h2>
|
||||
<div className="duel-gate-bar" role="progressbar" aria-valuemin={0} aria-valuemax={deckSize} aria-valuenow={Math.min(owned, deckSize)} aria-label="Cards owned"><i style={{ width: `${pct}%` }} /></div>
|
||||
<p className="muted">A duel deck is exactly {deckSize} cards, and every one is an NFT you own. You need {e.needed} more.
|
||||
Each block you mine is a new card: a random Wikipedia article, frozen with its stats at the moment it was mined.
|
||||
Trades with other players count too. Matches never move or burn your cards.</p>
|
||||
<div className="play-actions">
|
||||
{onExit && <button className="button outline" onClick={onExit}>Back</button>}
|
||||
{onMine && <button className="button dark" onClick={onMine}><Pickaxe size={16} /> Mine cards</button>}
|
||||
</div>
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { useState } from 'react';
|
||||
import { DuelCardFace } from './DuelCardFace.tsx';
|
||||
import { DuelTable } from './DuelTable.tsx';
|
||||
import { PREVIEW_POOL, previewView } from './mock.ts';
|
||||
import type { DuelUIAction } from './model.ts';
|
||||
|
||||
type Scene = 'main' | 'attack' | 'block' | 'over' | 'cards';
|
||||
const SCENES: Scene[] = ['main', 'attack', 'block', 'over', 'cards'];
|
||||
const ZOOM = ['Jess Harnell', 'Agda (programming language)', "April 2021 nor'easter", 'Pathrail Mosque', 'Hiroshima Electric Railway', 'Heart rot'];
|
||||
|
||||
/** Static board scenes from card-sample.json, for screenshots and review (`#duel-preview/<scene>`). Not a match. */
|
||||
export function DuelPreview() {
|
||||
const initial = (location.hash.split('/')[1] as Scene) || 'main';
|
||||
const [scene, setScene] = useState<Scene>(SCENES.includes(initial) ? initial : 'main');
|
||||
const [acted, setActed] = useState<string[]>([]);
|
||||
const { view, legal } = previewView(scene === 'cards' ? 'main' : scene);
|
||||
const onAct = (a: DuelUIAction) => setActed(l => [...l, JSON.stringify(a)]);
|
||||
return <div className="duel-preview-page" style={{ padding: 0 }}>
|
||||
<nav className="category-tabs" aria-label="Preview scene" style={{ padding: '4px 8px', display: location.hash.includes('clean') ? 'none' : undefined }}>
|
||||
{SCENES.map(s => <button key={s} className={s === scene ? 'selected' : ''} onClick={() => { setScene(s); location.hash = `duel-preview/${s}`; }}>{s}</button>)}
|
||||
{acted.length > 0 && <small style={{ marginLeft: 8 }}>last action: {acted.at(-1)}</small>}
|
||||
</nav>
|
||||
{scene === 'cards' ? <div className="duel" style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(280px,1fr))', gap: 16, padding: 12 }}>
|
||||
{ZOOM.map(t => PREVIEW_POOL.find(c => c.title === t)).filter(c => !!c).map((c, i) => <DuelCardFace key={c.id} card={c} size="zoom" refNumber={i + 1} />)}
|
||||
</div> : <DuelTable key={scene} view={{ ...view, log: [...view.log, ...acted.map(a => `(preview) ${a}`)] }} legal={legal} onAct={onAct} />}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
|
||||
import { Award, Flag, Hand, Library, LoaderCircle, Quote, ScrollText, Shield, Swords, Timer, X } from 'lucide-react';
|
||||
import { DuelCardFace } from './DuelCardFace.tsx';
|
||||
import '../play.css';
|
||||
import './duel.css';
|
||||
import {
|
||||
EMPTY_DECL, blockList, isMyTurn, nextTargets, playerTarget, previewCombat, targetsComplete, tapAttacker, tapBlocker, toggleAttacker,
|
||||
type Attack, type BoardCard, type Seat, type BoardView, type Declaration, type DuelUIAction, type Legal, type SideView,
|
||||
} from './model.ts';
|
||||
|
||||
type Sheet =
|
||||
| { kind: 'card'; card: BoardCard; where: 'hand' | 'mine' | 'theirs' }
|
||||
| { kind: 'combat'; attacks: Attack[]; mode: 'attack' | 'block' }
|
||||
| { kind: 'log' } | { kind: 'concede' } | null;
|
||||
|
||||
const PHASE_LABEL: Record<BoardView['phase'], string> = {
|
||||
mulligan: 'Opening hand', main: 'Main', attack: 'Combat', block: 'Blocks', over: 'Match over',
|
||||
};
|
||||
|
||||
function SideBar({ side, who, active, target, onTarget }: { side: SideView; who: 'me' | 'opponent'; active: boolean; target?: boolean; onTarget?: () => void }) {
|
||||
const label = `${who === 'me' ? 'You' : side.name}: ${side.notability} Notability, ${side.citations} of ${side.maxCitations} Citations, ${side.library} in library, ${side.hand} in hand`;
|
||||
const Tag = target ? 'button' : 'div';
|
||||
return <Tag className={`duel-side ${who} ${active ? 'is-active' : ''} ${target ? 'is-target' : ''}`} {...(target ? { type: 'button' as const, onClick: onTarget } : { role: 'group' })} aria-label={target ? `Target ${who === 'me' ? 'yourself' : side.name}. ${label}` : label}>
|
||||
<span className="duel-side-name">{who === 'me' ? 'You' : side.name}</span>
|
||||
<span className={`duel-stat life ${side.notability <= 5 ? 'low' : ''}`} title="Notability"><Award size={14} aria-hidden="true" /><b>{side.notability}</b></span>
|
||||
<span className="duel-stat cites" title="Citations"><Quote size={13} aria-hidden="true" /><b>{side.citations}</b><small>/{side.maxCitations}</small></span>
|
||||
<span className="duel-stat" title="Library"><Library size={13} aria-hidden="true" />{side.library}</span>
|
||||
<span className="duel-stat" title="Hand"><Hand size={13} aria-hidden="true" />{side.hand}</span>
|
||||
</Tag>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The duel table (presentational), 360 × 740 first. Controllers (local bot, PvP host) feed it a BoardView and the
|
||||
* legal moves, and get DuelUIActions back. Attack: tap a Figure (1 tap). Block: tap your Figure,
|
||||
* then the attacker (2 taps). Both go through a preview → confirm sheet; no drawn arrows.
|
||||
*/
|
||||
export function DuelTable({ view, legal, onAct, busy, error, onExit, onRecap }: {
|
||||
view: BoardView; legal: Legal; onAct: (a: DuelUIAction) => void; busy?: boolean; error?: string;
|
||||
onExit?: () => void; onRecap?: () => void;
|
||||
}) {
|
||||
const [sheet, setSheet] = useState<Sheet>(null);
|
||||
const [decl, setDecl] = useState<Declaration>(EMPTY_DECL);
|
||||
const [targeting, setTargeting] = useState<{ cardId: string; chosen: string[] }>();
|
||||
const logRef = useRef<HTMLOListElement>(null);
|
||||
// Hand overflow cue (QA #58): how many hand cards are past the right edge.
|
||||
const handRef = useRef<HTMLDivElement>(null);
|
||||
const [hiddenRight, setHiddenRight] = useState(0);
|
||||
useEffect(() => {
|
||||
const el = handRef.current;
|
||||
if (!el) return;
|
||||
const measure = () => {
|
||||
const edge = el.getBoundingClientRect().right;
|
||||
setHiddenRight([...el.children].filter(c => c.getBoundingClientRect().left > edge - 24).length);
|
||||
};
|
||||
measure();
|
||||
el.addEventListener('scroll', measure, { passive: true });
|
||||
const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(measure) : null;
|
||||
ro?.observe(el);
|
||||
return () => { el.removeEventListener('scroll', measure); ro?.disconnect(); };
|
||||
}, [view.hand.length]);
|
||||
|
||||
const mine = isMyTurn(view);
|
||||
const oppSeat = (1 - view.seat) as Seat;
|
||||
const attackMode = mine && view.phase === 'attack' && !busy;
|
||||
const blockMode = !mine && view.phase === 'block' && view.combat.length > 0 && !busy;
|
||||
const stepKey = `${view.turn}:${view.active}:${view.phase}`;
|
||||
useEffect(() => { setDecl(EMPTY_DECL); setTargeting(undefined); }, [stepKey]);
|
||||
useEffect(() => { logRef.current?.lastElementChild?.scrollIntoView?.({ block: 'nearest' }); }, [view.log.length]);
|
||||
|
||||
const cards = useMemo(() => new Map([...view.me.battlefield, ...view.opponent.battlefield, ...view.hand].map(c => [c.id, c])), [view]);
|
||||
const attackingIds = new Set(view.combat.map(a => a.attackerId));
|
||||
const targets = targeting ? nextTargets(legal.plays[targeting.cardId], targeting.chosen) : null;
|
||||
const refs = useMemo(() => { const m = new Map<string, number>(); for (const c of cards.values()) if (c.url && !m.has(c.url)) m.set(c.url, m.size + 1); return m; }, [cards]);
|
||||
|
||||
const play = (cardId: string, targetIds: string[]) => { setTargeting(undefined); setSheet(null); onAct({ type: 'play', cardId, targetIds }); };
|
||||
const startPlay = (card: BoardCard) => {
|
||||
const seqs = legal.plays[card.id];
|
||||
if (!seqs) return;
|
||||
if (targetsComplete(seqs, [])) play(card.id, []); else { setTargeting({ cardId: card.id, chosen: [] }); setSheet(null); }
|
||||
};
|
||||
const chooseTarget = (id: string) => {
|
||||
if (!targeting || !targets?.has(id)) return;
|
||||
const chosen = [...targeting.chosen, id];
|
||||
if (targetsComplete(legal.plays[targeting.cardId], chosen) && !nextTargets(legal.plays[targeting.cardId], chosen).size) play(targeting.cardId, chosen);
|
||||
else setTargeting({ ...targeting, chosen });
|
||||
};
|
||||
|
||||
const tapMine = (c: BoardCard) => {
|
||||
if (targets) { chooseTarget(c.id); return; }
|
||||
if (attackMode && legal.attackers.includes(c.id)) { setDecl(d => toggleAttacker(d, c.id, legal)); return; }
|
||||
if (blockMode && (legal.blockers[c.id]?.length || decl.blocks[c.id])) { setDecl(d => tapBlocker(d, c.id, legal)); return; }
|
||||
setSheet({ kind: 'card', card: c, where: 'mine' });
|
||||
};
|
||||
const tapTheirs = (c: BoardCard) => {
|
||||
if (targets) { chooseTarget(c.id); return; }
|
||||
if (blockMode && attackingIds.has(c.id) && (decl.picked || Object.values(decl.blocks).includes(c.id))) { setDecl(d => tapAttacker(d, c.id, legal)); return; }
|
||||
setSheet({ kind: 'card', card: c, where: 'theirs' });
|
||||
};
|
||||
|
||||
const blockedBy = (attackerId: string) => Object.entries(decl.blocks).find(([, a]) => a === attackerId)?.[0];
|
||||
const pendingAttacks: Attack[] = attackMode ? decl.attackers.map(attackerId => ({ attackerId }))
|
||||
: blockMode ? view.combat.map(a => ({ attackerId: a.attackerId, blockerId: blockedBy(a.attackerId) })) : view.combat;
|
||||
|
||||
const stateFor = (c: BoardCard, side: 'mine' | 'theirs') => {
|
||||
const t = targets?.has(c.id);
|
||||
if (side === 'mine') return {
|
||||
attacking: attackMode ? decl.attackers.includes(c.id) : attackingIds.has(c.id),
|
||||
blocking: !!decl.blocks[c.id] || view.combat.some(a => a.blockerId === c.id),
|
||||
selected: decl.picked === c.id,
|
||||
target: t,
|
||||
dim: (targets && !t) || (attackMode && c.type === 'Figure' && !legal.attackers.includes(c.id)) || (blockMode && !legal.blockers[c.id]?.length && !decl.blocks[c.id]),
|
||||
};
|
||||
const canBeBlocked = !!decl.picked && !!legal.blockers[decl.picked]?.includes(c.id);
|
||||
return { attacking: attackingIds.has(c.id), target: t || canBeBlocked, blocking: view.combat.some(a => a.blockerId === c.id), dim: (targets && !t) || (!!decl.picked && !canBeBlocked) };
|
||||
};
|
||||
|
||||
const row = (list: BoardCard[], side: 'mine' | 'theirs') => {
|
||||
const top = list.filter(c => !c.attachedTo);
|
||||
return <div className={`duel-row ${side}`} aria-label={side === 'mine' ? 'Your battlefield' : 'Opponent battlefield'}>
|
||||
{top.length ? top.map(c => <div key={c.id} className="duel-slot">
|
||||
<DuelCardFace card={c} size="board" state={stateFor(c, side)} onClick={() => (side === 'mine' ? tapMine(c) : tapTheirs(c))} />
|
||||
{!!c.attachments?.length && <span className="duel-attach" aria-label={`${c.attachments.length} Doctrine attached`}>+{c.attachments.length}</span>}
|
||||
{blockMode && side === 'theirs' && blockedBy(c.id) && <span className="duel-pair" aria-hidden="true">{cards.get(blockedBy(c.id)!)?.title}</span>}
|
||||
</div>) : <span className="duel-empty">No permanents</span>}
|
||||
</div>;
|
||||
};
|
||||
|
||||
// ---------- primary action ----------
|
||||
const nAtt = decl.attackers.length, nBlk = Object.keys(decl.blocks).length;
|
||||
let note: ReactNode = view.log.at(-1) ?? '';
|
||||
let primary: { label: string; run: () => void; disabled?: boolean } | null = null;
|
||||
let secondary: { label: string; run: () => void } | null = null;
|
||||
if (view.phase === 'over') {
|
||||
// The engine's own game-over sentence (DUEL_DESIGN §8.2); the board never writes story text itself.
|
||||
note = <span><b>{view.winner === 'draw' ? 'Draw.' : view.winner === view.seat ? 'You won.' : 'You lost.'}</b> {view.log.at(-1)}</span>;
|
||||
primary = onRecap ? { label: 'Battle recap', run: onRecap } : onExit ? { label: 'Done', run: onExit } : null;
|
||||
if (onRecap && onExit) secondary = { label: 'Done', run: onExit };
|
||||
} else if (busy) {
|
||||
note = <><LoaderCircle className="spin" size={14} /> {mine ? 'Resolving…' : `${view.opponent.name} is choosing…`}</>;
|
||||
} else if (legal.mulligan) {
|
||||
note = 'Keep this hand, or mulligan once: shuffle, draw 7, put 1 on the bottom.';
|
||||
primary = { label: 'Keep hand', run: () => onAct({ type: 'mulligan', keep: true }) };
|
||||
secondary = { label: 'Mulligan', run: () => onAct({ type: 'mulligan', keep: false }) };
|
||||
} else if (targeting) {
|
||||
const c = cards.get(targeting.cardId);
|
||||
note = <>{targeting.chosen.length ? 'Now choose the next target' : 'Choose a target'} for <b>{c?.title}</b>.</>;
|
||||
secondary = { label: 'Cancel', run: () => setTargeting(undefined) };
|
||||
} else if (attackMode) {
|
||||
note = nAtt ? `${nAtt} attacking. Tap a Figure to add or remove it.` : legal.attackers.length ? 'Tap Figures to attack with them.' : 'No Figure can attack.';
|
||||
primary = { label: nAtt ? `Attack with ${nAtt}` : 'No attack', run: () => (nAtt ? setSheet({ kind: 'combat', attacks: pendingAttacks, mode: 'attack' }) : onAct({ type: 'attack', attackerIds: [] })) };
|
||||
} else if (blockMode) {
|
||||
note = decl.picked ? <>Now tap the attacker <b>{cards.get(decl.picked)?.title}</b> blocks.</> : `${view.combat.length} attacking. Tap your Figure, then the attacker it blocks.`;
|
||||
primary = { label: nBlk ? `Review ${nBlk} block${nBlk > 1 ? 's' : ''}` : 'Review: no blocks', run: () => setSheet({ kind: 'combat', attacks: pendingAttacks, mode: 'block' }) };
|
||||
} else if (mine && view.phase === 'main') {
|
||||
note = Object.keys(legal.plays).length ? 'Tap a card in your hand to read or play it.' : note;
|
||||
if (legal.canGoToCombat && legal.attackers.length) { primary = { label: 'Combat', run: () => onAct({ type: 'toCombat' }) }; secondary = legal.canEndTurn ? { label: 'End turn', run: () => onAct({ type: 'endTurn' }) } : null; }
|
||||
else if (legal.canEndTurn) primary = { label: 'End turn', run: () => onAct({ type: 'endTurn' }) };
|
||||
} else if (mine && legal.canEndTurn) {
|
||||
primary = { label: 'End turn', run: () => onAct({ type: 'endTurn' }) };
|
||||
} else if (!mine) {
|
||||
note = <><LoaderCircle className="spin" size={14} /> {view.opponent.name}’s turn.</>;
|
||||
}
|
||||
|
||||
const outcome = sheet?.kind === 'combat' ? previewCombat(sheet.attacks, cards) : null;
|
||||
|
||||
return <section className="duel" aria-label={`Duel against ${view.opponent.name}`}>
|
||||
<header className="duel-bar">
|
||||
<span className="duel-turn">Turn <b>{view.turn}</b> · {PHASE_LABEL[view.phase]}{view.active !== view.seat && view.phase !== 'over' ? ` · ${view.opponent.name}` : ''}</span>
|
||||
{view.clock && view.phase !== 'over' && <span className={`duel-clock ${view.clock.turn <= 10 ? 'low' : ''}`} aria-label={`${view.clock.turn} seconds left this turn, ${view.clock.bank} in the bank`}><Timer size={13} aria-hidden="true" />{view.clock.turn}s<small>+{Math.floor(view.clock.bank / 60)}:{String(view.clock.bank % 60).padStart(2, '0')}</small></span>}
|
||||
<button className="icon-button duel-log-button" onClick={() => setSheet({ kind: 'log' })} aria-label="Match log"><ScrollText size={16} /></button>
|
||||
{view.phase !== 'over' && <button className="icon-button" onClick={() => setSheet({ kind: 'concede' })} aria-label="Concede match"><Flag size={16} /></button>}
|
||||
</header>
|
||||
|
||||
<div className="duel-main">
|
||||
<div className="duel-field">
|
||||
<SideBar side={view.opponent} who="opponent" active={view.active !== view.seat} target={targets?.has(playerTarget(oppSeat))} onTarget={() => chooseTarget(playerTarget(oppSeat))} />
|
||||
{row(view.opponent.battlefield, 'theirs')}
|
||||
<button className="duel-ticker" onClick={() => setSheet({ kind: 'log' })} aria-label="Open match log">
|
||||
{(attackMode || blockMode) && <span className="duel-ticker-phase">{attackMode ? <Swords size={12} /> : <Shield size={12} />}</span>}
|
||||
<span>{view.log.at(-1) ?? 'The match began.'}</span>
|
||||
</button>
|
||||
{row(view.me.battlefield, 'mine')}
|
||||
<SideBar side={view.me} who="me" active={view.active === view.seat} target={targets?.has(playerTarget(view.seat))} onTarget={() => chooseTarget(playerTarget(view.seat))} />
|
||||
</div>
|
||||
<aside className="duel-log-aside" aria-label="Match log">
|
||||
<h3>Log</h3>
|
||||
<ol ref={logRef} className="duel-log">{view.log.map((l, i) => <li key={i}>{l}</li>)}</ol>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
<div className="duel-dock">
|
||||
<div className="duel-hand-wrap">
|
||||
<div ref={handRef} className={`duel-hand ${hiddenRight ? 'has-more' : ''}`} aria-label={`Your hand, ${view.hand.length} cards`}>
|
||||
{view.hand.length ? view.hand.map(c => {
|
||||
const playable = !!legal.plays[c.id] && !busy;
|
||||
return <DuelCardFace key={c.id} card={c} size="hand" state={{ dim: !playable || !!targeting, selected: targeting?.cardId === c.id }}
|
||||
onClick={() => setSheet({ kind: 'card', card: c, where: 'hand' })} />;
|
||||
}) : <span className="duel-empty">No cards in hand.</span>}
|
||||
</div>
|
||||
{hiddenRight > 0 && <button type="button" className="duel-hand-more" aria-label={`${hiddenRight} more cards in hand: scroll right`} onClick={() => handRef.current?.scrollBy({ left: handRef.current.clientWidth * 0.8, behavior: 'smooth' })}>+{hiddenRight}</button>}
|
||||
</div>
|
||||
<p className="duel-note" role="status" aria-live="polite">{error ? <span className="dock-error">{error}</span> : note}</p>
|
||||
<div className="duel-actions">
|
||||
{secondary && <button className="button outline" onClick={secondary.run}>{secondary.label}</button>}
|
||||
{primary && <button className="button dark duel-primary" onClick={primary.run} disabled={primary.disabled}>{primary.label}</button>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{sheet && <div className="sheet-backdrop" onClick={e => { if (e.target === e.currentTarget) setSheet(null); }}>
|
||||
<div className={`sheet duel-sheet ${sheet.kind}`} role="dialog" aria-modal="true" aria-label={sheet.kind === 'card' ? sheet.card.title : sheet.kind === 'log' ? 'Match log' : sheet.kind === 'combat' ? 'Combat preview' : 'Concede'}>
|
||||
<button className="modal-close" onClick={() => setSheet(null)} aria-label="Close"><X size={18} /></button>
|
||||
{sheet.kind === 'card' && <>
|
||||
<DuelCardFace card={sheet.card} size="zoom" refNumber={sheet.card.url ? refs.get(sheet.card.url) : undefined} />
|
||||
<p className="muted small duel-sheet-meta">{sheet.where === 'theirs' ? `${view.opponent.name}’s card` : sheet.where === 'hand' ? 'In your hand' : 'Your card'}
|
||||
{sheet.card.tapped ? ' · tapped' : ''}{sheet.card.pending ? ' · Pending review (can’t attack this turn)' : ''}{sheet.card.damage ? ` · ${sheet.card.damage} damage marked` : ''}</p>
|
||||
{sheet.card.connectedNote && <p className="small duel-sheet-meta">Connected: {sheet.card.connectedNote}</p>}
|
||||
{sheet.where === 'hand' && <div className="play-actions">
|
||||
{legal.plays[sheet.card.id] && !busy
|
||||
? <button className="button dark" onClick={() => startPlay(sheet.card)}>{targetsComplete(legal.plays[sheet.card.id], []) ? `Play for ${sheet.card.cost}` : `Play for ${sheet.card.cost}, then choose a target`}</button>
|
||||
: <p className="muted small">{!mine ? 'You can play cards on your turn.' : view.phase !== 'main' ? 'Cards are played in your main phase.' : sheet.card.cost > view.me.citations ? `Needs ${sheet.card.cost} Citations; you have ${view.me.citations}.` : 'No legal target.'}</p>}
|
||||
</div>}
|
||||
</>}
|
||||
{sheet.kind === 'combat' && outcome && <>
|
||||
<h3>{sheet.mode === 'attack' ? 'Declare attackers' : 'Declare blockers'}</h3>
|
||||
<ul className="duel-preview">
|
||||
{outcome.rows.map(r => <li key={r.attacker.id}>
|
||||
<span className={r.attackerDies ? 'gone' : ''}>{r.attacker.title} <small>{r.attacker.power}/{r.attacker.toughness}</small></span>
|
||||
<span className="vs">{r.blocker ? 'blocked by' : sheet.mode === 'attack' ? '→' : 'unblocked →'}</span>
|
||||
{r.blocker ? <span className={r.blockerDies ? 'gone' : ''}>{r.blocker.title} <small>{r.blocker.power}/{r.blocker.toughness}</small></span>
|
||||
: <span>{sheet.mode === 'attack' ? view.opponent.name : 'you'} −{r.attacker.power ?? 0}</span>}
|
||||
</li>)}
|
||||
</ul>
|
||||
<p className="muted small">{sheet.mode === 'attack'
|
||||
? `If unblocked: ${outcome.toPlayer} damage to ${view.opponent.name} (${view.opponent.notability} → ${Math.max(0, view.opponent.notability - outcome.toPlayer)}). ${view.opponent.name} chooses blocks next.`
|
||||
: `You take ${outcome.toPlayer} (${view.me.notability} → ${Math.max(0, view.me.notability - outcome.toPlayer)}).${outcome.destroyed.length ? ` Struck through: destroyed.` : ''}`}</p>
|
||||
<div className="play-actions">
|
||||
<button className="button outline" onClick={() => setSheet(null)}>Change</button>
|
||||
<button className="button dark" onClick={() => { setSheet(null); onAct(sheet.mode === 'attack' ? { type: 'attack', attackerIds: decl.attackers } : { type: 'block', blocks: blockList(decl) }); }}>
|
||||
{sheet.mode === 'attack' ? <><Swords size={15} /> Confirm attack</> : <><Shield size={15} /> Confirm blocks</>}
|
||||
</button>
|
||||
</div>
|
||||
</>}
|
||||
{sheet.kind === 'log' && <><h3>Match log</h3>
|
||||
<ol className="duel-log full">{view.log.map((l, i) => <li key={i}>{l}</li>)}</ol></>}
|
||||
{sheet.kind === 'concede' && <><h3>Concede this match?</h3><p className="muted">It counts as a loss. Nothing on-chain changes.</p>
|
||||
<div className="play-actions"><button className="button outline" onClick={() => setSheet(null)}>Keep playing</button>
|
||||
<button className="button dark" onClick={() => { setSheet(null); onAct({ type: 'concede' }); }}><Flag size={15} /> Concede</button></div></>}
|
||||
</div>
|
||||
</div>}
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// QA ONLY (branch night2/ui-duel/engine-preview, never merged): a real bot match on duel-core's
|
||||
// engine-wip with duel-cards' derived sample. The player's "deck" is 40 sample cards, because QA has no
|
||||
// wallet here; the real DuelBotMatch only takes owned cards. Route: #duel-live[/<easy|normal>].
|
||||
import sample from '../../../docs/game/duel-card-sample.json';
|
||||
import { duelEngine, DEFAULT_DUEL_RULESET } from '../../../shared/duel/index.ts';
|
||||
import type { DuelCard } from './contract.ts';
|
||||
import { EASY_BOT, NORMAL_BOT } from './bots.ts';
|
||||
import { DuelBotMatch } from './DuelBotMatch.tsx';
|
||||
|
||||
const POOL = (sample as unknown as { cards: DuelCard[] }).cards;
|
||||
const mine = POOL.slice(0, 40);
|
||||
const cards = mine.map(c => ({ tokenId: c.cardId, title: c.title, duel: c }));
|
||||
const botPool = POOL.slice(40);
|
||||
|
||||
export function LivePreview() {
|
||||
const bot = location.hash.includes('easy') ? EASY_BOT : NORMAL_BOT;
|
||||
return <DuelBotMatch deck={cards.map(c => c.tokenId)} cards={cards} engine={duelEngine} rules={DEFAULT_DUEL_RULESET} bot={bot} botPool={botPool}
|
||||
playerName="QA" onExit={() => { location.hash = '#duel-live'; location.reload(); }} onFinish={() => { location.hash = '#duel-live'; location.reload(); }} />;
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
// duel-core (shared/duel) ↔ the board's view model. The only file that knows engine shapes.
|
||||
import type { DuelAction, LogEvent, PermanentView, PlayerView, Seat, TargetRef } from './contract.ts';
|
||||
import { boardCard, type ArticleBits } from './cards.ts';
|
||||
import type { Attack, BoardCard, BoardView, DuelUIAction, Legal, SideView } from './model.ts';
|
||||
import { NO_LEGAL } from './model.ts';
|
||||
|
||||
export const targetId = (t: TargetRef) => (t.kind === 'card' ? t.uid : `player:${t.seat}`);
|
||||
const targetRef = (id: string): TargetRef => (id.startsWith('player:') ? { kind: 'player', seat: Number(id.slice(7)) as Seat } : { kind: 'card', uid: id });
|
||||
|
||||
export type Articles = Record<string, ArticleBits | undefined>;
|
||||
|
||||
function permanentCard(p: PermanentView, all: PermanentView[], articles: Articles): BoardCard {
|
||||
const keywords: string[] = [...p.keywords];
|
||||
if (p.connected) keywords.push('Connected');
|
||||
return boardCard(p.card, articles[p.card.cardId], {
|
||||
id: p.uid, power: p.card.type === 'Figure' || (p.card.toughness ?? 0) > 0 ? p.power : undefined,
|
||||
toughness: p.card.type === 'Figure' || (p.card.toughness ?? 0) > 0 ? p.toughness : undefined,
|
||||
keywords, tapped: p.tapped, pending: p.card.type === 'Figure' && p.sick, damage: p.damage || undefined,
|
||||
attachedTo: p.attachedTo, attachments: all.filter(x => x.attachedTo === p.uid).map(x => x.uid), token: p.card.token,
|
||||
connectedNote: p.connected ? `${p.connected.tier} (${p.connected.via}): +${p.connected.bonus}/+${p.connected.bonus}` : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
export function boardFromView(v: PlayerView, names: [string, string], log: string[], articles: Articles = {}, clock?: BoardView['clock']): BoardView {
|
||||
const opp = (1 - v.seat) as Seat;
|
||||
const side = (s: PlayerView['opponent'], name: string, seat: Seat): SideView => ({
|
||||
name, notability: s.life, citations: s.citations, maxCitations: s.maxCitations, library: s.librarySize, hand: s.handSize,
|
||||
battlefield: v.battlefield.filter(p => p.controller === seat).map(p => permanentCard(p, v.battlefield, articles)), graveyard: s.graveyard.length,
|
||||
});
|
||||
const blockerOf = Object.fromEntries(Object.entries(v.combat.blocks).map(([b, a]) => [a, b]));
|
||||
const combat: Attack[] = v.combat.attackers.map(a => ({ attackerId: a, blockerId: blockerOf[a] }));
|
||||
return {
|
||||
seat: v.seat, turn: v.turn, active: v.active, phase: v.phase,
|
||||
me: side(v.you, names[v.seat], v.seat), opponent: side(v.opponent, names[opp], opp),
|
||||
hand: v.you.hand.map(i => boardCard(i.card, articles[i.card.cardId], { id: i.uid })),
|
||||
combat, log, winner: v.result ? (v.result.winner ?? 'draw') : undefined, clock,
|
||||
};
|
||||
}
|
||||
|
||||
export function legalFromActions(actions: DuelAction[]): Legal {
|
||||
if (!actions.length) return NO_LEGAL;
|
||||
const legal: Legal = { plays: {}, canGoToCombat: false, attackers: [], blockers: {}, canEndTurn: false, mulligan: false };
|
||||
for (const a of actions) {
|
||||
switch (a.type) {
|
||||
case 'play': (legal.plays[a.uid] ??= []).push((a.targets ?? []).map(targetId)); break;
|
||||
case 'endPhase': legal.canGoToCombat = true; legal.canEndTurn = true; break;
|
||||
case 'toggleAttacker': legal.attackers.push(a.uid); break;
|
||||
case 'confirmAttack': legal.canEndTurn = true; break;
|
||||
case 'block': (legal.blockers[a.blocker] ??= []).push(a.attacker); break;
|
||||
case 'keep': case 'mulligan': legal.mulligan = true; break;
|
||||
}
|
||||
}
|
||||
return legal;
|
||||
}
|
||||
|
||||
/**
|
||||
* One board intent → duel-core's atomic actions, in send order. Single-step intents return the exact
|
||||
* element of `legal` (so the host's deep-equal check passes); declarations are staged on the board and
|
||||
* sent here as toggle/block × N then confirm (DUEL_API: declarations are monotonic).
|
||||
*/
|
||||
export function expand(ui: DuelUIAction, legal: DuelAction[]): DuelAction[] {
|
||||
const find = (pred: (a: DuelAction) => boolean) => legal.find(pred);
|
||||
switch (ui.type) {
|
||||
case 'mulligan': return [ui.keep ? { type: 'keep' } : { type: 'mulligan' }];
|
||||
case 'play': {
|
||||
const want = ui.targetIds.join('|');
|
||||
const a = find(x => x.type === 'play' && x.uid === ui.cardId && (x.targets ?? []).map(targetId).join('|') === want);
|
||||
return a ? [a] : [{ type: 'play', uid: ui.cardId, ...(ui.targetIds.length ? { targets: ui.targetIds.map(targetRef) } : {}) }];
|
||||
}
|
||||
case 'toCombat': return [{ type: 'endPhase' }];
|
||||
case 'endTurn': return find(x => x.type === 'endPhase') ? [{ type: 'endPhase' }, { type: 'confirmAttack' }] : [{ type: 'confirmAttack' }];
|
||||
case 'attack': return [...ui.attackerIds.map(uid => ({ type: 'toggleAttacker', uid }) as DuelAction), { type: 'confirmAttack' }];
|
||||
case 'block': return [...ui.blocks.map(b => ({ type: 'block', blocker: b.blockerId, attacker: b.attackerId }) as DuelAction), { type: 'confirmBlocks' }];
|
||||
case 'concede': return [{ type: 'concede' }];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fallback log text, used only until duel-design's story renderer (shared/duel/story, DUEL_DESIGN §8.2)
|
||||
* can read engine events. First variant of each §8.2 template, real card and match data only.
|
||||
*/
|
||||
export function plainLog(events: LogEvent[], names: [string, string]): string[] {
|
||||
const out: string[] = [];
|
||||
for (const e of events) {
|
||||
const n = (s: Seat) => names[s];
|
||||
switch (e.kind) {
|
||||
case 'turnStart': out.push(`Turn ${e.turn}.`); break;
|
||||
case 'mulligan': out.push(`${n(e.seat)} took a mulligan.`); break;
|
||||
case 'deploy': out.push(`${n(e.seat)} deployed ${e.card.title}.`); break;
|
||||
case 'cast': out.push(`${n(e.seat)} cited ${e.card.title}.`); break;
|
||||
case 'adopt': out.push(`${e.to.title} adopted ${e.card.title}.`); break;
|
||||
case 'tokenCreated': out.push(`${e.source.title} created ${e.card.title}.`); break;
|
||||
case 'attack': out.push(`${e.attackers.map(a => `${a.title} (${a.power}/${a.toughness})`).join(', ')} attacked.`); break;
|
||||
case 'block': for (const b of e.blocks) out.push(`${b.blocker.title} blocked ${b.attacker.title}.`); break;
|
||||
case 'playerDamage': out.push(`${n(e.seat)} lost ${e.amount} Notability (${e.life} remaining).`); break;
|
||||
case 'lifeGain': out.push(`${n(e.seat)} gained ${e.amount} Notability (${e.life}).`); break;
|
||||
case 'destroyed': out.push(`${e.card.title} was moved to Deleted.`); break;
|
||||
case 'bounced': out.push(`${e.card.title} was returned to ${n(e.owner)}'s hand.`); break;
|
||||
case 'connected': out.push(`${e.card.title} was Connected to ${e.with.title} (${e.tier}).`); break;
|
||||
case 'concede': out.push(`${n(e.seat)} withdrew.`); break;
|
||||
case 'gameOver': out.push(e.winner === null ? `The match ended in a draw on turn ${e.turn}.`
|
||||
: e.reason === 'life' ? `${n((1 - e.winner) as Seat)} was nominated for deletion. The result was delete.`
|
||||
: e.reason === 'library' ? `${n((1 - e.winner) as Seat)} could not draw a card and lost.`
|
||||
: `${n(e.winner)} won on turn ${e.turn}.`); break;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
// View-only fallback duel bots for the browser bot match. They see only `viewFor` output (Night 1 rule, #5).
|
||||
// sim-balance owns the real duel bots (shared/bots/duel-bots.ts); these are swapped for its heuristic
|
||||
// once a PlayerView lens exists (#64). Deterministic given the rng.
|
||||
import type { DuelAction, PermanentView, PlayerView, Seat } from './contract.ts';
|
||||
import type { DuelBot } from './decks.ts';
|
||||
|
||||
const value = (p: PermanentView) => p.power + p.toughness + p.keywords.length;
|
||||
const opp = (s: Seat) => (1 - s) as Seat;
|
||||
|
||||
function chooseNormal(v: PlayerView, legal: DuelAction[], rng: () => number): DuelAction {
|
||||
const me = v.seat, them = opp(me);
|
||||
const mine = v.battlefield.filter(p => p.controller === me), theirs = v.battlefield.filter(p => p.controller === them);
|
||||
const find = <T extends DuelAction['type']>(t: T) => legal.filter((a): a is Extract<DuelAction, { type: T }> => a.type === t);
|
||||
|
||||
if (find('keep').length) return find('keep')[0];
|
||||
|
||||
const plays = find('play');
|
||||
if (plays.length) {
|
||||
const hand = new Map(v.you.hand.map(i => [i.uid, i.card]));
|
||||
// Prefer the most expensive card. Targets: harmful effects (damage, destroy, bounce, tap, fight, a
|
||||
// negative pump) aim at the opponent's side; everything else (pumps, Adopt) at ours.
|
||||
const owner = (uid: string) => v.battlefield.find(p => p.uid === uid)?.controller;
|
||||
const harmful = (effects: unknown[]) => effects.some(e => {
|
||||
const x = e as { op?: string; power?: number; amount?: number };
|
||||
return ['damage', 'damageEach', 'destroy', 'bounce', 'tap', 'fight', 'drain'].includes(x.op ?? '') || (x.op === 'pump' && ((x.power ?? x.amount ?? 0) < 0));
|
||||
});
|
||||
const score = (a: Extract<DuelAction, { type: 'play' }>) => {
|
||||
const c = hand.get(a.uid);
|
||||
if (!c) return -1;
|
||||
const hostile = harmful(c.effects);
|
||||
let s = c.cost * 10 + rng();
|
||||
for (const t of a.targets ?? []) s += ((t.kind === 'card' ? owner(t.uid) : t.seat) === them) === hostile ? 3 : -3;
|
||||
return s;
|
||||
};
|
||||
return plays.reduce((b, a) => (score(a) > score(b) ? a : b));
|
||||
}
|
||||
|
||||
const toggles = find('toggleAttacker');
|
||||
if (toggles.length || find('confirmAttack').length) {
|
||||
const blockers = theirs.filter(p => !p.tapped && (p.card.type === 'Figure' || p.toughness > 0));
|
||||
const ready = mine.filter(p => v.combat.attackers.includes(p.uid) || toggles.some(t => t.uid === p.uid));
|
||||
const lethal = ready.map(p => p.power).sort((a, b) => b - a).slice(blockers.length).reduce((t, x) => t + x, 0) >= v.opponent.life;
|
||||
const want = toggles.find(t => {
|
||||
const c = mine.find(p => p.uid === t.uid)!;
|
||||
if (v.combat.attackers.includes(c.uid)) return false;
|
||||
if (lethal) return true;
|
||||
return c.power > 0 && !blockers.some(b => b.power >= c.toughness && b.toughness > c.power);
|
||||
});
|
||||
return want ?? find('confirmAttack')[0] ?? legal[0];
|
||||
}
|
||||
|
||||
const blocks = find('block');
|
||||
if (blocks.length || find('confirmBlocks').length) {
|
||||
const used = new Set(Object.keys(v.combat.blocks)), covered = new Set(Object.values(v.combat.blocks));
|
||||
const incoming = v.combat.attackers.filter(a => !covered.has(a)).reduce((t, a) => t + (theirs.find(p => p.uid === a)?.power ?? 0), 0);
|
||||
const lethal = incoming >= v.you.life;
|
||||
let best: DuelAction | undefined, bestScore = 0;
|
||||
for (const b of blocks) {
|
||||
if (used.has(b.blocker) || covered.has(b.attacker)) continue;
|
||||
const B = mine.find(p => p.uid === b.blocker), A = theirs.find(p => p.uid === b.attacker);
|
||||
if (!A || !B) continue;
|
||||
const kills = B.power >= A.toughness, dies = A.power >= B.toughness;
|
||||
const s = kills && !dies ? 10 + value(A) : kills ? (value(A) > value(B) ? 5 : lethal ? 3 : 0) : !dies ? 2 : lethal ? 1 : 0;
|
||||
if (s > bestScore) { bestScore = s; best = b; }
|
||||
}
|
||||
return best ?? find('confirmBlocks')[0] ?? legal[0];
|
||||
}
|
||||
|
||||
return find('endPhase')[0] ?? legal[0];
|
||||
}
|
||||
|
||||
/** Chance that Easy makes a random legal move (never concede) instead of Normal's. */
|
||||
export const EASY_BLUNDER_RATE = 0.3;
|
||||
|
||||
export const NORMAL_BOT: DuelBot = { name: 'Normal', choose: chooseNormal };
|
||||
export const EASY_BOT: DuelBot = {
|
||||
name: 'Easy',
|
||||
choose(v, legal, rng) {
|
||||
if (rng() < EASY_BLUNDER_RATE) return legal[Math.floor(rng() * legal.length)];
|
||||
return chooseNormal(v, legal, rng);
|
||||
},
|
||||
};
|
||||
export const DUEL_BOTS: DuelBot[] = [EASY_BOT, NORMAL_BOT];
|
||||
@@ -0,0 +1,50 @@
|
||||
// DuelCard (duel-cards, shared/duel/derive.ts) → BoardCard. Declared structurally so this file doesn't
|
||||
// depend on an unmerged branch; once shared/duel/derive.ts is on the integration branch, `DuelCardLike`
|
||||
// can become `DuelCard` with no other change.
|
||||
import type { BoardCard, DuelCardType, Portal } from './model.ts';
|
||||
import { firstSentence } from './model.ts';
|
||||
|
||||
export type DuelCardLike = {
|
||||
cardId: string; pageId: number | null; revisionId?: number; title: string; type: DuelCardType; subtype?: string | null;
|
||||
description?: string; token?: boolean;
|
||||
portal: Portal; cost: number; power: number | null; toughness: number | null; keywords: readonly string[];
|
||||
rulesText: string; flavor: string;
|
||||
};
|
||||
|
||||
/** What the chain (not the derivation) knows about the card's article: art and link. */
|
||||
export type ArticleBits = { image?: string; url?: string; extract?: string };
|
||||
|
||||
export const articleUrl = (title: string) => `https://en.wikipedia.org/wiki/${encodeURIComponent(title.replace(/ /g, '_'))}`;
|
||||
|
||||
const SUBTYPE_LABEL: Record<string, string> = {
|
||||
organisation: 'Organisation', work: 'Work', sport: 'Sport', election: 'Election', conflict: 'Conflict', disaster: 'Disaster',
|
||||
period: 'Period', mathematics: 'Mathematics', pathology: 'Pathology', language: 'Language', ideology: 'Ideology', team: 'Team', vehicle: 'Vehicle',
|
||||
};
|
||||
/** "(1909–1994)", "(born 1963)", "(c.1872–1919)" in the description → "1909–1994", "1963–", "1872–1919". */
|
||||
export function lifespan(text: string | undefined): string | undefined {
|
||||
const m = text?.match(/\((?:c\.\s?)?(\d{3,4})\s?[–-]\s?(?:c\.\s?)?(\d{3,4})(?!\d)[^)]*\)|\(born (\d{3,4})\)/);
|
||||
if (!m) return undefined;
|
||||
return m[3] ? `${m[3]}–` : `${m[1]}–${m[2]}`;
|
||||
}
|
||||
|
||||
/** The part after the em dash: "History · 1530–1537", "Society · Election". */
|
||||
export function subtypeLine(card: Pick<DuelCardLike, 'type' | 'subtype' | 'portal' | 'flavor'>): string {
|
||||
const extra = card.type === 'Figure' ? lifespan(card.flavor) : card.subtype ? SUBTYPE_LABEL[card.subtype] : undefined;
|
||||
return extra ? `${card.portal} · ${extra}` : card.portal;
|
||||
}
|
||||
|
||||
export function boardCard(card: DuelCardLike, article: ArticleBits = {}, live: Partial<BoardCard> = {}): BoardCard {
|
||||
// Figures show P/T; Locations only when they have a Garrison (0/T); other types never.
|
||||
const body = card.type === 'Figure' || (card.type === 'Location' && (card.toughness ?? 0) > 0);
|
||||
const power = body ? card.power ?? 0 : undefined, toughness = body ? card.toughness ?? 0 : undefined;
|
||||
return {
|
||||
id: card.cardId, title: card.title, type: card.type,
|
||||
subtype: subtypeLine(card),
|
||||
portal: card.portal, cost: card.cost, power, toughness, basePower: power, baseToughness: toughness,
|
||||
keywords: [...card.keywords], rulesText: card.rulesText,
|
||||
flavour: firstSentence(card.flavor || article.extract || card.description),
|
||||
// Tokens are not articles: no link.
|
||||
image: article.image, url: card.token ? undefined : article.url ?? articleUrl(card.title), revisionId: card.revisionId, token: card.token,
|
||||
...live,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* The part of duel-core's contract (shared/duel/types.ts and index.ts, PR #72 at 7904199) that the
|
||||
* board uses, mirrored so this PR doesn't stack on #72 (HANDBOOK: stub the interface). Field names
|
||||
* and unions are copied verbatim; engine-only details are widened to `unknown`, so real engine values
|
||||
* are assignable here. When #72 is on night/2026-11-17 this file becomes re-exports of shared/duel.
|
||||
*/
|
||||
export type Seat = 0 | 1;
|
||||
export type CardType = 'Figure' | 'Location' | 'Event' | 'Institution' | 'Doctrine';
|
||||
export type Portal = 'Arts' | 'Earth' | 'History' | 'Science' | 'Society' | 'Neutral';
|
||||
export type Keyword = 'Protected' | 'Featured' | 'Legacy' | 'Multilingual' | 'Translated' | 'Well-sourced' | 'Stub' | 'Local' | 'Trending';
|
||||
export type ConnectedTier = 'Linked' | 'Compatriot' | 'Contemporary' | 'Kin';
|
||||
export type Phase = 'mulligan' | 'main' | 'attack' | 'block' | 'over';
|
||||
export type EndReason = 'life' | 'library' | 'concede' | 'timeout' | 'turnCap';
|
||||
|
||||
export interface DuelCard {
|
||||
cardId: string;
|
||||
pageId: number | null;
|
||||
revisionId?: number;
|
||||
title: string;
|
||||
description?: string;
|
||||
type: CardType;
|
||||
subtype?: string | null;
|
||||
portal: Portal;
|
||||
cost: number;
|
||||
power: number | null;
|
||||
toughness: number | null;
|
||||
keywords: Keyword[];
|
||||
territory?: number;
|
||||
effects: unknown[];
|
||||
rulesText: string;
|
||||
flavor: string;
|
||||
connect?: unknown;
|
||||
rarity?: 'Common' | 'Rare' | 'Epic' | 'Legendary';
|
||||
deriveVersion?: string;
|
||||
token?: boolean;
|
||||
}
|
||||
|
||||
/** Only deckSize is read here; the engine validates the rest. */
|
||||
export interface DuelRulesetLike { deckSize: number }
|
||||
|
||||
export interface CardInstance { uid: string; owner: Seat; card: DuelCard }
|
||||
export interface CombatState { attackers: string[]; blocks: Record<string, string> }
|
||||
export interface DuelResult { winner: Seat | null; reason: EndReason }
|
||||
|
||||
export type TargetRef = { kind: 'card'; uid: string } | { kind: 'player'; seat: Seat };
|
||||
|
||||
export type DuelAction =
|
||||
| { type: 'keep' }
|
||||
| { type: 'mulligan' }
|
||||
| { type: 'play'; uid: string; targets?: TargetRef[] }
|
||||
| { type: 'endPhase' }
|
||||
| { type: 'toggleAttacker'; uid: string }
|
||||
| { type: 'confirmAttack' }
|
||||
| { type: 'block'; blocker: string; attacker: string }
|
||||
| { type: 'confirmBlocks' }
|
||||
| { type: 'concede' }
|
||||
| { type: 'timeout' };
|
||||
|
||||
export interface CardRef { uid: string; cardId: string; title: string; pageId: number | null; type: CardType; power?: number; toughness?: number }
|
||||
|
||||
export type LogEvent = { seq: number; turn: number } & (
|
||||
| { kind: 'start'; firstSeat: Seat }
|
||||
| { kind: 'mulligan'; seat: Seat }
|
||||
| { kind: 'keep'; seat: Seat; handSize: number }
|
||||
| { kind: 'turnStart'; seat: Seat; citations: number; life: [number, number] }
|
||||
| { kind: 'draw'; seat: Seat; card?: CardRef }
|
||||
| { kind: 'deploy'; seat: Seat; card: CardRef }
|
||||
| { kind: 'cast'; seat: Seat; card: CardRef; targets: TargetRef[] }
|
||||
| { kind: 'adopt'; seat: Seat; card: CardRef; to: CardRef }
|
||||
| { kind: 'tokenCreated'; seat: Seat; card: CardRef; source: CardRef }
|
||||
| { kind: 'connected'; seat: Seat; card: CardRef; with: CardRef; tier: ConnectedTier; via: string; bonus: number }
|
||||
| { kind: 'rivalry'; card: CardRef; with: CardRef; tier: ConnectedTier; via: string }
|
||||
| { kind: 'effect'; seat: Seat; source: CardRef; op: string; template?: string; targets: TargetRef[] }
|
||||
| { kind: 'attack'; seat: Seat; attackers: CardRef[] }
|
||||
| { kind: 'block'; seat: Seat; blocks: { blocker: CardRef; attacker: CardRef }[] }
|
||||
| { kind: 'effectDamage'; source: CardRef; target: CardRef; amount: number }
|
||||
| { kind: 'combatDamage'; source: CardRef; target: CardRef; amount: number }
|
||||
| { kind: 'playerDamage'; source: CardRef | null; seat: Seat; amount: number; life: number; combat: boolean }
|
||||
| { kind: 'lifeGain'; source: CardRef; seat: Seat; amount: number; life: number }
|
||||
| { kind: 'destroyed'; card: CardRef; owner: Seat }
|
||||
| { kind: 'bounced'; card: CardRef; owner: Seat }
|
||||
| { kind: 'discard'; seat: Seat; card: CardRef }
|
||||
| { kind: 'fatigue'; seat: Seat; amount: number }
|
||||
| { kind: 'concede'; seat: Seat }
|
||||
| { kind: 'timeout'; seat: Seat }
|
||||
| { kind: 'gameOver'; winner: Seat | null; reason: EndReason; life: [number, number] }
|
||||
);
|
||||
|
||||
export interface PermanentView {
|
||||
uid: string;
|
||||
owner: Seat;
|
||||
controller: Seat;
|
||||
card: DuelCard;
|
||||
tapped: boolean;
|
||||
sick: boolean;
|
||||
damage: number;
|
||||
counters: number;
|
||||
attachedTo?: string;
|
||||
power: number;
|
||||
toughness: number;
|
||||
keywords: Keyword[];
|
||||
connected?: { with: string; tier: ConnectedTier; via: string; bonus: number };
|
||||
}
|
||||
|
||||
export interface SideView {
|
||||
seat: Seat;
|
||||
life: number;
|
||||
citations: number;
|
||||
maxCitations: number;
|
||||
handSize: number;
|
||||
librarySize: number;
|
||||
graveyard: CardInstance[];
|
||||
bankSeconds: number;
|
||||
ready: boolean;
|
||||
mulligansTaken: number;
|
||||
}
|
||||
|
||||
export interface PlayerView {
|
||||
engine: 'duel';
|
||||
seat: Seat;
|
||||
turn: number;
|
||||
active: Seat;
|
||||
phase: Phase;
|
||||
toAct: Seat | null;
|
||||
you: SideView & { hand: CardInstance[] };
|
||||
opponent: SideView;
|
||||
battlefield: PermanentView[];
|
||||
combat: CombatState;
|
||||
result: DuelResult | null;
|
||||
version: number;
|
||||
rules: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* The slice of `DuelEngineApi` (shared/duel/index.ts) the bot match calls. Method syntax on purpose:
|
||||
* the real engine (typed on the full DuelState/DuelRuleset/DuelCard) is assignable to it.
|
||||
*/
|
||||
export interface DuelEngineLike<S = unknown, R = unknown> {
|
||||
createDuel(rules: R, decks: [DuelCard[], DuelCard[]], seed: string): S;
|
||||
legalActions(state: S, seat: Seat): DuelAction[];
|
||||
applyAction(state: S, seat: Seat, action: DuelAction): S;
|
||||
toAct(state: S): Seat | null;
|
||||
isOver(state: S): boolean;
|
||||
viewFor(state: S, seat: Seat): PlayerView;
|
||||
logFor(state: S, seat: Seat): LogEvent[];
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// Local (in-browser) match driver, engine-agnostic. ./adapter.ts binds it to duel-core's shared/duel.
|
||||
// The bot gets only its own seat's view (viewFor), never the full state (Night 1 rule, #5).
|
||||
import type { BoardView, DuelUIAction, Legal, Seat } from './model.ts';
|
||||
|
||||
/** The engine as the board needs it. `A` is the engine's atomic action; `S` its state. */
|
||||
export interface DuelEnginePort<S, A> {
|
||||
legal(s: S, seat: Seat): A[];
|
||||
apply(s: S, seat: Seat, a: A): S;
|
||||
/** Whose input the engine is waiting for, or null when the match is over. */
|
||||
toAct(s: S): Seat | null;
|
||||
board(s: S, seat: Seat, names: [string, string]): BoardView;
|
||||
legalForBoard(actions: A[], view: BoardView): Legal;
|
||||
/** One board-level intent → the engine's atomic actions, in order. Each must be legal when sent. */
|
||||
expand(ui: DuelUIAction, actions: A[], view: BoardView): A[];
|
||||
}
|
||||
|
||||
export type BotChoose<S, A> = (s: S, seat: Seat, legal: A[], rng: () => number) => A;
|
||||
|
||||
/** Applies a sequence for one seat, re-checking legality at every step. Throws on the first illegal action. */
|
||||
export function applySequence<S, A>(port: DuelEnginePort<S, A>, s: S, seat: Seat, seq: A[], same: (a: A, b: A) => boolean): S {
|
||||
for (const a of seq) {
|
||||
const legal = port.legal(s, seat);
|
||||
if (!legal.some(l => same(l, a))) throw new Error('That move is no longer legal.');
|
||||
s = port.apply(s, seat, a);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/** Runs bot moves until the human must act or the match ends. Bounded, so a broken bot can't hang the tab. */
|
||||
export function runBot<S, A>(port: DuelEnginePort<S, A>, s: S, human: Seat, choose: BotChoose<S, A>, rng: () => number, maxSteps = 500): S {
|
||||
const bot = (human === 0 ? 1 : 0) as Seat;
|
||||
for (let i = 0; i < maxSteps; i++) {
|
||||
if (port.toAct(s) !== bot) return s;
|
||||
const legal = port.legal(s, bot);
|
||||
if (!legal.length) return s;
|
||||
s = port.apply(s, bot, choose(s, bot, legal, rng));
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/** Stable structural equality for plain JSON actions. */
|
||||
export const sameAction = (a: unknown, b: unknown): boolean => stable(a) === stable(b);
|
||||
const stable = (v: unknown): string => JSON.stringify(v, (_k, x) =>
|
||||
x && typeof x === 'object' && !Array.isArray(x) ? Object.fromEntries(Object.entries(x).sort(([p], [q]) => p.localeCompare(q))) : x);
|
||||
@@ -0,0 +1,40 @@
|
||||
// Pure deck helpers for the bot match (no React, no CSS), so they are unit-tested under Node.
|
||||
import type { DuelAction, DuelCard, PlayerView } from './contract.ts';
|
||||
|
||||
/** A collection card as ui-pvp passes it (ownership's ChainCard satisfies this). `duel` is the server-derived frozen profile. */
|
||||
export type BotMatchCard = { tokenId: string; title: string; url?: string; imageUrl?: string; extract?: string; duel?: unknown };
|
||||
|
||||
const TYPES = ['Figure', 'Location', 'Event', 'Institution', 'Doctrine'];
|
||||
/** Shape check for a profile that arrives untyped over the wire (the engine's validateDeck does the rest). */
|
||||
export function isDuelCard(v: unknown): v is DuelCard {
|
||||
const c = v as Partial<DuelCard> | null;
|
||||
return !!c && typeof c === 'object' && typeof c.title === 'string' && TYPES.includes(c.type as string) && typeof c.cost === 'number'
|
||||
&& Array.isArray(c.keywords) && Array.isArray(c.effects) && typeof c.rulesText === 'string';
|
||||
}
|
||||
/** The bot sees only its own seat's view (Night 1 rule, #5). */
|
||||
export type DuelBot = { name: string; choose(view: PlayerView, legal: DuelAction[], rng: () => number): DuelAction };
|
||||
|
||||
export function mulberry(seed: number) {
|
||||
return () => { seed = (seed + 0x6d2b79f5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
|
||||
}
|
||||
export const hash = (s: string) => { let h = 2166136261; for (const c of s) h = Math.imul(h ^ c.charCodeAt(0), 16777619); return h >>> 0; };
|
||||
|
||||
/** The bot's own deck: `size` distinct cards from a pool (the 236 real sample cards), seeded, within the copy limit. */
|
||||
export function botDeck(pool: readonly DuelCard[], size: number, seed: string): DuelCard[] {
|
||||
const rng = mulberry(hash(`bot-deck:${seed}`));
|
||||
const shuffled = [...pool].sort((a, b) => a.cardId.localeCompare(b.cardId));
|
||||
for (let i = shuffled.length - 1; i > 0; i--) { const j = Math.floor(rng() * (i + 1)); [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]; }
|
||||
return shuffled.slice(0, size).map(c => ({ ...c, cardId: `bot:${c.cardId}` }));
|
||||
}
|
||||
|
||||
/** Resolves the player's deck: exactly `deckSize` owned cards, each with a frozen profile. Returns problems instead of a partial deck. */
|
||||
export function playerDeck(deck: string[], cards: BotMatchCard[], deckSize: number): { cards: DuelCard[]; pending: string[]; missing: string[] } {
|
||||
const byId = new Map(cards.map(c => [c.tokenId, c]));
|
||||
const out: DuelCard[] = [], pending: string[] = [], missing: string[] = [];
|
||||
for (const id of deck) {
|
||||
const c = byId.get(id);
|
||||
if (!c) missing.push(id); else if (!isDuelCard(c.duel)) pending.push(c.title); else out.push({ ...c.duel, cardId: id });
|
||||
}
|
||||
return { cards: out.length === deckSize && deck.length === deckSize ? out : [], pending, missing };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
/* Duel board (ui-duel, #58). Mobile-first: everything must read at 360 × 740 with a full 5 + 5 board.
|
||||
Portals take MTG colour analogues: Arts red, Earth green, History black, Science blue, Society white. */
|
||||
.duel{--gap:6px;display:flex;flex-direction:column;gap:var(--gap);max-width:1180px;margin:0 auto;padding:6px 8px 0;color:var(--ctp-text);background:var(--ctp-mantle);border:1px solid var(--theme-border);border-radius:12px;min-height:min(100dvh,980px);font-size:13px}
|
||||
.duel button{font:inherit;color:inherit;cursor:pointer}
|
||||
.duel-bar{display:flex;align-items:center;gap:6px;min-height:36px}
|
||||
.duel-turn{font-size:12px;color:var(--ctp-subtext1);margin-right:auto;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.duel-clock{display:inline-flex;align-items:center;gap:3px;font-size:12px;font-variant-numeric:tabular-nums;color:var(--ctp-subtext1)}
|
||||
.duel-clock small{color:var(--ctp-overlay1);font-size:10px}
|
||||
.duel-clock.low{color:var(--ctp-red)}
|
||||
.duel .icon-button{min-width:36px;min-height:36px}
|
||||
|
||||
.duel-main{display:flex;gap:10px;flex:1 1 auto;min-height:0}
|
||||
.duel-field{display:flex;flex-direction:column;gap:var(--gap);flex:1 1 auto;min-width:0}
|
||||
|
||||
/* Player bars: Notability, Citations, library and hand are always visible. */
|
||||
.duel-side{display:flex;align-items:center;gap:10px;padding:5px 8px;border-radius:8px;background:var(--ctp-base);border:1px solid var(--ctp-surface0);font-size:12px;font-variant-numeric:tabular-nums}
|
||||
.duel-side.is-target{width:100%;text-align:left;box-shadow:0 0 0 2px var(--ctp-yellow);animation:dface-pulse 1.1s ease-in-out infinite}
|
||||
.duel-side.is-active{border-color:var(--theme-accent);box-shadow:inset 3px 0 0 var(--theme-accent)}
|
||||
.duel-side-name{font-weight:700;margin-right:auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.duel-stat{display:inline-flex;align-items:center;gap:3px;color:var(--ctp-subtext1)}
|
||||
.duel-stat b{font-size:15px;color:var(--ctp-text)}
|
||||
.duel-stat small{color:var(--ctp-overlay1)}
|
||||
.duel-stat.life svg{color:var(--ctp-yellow)}
|
||||
.duel-stat.life.low b{color:var(--ctp-red)}
|
||||
.duel-stat.cites svg{color:var(--ctp-blue)}
|
||||
|
||||
/* Battlefields: one scrollable row per side; 5 cards fit 344 px without scrolling. */
|
||||
.duel-row{display:flex;gap:4px;overflow-x:auto;overscroll-behavior-x:contain;scrollbar-width:none;min-height:102px;padding:4px 0;align-items:flex-start}
|
||||
.duel-zoomgrid .dface-zoom{align-self:start}
|
||||
.duel-row::-webkit-scrollbar{display:none}
|
||||
.duel-row.theirs{align-items:flex-end}
|
||||
.duel-slot{position:relative;display:flex;flex-direction:column;align-items:stretch;flex:1 1 0;min-width:62px;max-width:110px}
|
||||
.duel-empty{flex:1;align-self:center;text-align:center;font-size:12px;color:var(--ctp-overlay1);padding:8px}
|
||||
.duel-attach{position:absolute;top:-5px;right:-3px;z-index:3;font-size:12px;font-weight:800;padding:1px 5px;border-radius:8px;background:var(--ctp-mauve);color:var(--ctp-crust)}
|
||||
.duel-pair{font-size:9px;line-height:1.2;color:var(--ctp-green);text-align:center;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;margin-top:2px}
|
||||
|
||||
.duel-ticker{display:flex;align-items:center;gap:6px;width:100%;min-height:36px;padding:6px 10px;border-radius:8px;background:var(--ctp-crust);border:1px dashed var(--ctp-surface1);text-align:left;font-size:12px;line-height:1.35;color:var(--ctp-subtext1)}
|
||||
.duel-ticker>span:last-child{overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical}
|
||||
.duel-ticker-phase{display:inline-flex;color:var(--theme-accent);flex:0 0 auto}
|
||||
|
||||
.duel-log-aside{display:none}
|
||||
.duel-log{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:6px;font-size:13px;line-height:1.5;color:var(--ctp-subtext1)}
|
||||
.duel-log li{padding-left:10px;border-left:2px solid var(--ctp-surface1)}
|
||||
.duel-log li:last-child{border-left-color:var(--theme-accent);color:var(--ctp-text)}
|
||||
.duel-log.full{max-height:60vh;overflow:auto}
|
||||
|
||||
/* Dock: hand, status line, actions. Sticky so the thumb always reaches it. */
|
||||
.duel-dock{position:sticky;bottom:0;z-index:5;margin:0 -8px;padding:6px 8px calc(8px + env(safe-area-inset-bottom));background:var(--ctp-mantle);border-top:1px solid var(--theme-border);border-radius:0 0 12px 12px;display:flex;flex-direction:column;gap:6px}
|
||||
.duel-hand{display:flex;gap:6px;overflow-x:auto;scrollbar-width:none;padding:6px 0 2px;min-height:112px}
|
||||
.duel-hand::-webkit-scrollbar{display:none}
|
||||
.duel-hand-wrap{position:relative}
|
||||
.duel-hand.has-more{-webkit-mask-image:linear-gradient(to right,#000 78%,transparent);mask-image:linear-gradient(to right,#000 78%,transparent)}
|
||||
.duel-hand-more{position:absolute;right:0;top:50%;transform:translateY(-50%);min-width:40px;min-height:40px;border-radius:20px;background:var(--ctp-surface1);color:var(--ctp-text);font-weight:800;font-size:13px;box-shadow:0 2px 8px rgb(0 0 0/.4)}
|
||||
.duel-note{margin:0;min-height:18px;font-size:12px;line-height:1.35;color:var(--ctp-subtext1);display:flex;align-items:center;gap:6px}
|
||||
.duel-actions{display:flex;gap:8px;justify-content:flex-end}
|
||||
.duel-actions .button{min-height:46px;font-size:13px;padding:10px 16px}
|
||||
.duel-actions .duel-primary{flex:1 1 auto;max-width:280px}
|
||||
|
||||
/* ---------- card faces ---------- */
|
||||
.dface{--portal:var(--ctp-overlay1);--portal-ink:var(--ctp-crust);position:relative;display:flex;flex-direction:column;align-items:stretch;text-align:left;padding:0;background:var(--ctp-base);color:var(--ctp-text);border:1.5px solid color-mix(in srgb,var(--portal) 65%,var(--ctp-surface1));border-radius:8px;overflow:hidden;transition:transform .15s ease,box-shadow .15s ease,opacity .15s ease}
|
||||
.dface.portal-arts{--portal:var(--ctp-red)}
|
||||
.dface.portal-earth{--portal:var(--ctp-green)}
|
||||
.dface.portal-history{--portal:var(--ctp-surface2);--portal-ink:var(--ctp-text)}
|
||||
.dface.portal-science{--portal:var(--ctp-blue)}
|
||||
.dface.portal-society{--portal:var(--ctp-rosewater)}
|
||||
.dface.portal-neutral{--portal:var(--ctp-overlay0);--portal-ink:var(--ctp-text)}
|
||||
.dface-art{position:relative;display:flex;align-items:center;justify-content:center;height:32px;overflow:hidden;color:var(--portal);background:color-mix(in srgb,var(--portal) 25%,var(--ctp-surface0))}
|
||||
.dface-art img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}
|
||||
.dface-art svg{position:relative;opacity:.9}
|
||||
.dface-art:has(img:not([style*="none"])) svg{position:absolute;right:3px;bottom:3px;width:14px;height:14px;padding:2px;border-radius:4px;background:rgb(0 0 0/.55);color:#fff;box-sizing:content-box}
|
||||
.dface-cost{position:absolute;top:3px;left:3px;z-index:2;min-width:20px;height:20px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:800;font-size:12px;background:var(--ctp-blue);color:var(--ctp-crust);box-shadow:0 1px 3px rgb(0 0 0/.4)}
|
||||
.dface-title{font-size:10.5px;font-weight:700;line-height:1.2;padding:3px 4px 0;overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;min-height:2.4em;overflow-wrap:break-word;hyphens:auto}
|
||||
.dface-bottom{display:flex;align-items:center;gap:2px;padding:2px 2px 3px;margin-top:auto;min-width:0}
|
||||
.dface-type{display:inline-flex;color:var(--portal);flex:0 0 auto}
|
||||
.dface-kwicon{display:inline-flex;align-items:center;justify-content:center;width:15px;height:16px;border-radius:4px;flex:0 0 auto;background:color-mix(in srgb,var(--portal) 30%,var(--ctp-surface0));color:var(--ctp-text)}
|
||||
.dface-chip{font-size:9px;font-weight:700;padding:1px 3px;border-radius:3px;background:color-mix(in srgb,var(--portal) 30%,var(--ctp-surface0));color:var(--ctp-text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}
|
||||
.dface-pt{margin-left:auto;flex:0 0 auto;font-size:12px;font-weight:800;padding:0 3px;letter-spacing:-.3px;border-radius:4px;background:var(--ctp-surface0);font-variant-numeric:tabular-nums}
|
||||
.dface-pt .up{color:var(--ctp-green)}.dface-pt .down{color:var(--ctp-red)}
|
||||
.dface-flag{position:absolute;top:3px;right:3px;z-index:2;display:flex;padding:3px;border-radius:50%}
|
||||
.dface-flag.attack{background:var(--ctp-red);color:var(--ctp-crust)}
|
||||
.dface-flag.block{background:var(--ctp-green);color:var(--ctp-crust)}
|
||||
|
||||
.dface-board{width:100%;min-height:90px}
|
||||
.dface-hand{flex:0 0 80px;width:80px;min-height:106px}
|
||||
.dface-hand .dface-art{height:42px}
|
||||
.dface-hand .dface-title{font-size:11px}
|
||||
|
||||
.dface.is-tapped{opacity:.62;filter:saturate(.6)}
|
||||
.dface.is-tapped::after{content:'';position:absolute;inset:0;background:repeating-linear-gradient(135deg,transparent 0 6px,rgb(0 0 0/.12) 6px 8px);pointer-events:none}
|
||||
.dface.is-pending .dface-art{filter:grayscale(.7)}
|
||||
.dface.is-selected{box-shadow:0 0 0 2px var(--theme-accent);transform:translateY(-4px)}
|
||||
.dface.is-attacking{box-shadow:0 0 0 2px var(--ctp-red);transform:translateY(-4px)}
|
||||
.duel-row.theirs .dface.is-attacking{transform:translateY(4px)}
|
||||
.dface.is-blocking{box-shadow:0 0 0 2px var(--ctp-green)}
|
||||
.dface.is-target{box-shadow:0 0 0 2px var(--ctp-yellow);animation:dface-pulse 1.1s ease-in-out infinite}
|
||||
.dface.is-dim{opacity:.42}
|
||||
.dface.is-token{border-style:dashed}
|
||||
.dface.is-fresh{animation:dface-in .4s ease-out}
|
||||
.dface:focus-visible{outline:2px solid var(--theme-accent);outline-offset:2px}
|
||||
@keyframes dface-pulse{50%{box-shadow:0 0 0 4px color-mix(in srgb,var(--ctp-yellow) 55%,transparent)}}
|
||||
@keyframes dface-in{from{transform:scale(.7);opacity:0}to{transform:none;opacity:1}}
|
||||
@media (prefers-reduced-motion:reduce){.dface{transition:none}.dface.is-target,.dface.is-fresh{animation:none}}
|
||||
|
||||
/* Zoom face: the full MTG layout, in the tap-to-zoom sheet. */
|
||||
.dface-zoom{width:min(300px,100%);margin:0 auto;border-width:3px;border-radius:14px;background:color-mix(in srgb,var(--portal) 10%,var(--ctp-base));padding:8px;gap:6px}
|
||||
.dface-namebar{display:flex;align-items:center;gap:8px;padding:4px 8px;border-radius:7px;background:var(--ctp-surface0)}
|
||||
.dface-name{font-family:Georgia,'Times New Roman',serif;font-size:17px !important;font-weight:700;line-height:1.2;margin:0 !important;flex:1 1 auto;min-width:0}
|
||||
.dface-zoom .dface-cost{position:static;min-width:26px;height:26px;font-size:15px}
|
||||
.dface-zoom .dface-art{height:150px;border-radius:6px}
|
||||
.dface-typeline{display:flex;align-items:center;gap:6px;margin:0;padding:4px 8px;border-radius:7px;background:var(--ctp-surface0);font-size:13px !important;font-weight:600}
|
||||
.dface-portal{margin-left:auto;font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.5px;padding:2px 6px;border-radius:4px;background:var(--portal);color:var(--portal-ink)}
|
||||
.dface-textbox{padding:8px 10px;border-radius:7px;background:var(--ctp-crust);display:flex;flex-direction:column;gap:6px;min-height:88px}
|
||||
.dface-textbox p{margin:0;font-size:13.5px !important;line-height:1.45 !important}
|
||||
.dface-keywords{font-weight:700}
|
||||
.dface-flavour{font-family:Georgia,'Times New Roman',serif;font-style:italic;color:var(--ctp-subtext0);border-top:1px solid var(--ctp-surface0);padding-top:6px}
|
||||
.dface-flavour sup a{font-style:normal;font-family:inherit;color:var(--ctp-blue);text-decoration:none;margin-left:1px;padding:4px 2px}
|
||||
.dface-footer{display:flex;align-items:center;gap:6px}
|
||||
.dface-rev{font-size:10px;color:var(--ctp-overlay1);font-variant-numeric:tabular-nums}
|
||||
.dface-zoom .dface-pt{font-size:18px;padding:2px 10px;border:2px solid var(--portal);background:var(--ctp-base)}
|
||||
|
||||
.duel-sheet .duel-sheet-meta{text-align:center;margin:8px 0}
|
||||
.duel-preview{list-style:none;padding:0;margin:8px 0;display:flex;flex-direction:column;gap:6px}
|
||||
.duel-preview li{display:flex;flex-wrap:wrap;align-items:baseline;gap:6px;font-size:14px;padding:8px 10px;border-radius:8px;background:var(--ctp-base)}
|
||||
.duel-preview small{color:var(--ctp-overlay1);font-variant-numeric:tabular-nums}
|
||||
.duel-preview .vs{color:var(--ctp-subtext0);font-size:12px}
|
||||
.duel-preview .gone{text-decoration:line-through;color:var(--ctp-red)}
|
||||
|
||||
/* Eligibility gate */
|
||||
.duel-gate{max-width:560px;margin:0 auto;padding:22px 16px;border:1px solid var(--theme-border);border-radius:12px;background:var(--ctp-mantle);color:var(--ctp-text)}
|
||||
.duel-gate h2{font-size:22px;margin:0 0 8px}
|
||||
.duel-gate-bar{height:10px;border-radius:5px;background:var(--ctp-surface0);overflow:hidden;margin:12px 0 6px}
|
||||
.duel-gate-bar i{display:block;height:100%;background:var(--theme-accent)}
|
||||
|
||||
/* Tall phones (≥ 720 px): give the spare height to the cards, with 3-line titles (QA #58). */
|
||||
@media (max-width:899px) and (min-height:720px){
|
||||
.dface-board{min-height:112px}
|
||||
.dface-board .dface-art{height:42px}
|
||||
.dface-board .dface-title{-webkit-line-clamp:3;min-height:3.6em}
|
||||
.dface-hand{min-height:128px}
|
||||
.dface-hand .dface-art{height:52px}
|
||||
.dface-hand .dface-title{-webkit-line-clamp:3;min-height:3.6em}
|
||||
.duel-hand{min-height:134px}
|
||||
}
|
||||
|
||||
/* Desktop: bigger cards, log always visible beside the field. */
|
||||
@media (min-width:900px){
|
||||
.duel{padding:10px 14px 0;font-size:14px}
|
||||
.duel-log-button{display:none}
|
||||
.duel-log-aside{display:flex;flex-direction:column;flex:0 0 300px;max-height:calc(100dvh - 240px);min-height:380px;padding:10px 12px;border-radius:10px;background:var(--ctp-base);border:1px solid var(--ctp-surface0)}
|
||||
.duel-log-aside h3{font-size:12px;letter-spacing:1px;text-transform:uppercase;color:var(--ctp-subtext0);margin:0 0 8px}
|
||||
.duel-log-aside .duel-log{overflow:auto}
|
||||
.duel-ticker{display:none}
|
||||
.duel-row{justify-content:center;min-height:150px;gap:8px}
|
||||
.duel-slot{min-width:96px;max-width:120px}
|
||||
.dface-board{min-height:140px}
|
||||
.dface-board .dface-art{height:62px}
|
||||
.dface-board .dface-title{font-size:12.5px}
|
||||
.dface-board .dface-chip{font-size:9px}
|
||||
.dface-board .dface-kwicon{width:20px;height:20px}
|
||||
.dface-board .dface-pt{font-size:14px}
|
||||
.dface-board .dface-cost{min-width:24px;height:24px;font-size:13px}
|
||||
.dface-hand{flex-basis:104px;width:104px;min-height:138px}
|
||||
.dface-hand .dface-art{height:60px}
|
||||
.dface-hand .dface-title{font-size:12.5px}
|
||||
.duel-hand{justify-content:center;min-height:146px}
|
||||
.duel-dock{margin:0 -14px;padding:8px 14px 12px}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
// Preview data for the duel board: real cards from docs/game/card-sample.json, with a deliberately
|
||||
// crude stand-in derivation so the board can be built and screenshotted before duel-cards' real
|
||||
// shared/duel/derive.ts lands. Never used for real matches. No network calls.
|
||||
import sample from '../../../docs/game/card-sample.json';
|
||||
import type { BoardCard, BoardView, DuelCardType, Legal, Portal } from './model.ts';
|
||||
|
||||
type SampleCard = {
|
||||
pageId: number; title: string; description?: string | null; revisionId: number; pageBytes: number; languageCount: number;
|
||||
categories: string[]; instanceOf?: { id: string; label: string }[]; tiers: { attention: number; depth: number; reach: number };
|
||||
};
|
||||
const CARDS = (sample as unknown as { cards: SampleCard[] }).cards;
|
||||
|
||||
function previewType(c: SampleCard): DuelCardType {
|
||||
const labels = (c.instanceOf ?? []).map(i => i.label).join(' ');
|
||||
const d = c.description ?? '';
|
||||
if (c.instanceOf?.some(i => i.id === 'Q5') || /\btaxon\b/.test(labels) || /^(Species|Genus) of/.test(d)) return 'Figure';
|
||||
if (/commune|municipality|village|town|river|settlement|mosque|parish|area/i.test(labels + d)) return 'Location';
|
||||
if (/election|storm|nor.easter|battle|match|final|season|war/i.test(labels + d)) return 'Event';
|
||||
if (/company|band|group|film|team|organi[sz]ation|party/i.test(labels + d)) return 'Institution';
|
||||
return 'Doctrine';
|
||||
}
|
||||
function previewPortal(c: SampleCard, t: DuelCardType): Portal {
|
||||
const s = `${c.description ?? ''} ${c.categories.join(' ')}`;
|
||||
if (/century|deaths|sultan|empire|medieval|monarch|queen|king/i.test(s)) return 'History';
|
||||
if (/mathemat|algebra|programming|gene|disease|scientist|botanist|archaeolog/i.test(s)) return 'Science';
|
||||
if (/actor|singer|film|band|music|novel|television/i.test(s)) return 'Arts';
|
||||
if (/species|genus|river|fungus|plant|orchid|commune|village/i.test(s)) return 'Earth';
|
||||
if (/politic|election|protest|footballer|team|government/i.test(s)) return 'Society';
|
||||
return t === 'Figure' ? 'Society' : t === 'Location' ? 'Earth' : 'Neutral';
|
||||
}
|
||||
const years = (d?: string | null) => d?.match(/\(([^)]*\d{3,4}[^)]*)\)/)?.[1]?.replace(/^(c\.|born )/, '').replace('born ', '');
|
||||
|
||||
export function previewCard(c: SampleCard, suffix = ''): BoardCard {
|
||||
const type = previewType(c), portal = previewPortal(c, type);
|
||||
const fame = Math.round((c.tiers.attention * 2 + c.tiers.depth + c.tiers.reach) / 4);
|
||||
const cost = Math.max(1, Math.min(6, Math.ceil(fame * 0.6)));
|
||||
const keywords: string[] = [];
|
||||
if (c.categories.includes('Living people')) keywords.push('Protected');
|
||||
if (c.tiers.attention >= 9) keywords.push('Featured');
|
||||
if (c.languageCount >= 20 && keywords.length < 2) keywords.push('Translated');
|
||||
if (c.categories.some(x => /\d+ deaths/.test(x)) && keywords.length < 2) keywords.push('Legacy');
|
||||
if ((c.pageBytes < 3000 || c.categories.some(x => /stubs/.test(x))) && keywords.length < 2) keywords.push('Stub');
|
||||
const k = Math.ceil(cost / 2);
|
||||
let power: number | undefined, toughness: number | undefined, rulesText = '';
|
||||
if (type === 'Figure') {
|
||||
const b = 2 * cost + 1, s = Math.min(0.7, Math.max(0.3, c.tiers.attention / (c.tiers.attention + c.tiers.depth || 1)));
|
||||
power = Math.max(1, Math.round(b * s)) - (keywords.length > 1 ? 1 : 0); toughness = Math.max(1, b - Math.round(b * s));
|
||||
} else if (type === 'Location') {
|
||||
power = 0; toughness = 1 + Math.floor(c.tiers.depth / 3);
|
||||
rulesText = `Territory. Garrison 0/${toughness}.`;
|
||||
} else if (type === 'Event') {
|
||||
rulesText = /storm|nor.easter/i.test(c.description ?? '') ? `Deal ${Math.max(1, k - 1)} damage to each Figure and each Location.`
|
||||
: /election/i.test(c.description ?? '') ? `Create ${k} 1/1 Society Figure tokens named Elected Member.`
|
||||
: `Target Figure you control gets +${k}/+0 until end of turn, then fights target Figure you don't control.`;
|
||||
} else if (type === 'Institution') {
|
||||
rulesText = cost >= 4 ? 'At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member.' : 'Figures you control with power 2 or less get +1/+0.';
|
||||
} else {
|
||||
rulesText = /disease/i.test(c.description ?? '') ? `Attach to target Figure. It gets −${k}/−${k}.` : `Adopt. Adopted Figure gets +${k}/+${k}.`;
|
||||
}
|
||||
const sub = type === 'Figure' ? [portal, years(c.description)].filter(Boolean).join(' · ') : portal;
|
||||
return {
|
||||
id: `${c.pageId}${suffix}`, title: c.title, type, subtype: sub, portal, cost, power, toughness, basePower: power, baseToughness: toughness,
|
||||
keywords: type === 'Figure' ? keywords.slice(0, 2) : [], rulesText, flavour: c.description ? `${c.description}.` : undefined,
|
||||
url: `https://en.wikipedia.org/wiki/${encodeURIComponent(c.title.replace(/ /g, '_'))}`, revisionId: c.revisionId,
|
||||
};
|
||||
}
|
||||
|
||||
export const PREVIEW_POOL: BoardCard[] = CARDS.map(c => previewCard(c));
|
||||
const byTitle = (t: string) => PREVIEW_POOL.find(c => c.title === t) ?? PREVIEW_POOL[0];
|
||||
const figures = PREVIEW_POOL.filter(c => c.type === 'Figure');
|
||||
|
||||
/** A full 5 + 5 board for screenshots and tests. `scene` picks whose step it is. */
|
||||
export function previewView(scene: 'main' | 'attack' | 'block' | 'over' = 'main'): { view: BoardView; legal: Legal } {
|
||||
const mine = [byTitle('Jess Harnell'), byTitle('Dichromorpha viridis'), byTitle('Salahuddin of Aceh'), byTitle('Pathrail Mosque'), byTitle('Hiroshima Electric Railway')]
|
||||
.map((c, i) => ({ ...c, pending: i === 1 && scene === 'main' }));
|
||||
const theirs = [byTitle('Isabella of Aragon, Queen of Portugal'), byTitle('Miloje Vasić'), figures[12], byTitle('Topusko'), byTitle('Zbyszek Godlewski')]
|
||||
.map((c, i) => ({ ...c, id: `${c.id}-o`, damage: i === 1 ? 1 : 0 }));
|
||||
mine[0] = { ...mine[0], attachments: ['doc-1'], power: (mine[0].power ?? 0) + 2, toughness: (mine[0].toughness ?? 0) + 2 };
|
||||
const hand = [byTitle('Agda (programming language)'), byTitle('April 2021 nor\'easter'), byTitle('Mary Sophie Young'), byTitle('Charmont-en-Beauce'), byTitle('Heart rot'), byTitle('Joseph Ujlaki')];
|
||||
const log = [
|
||||
'Turn 1. Bot (Normal) kept a hand of seven.',
|
||||
'Turn 3. You cited Pathrail Mosque. Maximum Citations rose to 4.',
|
||||
'Turn 4. Isabella of Aragon, Queen of Portugal (6/5) attacked. Dichromorpha viridis (4/2) blocked and was reverted.[2]',
|
||||
'Turn 5. You deployed Jess Harnell. Bot (Normal) lost 3 Notability.',
|
||||
'Turn 6. Miloje Vasić was assigned 1 damage.',
|
||||
];
|
||||
const view: BoardView = {
|
||||
seat: 0, turn: 6, active: scene === 'block' ? 1 : 0, phase: scene === 'main' ? 'main' : scene === 'attack' ? 'attack' : scene === 'block' ? 'block' : 'over',
|
||||
me: { name: 'You', notability: 14, citations: scene === 'main' ? 4 : 1, maxCitations: 6, library: 27, hand: hand.length, battlefield: mine, graveyard: 3 },
|
||||
opponent: { name: 'Bot (Normal)', notability: scene === 'over' ? 0 : 11, citations: 0, maxCitations: 6, library: 26, hand: 4, battlefield: theirs, graveyard: 2 },
|
||||
hand, combat: scene === 'block' ? [{ attackerId: theirs[0].id }, { attackerId: theirs[1].id }, { attackerId: theirs[2].id }] : [],
|
||||
log, winner: scene === 'over' ? 0 : undefined, clock: { turn: 42, bank: 251 },
|
||||
};
|
||||
const myFigs = mine.filter(c => c.type === 'Figure' && !c.pending).map(c => c.id);
|
||||
const legal: Legal = scene === 'main' ? {
|
||||
...emptyLegal(), canGoToCombat: true, canEndTurn: true, attackers: myFigs,
|
||||
plays: Object.fromEntries(hand.filter(c => c.cost <= 4).map(c => [c.id,
|
||||
c.type === 'Doctrine' ? mine.filter(m => m.type === 'Figure').map(m => [m.id])
|
||||
: c.type === 'Event' ? mine.filter(m => m.type === 'Figure').flatMap(m => theirs.filter(t => t.type === 'Figure').map(t => [m.id, t.id])) : [[]]])),
|
||||
} : scene === 'attack' ? { ...emptyLegal(), attackers: myFigs, canEndTurn: true }
|
||||
: scene === 'block' ? { ...emptyLegal(), blockers: Object.fromEntries(mine.filter(c => c.type === 'Figure' || c.type === 'Location').map(c => [c.id, view.combat.map(a => a.attackerId)])) }
|
||||
: emptyLegal();
|
||||
return { view, legal };
|
||||
}
|
||||
const emptyLegal = (): Legal => ({ plays: {}, canGoToCombat: false, attackers: [], blockers: {}, canEndTurn: false, mulligan: false });
|
||||
@@ -0,0 +1,235 @@
|
||||
// ui-duel (#58): the duel board's own view model. Board components read only these types, so the
|
||||
// engine contract (duel-core, mirrored in ./contract.ts) is mapped in exactly one place: ./adapter.ts.
|
||||
// Nothing here moves cards on-chain; matches are off-chain and never burn or transfer.
|
||||
|
||||
export type DuelCardType = 'Figure' | 'Location' | 'Event' | 'Institution' | 'Doctrine';
|
||||
export type Portal = 'Arts' | 'Earth' | 'History' | 'Science' | 'Society' | 'Neutral';
|
||||
export type Seat = 0 | 1;
|
||||
/** duel-core's phases (refresh, draw, damage and end are automatic). */
|
||||
export type Phase = 'mulligan' | 'main' | 'attack' | 'block' | 'over';
|
||||
|
||||
/** One card as the board shows it. Hidden cards never reach the board (opponent's hand is a count). */
|
||||
export type BoardCard = {
|
||||
id: string;
|
||||
title: string;
|
||||
type: DuelCardType;
|
||||
/** The line after the em dash, e.g. "People · 1961–". */
|
||||
subtype?: string;
|
||||
portal: Portal;
|
||||
cost: number;
|
||||
power?: number;
|
||||
toughness?: number;
|
||||
/** Base stats, to colour buffs and debuffs. */
|
||||
basePower?: number;
|
||||
baseToughness?: number;
|
||||
/** Damage marked this turn. */
|
||||
damage?: number;
|
||||
keywords: string[];
|
||||
rulesText: string;
|
||||
/** First sentence of the on-chain extract. */
|
||||
flavour?: string;
|
||||
image?: string;
|
||||
url?: string;
|
||||
revisionId?: number;
|
||||
tapped?: boolean;
|
||||
/** "Pending review": entered this turn, can't attack. */
|
||||
pending?: boolean;
|
||||
/** Doctrine attached to this card (ids), or the Figure a Doctrine is attached to. */
|
||||
attachments?: string[];
|
||||
attachedTo?: string;
|
||||
token?: boolean;
|
||||
/** Active Connected bonus, e.g. "Compatriot (Portugal): +1/+1". */
|
||||
connectedNote?: string;
|
||||
};
|
||||
|
||||
export type SideView = {
|
||||
name: string;
|
||||
notability: number;
|
||||
citations: number;
|
||||
maxCitations: number;
|
||||
library: number;
|
||||
hand: number;
|
||||
battlefield: BoardCard[];
|
||||
graveyard: number;
|
||||
};
|
||||
|
||||
export type Attack = { attackerId: string; blockerId?: string };
|
||||
|
||||
export type BoardView = {
|
||||
seat: Seat;
|
||||
turn: number;
|
||||
/** Whose turn it is. */
|
||||
active: Seat;
|
||||
phase: Phase;
|
||||
me: SideView;
|
||||
opponent: SideView;
|
||||
hand: BoardCard[];
|
||||
/** Current combat: attackers (opponent's when I'm blocking) and any blocks already declared. */
|
||||
combat: Attack[];
|
||||
log: string[];
|
||||
winner?: Seat | 'draw';
|
||||
/** Seconds left this turn, and in the bank, for the player to act. */
|
||||
clock?: { turn: number; bank: number };
|
||||
};
|
||||
|
||||
/** What the board can ask the controller to do. The adapter turns these into engine actions. */
|
||||
export type DuelUIAction =
|
||||
| { type: 'mulligan'; keep: boolean }
|
||||
/** targetIds: card uids or `player:<seat>`, one per chosen-target effect, in order. */
|
||||
| { type: 'play'; cardId: string; targetIds: string[] }
|
||||
| { type: 'toCombat' }
|
||||
| { type: 'attack'; attackerIds: string[] }
|
||||
| { type: 'block'; blocks: { blockerId: string; attackerId: string }[] }
|
||||
| { type: 'endTurn' }
|
||||
| { type: 'concede' };
|
||||
|
||||
/** What the engine says is legal right now, in board terms. */
|
||||
export type Legal = {
|
||||
/** Hand card id → every legal target sequence ([[]] = needs no target). Absent = can't be played now. */
|
||||
plays: Record<string, string[][]>;
|
||||
canGoToCombat: boolean;
|
||||
/** Figures that may be declared as attackers. */
|
||||
attackers: string[];
|
||||
/** blocker id → attacker ids it may block (Featured, Translated and Garrison are the engine's call). */
|
||||
blockers: Record<string, string[]>;
|
||||
canEndTurn: boolean;
|
||||
mulligan: boolean;
|
||||
};
|
||||
|
||||
export const NO_LEGAL: Legal = { plays: {}, canGoToCombat: false, attackers: [], blockers: {}, canEndTurn: false, mulligan: false };
|
||||
|
||||
// ---------- targeting (multi-step: e.g. a sport Event picks your Figure, then theirs) ----------
|
||||
|
||||
export const playerTarget = (seat: Seat) => `player:${seat}`;
|
||||
|
||||
/** Ids that may be chosen next, given the targets already chosen for this card. */
|
||||
export function nextTargets(seqs: string[][] | undefined, chosen: string[]): Set<string> {
|
||||
const out = new Set<string>();
|
||||
for (const q of seqs ?? []) if (q.length > chosen.length && chosen.every((t, i) => q[i] === t)) out.add(q[chosen.length]);
|
||||
return out;
|
||||
}
|
||||
/** True when `chosen` is a complete legal sequence. */
|
||||
export const targetsComplete = (seqs: string[][] | undefined, chosen: string[]) =>
|
||||
!!seqs?.some(q => q.length === chosen.length && q.every((t, i) => t === chosen[i]));
|
||||
|
||||
// ---------- combat declaration (pure, so it is unit-tested) ----------
|
||||
|
||||
/**
|
||||
* Attack: one tap toggles a Figure in or out. Block: tap your blocker (1), then the attacker it
|
||||
* blocks (2). Tapping an assigned blocker again removes it. At most one blocker per attacker and
|
||||
* one attacker per blocker (BRIEF: single blocks).
|
||||
*/
|
||||
export type Declaration = { attackers: string[]; blocks: Record<string, string>; picked?: string };
|
||||
export const EMPTY_DECL: Declaration = { attackers: [], blocks: {} };
|
||||
|
||||
export function toggleAttacker(d: Declaration, id: string, legal: Legal): Declaration {
|
||||
if (!legal.attackers.includes(id)) return d;
|
||||
const attackers = d.attackers.includes(id) ? d.attackers.filter(a => a !== id) : [...d.attackers, id];
|
||||
return { ...d, attackers };
|
||||
}
|
||||
|
||||
/** Tap on one of my cards during blocks. */
|
||||
export function tapBlocker(d: Declaration, blockerId: string, legal: Legal): Declaration {
|
||||
if (d.blocks[blockerId]) { const blocks = { ...d.blocks }; delete blocks[blockerId]; return { ...d, blocks, picked: undefined }; }
|
||||
if (!legal.blockers[blockerId]?.length) return d;
|
||||
return { ...d, picked: d.picked === blockerId ? undefined : blockerId };
|
||||
}
|
||||
|
||||
/** Tap on an attacker during blocks. With a blocker picked, assign it; the attacker's old blocker is freed. */
|
||||
export function tapAttacker(d: Declaration, attackerId: string, legal: Legal): Declaration {
|
||||
const picked = d.picked;
|
||||
if (!picked) {
|
||||
// No blocker picked: tapping a blocked attacker clears its block.
|
||||
const owner = Object.entries(d.blocks).find(([, a]) => a === attackerId)?.[0];
|
||||
if (!owner) return d;
|
||||
const blocks = { ...d.blocks }; delete blocks[owner]; return { ...d, blocks };
|
||||
}
|
||||
if (!legal.blockers[picked]?.includes(attackerId)) return d;
|
||||
const blocks = Object.fromEntries(Object.entries(d.blocks).filter(([, a]) => a !== attackerId));
|
||||
blocks[picked] = attackerId;
|
||||
return { ...d, blocks, picked: undefined };
|
||||
}
|
||||
|
||||
export const blockList = (d: Declaration) => Object.entries(d.blocks).map(([blockerId, attackerId]) => ({ blockerId, attackerId }));
|
||||
|
||||
// ---------- combat preview ----------
|
||||
|
||||
export type CombatOutcome = {
|
||||
/** Damage the defending player takes. */
|
||||
toPlayer: number;
|
||||
/** Card ids that would be destroyed. */
|
||||
destroyed: string[];
|
||||
rows: { attacker: BoardCard; blocker?: BoardCard; attackerDies: boolean; blockerDies: boolean }[];
|
||||
};
|
||||
|
||||
const has = (c: BoardCard | undefined, kw: string) => !!c?.keywords.some(k => k.toLowerCase() === kw.toLowerCase());
|
||||
/** Damage a card takes from one source, after Well-sourced (prevent the first 1 each turn). */
|
||||
const taken = (c: BoardCard, dmg: number) => Math.max(0, dmg - (has(c, 'Well-sourced') && !(c.damage ?? 0) ? 1 : 0));
|
||||
const dies = (c: BoardCard, dmg: number) => c.toughness !== undefined && (c.damage ?? 0) + taken(c, dmg) >= c.toughness && dmg > 0;
|
||||
|
||||
/**
|
||||
* A preview for the confirm sheet: simultaneous damage, single blocks, no trample or first strike
|
||||
* (BRIEF). The engine resolves for real; this is only so the player sees what they are confirming.
|
||||
*/
|
||||
export function previewCombat(attacks: Attack[], cards: Map<string, BoardCard>): CombatOutcome {
|
||||
const out: CombatOutcome = { toPlayer: 0, destroyed: [], rows: [] };
|
||||
for (const { attackerId, blockerId } of attacks) {
|
||||
const attacker = cards.get(attackerId);
|
||||
if (!attacker) continue;
|
||||
const blocker = blockerId ? cards.get(blockerId) : undefined;
|
||||
if (!blocker) { out.toPlayer += attacker.power ?? 0; out.rows.push({ attacker, attackerDies: false, blockerDies: false }); continue; }
|
||||
const attackerDies = dies(attacker, blocker.power ?? 0);
|
||||
const blockerDies = dies(blocker, attacker.power ?? 0);
|
||||
if (attackerDies) out.destroyed.push(attacker.id);
|
||||
if (blockerDies) out.destroyed.push(blocker.id);
|
||||
out.rows.push({ attacker, blocker, attackerDies, blockerDies });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---------- eligibility (BRIEF decisions 1–3) ----------
|
||||
|
||||
export const DEFAULT_DECK_SIZE = 40;
|
||||
|
||||
export type Eligibility = { eligible: boolean; owned: number; needed: number; label: string };
|
||||
|
||||
/** Bot and PvP matches are only for players who own a full deck. There is no borrowed-card play. */
|
||||
export function eligibility(owned: number, deckSize = DEFAULT_DECK_SIZE): Eligibility {
|
||||
const needed = Math.max(0, deckSize - owned);
|
||||
return { eligible: needed === 0, owned, needed, label: `${Math.min(owned, deckSize)} / ${deckSize} cards` };
|
||||
}
|
||||
|
||||
// ---------- text helpers ----------
|
||||
|
||||
/**
|
||||
* First sentence of an extract, for flavour text. Doesn't split on initials ("J. R. R."), common
|
||||
* abbreviations or decimals. Falls back to the whole (trimmed) text.
|
||||
*/
|
||||
export function firstSentence(text: string | undefined, max = 220): string | undefined {
|
||||
const t = text?.replace(/\s+/g, ' ').trim();
|
||||
if (!t) return undefined;
|
||||
const re = /[.!?](?=\s+[A-Z0-9"“(])/g;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(t))) {
|
||||
const before = t.slice(0, m.index);
|
||||
const word = before.split(' ').at(-1) ?? '';
|
||||
if (/^[A-Z]$/.test(word) || /^(Mr|Mrs|Ms|Dr|St|Jr|Sr|No|Mt|Ft|vs|c|ca|approx|e\.g|i\.e|U\.S|U\.K)$/i.test(word)) continue;
|
||||
return clip(t.slice(0, m.index + 1), max);
|
||||
}
|
||||
return clip(t, max);
|
||||
}
|
||||
const clip = (s: string, max: number) => (s.length <= max ? s : `${s.slice(0, max - 1).replace(/\s+\S*$/, '')}…`);
|
||||
|
||||
/** "Figure — People · 1961–" */
|
||||
export const typeLine = (c: Pick<BoardCard, 'type' | 'subtype' | 'portal'>) =>
|
||||
`${c.type} — ${c.subtype ?? c.portal}`;
|
||||
|
||||
/** Accessible one-line summary of a card. */
|
||||
export function cardSummary(c: BoardCard): string {
|
||||
const stats = c.power !== undefined ? `, ${c.power}/${c.toughness ?? 0}` : '';
|
||||
const kw = c.keywords.length ? `, ${c.keywords.join(', ')}` : '';
|
||||
const state = `${c.tapped ? ', tapped' : ''}${c.pending ? ', pending review' : ''}${c.damage ? `, ${c.damage} damage` : ''}`;
|
||||
return `${c.title}, ${typeLine(c)}, cost ${c.cost}${stats}${kw}${state}`;
|
||||
}
|
||||
|
||||
export const isMyTurn = (v: BoardView) => v.active === v.seat && v.phase !== 'over';
|
||||
+12
-8
@@ -1,8 +1,12 @@
|
||||
import './native.ts';
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import App from './App.tsx';
|
||||
import './index.css';
|
||||
import './themes.css';
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(<React.StrictMode><App /></React.StrictMode>);
|
||||
import './native.ts';
|
||||
import React, { Suspense, lazy } from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import App from './App.tsx';
|
||||
import './index.css';
|
||||
import './themes.css';
|
||||
|
||||
// ui-duel review aid: `#duel-preview` renders static duel board scenes from card-sample.json.
|
||||
const DuelPreview = lazy(() => import('./game/duel/DuelPreview.tsx').then(m => ({ default: m.DuelPreview })));
|
||||
const LivePreview = lazy(() => import('./game/duel/LivePreview.tsx').then(m => ({ default: m.LivePreview })));
|
||||
const root = location.hash.startsWith('#duel-live') ? <Suspense fallback={null}><LivePreview /></Suspense> : location.hash.startsWith('#duel-preview') ? <Suspense fallback={null}><DuelPreview /></Suspense> : <App />;
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(<React.StrictMode>{root}</React.StrictMode>);
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
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 === undefined || /^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: [], 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}`);
|
||||
});
|
||||
|
||||
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]]);
|
||||
});
|
||||
@@ -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'));
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import type { DuelAction, DuelCard, LogEvent, PermanentView, PlayerView, SideView } from '../src/game/duel/contract.ts';
|
||||
import { boardFromView, expand, legalFromActions, plainLog } from '../src/game/duel/adapter.ts';
|
||||
|
||||
const card = (id: string, extra: Partial<DuelCard> = {}): DuelCard => ({
|
||||
cardId: id, pageId: 1, revisionId: 100, title: id, type: 'Figure', portal: 'Society', cost: 2, power: 2, toughness: 2,
|
||||
keywords: [], effects: [], rulesText: '', flavor: 'A thing. More.', ...extra,
|
||||
});
|
||||
const perm = (uid: string, controller: 0 | 1, c: DuelCard, extra: Partial<PermanentView> = {}): PermanentView => ({
|
||||
uid, owner: controller, controller, card: c, tapped: false, sick: false, damage: 0, counters: 0,
|
||||
power: c.power ?? 0, toughness: c.toughness ?? 0, keywords: c.keywords, ...extra,
|
||||
});
|
||||
const side = (seat: 0 | 1, extra: Partial<SideView> = {}): SideView => ({
|
||||
seat, life: 20, citations: 3, maxCitations: 4, handSize: 2, librarySize: 30, graveyard: [], bankSeconds: 300, ready: true, mulligansTaken: 0, ...extra,
|
||||
});
|
||||
|
||||
function view(): PlayerView {
|
||||
const fig = card('fig', { keywords: ['Legacy'] });
|
||||
return {
|
||||
engine: 'duel', seat: 1, turn: 5, active: 0, phase: 'block', toAct: 1,
|
||||
you: { ...side(1), hand: [{ uid: '1:7', owner: 1, card: card('ev', { type: 'Event', power: null, toughness: null }) }] },
|
||||
opponent: side(0, { life: 12 }),
|
||||
battlefield: [
|
||||
perm('0:1', 0, fig, { tapped: true, power: 4, toughness: 3 }),
|
||||
perm('0:2', 0, card('loc', { type: 'Location', power: 0, toughness: 0 })),
|
||||
perm('1:3', 1, card('mine'), { sick: true, connected: { with: '1:4', tier: 'Compatriot', via: 'Portugal', bonus: 1 } }),
|
||||
perm('1:4', 1, card('gar', { type: 'Location', power: 0, toughness: 3 })),
|
||||
perm('1:5', 1, card('doc', { type: 'Doctrine', power: null, toughness: null }), { attachedTo: '1:3' }),
|
||||
],
|
||||
combat: { attackers: ['0:1'], blocks: {} }, result: null, version: 9, rules: {},
|
||||
};
|
||||
}
|
||||
|
||||
test('PlayerView → board: sides from my seat, current stats, Garrison only when T > 0, attachments, Connected', () => {
|
||||
const b = boardFromView(view(), ['alice', 'bob'], ['Turn 5.']);
|
||||
assert.equal(b.me.name, 'bob');
|
||||
assert.equal(b.opponent.name, 'alice');
|
||||
assert.equal(b.opponent.notability, 12);
|
||||
assert.deepEqual(b.combat, [{ attackerId: '0:1', blockerId: undefined }]);
|
||||
const att = b.opponent.battlefield.find(c => c.id === '0:1')!;
|
||||
assert.equal(att.power, 4); assert.equal(att.basePower, 2); assert.equal(att.tapped, true);
|
||||
assert.equal(b.opponent.battlefield.find(c => c.id === '0:2')!.power, undefined);
|
||||
assert.equal(b.me.battlefield.find(c => c.id === '1:4')!.toughness, 3);
|
||||
const mine = b.me.battlefield.find(c => c.id === '1:3')!;
|
||||
assert.deepEqual(mine.attachments, ['1:5']);
|
||||
assert.ok(mine.keywords.includes('Connected'));
|
||||
assert.equal(mine.pending, true);
|
||||
assert.equal(mine.connectedNote, 'Compatriot (Portugal): +1/+1');
|
||||
assert.equal(b.hand[0].id, '1:7');
|
||||
assert.equal(b.hand[0].flavour, 'A thing.');
|
||||
});
|
||||
|
||||
test('legal actions → board legality, and board intents → atomic action sequences', () => {
|
||||
const legal: DuelAction[] = [
|
||||
{ type: 'block', blocker: '1:3', attacker: '0:1' }, { type: 'block', blocker: '1:4', attacker: '0:1' }, { type: 'confirmBlocks' },
|
||||
];
|
||||
const l = legalFromActions(legal);
|
||||
assert.deepEqual(l.blockers, { '1:3': ['0:1'], '1:4': ['0:1'] });
|
||||
assert.deepEqual(expand({ type: 'block', blocks: [{ blockerId: '1:4', attackerId: '0:1' }] }, legal),
|
||||
[{ type: 'block', blocker: '1:4', attacker: '0:1' }, { type: 'confirmBlocks' }]);
|
||||
|
||||
const main: DuelAction[] = [
|
||||
{ type: 'play', uid: 'h1' },
|
||||
{ type: 'play', uid: 'h2', targets: [{ kind: 'card', uid: 'a' }, { kind: 'card', uid: 'x' }] },
|
||||
{ type: 'play', uid: 'h3', targets: [{ kind: 'player', seat: 0 }] },
|
||||
{ type: 'endPhase' },
|
||||
];
|
||||
const m = legalFromActions(main);
|
||||
assert.deepEqual(m.plays, { h1: [[]], h2: [['a', 'x']], h3: [['player:0']] });
|
||||
assert.equal(m.canGoToCombat, true);
|
||||
// The exact legal element comes back, so the host's deep-equal check passes (no `targets: []`).
|
||||
assert.strictEqual(expand({ type: 'play', cardId: 'h1', targetIds: [] }, main)[0], main[0]);
|
||||
assert.strictEqual(expand({ type: 'play', cardId: 'h3', targetIds: ['player:0'] }, main)[0], main[2]);
|
||||
assert.deepEqual(expand({ type: 'endTurn' }, main), [{ type: 'endPhase' }, { type: 'confirmAttack' }]);
|
||||
assert.deepEqual(expand({ type: 'attack', attackerIds: ['a', 'b'] }, [{ type: 'toggleAttacker', uid: 'a' }, { type: 'toggleAttacker', uid: 'b' }, { type: 'confirmAttack' }]),
|
||||
[{ type: 'toggleAttacker', uid: 'a' }, { type: 'toggleAttacker', uid: 'b' }, { type: 'confirmAttack' }]);
|
||||
assert.deepEqual(expand({ type: 'mulligan', keep: true }, [{ type: 'keep' }, { type: 'mulligan' }]), [{ type: 'keep' }]);
|
||||
assert.equal(legalFromActions([]).canEndTurn, false);
|
||||
});
|
||||
|
||||
test('fallback log: real names and titles only, no adjectives', () => {
|
||||
const ref = (title: string) => ({ uid: title, cardId: title, title, pageId: 1, type: 'Figure' as const, power: 3, toughness: 2 });
|
||||
const events: LogEvent[] = [
|
||||
{ seq: 1, turn: 3, kind: 'turnStart', seat: 0, citations: 3, life: [20, 20] },
|
||||
{ seq: 2, turn: 3, kind: 'deploy', seat: 0, card: ref('Cho Yang-ho') },
|
||||
{ seq: 3, turn: 3, kind: 'attack', seat: 0, attackers: [ref('Cho Yang-ho')] },
|
||||
{ seq: 4, turn: 3, kind: 'playerDamage', source: ref('Cho Yang-ho'), seat: 1, amount: 3, life: 17, combat: true },
|
||||
{ seq: 5, turn: 3, kind: 'destroyed', card: ref('Dichromorpha viridis'), owner: 1 },
|
||||
{ seq: 6, turn: 9, kind: 'gameOver', winner: 0, reason: 'life', life: [12, 0] },
|
||||
];
|
||||
assert.deepEqual(plainLog(events, ['Eric', 'Bot (Normal)']), [
|
||||
'Turn 3.', 'Eric deployed Cho Yang-ho.', 'Cho Yang-ho (3/2) attacked.', 'Bot (Normal) lost 3 Notability (17 remaining).',
|
||||
'Dichromorpha viridis was moved to Deleted.', 'Bot (Normal) was nominated for deletion. The result was delete.',
|
||||
]);
|
||||
});
|
||||
|
||||
test('bot match decks: exactly deckSize owned, profiled cards; the bot deck is its own and deterministic', async () => {
|
||||
const { botDeck, playerDeck } = await import('../src/game/duel/decks.ts');
|
||||
const cards = Array.from({ length: 41 }, (_, i) => ({ tokenId: `t${i}`, title: `Card ${i}`, duel: card(`d${i}`, { pageId: i }) }));
|
||||
const ids = cards.slice(0, 40).map(c => c.tokenId);
|
||||
const ok = playerDeck(ids, cards, 40);
|
||||
assert.equal(ok.cards.length, 40);
|
||||
assert.equal(ok.cards[0].cardId, 't0'); // the NFT tokenId, not the profile id
|
||||
assert.equal(playerDeck(ids.slice(0, 39), cards, 40).cards.length, 0); // no partial decks, no filler
|
||||
assert.deepEqual(playerDeck([...ids.slice(0, 39), 'nope'], cards, 40).missing, ['nope']);
|
||||
const noProfile = cards.map((c, i) => (i === 3 ? { tokenId: c.tokenId, title: c.title } : c));
|
||||
assert.deepEqual(playerDeck(ids, noProfile, 40).pending, ['Card 3']);
|
||||
const pool = Array.from({ length: 236 }, (_, i) => card(`s${i}`, { pageId: i }));
|
||||
const a = botDeck(pool, 40, 'seed'), b = botDeck(pool, 40, 'seed');
|
||||
assert.deepEqual(a, b);
|
||||
assert.equal(new Set(a.map(c => c.cardId)).size, 40);
|
||||
assert.ok(a.every(c => c.cardId.startsWith('bot:')));
|
||||
assert.notDeepEqual(botDeck(pool, 40, 'other').map(c => c.cardId), a.map(c => c.cardId));
|
||||
});
|
||||
|
||||
test('bot match: untyped profiles from the wire are shape-checked', async () => {
|
||||
const { playerDeck, isDuelCard } = await import('../src/game/duel/decks.ts');
|
||||
assert.equal(isDuelCard(card('x')), true);
|
||||
assert.equal(isDuelCard({ title: 'x' }), false);
|
||||
assert.equal(isDuelCard(null), false);
|
||||
const cards = Array.from({ length: 40 }, (_, i) => ({ tokenId: `t${i}`, title: `C${i}`, duel: i === 5 ? { junk: true } : card(`d${i}`) }));
|
||||
assert.deepEqual(playerDeck(cards.map(c => c.tokenId), cards, 40).pending, ['C5']);
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { EASY_BOT, NORMAL_BOT } from '../src/game/duel/bots.ts';
|
||||
import type { DuelAction, DuelCard, PermanentView, PlayerView } from '../src/game/duel/contract.ts';
|
||||
|
||||
const card = (id: string, extra: Partial<DuelCard> = {}): DuelCard => ({
|
||||
cardId: id, pageId: 1, title: id, type: 'Figure', portal: 'Society', cost: 2, power: 2, toughness: 2, keywords: [], effects: [], rulesText: '', flavor: '', ...extra,
|
||||
});
|
||||
const perm = (uid: string, controller: 0 | 1, power: number, toughness: number, extra: Partial<PermanentView> = {}): PermanentView => ({
|
||||
uid, owner: controller, controller, card: card(uid, { power, toughness }), tapped: false, sick: false, damage: 0, counters: 0, power, toughness, keywords: [], ...extra,
|
||||
});
|
||||
const side = (seat: 0 | 1, life = 20) => ({ seat, life, citations: 3, maxCitations: 3, handSize: 0, librarySize: 30, graveyard: [], bankSeconds: 300, ready: true, mulligansTaken: 0 });
|
||||
const view = (p: Partial<PlayerView>): PlayerView => ({
|
||||
engine: 'duel', seat: 1, turn: 4, active: 1, phase: 'main', toAct: 1, you: { ...side(1), hand: [] }, opponent: side(0),
|
||||
battlefield: [], combat: { attackers: [], blocks: {} }, result: null, version: 1, rules: {}, ...p,
|
||||
});
|
||||
const rng = () => 0.5;
|
||||
|
||||
test('normal bot: plays the priciest card, harmful effects at the opponent', () => {
|
||||
const hand = [{ uid: '1:1', owner: 1 as const, card: card('cheap', { cost: 1 }) },
|
||||
{ uid: '1:2', owner: 1 as const, card: card('bolt', { type: 'Event', cost: 3, power: null, toughness: null, effects: [{ op: 'damage', amount: 3 }] }) }];
|
||||
const v = view({ you: { ...side(1), hand }, battlefield: [perm('0:9', 0, 3, 3), perm('1:8', 1, 2, 2)] });
|
||||
const legal: DuelAction[] = [{ type: 'play', uid: '1:1' },
|
||||
{ type: 'play', uid: '1:2', targets: [{ kind: 'card', uid: '1:8' }] }, { type: 'play', uid: '1:2', targets: [{ kind: 'card', uid: '0:9' }] }, { type: 'endPhase' }];
|
||||
assert.deepEqual(NORMAL_BOT.choose(v, legal, rng), legal[2]);
|
||||
});
|
||||
|
||||
test('normal bot: attacks unless a blocker eats it, all-in on lethal, then confirms', () => {
|
||||
const bf = [perm('1:1', 1, 3, 3), perm('1:2', 1, 1, 1), perm('0:1', 0, 2, 4)];
|
||||
const legal: DuelAction[] = [{ type: 'toggleAttacker', uid: '1:1' }, { type: 'toggleAttacker', uid: '1:2' }, { type: 'confirmAttack' }];
|
||||
// 1:1 (3/3) faces a 2/4 that survives but doesn't kill: attack. 1:2 (1/1) would die to it for nothing.
|
||||
const v = view({ phase: 'attack', battlefield: bf });
|
||||
assert.deepEqual(NORMAL_BOT.choose(v, legal, rng), legal[0]);
|
||||
const after = view({ phase: 'attack', battlefield: bf, combat: { attackers: ['1:1'], blocks: {} } });
|
||||
assert.deepEqual(NORMAL_BOT.choose(after, legal.slice(1), rng), { type: 'confirmAttack' });
|
||||
const lethal = view({ phase: 'attack', battlefield: bf, opponent: side(0, 1), combat: { attackers: ['1:1'], blocks: {} } });
|
||||
assert.deepEqual(NORMAL_BOT.choose(lethal, legal.slice(1), rng), legal[1]);
|
||||
});
|
||||
|
||||
test('normal bot: takes the kill-and-survive block, otherwise no block', () => {
|
||||
const bf = [perm('0:1', 0, 2, 2), perm('1:1', 1, 3, 3), perm('1:2', 1, 1, 1)];
|
||||
const v = view({ phase: 'block', active: 0, battlefield: bf, combat: { attackers: ['0:1'], blocks: {} } });
|
||||
const legal: DuelAction[] = [{ type: 'block', blocker: '1:1', attacker: '0:1' }, { type: 'block', blocker: '1:2', attacker: '0:1' }, { type: 'confirmBlocks' }];
|
||||
assert.deepEqual(NORMAL_BOT.choose(v, legal, rng), legal[0]);
|
||||
assert.deepEqual(NORMAL_BOT.choose(v, legal.slice(1), rng), { type: 'confirmBlocks' });
|
||||
});
|
||||
|
||||
test('bots always return a listed action and keep their opening hand', () => {
|
||||
const legal: DuelAction[] = [{ type: 'keep' }, { type: 'mulligan' }];
|
||||
assert.deepEqual(NORMAL_BOT.choose(view({ phase: 'mulligan' }), legal, rng), { type: 'keep' });
|
||||
let x = 1; const r = () => ((x = (x * 48271) % 2147483647) / 2147483647);
|
||||
for (let i = 0; i < 50; i++) assert.ok(legal.includes(EASY_BOT.choose(view({ phase: 'mulligan' }), legal, r)));
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
EMPTY_DECL, NO_LEGAL, blockList, cardSummary, eligibility, firstSentence, previewCombat, tapAttacker, tapBlocker, toggleAttacker, typeLine,
|
||||
type BoardCard, type Legal,
|
||||
} from '../src/game/duel/model.ts';
|
||||
import { PREVIEW_POOL, previewView } from '../src/game/duel/mock.ts';
|
||||
|
||||
const fig = (id: string, power: number, toughness: number, extra: Partial<BoardCard> = {}): BoardCard =>
|
||||
({ id, title: id, type: 'Figure', portal: 'Society', cost: 2, power, toughness, keywords: [], rulesText: '', ...extra });
|
||||
|
||||
test('attack declaration: one tap toggles a legal attacker, illegal ones are ignored', () => {
|
||||
const legal: Legal = { ...NO_LEGAL, attackers: ['a', 'b'] };
|
||||
let d = toggleAttacker(EMPTY_DECL, 'a', legal);
|
||||
assert.deepEqual(d.attackers, ['a']);
|
||||
d = toggleAttacker(d, 'z', legal);
|
||||
assert.deepEqual(d.attackers, ['a']);
|
||||
d = toggleAttacker(d, 'b', legal);
|
||||
d = toggleAttacker(d, 'a', legal);
|
||||
assert.deepEqual(d.attackers, ['b']);
|
||||
});
|
||||
|
||||
test('block declaration: two taps per blocker, single blocks, re-tap clears', () => {
|
||||
const legal: Legal = { ...NO_LEGAL, blockers: { x: ['A', 'B'], y: ['A'], z: [] } };
|
||||
let d = tapBlocker(EMPTY_DECL, 'x', legal);
|
||||
assert.equal(d.picked, 'x');
|
||||
d = tapAttacker(d, 'A', legal);
|
||||
assert.deepEqual(blockList(d), [{ blockerId: 'x', attackerId: 'A' }]);
|
||||
assert.equal(d.picked, undefined);
|
||||
// y takes over A; x is freed (at most one blocker per attacker).
|
||||
d = tapAttacker(tapBlocker(d, 'y', legal), 'A', legal);
|
||||
assert.deepEqual(blockList(d), [{ blockerId: 'y', attackerId: 'A' }]);
|
||||
// y can't block B: the tap is ignored and y stays picked.
|
||||
d = tapAttacker(tapBlocker(EMPTY_DECL, 'y', legal), 'B', legal);
|
||||
assert.deepEqual(blockList(d), []);
|
||||
// A blocker with no legal attacker can't be picked.
|
||||
assert.equal(tapBlocker(EMPTY_DECL, 'z', legal).picked, undefined);
|
||||
// Re-tapping an assigned blocker removes the block; so does tapping its attacker with nothing picked.
|
||||
d = tapAttacker(tapBlocker(EMPTY_DECL, 'x', legal), 'B', legal);
|
||||
assert.deepEqual(blockList(tapBlocker(d, 'x', legal)), []);
|
||||
assert.deepEqual(blockList(tapAttacker(d, 'B', legal)), []);
|
||||
// One blocker per attacker, and one attacker per blocker.
|
||||
d = tapAttacker(tapBlocker(d, 'x', legal), 'A', legal);
|
||||
assert.equal(blockList(d).length <= 1, true);
|
||||
});
|
||||
|
||||
test('combat preview: simultaneous damage, single blocks, Well-sourced, marked damage', () => {
|
||||
const cards = new Map([fig('a', 3, 3), fig('b', 2, 2), fig('c', 4, 1), fig('w', 1, 3, { keywords: ['Well-sourced'] }), fig('d', 2, 3, { damage: 1 })].map(c => [c.id, c]));
|
||||
const out = previewCombat([{ attackerId: 'a', blockerId: 'b' }, { attackerId: 'c' }], cards);
|
||||
assert.equal(out.toPlayer, 4);
|
||||
assert.deepEqual(out.destroyed.sort(), ['b']);
|
||||
// Well-sourced prevents the first 1: a 3-power attacker deals 2 to a 1/3, which survives.
|
||||
assert.deepEqual(previewCombat([{ attackerId: 'a', blockerId: 'w' }], cards).destroyed, []);
|
||||
// Damage already marked counts: 2 more kills a 2/3 with 1 damage.
|
||||
assert.deepEqual(previewCombat([{ attackerId: 'b', blockerId: 'd' }], cards).destroyed.sort(), ['b', 'd']);
|
||||
});
|
||||
|
||||
test('eligibility: exactly the deck size, no borrowed cards, progress label', () => {
|
||||
assert.deepEqual(eligibility(23), { eligible: false, owned: 23, needed: 17, label: '23 / 40 cards' });
|
||||
assert.equal(eligibility(40).eligible, true);
|
||||
assert.equal(eligibility(57).label, '40 / 40 cards');
|
||||
assert.equal(eligibility(12, 12).eligible, true); // testnet mode file may lower deckSize
|
||||
});
|
||||
|
||||
test('flavour: first sentence of the extract, not split on initials or abbreviations', () => {
|
||||
assert.equal(firstSentence('J. R. R. Tolkien was an English writer. He wrote books.'), 'J. R. R. Tolkien was an English writer.');
|
||||
assert.equal(firstSentence('St. Georgen am Längsee is a town. It is in Austria.'), 'St. Georgen am Längsee is a town.');
|
||||
assert.equal(firstSentence('Pi is about 3.14 in value. More.'), 'Pi is about 3.14 in value.');
|
||||
assert.equal(firstSentence('No full stop here'), 'No full stop here');
|
||||
assert.equal(firstSentence(''), undefined);
|
||||
assert.ok((firstSentence('word '.repeat(100)) ?? '').length <= 220);
|
||||
});
|
||||
|
||||
test('type line and accessible summary', () => {
|
||||
const c = fig('Barack Obama', 3, 4, { subtype: 'People · 1961–', keywords: ['Protected'], tapped: true });
|
||||
assert.equal(typeLine(c), 'Figure — People · 1961–');
|
||||
assert.equal(cardSummary(c), 'Barack Obama, Figure — People · 1961–, cost 2, 3/4, Protected, tapped');
|
||||
});
|
||||
|
||||
test('preview scenes: a full 5 + 5 board with every card from the real sample', () => {
|
||||
assert.equal(PREVIEW_POOL.length, 236);
|
||||
for (const scene of ['main', 'attack', 'block', 'over'] as const) {
|
||||
const { view } = previewView(scene);
|
||||
assert.equal(view.me.battlefield.length, 5);
|
||||
assert.equal(view.opponent.battlefield.length, 5);
|
||||
}
|
||||
for (const c of PREVIEW_POOL) {
|
||||
assert.ok(c.keywords.length <= 2, c.title);
|
||||
assert.ok(c.cost >= 1 && c.cost <= 6, c.title);
|
||||
}
|
||||
});
|
||||
|
||||
test('DuelCard → board card: type line from real data only, flavour is one sentence', async () => {
|
||||
const { boardCard, lifespan } = await import('../src/game/duel/cards.ts');
|
||||
assert.equal(lifespan('Sultan of Aceh (1530–1537/9)'), '1530–1537');
|
||||
assert.equal(lifespan('American voice actor and singer (born 1963)'), '1963–');
|
||||
assert.equal(lifespan('American botanist (c.1872–1919)'), '1872–1919');
|
||||
assert.equal(lifespan('Species of grasshopper'), undefined);
|
||||
const c = boardCard({ cardId: 't', pageId: 1, revisionId: 9, title: 'Salahuddin of Aceh', type: 'Figure', subtype: null, portal: 'History',
|
||||
cost: 4, power: 4, toughness: 3, keywords: ['Legacy'], rulesText: 'Legacy.', flavor: 'Sultan of Aceh (1530–1537/9). Second sentence.' });
|
||||
assert.equal(typeLine(c), 'Figure — History · 1530–1537');
|
||||
assert.equal(c.flavour, 'Sultan of Aceh (1530–1537/9).');
|
||||
assert.equal(c.url, 'https://en.wikipedia.org/wiki/Salahuddin_of_Aceh');
|
||||
const e = boardCard({ cardId: 'e', pageId: 2, revisionId: 9, title: '1954 Gold Coast general election', type: 'Event', subtype: 'election', portal: 'Society',
|
||||
cost: 4, power: null, toughness: null, keywords: [], rulesText: 'x', flavor: '' });
|
||||
assert.equal(typeLine(e), 'Event — Society · Election');
|
||||
assert.equal(e.power, undefined);
|
||||
});
|
||||
|
||||
test('targeting: multi-step sequences (own Figure, then theirs), players as targets', async () => {
|
||||
const { nextTargets, targetsComplete, playerTarget } = await import('../src/game/duel/model.ts');
|
||||
const seqs = [['a', 'x'], ['a', 'y'], ['b', 'x']];
|
||||
assert.deepEqual([...nextTargets(seqs, [])].sort(), ['a', 'b']);
|
||||
assert.deepEqual([...nextTargets(seqs, ['a'])].sort(), ['x', 'y']);
|
||||
assert.deepEqual([...nextTargets(seqs, ['b'])], ['x']);
|
||||
assert.equal(targetsComplete(seqs, ['a']), false);
|
||||
assert.equal(targetsComplete(seqs, ['a', 'y']), true);
|
||||
assert.equal(targetsComplete([[]], []), true);
|
||||
assert.equal(nextTargets([[playerTarget(1)], ['c']], []).has('player:1'), true);
|
||||
});
|
||||
Reference in New Issue
Block a user