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>
230 lines
14 KiB
TypeScript
230 lines
14 KiB
TypeScript
// Stand-in duel engine for sim-balance, used only until (and as a test double alongside) duel-core's
|
|
// shared/duel engine. Implements the BRIEF "Game rules core" in miniature: 40-card decks, 20 Notability,
|
|
// Citations +1/turn to 10, no stack, sorcery-speed Events, single blocks, simultaneous damage,
|
|
// summoning sickness, empty-library loss. Card derivation is a rough copy of duel-cards' plan
|
|
// (fame percentile -> cost 1..6, P+T budget per cost). Pure and deterministic.
|
|
import { readFileSync } from 'node:fs';
|
|
import { mulberry32 } from '../../shared/bots/index.ts';
|
|
|
|
export type CardType = 'Figure' | 'Location' | 'Event' | 'Institution' | 'Doctrine';
|
|
export interface SCard {
|
|
id: string; pageId: number; title: string; type: CardType; portal: string;
|
|
cost: number; power: number; toughness: number; keywords: string[];
|
|
fame: number; connect: string[];
|
|
}
|
|
export interface SPerm { card: SCard; uid: number; damage: number; tapped: boolean; sick: boolean; buff: [number, number]; attachedTo?: number }
|
|
export interface SPlayer { life: number; library: SCard[]; hand: SCard[]; grave: SCard[]; board: SPerm[]; citations: number; maxCitations: number; ramp: number }
|
|
export type Phase = 'main' | 'attack' | 'block';
|
|
export interface SState {
|
|
rules: SRules; seed: number; rngState: number; turn: number; active: 0 | 1; phase: Phase;
|
|
players: [SPlayer, SPlayer]; attackers: number[]; blocks: [number, number][]; uid: number;
|
|
winner: 0 | 1 | null; over: boolean; reason?: string; first: 0 | 1;
|
|
stats: { connectedFires: number; plays: number };
|
|
}
|
|
export interface SRules { deckSize: number; startingLife: number; maxCitations: number; handSize: number; openingHand: number; turnCap?: number; connectedBonus: number }
|
|
export const STANDIN_RULES: SRules = { deckSize: 40, startingLife: 20, maxCitations: 10, handSize: 7, openingHand: 7, connectedBonus: 1 };
|
|
|
|
export type SAction =
|
|
| { type: 'play'; seat: 0 | 1; card: string; target?: number | 'face' }
|
|
| { type: 'toggleAttacker'; seat: 0 | 1; uid: number }
|
|
| { type: 'confirmAttack'; seat: 0 | 1 }
|
|
| { type: 'block'; seat: 0 | 1; blocker: number; attacker: number }
|
|
| { type: 'confirmBlocks'; seat: 0 | 1 }
|
|
| { type: 'endPhase'; seat: 0 | 1 };
|
|
|
|
// ---------- card derivation (sample JSON -> SCard) ----------
|
|
const COST_T = [26, 39, 51, 63, 78];
|
|
const BUDGET = [3, 4, 6, 8, 10, 12];
|
|
function classify(c: any): CardType {
|
|
const p31 = (c.instanceOf ?? []).map((x: any) => String(x.label ?? ''));
|
|
const ids = (c.instanceOf ?? []).map((x: any) => x.id);
|
|
if (ids.some((i: string) => ['Q5', 'Q16521', 'Q95074'].includes(i))) return 'Figure';
|
|
if (p31.some((l: string) => /settlement|commune|village|town|city|municipality|river|island|castle|building|township|mountain|lake/i.test(l))) return 'Location';
|
|
if (p31.some((l: string) => /election|storm|protest|battle|season|events|war|nor'easter|tournament|final/i.test(l))) return 'Event';
|
|
if (p31.some((l: string) => /group|company|film|album|band|team|organi[sz]ation|club|school|novel|song|series/i.test(l))) return 'Institution';
|
|
const cats = (c.categories ?? []).join('|');
|
|
if (/\d+ births|\d+ deaths|Living people/.test(cats)) return 'Figure';
|
|
if (/Communes of|Villages in|Populated places/.test(cats)) return 'Location';
|
|
return 'Doctrine';
|
|
}
|
|
function pctTable(cards: any[], key: string): number[] { return cards.map(c => c.stats?.[key]).filter((v: any) => typeof v === 'number').sort((a: number, b: number) => a - b); }
|
|
function pct(v: number | null | undefined, t: number[]): number | null { if (typeof v !== 'number') return null; let b = 0; for (const x of t) if (x < v) b++; return Math.round(100 * b / t.length); }
|
|
const COUNTRY = /\b(American|United States|English|British|France|French|German|Japan|Japanese|Chin(a|ese)|India|Brazil|Pol(and|ish)|Ital(y|ian)|Spa(in|nish)|Austria|Canad|Australia|Russia|Mexic|Iran|Pakistan|Swed|Norw|Estonia|Ukrain|Croatia|Philippin|Indonesia|Korea)/g;
|
|
export function deriveSample(file: string): SCard[] {
|
|
const raw = JSON.parse(readFileSync(file, 'utf8')).cards as any[];
|
|
const tA = pctTable(raw, 'attention'), tD = pctTable(raw, 'depth'), tR = pctTable(raw, 'reach');
|
|
return raw.map(c => {
|
|
const ps = [pct(c.stats?.attention, tA), pct(c.stats?.depth, tD), pct(c.stats?.reach, tR)].filter((x): x is number => x !== null);
|
|
const fame = ps.length ? Math.round(ps.reduce((a, b) => a + b, 0) / ps.length) : 0;
|
|
const cost = 1 + COST_T.filter(t => t <= fame).length;
|
|
const budget = BUDGET[cost - 1];
|
|
const a = pct(c.stats?.attention, tA) ?? 50, d = pct(c.stats?.depth, tD) ?? 50;
|
|
const share = Math.min(0.7, Math.max(0.3, a / Math.max(1, a + d)));
|
|
const power = Math.max(1, Math.round(budget * share)), toughness = Math.max(1, budget - power);
|
|
const txt = `${c.description ?? ''} ${(c.categories ?? []).join(' ')}`;
|
|
const countries = [...new Set([...txt.matchAll(COUNTRY)].map(m => m[1].slice(0, 5)))].map(x => `c:${x}`);
|
|
const cents = [...new Set([...`${c.title} ${txt}`.matchAll(/\b(1[0-9]{3}|20[0-2][0-9])\b/g)].map(m => `t:${Math.floor(Number(m[1]) / 100)}`))];
|
|
const type = classify(c);
|
|
if (type === 'Location') return { id: `p${c.pageId}`, pageId: c.pageId, title: c.title, type, portal: c.faction ?? 'Other', cost: Math.ceil(cost / 2), power: 0, toughness: Math.max(1, Math.ceil(toughness / 2)), keywords: [], fame, connect: [...countries, ...cents] };
|
|
const kw: string[] = [];
|
|
if (c.languageCount >= 20) kw.push('Multilingual');
|
|
if (c.pageBytes < 3000) kw.push('Stub');
|
|
return { id: `p${c.pageId}`, pageId: c.pageId, title: c.title, type, portal: c.faction ?? 'Other', cost, power, toughness, keywords: kw.slice(0, 2), fame, connect: [...countries, ...cents] };
|
|
});
|
|
}
|
|
|
|
// ---------- engine ----------
|
|
const clone = <T>(x: T): T => structuredClone(x);
|
|
function rng(s: SState) { const r = mulberry32(s.rngState); return () => { const v = r(); s.rngState = (s.rngState + 0x6d2b79f5) >>> 0; return v; }; }
|
|
function shuffle<T>(xs: T[], r: () => number) { for (let i = xs.length - 1; i > 0; i--) { const j = Math.floor(r() * (i + 1)); [xs[i], xs[j]] = [xs[j], xs[i]]; } }
|
|
const opp = (p: 0 | 1): 0 | 1 => (p === 0 ? 1 : 0);
|
|
export const pow = (p: SPerm) => p.card.power + p.buff[0];
|
|
export const tough = (p: SPerm) => p.card.toughness + p.buff[1];
|
|
export const isCreature = (p: SPerm) => p.card.type === 'Figure' || (p.card.type === 'Location' && p.attachedTo === undefined);
|
|
|
|
export function createDuel(decks: [SCard[], SCard[]], seed: number, rules: SRules = STANDIN_RULES): SState {
|
|
const s: SState = { rules, seed, rngState: seed >>> 0, turn: 1, active: 0, phase: 'main', players: [null, null] as any, attackers: [], blocks: [], uid: 1, winner: null, over: false, first: 0, stats: { connectedFires: 0, plays: 0 } };
|
|
const r = rng(s);
|
|
s.first = r() < 0.5 ? 0 : 1; s.active = s.first;
|
|
for (const p of [0, 1] as const) {
|
|
const lib = decks[p].slice(0, rules.deckSize).map(c => ({ ...c }));
|
|
shuffle(lib, r);
|
|
s.players[p] = { life: rules.startingLife, library: lib, hand: lib.splice(0, rules.openingHand), grave: [], board: [], citations: 0, maxCitations: 0, ramp: 0 };
|
|
}
|
|
refresh(s, false);
|
|
return s;
|
|
}
|
|
function lose(s: SState, p: 0 | 1, reason: string) { if (!s.over) { s.over = true; s.winner = opp(p); s.reason = reason; } }
|
|
function draw(s: SState, p: 0 | 1) { const pl = s.players[p]; const c = pl.library.shift(); if (!c) return lose(s, p, 'library-empty'); pl.hand.push(c); }
|
|
function refresh(s: SState, doDraw: boolean) {
|
|
const pl = s.players[s.active];
|
|
pl.maxCitations = Math.min(s.rules.maxCitations, pl.maxCitations + 1);
|
|
pl.citations = pl.maxCitations + pl.ramp;
|
|
for (const b of pl.board) { b.tapped = false; b.sick = false; }
|
|
if (doDraw) draw(s, s.active);
|
|
s.phase = 'main'; s.attackers = []; s.blocks = [];
|
|
}
|
|
function endTurn(s: SState) {
|
|
for (const pl of s.players) for (const b of pl.board) b.damage = 0;
|
|
const pl = s.players[s.active];
|
|
while (pl.hand.length > s.rules.handSize) pl.grave.push(pl.hand.pop()!);
|
|
if (s.rules.turnCap && s.turn >= s.rules.turnCap * 2) {
|
|
const [a, b] = s.players; s.over = true; s.reason = 'turn-cap';
|
|
s.winner = a.life === b.life ? null : a.life > b.life ? 0 : 1; return;
|
|
}
|
|
s.turn++; s.active = opp(s.active); refresh(s, true);
|
|
}
|
|
function connectedWith(card: SCard, board: SPerm[]): boolean { return board.some(b => b.card.connect.some(k => card.connect.includes(k))); }
|
|
|
|
export function legalActions(s: SState, seat: 0 | 1): SAction[] {
|
|
if (s.over) return [];
|
|
const pl = s.players[seat], foe = s.players[opp(seat)];
|
|
if (s.phase === 'block') {
|
|
if (seat !== opp(s.active)) return [];
|
|
const out: SAction[] = [{ type: 'confirmBlocks', seat }];
|
|
const used = new Set(s.blocks.map(b => b[0])), blocked = new Set(s.blocks.map(b => b[1]));
|
|
for (const bl of pl.board) if (isCreature(bl) && !bl.tapped && !used.has(bl.uid) && (bl.card.type === 'Figure' || tough(bl) > 0))
|
|
for (const a of s.attackers) if (!blocked.has(a)) out.push({ type: 'block', seat, blocker: bl.uid, attacker: a });
|
|
return out;
|
|
}
|
|
if (seat !== s.active) return [];
|
|
if (s.phase === 'attack') {
|
|
const out: SAction[] = [{ type: 'confirmAttack', seat }];
|
|
for (const b of pl.board) if (b.card.type === 'Figure' && !b.tapped && !b.sick) out.push({ type: 'toggleAttacker', seat, uid: b.uid });
|
|
return out;
|
|
}
|
|
const out: SAction[] = [{ type: 'endPhase', seat }];
|
|
const seen = new Set<string>();
|
|
for (const c of pl.hand) {
|
|
if (c.cost > pl.citations || seen.has(c.id)) continue; seen.add(c.id);
|
|
if (c.type === 'Event') {
|
|
out.push({ type: 'play', seat, card: c.id, target: 'face' });
|
|
for (const b of foe.board) if (b.card.type === 'Figure' && !b.card.keywords.includes('Protected')) out.push({ type: 'play', seat, card: c.id, target: b.uid });
|
|
} else if (c.type === 'Doctrine') {
|
|
for (const b of pl.board) if (b.card.type === 'Figure') out.push({ type: 'play', seat, card: c.id, target: b.uid });
|
|
} else out.push({ type: 'play', seat, card: c.id });
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function kill(s: SState) {
|
|
for (const p of [0, 1] as const) {
|
|
const pl = s.players[p];
|
|
const dead = pl.board.filter(b => isCreature(b) && b.damage >= tough(b) && tough(b) > 0);
|
|
if (!dead.length) continue;
|
|
const ids = new Set(dead.map(d => d.uid));
|
|
for (const d of dead) pl.grave.push(d.card);
|
|
pl.board = pl.board.filter(b => !ids.has(b.uid) && !(b.attachedTo !== undefined && ids.has(b.attachedTo)));
|
|
}
|
|
}
|
|
|
|
export function applyAction(s0: SState, a: SAction): SState {
|
|
const s = clone(s0);
|
|
const pl = s.players[a.seat], foe = s.players[opp(a.seat)];
|
|
switch (a.type) {
|
|
case 'play': {
|
|
const i = pl.hand.findIndex(c => c.id === a.card); const c = pl.hand[i];
|
|
pl.hand.splice(i, 1); pl.citations -= c.cost; s.stats.plays++;
|
|
const conn = connectedWith(c, pl.board); if (conn) s.stats.connectedFires++;
|
|
const bonus = conn ? s.rules.connectedBonus : 0;
|
|
if (c.type === 'Event') {
|
|
const dmg = c.cost + 1 + bonus;
|
|
if (a.target === 'face') foe.life -= Math.ceil(dmg / 2);
|
|
else { const t = foe.board.find(b => b.uid === a.target); if (t) t.damage += dmg; kill(s); }
|
|
pl.grave.push(c);
|
|
} else if (c.type === 'Doctrine') {
|
|
const t = pl.board.find(b => b.uid === a.target)!;
|
|
t.buff = [t.buff[0] + Math.ceil(c.power / 2) + bonus, t.buff[1] + Math.ceil(c.toughness / 2) + bonus];
|
|
pl.board.push({ card: c, uid: s.uid++, damage: 0, tapped: false, sick: false, buff: [0, 0], attachedTo: t.uid });
|
|
} else if (c.type === 'Institution') {
|
|
pl.board.push({ card: c, uid: s.uid++, damage: 0, tapped: false, sick: false, buff: [0, 0], attachedTo: -1 });
|
|
draw(s, a.seat); if (c.cost >= 4) draw(s, a.seat);
|
|
} else if (c.type === 'Location') {
|
|
if (pl.ramp < 2) pl.ramp++;
|
|
pl.board.push({ card: { ...c, power: 0 }, uid: s.uid++, damage: 0, tapped: false, sick: false, buff: [0, bonus] });
|
|
} else pl.board.push({ card: c, uid: s.uid++, damage: 0, tapped: false, sick: true, buff: [bonus, bonus] });
|
|
if (foe.life <= 0) lose(s, opp(a.seat), 'notability');
|
|
return s;
|
|
}
|
|
case 'endPhase': s.phase = 'attack'; return s;
|
|
case 'toggleAttacker': { const k = s.attackers.indexOf(a.uid); if (k >= 0) s.attackers.splice(k, 1); else s.attackers.push(a.uid); return s; }
|
|
case 'confirmAttack':
|
|
if (!s.attackers.length) { endTurn(s); return s; }
|
|
for (const u of s.attackers) pl.board.find(b => b.uid === u)!.tapped = true;
|
|
s.phase = 'block'; return s;
|
|
case 'block': s.blocks.push([a.blocker, a.attacker]); return s;
|
|
case 'confirmBlocks': {
|
|
const att = s.players[s.active], def = s.players[a.seat];
|
|
for (const u of s.attackers) {
|
|
const A = att.board.find(b => b.uid === u); if (!A) continue;
|
|
const bl = s.blocks.find(b => b[1] === u);
|
|
const B = bl && def.board.find(b => b.uid === bl[0]);
|
|
if (B) { B.damage += pow(A); A.damage += pow(B); } else def.life -= pow(A);
|
|
}
|
|
kill(s);
|
|
if (def.life <= 0) { lose(s, a.seat, 'notability'); return s; }
|
|
endTurn(s); return s;
|
|
}
|
|
}
|
|
}
|
|
|
|
/** Seat-local copy: opponent hand and both libraries' contents are hidden (replaced by counts). */
|
|
export function viewFor(s: SState, seat: 0 | 1) {
|
|
const v = clone(s) as any;
|
|
const o = v.players[opp(seat)];
|
|
v.view = { seat, oppHand: o.hand.length, oppLib: o.library.length, myLib: v.players[seat].library.length };
|
|
o.hand = []; o.library = []; v.players[seat].library = [];
|
|
return v as SState & { view: { seat: 0 | 1; oppHand: number; oppLib: number; myLib: number } };
|
|
}
|
|
|
|
/** duel-cards' derived DuelCards (docs/game/duel-card-sample.json) mapped onto the stand-in's card shape. */
|
|
export function fromDuelCards(file: string): SCard[] {
|
|
const cards = JSON.parse(readFileSync(file, 'utf8')).cards as any[];
|
|
return cards.map(c => ({
|
|
id: c.cardId, pageId: c.pageId, title: c.title, type: c.type, portal: c.portal, cost: c.cost,
|
|
power: c.type === 'Location' ? 0 : (c.power ?? c.basis?.magnitude ?? 1), toughness: c.type === 'Location' ? Math.max(1, c.toughness ?? 1) : (c.toughness ?? c.basis?.magnitude ?? 1),
|
|
keywords: c.keywords ?? [], fame: c.basis?.fame ?? 0,
|
|
connect: [...(c.connect?.countries ?? []).map((x: string) => `c:${x}`), ...(c.connect?.centuries ?? []).map((x: number) => `t:${x}`)],
|
|
}));
|
|
}
|