Files
wikideck/scripts/sim/card-pool.ts

86 lines
5.3 KiB
TypeScript

// Sim card pool from council-data's docs/game/card-sample.json (or starter-cards.json),
// derived per DESIGN §1 (percentile -> fame -> cost, home stat) and §10.1 (faction keyword).
// Percentile cut points come from the file itself. Power is (re)set from the ruleset by the adapter.
import { readFileSync } from 'node:fs';
import { KEYWORD_IDS, type GameCard, type Stat } from '../../shared/game/index.ts';
import { mulberry32 } from '../../shared/bots/index.ts';
import type { DeckSpec } from '../../shared/bots/types.ts';
const STATS: Stat[] = ['attention', 'depth', 'reach'];
const HOME_TIE: Stat[] = ['depth', 'reach', 'attention'];
/** DESIGN v1 §10.2 (PR #17): one keyword per faction. */
export const FACTION_KEYWORD: Record<string, string> = {
Culture: 'viral', Nature: 'rising', People: 'local', Science: 'encyclopedic', History: 'nostalgic', Space: 'translated',
};
interface RawCard { pageId: number; title: string; category?: string; legacyCategory?: string; stats: Record<Stat, number | null>; trendPercent?: number; pageviews?: { trendPercent?: number | null; dailyAverage?: number | null } }
function cuts(values: number[]): number[] {
const s = [...values].sort((a, b) => a - b);
return Array.from({ length: 99 }, (_, i) => s[Math.min(s.length - 1, Math.floor(((i + 1) / 100) * s.length))]);
}
function percentile(score: number, c: number[]): number {
let below = 0, equal = 0;
for (const x of c) { if (x < score) below++; else if (x === score) equal++; }
return Math.floor(below + equal / 2);
}
export interface PoolOptions { costThresholds?: number[]; keywords?: 'faction' | 'none'; table?: string; /** v1.1 proposal: Culture takes its home-stat keyword. */ cultureKeyword?: 'faction' | 'home' }
const CULTURE_HOME: Record<Stat, string> = { attention: 'viral', depth: 'encyclopedic', reach: 'translated' };
export function loadPool(file: string, opts: PoolOptions = {}): GameCard[] {
const raw = JSON.parse(readFileSync(file, 'utf8')).cards as RawCard[];
const tableRaw = opts.table ? (JSON.parse(readFileSync(opts.table, 'utf8')).cards as RawCard[]) : raw;
const table = Object.fromEntries(STATS.map(s => [s, cuts(tableRaw.map(c => c.stats[s]).filter((v): v is number => v !== null))])) as Record<Stat, number[]>;
const thresholds = opts.costThresholds ?? [15, 35, 55, 75, 90];
return raw.map(c => {
const pct = Object.fromEntries(STATS.map(s => [s, c.stats[s] === null ? null : percentile(c.stats[s]!, table[s])])) as Record<Stat, number | null>;
const vals = STATS.map(s => pct[s]).filter((v): v is number => v !== null);
const fame = Math.floor(vals.reduce((a, b) => a + b, 0) / vals.length + 0.5);
const cost = 1 + thresholds.filter(t => t <= fame).length;
let home: Stat = HOME_TIE[0];
for (const s of HOME_TIE) { const v = pct[s], cur = pct[home]; if (v !== null && (cur === null || v > cur)) home = s; }
const faction = (c.category ?? c.legacyCategory ?? 'Culture') as GameCard['faction'];
const kw = faction === 'Culture' && opts.cultureKeyword === 'home' ? CULTURE_HOME[home] : FACTION_KEYWORD[faction];
const keyword = cost === 1 || opts.keywords === 'none' || !kw || !(KEYWORD_IDS as readonly string[]).includes(kw) ? null : kw;
return {
cardId: `loaner:${c.pageId}`, pageId: c.pageId, title: c.title, faction, rarity: 'Common', cost, power: 0,
home, trend: 0, keyword, source: 'loaner',
} satisfies GameCard;
});
}
const kebab = (t: string) => t.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
/** The DESIGN §2.1 starter decks: "**A. Name: ...**" headings followed by | Cost | Card | Faction | Home | tables. */
export function loadStarterDecks(designMd: string): DeckSpec[] {
const text = readFileSync(designMd, 'utf8');
const sec = text.slice(text.indexOf('### 2.1'), text.indexOf('## 3.'));
const decks: DeckSpec[] = [];
let cur: { id: string; cards: GameCard[] } | null = null;
for (const line of sec.split('\n')) {
const h = line.match(/^\*\*([A-Z])\. ([^:*]+)/);
if (h) { cur = { id: `starter-${h[1]}-${kebab(h[2])}`, cards: [] }; decks.push({ id: cur.id, tags: ['arch:starter-v1'], payload: cur.cards }); continue; }
const r = line.match(/^\| (\d) \| ([^|]+) \| (\w+) \| (\w+) \|$/);
if (r && cur) {
const [, cost, title, faction, home] = r;
const c = Number(cost), kw = FACTION_KEYWORD[faction];
cur.cards.push({
cardId: `loaner:${kebab(title.trim())}`, pageId: null, title: title.trim(), faction: faction as GameCard['faction'], rarity: 'Common',
cost: c, power: 0, home: home as Stat, trend: 0, keyword: c === 1 || !(KEYWORD_IDS as readonly string[]).includes(kw) ? null : kw, source: 'loaner',
});
}
}
return decks.filter(d => (d.payload as GameCard[]).length === 12);
}
/** "Realistic owned" decks (DESIGN §2.1 v1.1 note): `n` seeded draws of 12 distinct cards from the pool, real category mix. */
export function ownedDecks(pool: GameCard[], n: number, size = 12, seed = 7): DeckSpec[] {
const rng = mulberry32(seed);
return Array.from({ length: n }, (_, i) => {
const p = [...pool];
for (let k = p.length - 1; k > 0; k--) { const j = Math.floor(rng() * (k + 1)); [p[k], p[j]] = [p[j], p[k]]; }
return { id: `owned-${i}`, tags: ['arch:owned-random'], payload: p.slice(0, size).map(c => ({ ...c, cardId: `${c.cardId}:0` })) };
});
}