From 4160086d16976c0fa9e38fea94dd0348169fdbc7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:54:04 -0500 Subject: [PATCH] ui-duel: duel-core adapter and DuelBoard (PlayerView + DuelAction[]) for ui-pvp (#58) Board intents expand to duel-core's atomic actions (toggleAttacker x N, confirmAttack; block x N, confirmBlocks), sent in order and awaited. Fallback log uses the first DUEL_DESIGN 8.2 variant until the story renderer reads engine events. Co-Authored-By: Claude Opus 5.5 --- src/game/duel/DuelBoard.tsx | 39 ++++++++++++ src/game/duel/DuelTable.tsx | 1 + src/game/duel/adapter.ts | 109 ++++++++++++++++++++++++++++++++++ src/game/duel/cards.ts | 12 ++-- src/game/duel/model.ts | 2 + tests/ui-duel-adapter.test.ts | 97 ++++++++++++++++++++++++++++++ 6 files changed, 256 insertions(+), 4 deletions(-) create mode 100644 src/game/duel/DuelBoard.tsx create mode 100644 src/game/duel/adapter.ts create mode 100644 tests/ui-duel-adapter.test.ts diff --git a/src/game/duel/DuelBoard.tsx b/src/game/duel/DuelBoard.tsx new file mode 100644 index 0000000..cb661a3 --- /dev/null +++ b/src/game/duel/DuelBoard.tsx @@ -0,0 +1,39 @@ +import { useMemo, useState } from 'react'; +import type { DuelAction, LogEvent, PlayerView } from '../../../shared/duel/types.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; + 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(); + 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 { void act(ui); }} busy={busy || sending} + error={error ?? sendError} onExit={onExit} onRecap={onRecap} />; +} diff --git a/src/game/duel/DuelTable.tsx b/src/game/duel/DuelTable.tsx index 5595336..42f8cc8 100644 --- a/src/game/duel/DuelTable.tsx +++ b/src/game/duel/DuelTable.tsx @@ -194,6 +194,7 @@ export function DuelTable({ view, legal, onAct, busy, error, onExit, onRecap }:

{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` : ''}

+ {sheet.card.connectedNote &&

Connected: {sheet.card.connectedNote}

} {sheet.where === 'hand' &&
{legal.plays[sheet.card.id] && !busy ? diff --git a/src/game/duel/adapter.ts b/src/game/duel/adapter.ts new file mode 100644 index 0000000..3a7b1b8 --- /dev/null +++ b/src/game/duel/adapter.ts @@ -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 '../../../shared/duel/types.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; + +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; +} diff --git a/src/game/duel/cards.ts b/src/game/duel/cards.ts index c66911c..77ed378 100644 --- a/src/game/duel/cards.ts +++ b/src/game/duel/cards.ts @@ -5,7 +5,8 @@ import type { BoardCard, DuelCardType, Portal } from './model.ts'; import { firstSentence } from './model.ts'; export type DuelCardLike = { - cardId: string; pageId: number; revisionId: number; title: string; type: DuelCardType; subtype: string | null; + 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; }; @@ -33,14 +34,17 @@ export function subtypeLine(card: Pick = {}): BoardCard { - const power = card.power ?? undefined, toughness = card.toughness ?? undefined; + // 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), - image: article.image, url: article.url ?? articleUrl(card.title), revisionId: card.revisionId, + 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, }; } diff --git a/src/game/duel/model.ts b/src/game/duel/model.ts index 49aadcc..6100361 100644 --- a/src/game/duel/model.ts +++ b/src/game/duel/model.ts @@ -38,6 +38,8 @@ export type BoardCard = { attachments?: string[]; attachedTo?: string; token?: boolean; + /** Active Connected bonus, e.g. "Compatriot (Portugal): +1/+1". */ + connectedNote?: string; }; export type SideView = { diff --git a/tests/ui-duel-adapter.test.ts b/tests/ui-duel-adapter.test.ts new file mode 100644 index 0000000..c229b24 --- /dev/null +++ b/tests/ui-duel-adapter.test.ts @@ -0,0 +1,97 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { DEFAULT_DUEL_RULESET } from '../shared/duel/ruleset.ts'; +import type { DuelAction, DuelCard, LogEvent, PermanentView, PlayerView, SideView } from '../shared/duel/types.ts'; +import { boardFromView, expand, legalFromActions, plainLog } from '../src/game/duel/adapter.ts'; + +const card = (id: string, extra: Partial = {}): 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 => ({ + 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 => ({ + 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: DEFAULT_DUEL_RULESET, + }; +} + +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.', + ]); +});