forked from WikiDeck/wikideck
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: WikiDeck/wikideck#23
Co-authored-by: Claude <claude@eom.dev>
177 lines
10 KiB
TypeScript
177 lines
10 KiB
TypeScript
// EngineAdapter + DuelLens over duel-core's shared/duel engine (DuelEngineApi, docs/game/DUEL_API.md),
|
|
// for the duel bots (shared/bots/duel-bots.ts) and the balance sim (scripts/sim/duel-run.ts). Pure, no I/O:
|
|
// the engine module and the card pool are passed in.
|
|
import type {
|
|
CardInstance, ConnectedTier, DuelAction, DuelCard, DuelEngineApi, DuelRuleset, DuelState, Permanent, PlayerView, Seat,
|
|
} from '../duel/index.ts';
|
|
import type { EngineAdapter, Rng } from './types.ts';
|
|
import { duelEvaluate, type DuelLens, type LensAction, type LensCreature } from './duel-bots.ts';
|
|
|
|
/** What a duel bot sees: its seat's view, its own decklist (players know their deck) and its legal actions. */
|
|
export interface DuelObservation { view: PlayerView; deck: DuelCard[]; legal: DuelAction[] }
|
|
|
|
const KW_VALUE: Record<string, number> = { Featured: 1, Protected: 0.4, 'Well-sourced': 0.5, Legacy: 0.5, Stub: 0.5, Multilingual: 0.4, Translated: 0.2, Local: 0.2, Trending: 0.3 };
|
|
|
|
/** Connected test between two cards (DUEL_API "Connected"), for the pairwise pool rate. */
|
|
export function connectedTierOf(a: DuelCard, b: DuelCard, tiers: readonly ConnectedTier[]): ConnectedTier | null {
|
|
if (a.cardId === b.cardId || !a.connect || !b.connect) return null;
|
|
const meets = <T>(x: readonly T[], y: readonly T[]) => x.some(v => y.includes(v));
|
|
for (const t of tiers) {
|
|
if (t === 'Linked' && ((b.pageId !== null && a.connect.links.includes(b.pageId)) || (a.pageId !== null && b.connect.links.includes(a.pageId)))) return t;
|
|
if (t === 'Compatriot' && meets(a.connect.countries, b.connect.countries)) return t;
|
|
if (t === 'Contemporary' && a.type !== b.type && meets(a.connect.centuries, b.connect.centuries)) return t;
|
|
if (t === 'Kin' && meets(a.connect.p31.filter(q => q !== 'Q5' && q !== 'Q16521'), b.connect.p31)) return t;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
export function makeDuelLens(api: DuelEngineApi): DuelLens<DuelState, DuelAction> {
|
|
const stats = (s: DuelState, p: Permanent) => { try { return api.statsOf(s, p.uid); } catch { return { power: p.card.power ?? 0, toughness: p.card.toughness ?? 0 }; } };
|
|
const blocker = (p: Permanent) => p.card.type === 'Figure' || (p.card.type === 'Location' && (p.card.toughness ?? 0) > 0);
|
|
return {
|
|
phase: s => (s.phase === 'over' ? 'other' : s.phase),
|
|
life: (s, seat) => s.players[seat].life,
|
|
handSize: (s, seat) => s.players[seat].hand.length,
|
|
creatures: (s, seat): LensCreature[] => s.battlefield.filter(p => p.controller === seat && blocker(p)).map(p => {
|
|
const { power, toughness } = stats(s, p);
|
|
const left = Math.max(0, toughness - p.damage);
|
|
const kw = (p.card.keywords ?? []).reduce((t, k) => t + (KW_VALUE[k] ?? 0), 0);
|
|
const fig = p.card.type === 'Figure';
|
|
return { uid: p.uid, power, toughness: left, tapped: p.tapped, canAttack: fig && !p.tapped && !p.sick, canBlock: !p.tapped, value: fig ? power + left * 0.8 + 0.5 + kw : left * 0.5 };
|
|
}),
|
|
attackers: s => s.combat.attackers,
|
|
blocks: s => Object.entries(s.combat.blocks) as [string, string][],
|
|
decode: (s, a): LensAction => {
|
|
switch (a.type) {
|
|
case 'play': {
|
|
const c = s.players[s.active].hand.find(h => h.uid === a.uid)?.card;
|
|
return { kind: 'play', cost: c?.cost ?? 0, cardType: c?.type ?? '?' };
|
|
}
|
|
case 'toggleAttacker': return { kind: 'attack', uid: a.uid, on: true };
|
|
case 'confirmAttack': return { kind: 'confirmAttack' };
|
|
case 'block': return { kind: 'block', blocker: a.blocker, attacker: a.attacker };
|
|
case 'confirmBlocks': return { kind: 'confirmBlocks' };
|
|
case 'endPhase': return { kind: 'endMain' };
|
|
case 'keep': return { kind: 'keep' };
|
|
case 'mulligan': return { kind: 'mulligan' };
|
|
default: return { kind: 'other' };
|
|
}
|
|
},
|
|
};
|
|
}
|
|
|
|
function shuffled<T>(xs: T[], rng: Rng): T[] {
|
|
const a = [...xs];
|
|
for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(rng() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; }
|
|
return a;
|
|
}
|
|
|
|
/**
|
|
* Rebuild a full DuelState from a seat's observation (a determinization). Hidden zones are sampled:
|
|
* our library from our decklist minus every card we can see, the opponent's hand and library from `pool`
|
|
* minus everything visible. Permanent modifiers are recovered exactly from the view's current
|
|
* power/toughness (whatever statsOf doesn't recompute goes into permPower/permToughness).
|
|
*/
|
|
export function stateFromObservation(api: DuelEngineApi, obs: DuelObservation, seat: Seat, rng: Rng, pool: readonly DuelCard[]): DuelState {
|
|
const v = obs.view, o = (1 - seat) as Seat;
|
|
const seen = new Set<string>();
|
|
const mark = (c: DuelCard) => seen.add(c.cardId);
|
|
v.you.hand.forEach(h => mark(h.card));
|
|
v.you.graveyard.forEach(g => mark(g.card));
|
|
v.opponent.graveyard.forEach(g => mark(g.card));
|
|
v.battlefield.forEach(p => mark(p.card));
|
|
const ownLeft = shuffled(obs.deck.filter(c => !seen.has(c.cardId) && !v.battlefield.some(p => p.card.cardId === c.cardId && p.owner === seat)), rng);
|
|
const oppPool = shuffled(pool.filter(c => !seen.has(c.cardId) && !obs.deck.some(d => d.cardId === c.cardId)), rng);
|
|
let k = 0;
|
|
const hidden = (owner: Seat, card: DuelCard): CardInstance => ({ uid: `${owner}:h${k++}`, owner, card });
|
|
const take = (n: number) => Array.from({ length: n }, (_, i) => hidden(o, oppPool[i % Math.max(1, oppPool.length)] ?? obs.deck[0]));
|
|
const oppHand = take(v.opponent.handSize);
|
|
const oppLib = Array.from({ length: v.opponent.librarySize }, (_, i) => hidden(o, oppPool[(v.opponent.handSize + i) % Math.max(1, oppPool.length)] ?? obs.deck[0]));
|
|
const myLib = Array.from({ length: v.you.librarySize }, (_, i) => hidden(seat, ownLeft[i % Math.max(1, ownLeft.length)] ?? obs.deck[0]));
|
|
const side = (sv: PlayerView['opponent'], hand: CardInstance[], library: CardInstance[]) => {
|
|
const territory = Math.min(v.rules.territoryCap, v.battlefield.filter(p => p.controller === sv.seat && p.card.type === 'Location').reduce((t, p) => t + (p.card.territory ?? 0), 0));
|
|
return {
|
|
life: sv.life, citations: sv.citations, baseCitations: Math.max(0, sv.maxCitations - territory), library, hand, graveyard: sv.graveyard,
|
|
mulligansTaken: sv.mulligansTaken, ready: sv.ready, locationsThisTurn: 0, bankSeconds: sv.bankSeconds, timeouts: 0, fatigue: 0,
|
|
};
|
|
};
|
|
const players = [] as unknown as DuelState['players'];
|
|
players[seat] = side(v.you, v.you.hand, myLib);
|
|
players[o] = side(v.opponent, oppHand, oppLib);
|
|
// Locations played this turn aren't in the view: if we hold an affordable Location that isn't legal to play, assume one was played.
|
|
if (v.active === seat && v.phase === 'main') {
|
|
const legalUids = new Set(obs.legal.flatMap(a => (a.type === 'play' ? [a.uid] : [])));
|
|
players[seat].locationsThisTurn = v.you.hand.some(h => h.card.type === 'Location' && h.card.cost <= v.you.citations && !legalUids.has(h.uid)) ? 1 : 0;
|
|
}
|
|
const battlefield: Permanent[] = v.battlefield.map((p, i) => ({
|
|
uid: p.uid, owner: p.owner, controller: p.controller, card: p.card, tapped: p.tapped, sick: p.sick, damage: p.damage, counters: p.counters,
|
|
permPower: 0, permToughness: 0, tempPower: 0, tempToughness: 0, tempKeywords: [], permKeywords: [], attachedTo: p.attachedTo,
|
|
shielded: false, entered: i, connectedLogged: true,
|
|
}));
|
|
const s: DuelState = {
|
|
engine: 'duel', rules: v.rules, seed: 'assumed', rng: Math.floor(rng() * 2 ** 32) >>> 0, turn: v.turn, active: v.active,
|
|
firstSeat: v.active, phase: v.phase, players, battlefield, combat: structuredClone(v.combat), log: [], result: v.result,
|
|
version: v.version, nextToken: 100000 + v.version, nextEntry: battlefield.length,
|
|
};
|
|
for (const p of battlefield) {
|
|
const want = v.battlefield.find(x => x.uid === p.uid)!;
|
|
try {
|
|
const got = api.statsOf(s, p.uid);
|
|
p.permPower = want.power - got.power;
|
|
p.permToughness = want.toughness - got.toughness;
|
|
} catch { /* keep zero */ }
|
|
const extra = want.keywords.filter(kw => !(p.card.keywords ?? []).includes(kw));
|
|
if (extra.length) p.permKeywords = extra;
|
|
}
|
|
return s;
|
|
}
|
|
|
|
export interface DuelAdapterOptions { rules: DuelRuleset; pool: readonly DuelCard[] }
|
|
|
|
export function makeDuelAdapter(api: DuelEngineApi, opts: DuelAdapterOptions): EngineAdapter<DuelState, DuelAction> & { lens: DuelLens<DuelState, DuelAction> } {
|
|
const lens = makeDuelLens(api);
|
|
const decks = new WeakMap<DuelState, [DuelCard[], DuelCard[]]>();
|
|
const deckOf = new Map<string, [DuelCard[], DuelCard[]]>();
|
|
const adapter: EngineAdapter<DuelState, DuelAction> & { lens: typeof lens } = {
|
|
name: 'duel',
|
|
lens,
|
|
rulesets: () => [opts.rules.version],
|
|
decks: () => [],
|
|
createMatch: (_r, specs, seed) => {
|
|
const d: [DuelCard[], DuelCard[]] = [specs[0].payload as DuelCard[], specs[1].payload as DuelCard[]];
|
|
const s = api.createDuel(opts.rules, d, String(seed));
|
|
decks.set(s, d); deckOf.set(s.seed, d);
|
|
return s;
|
|
},
|
|
toAct: s => api.toAct(s) ?? s.active,
|
|
legalActions: (s, seat) => api.legalActions(s, seat),
|
|
applyAction: (s, a) => api.applyAction(s, api.toAct(s) ?? s.active, a),
|
|
isOver: s => api.isOver(s),
|
|
result: s => { const r = api.result(s); return { winner: r?.winner ?? null, reason: r?.reason }; },
|
|
turn: s => s.turn,
|
|
evaluate: (s, seat) => duelEvaluate(lens, s, seat),
|
|
cardsOf: (s, a) => (a.type === 'play' ? [s.players[api.toAct(s) ?? s.active].hand.find(h => h.uid === a.uid)?.card.cardId ?? a.uid] : []),
|
|
actionKind: a => a.type,
|
|
firstSeat: s => s.firstSeat,
|
|
observe: (s, seat): DuelObservation => ({ view: api.viewFor(s, seat), deck: (deckOf.get(s.seed) ?? decks.get(s) ?? [[], []])[seat], legal: api.legalActions(s, seat) }),
|
|
assume: (obs, seat, rng) => stateFromObservation(api, obs as DuelObservation, seat, rng, opts.pool),
|
|
};
|
|
return adapter;
|
|
}
|
|
|
|
/** Per-match numbers from the omniscient log, for DUEL_BALANCE.md. */
|
|
export function duelMetrics(s: DuelState): Record<string, number> {
|
|
const m: Record<string, number> = { connectedFires: 0, plays: 0, rivalries: 0, destroyed: 0, mulligans: 0, tokens: 0, discards: 0 };
|
|
for (const e of s.log) {
|
|
if (e.kind === 'connected') m.connectedFires++;
|
|
else if (e.kind === 'deploy' || e.kind === 'cast' || e.kind === 'adopt') m.plays++;
|
|
else if (e.kind === 'rivalry') m.rivalries++;
|
|
else if (e.kind === 'destroyed') m.destroyed++;
|
|
else if (e.kind === 'mulligan') m.mulligans++;
|
|
else if (e.kind === 'tokenCreated') m.tokens++;
|
|
else if (e.kind === 'discard') m.discards++;
|
|
}
|
|
m.lifeLeft = s.result?.winner != null ? s.players[s.result.winner].life : 0;
|
|
return m;
|
|
}
|