forked from WikiDeck/wikideck
ui-duel: follow duel-core contract phases; multi-step targets incl. players (#58)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+29
-21
@@ -4,8 +4,8 @@ import { DuelCardFace } from './DuelCardFace.tsx';
|
||||
import '../play.css';
|
||||
import './duel.css';
|
||||
import {
|
||||
EMPTY_DECL, blockList, isMyTurn, previewCombat, tapAttacker, tapBlocker, toggleAttacker,
|
||||
type Attack, type BoardCard, type BoardView, type Declaration, type DuelUIAction, type Legal, type SideView,
|
||||
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 =
|
||||
@@ -14,18 +14,19 @@ type Sheet =
|
||||
| { kind: 'log' } | { kind: 'concede' } | null;
|
||||
|
||||
const PHASE_LABEL: Record<BoardView['phase'], string> = {
|
||||
mulligan: 'Opening hand', refresh: 'Refresh', draw: 'Draw', main: 'Main', combat: 'Combat', block: 'Blocks', end: 'End', over: 'Match over',
|
||||
mulligan: 'Opening hand', main: 'Main', attack: 'Combat', block: 'Blocks', over: 'Match over',
|
||||
};
|
||||
|
||||
function SideBar({ side, who, active }: { side: SideView; who: 'me' | 'opponent'; active: boolean }) {
|
||||
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`;
|
||||
return <div className={`duel-side ${who} ${active ? 'is-active' : ''}`} role="group" aria-label={label}>
|
||||
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>
|
||||
</div>;
|
||||
</Tag>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -39,11 +40,12 @@ export function DuelTable({ view, legal, onAct, busy, error, onExit, onRecap }:
|
||||
}) {
|
||||
const [sheet, setSheet] = useState<Sheet>(null);
|
||||
const [decl, setDecl] = useState<Declaration>(EMPTY_DECL);
|
||||
const [targeting, setTargeting] = useState<string>();
|
||||
const [targeting, setTargeting] = useState<{ cardId: string; chosen: string[] }>();
|
||||
const logRef = useRef<HTMLOListElement>(null);
|
||||
|
||||
const mine = isMyTurn(view);
|
||||
const attackMode = mine && view.phase === 'combat' && !busy;
|
||||
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]);
|
||||
@@ -51,24 +53,30 @@ export function DuelTable({ view, legal, onAct, busy, error, onExit, onRecap }:
|
||||
|
||||
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 ? new Set(legal.plays[targeting] ?? []) : null;
|
||||
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, targetId?: string) => { setTargeting(undefined); setSheet(null); onAct({ type: 'play', cardId, targetId }); };
|
||||
const play = (cardId: string, targetIds: string[]) => { setTargeting(undefined); setSheet(null); onAct({ type: 'play', cardId, targetIds }); };
|
||||
const startPlay = (card: BoardCard) => {
|
||||
const t = legal.plays[card.id];
|
||||
if (!t) return;
|
||||
if (t.length) { setTargeting(card.id); setSheet(null); } else play(card.id);
|
||||
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) { if (targets.has(c.id)) play(targeting!, c.id); return; }
|
||||
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) { if (targets.has(c.id)) play(targeting!, c.id); return; }
|
||||
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' });
|
||||
};
|
||||
@@ -118,8 +126,8 @@ export function DuelTable({ view, legal, onAct, busy, error, onExit, onRecap }:
|
||||
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);
|
||||
note = <>Choose a target for <b>{c?.title}</b>.</>;
|
||||
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.';
|
||||
@@ -149,14 +157,14 @@ export function DuelTable({ view, legal, onAct, busy, error, onExit, onRecap }:
|
||||
|
||||
<div className="duel-main">
|
||||
<div className="duel-field">
|
||||
<SideBar side={view.opponent} who="opponent" active={view.active !== view.seat} />
|
||||
<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} />
|
||||
<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>
|
||||
@@ -168,7 +176,7 @@ export function DuelTable({ view, legal, onAct, busy, error, onExit, onRecap }:
|
||||
<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 === c.id }}
|
||||
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>
|
||||
@@ -188,7 +196,7 @@ export function DuelTable({ view, legal, onAct, busy, error, onExit, onRecap }:
|
||||
{sheet.card.tapped ? ' · tapped' : ''}{sheet.card.pending ? ' · Pending review (can’t attack this turn)' : ''}{sheet.card.damage ? ` · ${sheet.card.damage} damage marked` : ''}</p>
|
||||
{sheet.where === 'hand' && <div className="play-actions">
|
||||
{legal.plays[sheet.card.id] && !busy
|
||||
? <button className="button dark" onClick={() => startPlay(sheet.card)}>{legal.plays[sheet.card.id].length ? 'Play, then choose a target' : `Play for ${sheet.card.cost}`}</button>
|
||||
? <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>}
|
||||
</>}
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
|
||||
/* 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)}
|
||||
|
||||
@@ -84,7 +84,7 @@ export function previewView(scene: 'main' | 'attack' | 'block' | 'over' = 'main'
|
||||
'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' ? 'combat' : scene === 'block' ? 'block' : 'over',
|
||||
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 }] : [],
|
||||
@@ -93,7 +93,9 @@ export function previewView(scene: 'main' | 'attack' | 'block' | 'over' = 'main'
|
||||
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) : []])),
|
||||
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();
|
||||
|
||||
+20
-4
@@ -5,7 +5,8 @@
|
||||
export type DuelCardType = 'Figure' | 'Location' | 'Event' | 'Institution' | 'Doctrine';
|
||||
export type Portal = 'Arts' | 'Earth' | 'History' | 'Science' | 'Society' | 'Neutral';
|
||||
export type Seat = 0 | 1;
|
||||
export type Phase = 'mulligan' | 'refresh' | 'draw' | 'main' | 'combat' | 'block' | 'end' | 'over';
|
||||
/** 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 = {
|
||||
@@ -72,7 +73,8 @@ export type BoardView = {
|
||||
/** What the board can ask the controller to do. The adapter turns these into engine actions. */
|
||||
export type DuelUIAction =
|
||||
| { type: 'mulligan'; keep: boolean }
|
||||
| { type: 'play'; cardId: string; targetId?: string }
|
||||
/** 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 }[] }
|
||||
@@ -81,8 +83,8 @@ export type DuelUIAction =
|
||||
|
||||
/** What the engine says is legal right now, in board terms. */
|
||||
export type Legal = {
|
||||
/** Hand card id → legal target ids ([] = needs no target). Absent = can't be played now. */
|
||||
plays: Record<string, string[]>;
|
||||
/** 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[];
|
||||
@@ -94,6 +96,20 @@ export type Legal = {
|
||||
|
||||
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) ----------
|
||||
|
||||
/**
|
||||
|
||||
@@ -106,3 +106,15 @@ test('DuelCard → board card: type line from real data only, flavour is one sen
|
||||
assert.equal(typeLine(e), 'Event — Society · Election');
|
||||
assert.equal(e.power, undefined);
|
||||
});
|
||||
|
||||
test('targeting: multi-step sequences (own Figure, then theirs), players as targets', async () => {
|
||||
const { nextTargets, targetsComplete, playerTarget } = await import('../src/game/duel/model.ts');
|
||||
const seqs = [['a', 'x'], ['a', 'y'], ['b', 'x']];
|
||||
assert.deepEqual([...nextTargets(seqs, [])].sort(), ['a', 'b']);
|
||||
assert.deepEqual([...nextTargets(seqs, ['a'])].sort(), ['x', 'y']);
|
||||
assert.deepEqual([...nextTargets(seqs, ['b'])], ['x']);
|
||||
assert.equal(targetsComplete(seqs, ['a']), false);
|
||||
assert.equal(targetsComplete(seqs, ['a', 'y']), true);
|
||||
assert.equal(targetsComplete([[]], []), true);
|
||||
assert.equal(nextTargets([[playerTarget(1)], ['c']], []).has('player:1'), true);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user