Night 2 (2026-11-17), from the `claude/wikideck` fork's `night/2026-11-17` branch. It follows Night 1 (#22).
## What's in it
- **Duel engine** (fork #72, #80): 40-card decks of cards you own, Notability/Citations, keywords, effects T1–T12, Connected, a hidden-information-safe `viewFor`/`logFor`, and replay. Balance v1 tuning (#84) gives the first player about 51%.
- **Card profiles** (#70, #82): Figure, Location, Event, Institution or Doctrine, plus stats, keywords and rules text, all derived from real article data. Templates only.
- **Design and story** (#66, #69, #83): DUEL_DESIGN.md, plus the match log and the encyclopedic "Battle of X (2026)" recap.
- **PvP** (#74, #77, #81, #76, #85):
- The server checks ownership, and 40-card eligibility is enforced.
- Modes: Classic (ranked), Draft and Trending.
- Invites, quick match, Elo, a ladder and recap pages. Online matches render on the duel board.
- **Duel board UI** (#79): MTG-style card faces and combat declaration, built for 360 px first.
- **Polite Wikimedia client** (#73, #75): throttled, cached and identified requests, the mint-path fix, and a prefetch pool.
- **Android mining** (#78): native RandomX, as a sideload build. The emulator mined a testnet block.
- **Testnet ops** (#67, #68).
PR numbers refer to `claude/wikideck`.
## Status
- **Tests:** 423, of which 422 pass, 0 fail and 1 is skipped. The build is OK (`node:24-alpine`, `--network none`).
- **Testnet:** running this commit (036489c) on r350.
- **Untouched:** no changes to `server/testnet/consensus.ts`, `randomx.ts`, `native/` or the mainnet compose.
- **Review:** night-review reviewed fork #66–#79. #80–#85 came from the agents' unfinished branches and were not reviewed.
- **Known gaps:**
- The PvP end-to-end test hasn't been run (it needs two eom.dev accounts).
- Bot matches aren't reachable from Play.
- Card identity pre-bake hasn't been done.
- The RandomX verifier latch (`server/testnet/randomx.ts:140`) is still open.
This PR is for Eric to merge.
🤖 Generated with [Claude Code](https://claude.com/claude-code)Reviewed-on: #23
Co-authored-by: Claude <claude@eom.dev>
234 lines
12 KiB
TypeScript
234 lines
12 KiB
TypeScript
// Duel bots: engine-agnostic heuristics for a Magic-style duel (attack/block/sorcery-speed plays).
|
|
// Bots see the duel through a DuelLens (a few accessors over state and action), so the same bots run
|
|
// on duel-core's shared/duel engine and on the sim stand-in. Pure: no I/O.
|
|
import type { EngineAdapter, Rng, Seat, BotFn } from './types.ts';
|
|
import { lookaheadBot } from './index.ts';
|
|
|
|
/**
|
|
* Observations may carry the acting seat's legal actions (`legal`): the UI shows them anyway, and choosing
|
|
* from them guarantees a bot never returns an action that is legal only in its determinized guess.
|
|
*/
|
|
function legalOf<S, A>(engine: EngineAdapter<S, A>, obs: unknown, s: S, seat: Seat): A[] {
|
|
const l = (obs as { legal?: A[] } | null)?.legal;
|
|
return Array.isArray(l) ? l : engine.legalActions(s, seat);
|
|
}
|
|
const seeState = <S, A>(engine: EngineAdapter<S, A>, obs: unknown, seat: Seat, rng: Rng): S => (engine.assume ? engine.assume(obs, seat, rng) : (obs as S));
|
|
|
|
/** Uniformly random legal action. */
|
|
export function duelRandomBot<S, A>(engine: EngineAdapter<S, A>): BotFn<unknown, A> {
|
|
return (obs, seat, rng) => { const l = (obs as { legal?: A[] })?.legal; const legal = Array.isArray(l) ? l : engine.legalActions(seeState(engine, obs, seat, rng), seat); return legal[Math.floor(rng() * legal.length)]; };
|
|
}
|
|
|
|
/** One-ply greedy on the evaluation over every legal action (weak at combat: toggles have no immediate value). */
|
|
export function duelGreedyBot<S, A>(engine: EngineAdapter<S, A>): BotFn<unknown, A> {
|
|
return (obs, seat, rng) => {
|
|
const s = seeState(engine, obs, seat, rng);
|
|
const legal = legalOf(engine, obs, s, seat);
|
|
let best = legal[0], bestV = -Infinity;
|
|
for (const a of legal) { const v = safeEval(engine, s, a, seat) + rng() * 1e-6; if (v > bestV) { bestV = v; best = a; } }
|
|
return best;
|
|
};
|
|
}
|
|
|
|
/** Evaluate `a` from `s`; an action the determinized state rejects scores -5 (it stays a candidate). */
|
|
function safeEval<S, A>(engine: EngineAdapter<S, A>, s: S, a: A, seat: Seat): number {
|
|
try { const n = engine.applyAction(s, a); return engine.isOver(n) ? (engine.result(n).winner === seat ? 10 : engine.result(n).winner === null ? 0 : -10) : engine.evaluate(n, seat); }
|
|
catch { return -5; }
|
|
}
|
|
|
|
export interface LensCreature { uid: string; power: number; toughness: number; tapped: boolean; canAttack: boolean; canBlock: boolean; value: number }
|
|
export type LensAction =
|
|
| { kind: 'play'; cost: number; cardType: string }
|
|
| { kind: 'attack'; uid: string; on: boolean }
|
|
| { kind: 'confirmAttack' }
|
|
| { kind: 'block'; blocker: string; attacker: string }
|
|
| { kind: 'confirmBlocks' }
|
|
| { kind: 'endMain' }
|
|
| { kind: 'mulligan' | 'keep' | 'other' };
|
|
|
|
export interface DuelLens<S, A> {
|
|
phase(s: S): 'main' | 'attack' | 'block' | 'mulligan' | 'other';
|
|
life(s: S, seat: Seat): number;
|
|
creatures(s: S, seat: Seat): LensCreature[];
|
|
handSize(s: S, seat: Seat): number;
|
|
/** Attackers currently declared by the active player (uids). */
|
|
attackers(s: S): string[];
|
|
/** Blocks declared so far [blocker, attacker]. */
|
|
blocks(s: S): [string, string][];
|
|
decode(s: S, a: A): LensAction;
|
|
}
|
|
|
|
/** Material evaluation in [-1, 1]: life, board (power+toughness) and cards in hand. */
|
|
export function duelEvaluate<S, A>(lens: DuelLens<S, A>, s: S, seat: Seat): number {
|
|
const o = (seat === 0 ? 1 : 0) as Seat;
|
|
const board = (p: Seat) => lens.creatures(s, p).reduce((t, c) => t + c.value, 0);
|
|
const myLife = lens.life(s, seat), oLife = lens.life(s, o);
|
|
const lifeTerm = (Math.min(myLife, 20) - Math.min(oLife, 20)) / 20 + (oLife <= 0 ? 1 : 0) - (myLife <= 0 ? 1 : 0);
|
|
const boardTerm = Math.tanh((board(seat) - board(o)) / 12);
|
|
const handTerm = Math.tanh((lens.handSize(s, seat) - lens.handSize(s, o)) / 6);
|
|
return Math.max(-1, Math.min(1, 0.4 * lifeTerm + 0.45 * boardTerm + 0.15 * handTerm));
|
|
}
|
|
|
|
const pick = <T>(xs: T[], rng: Rng): T => xs[Math.floor(rng() * xs.length)];
|
|
|
|
/** Choose attackers: attack with a creature unless the foe has an untapped blocker that kills it and survives; all-in when lethal-ish. */
|
|
function wantAttack<S, A>(lens: DuelLens<S, A>, s: S, seat: Seat, c: LensCreature): boolean {
|
|
const o = (seat === 0 ? 1 : 0) as Seat;
|
|
const blockers = lens.creatures(s, o).filter(b => b.canBlock);
|
|
const mine = lens.creatures(s, seat).filter(x => x.canAttack);
|
|
// Lethal check: assume the foe blocks our biggest attackers; the rest must cover its life.
|
|
const unblocked = mine.map(x => x.power).sort((a, b) => b - a).slice(blockers.length).reduce((t, p) => t + p, 0);
|
|
if (unblocked >= lens.life(s, o)) return true;
|
|
if (c.power <= 0) return false;
|
|
const badBlock = blockers.some(b => b.power >= c.toughness && b.toughness > c.power);
|
|
if (badBlock) return false;
|
|
const trade = blockers.some(b => b.power >= c.toughness);
|
|
// Trading is fine if we are ahead on board or the foe is low.
|
|
if (trade) return lens.life(s, o) <= 8 || mine.length > blockers.length;
|
|
return true;
|
|
}
|
|
|
|
/** Choose a block for an attacker: kill-and-survive > chump only when lethal > even trade if attacker is worth more. */
|
|
function chooseBlock<S, A>(lens: DuelLens<S, A>, s: S, seat: Seat, legal: { a: A; d: LensAction & { kind: 'block' } }[]): A | null {
|
|
if (!legal.length) return null;
|
|
const o = (seat === 0 ? 1 : 0) as Seat;
|
|
const att = new Map(lens.creatures(s, o).map(c => [c.uid, c]));
|
|
const mine = new Map(lens.creatures(s, seat).map(c => [c.uid, c]));
|
|
const blocked = new Set(lens.blocks(s).map(b => b[1]));
|
|
const incoming = lens.attackers(s).filter(u => !blocked.has(u)).reduce((t, u) => t + (att.get(u)?.power ?? 0), 0);
|
|
const lethal = incoming >= lens.life(s, seat);
|
|
let best: A | null = null, bestScore = 0;
|
|
for (const { a, d } of legal) {
|
|
const A = att.get(d.attacker), B = mine.get(d.blocker);
|
|
if (!A || !B) continue;
|
|
const kills = B.power >= A.toughness, dies = A.power >= B.toughness;
|
|
let score = 0;
|
|
if (kills && !dies) score = 10 + A.value;
|
|
else if (kills && dies) score = A.value > B.value ? 5 + A.value - B.value : lethal ? 3 : 0;
|
|
else if (!dies) score = 2 + A.power * 0.5; // safe absorb
|
|
else score = lethal ? 1 + A.power - B.value * 0.1 : 0;
|
|
if (score > bestScore) { bestScore = score; best = a; }
|
|
}
|
|
return best;
|
|
}
|
|
|
|
/**
|
|
* Heuristic duel bot: main phase is one-ply greedy over plays (material eval), attacks and blocks follow
|
|
* simple Magic heuristics. Strong enough to be the balance baseline; deterministic given rng.
|
|
*/
|
|
export function heuristicBot<S, A>(engine: EngineAdapter<S, A>, lens: DuelLens<S, A>): BotFn<unknown, A> {
|
|
return (obs, seat, rng) => {
|
|
const s = seeState(engine, obs, seat, rng);
|
|
const legal = legalOf(engine, obs, s, seat);
|
|
if (legal.length === 1) return legal[0];
|
|
return heuristicChoice(engine, lens, s, seat, legal, rng);
|
|
};
|
|
}
|
|
|
|
export function heuristicChoice<S, A>(engine: EngineAdapter<S, A>, lens: DuelLens<S, A>, s: S, seat: Seat, legal: A[], rng: Rng): A {
|
|
const dec = legal.map(a => ({ a, d: lens.decode(s, a) }));
|
|
const find = (k: LensAction['kind']) => dec.find(x => x.d.kind === k)?.a;
|
|
switch (lens.phase(s)) {
|
|
case 'mulligan': return find('keep') ?? legal[0];
|
|
case 'main': {
|
|
const plays = dec.filter(x => x.d.kind === 'play');
|
|
const base = engine.evaluate(s, seat);
|
|
let best: A | undefined, bestV = -Infinity;
|
|
for (const { a, d } of plays) {
|
|
const v = safeEval(engine, s, a, seat) + 0.004 * (d as any).cost + rng() * 1e-6;
|
|
if (v > bestV) { bestV = v; best = a; }
|
|
}
|
|
if (best !== undefined && bestV > base - 0.02) return best;
|
|
return find('endMain') ?? find('other') ?? legal[0];
|
|
}
|
|
case 'attack': {
|
|
const declared = new Set(lens.attackers(s));
|
|
for (const { a, d } of dec) {
|
|
if (d.kind !== 'attack') continue;
|
|
const c = lens.creatures(s, seat).find(x => x.uid === d.uid);
|
|
if (!c) continue;
|
|
const want = wantAttack(lens, s, seat, c);
|
|
if (want !== declared.has(d.uid) && d.on === want) return a;
|
|
}
|
|
return find('confirmAttack') ?? legal[0];
|
|
}
|
|
case 'block': {
|
|
const b = chooseBlock(lens, s, seat, dec.filter((x): x is { a: A; d: LensAction & { kind: 'block' } } => x.d.kind === 'block'));
|
|
return b ?? find('confirmBlocks') ?? legal[0];
|
|
}
|
|
default: return pick(legal, rng);
|
|
}
|
|
}
|
|
|
|
export interface DuelMCOptions { rollouts?: number; k?: number; horizon?: number }
|
|
|
|
/**
|
|
* Shallow Monte Carlo over the heuristic: in the main and block phases, shortlist up to k candidate actions,
|
|
* run `rollouts` heuristic playouts (fresh determinization each) for `horizon` actions and pick the best mean.
|
|
* Attack declarations use the heuristic directly (toggles have no immediate value to rank).
|
|
*/
|
|
export function duelMCBot<S, A>(engine: EngineAdapter<S, A>, lens: DuelLens<S, A>, opts: DuelMCOptions = {}): BotFn<unknown, A> {
|
|
const rollouts = opts.rollouts ?? 6, k = opts.k ?? 4, horizon = opts.horizon ?? 120;
|
|
return (obs, seat, rng) => {
|
|
const s = seeState(engine, obs, seat, rng);
|
|
const legal = legalOf(engine, obs, s, seat);
|
|
if (legal.length === 1) return legal[0];
|
|
const ph = lens.phase(s);
|
|
if (ph !== 'main' && ph !== 'attack') return heuristicChoice(engine, lens, s, seat, legal, rng);
|
|
const h = heuristicChoice(engine, lens, s, seat, legal, rng);
|
|
let cands: A[];
|
|
if (ph === 'attack') {
|
|
// Candidates: heuristic choice, confirm now, or all-in (toggle every not-yet-declared attacker).
|
|
const dec = legal.map(a => ({ a, d: lens.decode(s, a) }));
|
|
cands = [h, ...dec.filter(x => x.d.kind === 'confirmAttack' || (x.d.kind === 'attack' && x.d.on)).map(x => x.a)];
|
|
} else {
|
|
cands = [h, ...legal.map(a => ({ a, v: safeEval(engine, s, a, seat) })).sort((x, y) => y.v - x.v).map(x => x.a)];
|
|
}
|
|
const uniq: A[] = [];
|
|
for (const c of cands) if (!uniq.some(u => JSON.stringify(u) === JSON.stringify(c))) uniq.push(c);
|
|
const short = uniq.slice(0, k);
|
|
if (short.length === 1) return short[0];
|
|
let best = short[0], bestScore = -Infinity;
|
|
for (const c of short) {
|
|
let total = 0;
|
|
for (let r = 0; r < rollouts; r++) {
|
|
let st: S, steps = 0;
|
|
try { st = engine.applyAction(seeState(engine, obs, seat, rng), c); } catch { total -= 1; continue; }
|
|
while (!engine.isOver(st) && steps < horizon) {
|
|
const who = engine.toAct(st);
|
|
const lg = engine.legalActions(st, who);
|
|
if (!lg.length) break;
|
|
st = engine.applyAction(st, lg.length === 1 ? lg[0] : heuristicChoice(engine, lens, st, who, lg, rng));
|
|
steps++;
|
|
}
|
|
if (engine.isOver(st)) { const w = engine.result(st).winner; total += w === null ? 0 : w === seat ? 1 : -1; }
|
|
else total += engine.evaluate(st, seat);
|
|
}
|
|
const score = total / rollouts + (c === h ? 0.02 : 0);
|
|
if (score > bestScore) { bestScore = score; best = c; }
|
|
}
|
|
return best;
|
|
};
|
|
}
|
|
|
|
/** Heuristic with blunders: with probability `rate` a uniformly random legal action instead (UI "Easy"). */
|
|
export function blunderBot<S, A>(engine: EngineAdapter<S, A>, lens: DuelLens<S, A>, rate = 0.3): BotFn<unknown, A> {
|
|
const h = heuristicBot(engine, lens), r = duelRandomBot(engine);
|
|
return (obs, seat, rng) => (rng() < rate ? r(obs, seat, rng) : h(obs, seat, rng));
|
|
}
|
|
|
|
export const DUEL_BOT_NAMES = ['random', 'greedy', 'easy', 'heuristic', 'mc', 'mc-lite'] as const;
|
|
|
|
export function makeDuelBot<S, A>(name: string, engine: EngineAdapter<S, A>, lens: DuelLens<S, A>): BotFn<unknown, A> {
|
|
switch (name) {
|
|
case 'random': return duelRandomBot(engine);
|
|
case 'greedy': return duelGreedyBot(engine);
|
|
case 'heuristic': return heuristicBot(engine, lens);
|
|
case 'easy': return blunderBot(engine, lens);
|
|
case 'mc': return duelMCBot(engine, lens);
|
|
case 'mc-lite': return duelMCBot(engine, lens, { rollouts: 3, k: 3, horizon: 60 });
|
|
case 'lookahead': return lookaheadBot(engine);
|
|
default: throw new Error(`unknown duel bot ${name}`);
|
|
}
|
|
}
|