Merge remote-tracking branch 'origin/night2/ui-duel/board' into prep/board

This commit is contained in:
2026-11-17 23:03:17 -05:00
19 changed files with 1762 additions and 8 deletions
+39
View File
@@ -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} />;
}
+78
View File
@@ -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} />;
}
+90
View File
@@ -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>;
}
+24
View File
@@ -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>;
}
+27
View File
@@ -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>;
}
+232
View File
@@ -0,0 +1,232 @@
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);
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" aria-label="Your hand">
{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>
<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>;
}
+109
View File
@@ -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;
}
+83
View File
@@ -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];
+50
View File
@@ -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,
};
}
+146
View File
@@ -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[];
}
+44
View File
@@ -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);
+40
View File
@@ -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 };
}
+153
View File
@@ -0,0 +1,153 @@
/* 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:-4px;right:-3px;z-index:3;font-size:10px;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-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)}
/* 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}
}
+104
View File
@@ -0,0 +1,104 @@
// 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') {
rulesText = `Territory. Garrison 0/${1 + Math.floor(c.tiers.depth / 3)}.`;
} 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 });
+235
View File
@@ -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';
+11 -8
View File
@@ -1,8 +1,11 @@
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 root = location.hash.startsWith('#duel-preview') ? <Suspense fallback={null}><DuelPreview /></Suspense> : <App />;
ReactDOM.createRoot(document.getElementById('root')!).render(<React.StrictMode>{root}</React.StrictMode>);
+124
View File
@@ -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']);
});
+53
View File
@@ -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)));
});
+120
View File
@@ -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);
});