Files
wikideck/shared/duel/story/log.ts

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;
}