Files
claudeanderic dbb89ce9c5 Night 2: 40-card Magic-style duel, PvP with owned decks, polite Wikimedia client, Android mining (#23)
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>
2026-11-18 18:12:24 +00:00

197 lines
8.8 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Deterministic match log (DUEL_DESIGN.md §8.2). Pure: the same MatchRecord always gives the
* same lines, so `replay` and stored records regenerate the log exactly. No network, no clock.
*/
import { Rng } from '../../game/rng.ts';
import { LOG_TEMPLATES, fill, numberWord, type TemplateKey } from './templates.ts';
import type { LogLine, MatchRecord, Reference, Seat, StoryCard, StoryEvent } from './types.ts';
/** Deterministic variant choice: one fresh mulberry32 per (seed, salt, event index). */
export function variantIndex(seed: number | string, salt: string, index: number, n: number): number {
return Rng.fromSeed(`${seed}|${salt}|${index}`).int(n);
}
/** "American actor (1909–1994)" → "American actor, 1909–1994". Verbatim otherwise. */
export function gloss(description: string | undefined): string {
const d = (description ?? '').trim();
if (!d) return '';
const m = /^(.*\S)\s*\(([^()]+)\)$/.exec(d);
return m ? `${m[1]}, ${m[2]}` : d;
}
export function articleUrl(title: string, revisionId: number): string {
return `https://en.wikipedia.org/w/index.php?title=${encodeURIComponent(title.replace(/ /g, '_'))}&oldid=${revisionId}`;
}
/**
* Tracks first mentions and reference numbers for one rendering (a log view or a recap).
* The first mention of a card in a rendering adds its description and the next [n].
*/
export class Narrator {
readonly record: MatchRecord;
readonly salt: string;
readonly references: Reference[] = [];
private refByCard = new Map<string, number>();
private pending: number[] = [];
constructor(record: MatchRecord, salt: string) {
this.record = record;
this.salt = salt;
}
card(id: string): StoryCard {
const c = this.record.cards[id];
if (!c) throw new Error(`story: unknown card id ${id}`);
return c;
}
player(seat: Seat): string { return this.record.players[seat].name; }
/** Assigns a reference number without mentioning the card (e.g. for the References list). Tokens get none (0). */
cite(id: string): number {
let n = this.refByCard.get(id);
if (n === undefined) {
const c = this.card(id);
if (c.token || c.revisionId === undefined) return 0;
n = this.references.length + 1;
this.refByCard.set(id, n);
this.references.push({
n, cardId: id, title: c.title, revisionId: c.revisionId, tokenId: c.tokenId,
url: articleUrl(c.title, c.revisionId),
text: `"${c.title}". Wikipedia. Revision ${c.revisionId}.${c.tokenId ? ` Minted as token ${c.tokenId}.` : ''}`,
});
}
return n;
}
/** A card's name for a sentence: italic, with its description on first mention. */
mention(id: string): string {
const c = this.card(id);
if (c.token || c.revisionId === undefined) return c.title;
const first = !this.refByCard.has(id);
const n = this.cite(id);
if (!first) return `*${c.title}*`;
this.pending.push(n);
const g = gloss(c.description);
return g ? `*${c.title}* (${g})` : `*${c.title}*`;
}
/** Take the citations of first mentions made since the last sentence. */
flush(): number[] {
const refs = this.pending;
this.pending = [];
return refs;
}
/** Fill a variant of `key` and append the citations of first mentions made while filling. */
sentence(key: TemplateKey, index: number, values: Record<string, () => string | number>, must: string[] = []): { text: string; refs: number[] } {
const fits = (t: string) => [...t.matchAll(/\{(\w+)\}/g)].every(m => m[1] in values);
const all = LOG_TEMPLATES[key].filter(fits);
const preferred = all.filter(t => must.every(k => t.includes(`{${k}}`)));
const usable = preferred.length ? preferred : all;
if (!usable.length) throw new Error(`story: no usable template for ${key}`);
const template = usable[variantIndex(this.record.seed, `${this.salt}:${key}`, index, usable.length)];
// Evaluate placeholders in template order so first mentions are numbered left to right.
const filled: Record<string, string | number> = {};
for (const m of template.matchAll(/\{(\w+)\}/g)) if (!(m[1] in filled)) filled[m[1]] = values[m[1]]();
const refs = this.flush();
const body = fill(template, filled);
return { text: body + refs.map(r => `[${r}]`).join(''), refs };
}
}
/** Pluralise a fixed token name ("Staff Member" → "Staff Members"). */
export function tokenName(token: string, count: number): string {
return count === 1 ? token : `${token}s`;
}
/**
* Render one event as a sentence, or null if it is not shown to this viewer.
* `viewer` null = omniscient (post-match, spectators after the end).
*/
export interface RenderOptions {
/** Prefer variants that name the source card (the recap uses this for damage lines). */
preferSource?: boolean;
}
export function renderEvent(nar: Narrator, ev: StoryEvent, index: number, viewer: Seat | null, opts: RenderOptions = {}): { text: string; refs: number[] } | null {
const P = (s: Seat) => () => nar.player(s);
const M = (id: string) => () => nar.mention(id);
const N = (n: number) => () => n;
const other = (s: Seat): Seat => (s === 0 ? 1 : 0);
switch (ev.kind) {
case 'turnStart':
return { text: `Turn ${ev.turn}.`, refs: [] };
case 'deploy':
return nar.sentence('deploy', index, { player: P(ev.seat), card: M(ev.card) });
case 'cast':
return nar.sentence('cast', index, { player: P(ev.seat), card: M(ev.card) });
case 'adopt':
return nar.sentence('adopt', index, { player: P(ev.seat), doctrine: M(ev.doctrine), figure: M(ev.figure), p: N(ev.power), t: N(ev.toughness) });
case 'attack':
return nar.sentence('attack', index, { player: P(ev.seat), opponent: P(other(ev.seat)), card: M(ev.card), p: N(ev.power), t: N(ev.toughness) });
case 'block':
return nar.sentence('block', index, { player: P(ev.seat), blocker: M(ev.blocker), attacker: M(ev.attacker), p: N(ev.power), t: N(ev.toughness) });
case 'playerDamage': {
const v: Record<string, () => string | number> = { player: P(ev.seat), n: N(ev.amount), life: N(Math.max(0, ev.life)) };
if (ev.source) v.source = M(ev.source);
return nar.sentence('playerDamage', index, v, opts.preferSource && ev.source ? ['source'] : []);
}
case 'lifeGain':
return nar.sentence('lifeGain', index, { player: P(ev.seat), source: M(ev.source), n: N(ev.amount), life: N(ev.life) });
case 'effectDamage':
return nar.sentence('effectDamage', index, { source: M(ev.source), target: M(ev.target), n: N(ev.amount) });
case 'destroyed':
return nar.sentence('destroyed', index, { card: M(ev.card) });
case 'tokenCreated':
return nar.sentence('tokenCreated', index, {
source: M(ev.source), count: () => numberWord(ev.count), token: () => tokenName(ev.token, ev.count),
});
case 'draw': {
const count = ev.count ?? 1;
const visible = ev.card !== undefined && (viewer === null || viewer === ev.seat);
if (visible) return nar.sentence('drawKnown', index, { player: P(ev.seat), card: M(ev.card as string) });
if (count > 1) return nar.sentence('drawHiddenMany', index, { player: P(ev.seat), count: () => numberWord(count) });
return nar.sentence('drawHidden', index, { player: P(ev.seat) });
}
case 'discard':
return nar.sentence('discard', index, { player: P(ev.seat), card: M(ev.card) });
case 'connected':
return nar.sentence('connected', index, { a: M(ev.a), b: M(ev.b), reason: () => ev.reason });
case 'rivalry':
return nar.sentence('rivalry', index, { a: M(ev.a), b: M(ev.b), reason: () => ev.reason });
case 'gameOver': {
if (ev.winner === null) return nar.sentence('gameOverDraw', index, { turn: N(ev.turn) });
const key = ({ life: 'gameOverLife', library: 'gameOverLibrary', concede: 'gameOverConcede', timeout: 'gameOverTimeout', turnCap: 'gameOverTurnCap' } as const)[ev.reason];
return nar.sentence(key, index, { winner: P(ev.winner), loser: P(other(ev.winner)), turn: N(ev.turn) });
}
}
}
/** The match log for one viewer (DUEL_DESIGN §8.2). Hidden draws by the opponent stay hidden. */
export function renderLog(record: MatchRecord, viewer: Seat | null = null): { lines: LogLine[]; references: Reference[] } {
const nar = new Narrator(record, 'log');
const lines: LogLine[] = [];
let turn = 0;
record.events.forEach((ev, i) => {
if (ev.kind === 'turnStart') turn = ev.turn;
const out = renderEvent(nar, ev, i, viewer);
if (out) lines.push({ turn, ...out });
});
return { lines, references: nar.references };
}
/** Join lines into one paragraph per turn: "Turn 5. alice deployed …". */
export function logParagraphs(lines: LogLine[]): string[] {
const out: string[] = [];
let cur: string[] = [];
let curTurn = -1;
for (const l of lines) {
if (l.turn !== curTurn && cur.length) { out.push(cur.join(' ')); cur = []; }
curTurn = l.turn;
cur.push(l.text);
}
if (cur.length) out.push(cur.join(' '));
return out;
}