ui-duel: DuelBotMatch (eligible players only, bot sees viewFor only) (#58)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 21:56:01 -05:00
co-authored by Claude Opus 5.5
parent 4160086d16
commit a7e46583fb
2 changed files with 125 additions and 0 deletions
+106
View File
@@ -0,0 +1,106 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import type { DuelEngineApi } from '../../../shared/duel/index.ts';
import { DEFAULT_DUEL_RULESET } from '../../../shared/duel/ruleset.ts';
import type { DuelAction, DuelCard, DuelRuleset, DuelState, PlayerView, Seat } from '../../../shared/duel/types.ts';
import type { Articles } from './adapter.ts';
import { DuelBoard } from './DuelBoard.tsx';
import { DuelGate } from './DuelGate.tsx';
/** 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?: DuelCard };
/** 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 };
const HUMAN: Seat = 0, BOT: Seat = 1;
const BOT_STEP_MS = 300;
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; };
}
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 (!c.duel) pending.push(c.title); else out.push({ ...c.duel, cardId: id });
}
return { cards: out.length === deckSize && deck.length === deckSize ? out : [], pending, missing };
}
/**
* 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({ deck, cards, onExit, onFinish, engine, bot, botPool, rules = DEFAULT_DUEL_RULESET, playerName = 'You', onMine }: {
deck: string[]; cards: BotMatchCard[]; onExit: () => void; onFinish: (matchId?: string) => void;
engine: DuelEngineApi; bot: DuelBot; botPool: readonly DuelCard[]; rules?: DuelRuleset; 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<DuelState | null>(null);
const [error, setError] = useState<string>();
const rng = useRef(mulberry(hash(seed)));
const current = useRef<DuelState | 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} />;
}
+19
View File
@@ -95,3 +95,22 @@ test('fallback log: real names and titles only, no adjectives', () => {
'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/DuelBotMatch.tsx');
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));
});