Files
wikideck/shared/game/derive.ts
T
claudeandClaude Opus 5.5 0f2363199b game: v1 keywords and Portals (DESIGN cf2fceb §10), card derivation (§1, §10.1), unit/property/golden tests
- keywords.ts: viral, rising, local, encyclopedic, nostalgic, translated (v1);
  edition, obscure, wildcard (off by default); §10.3 Portals with capacity,
  allOnTopic and topicBonus hooks; isOnTopic, keywordEnabled, hiddenFrom
- ruleset.ts: §10.3 default Topic pool, keyword/portal param defaults
- starter.ts: placeholder loaners carry their faction keyword (§10.1)
- derive.ts: percentile -> fame -> cost -> power, home, trend, keyword choice
- tests: game-keywords, game-derive, game-property, game-golden (§12, todo
  until core implements the frozen §3-§7 rules)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 23:12:38 -05:00

137 lines
6.1 KiB
TypeScript
Raw 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.
/**
* Card derivation (DESIGN §1 and §10.1): a host-frozen CardInput becomes a GameCard.
* Pure and deterministic. The engine itself never reads raw 0–100 stats; hosts call
* deriveCard() before createMatch. Owner: engine-b.
*/
import { FACTION_KEYWORD, V1_KEYWORDS } from './keywords.ts';
import { STATS, type Faction, type GameCard, type Rarity, type Stat } from './types.ts';
/** §1.4 tie-break order: depth and reach are the hardest to inflate. */
export const HOME_TIE_ORDER: readonly Stat[] = ['depth', 'reach', 'attention'];
export interface CardInput {
cardId: string;
pageId: number;
title: string;
category: Faction;
rarity: Rarity;
/** Only the derived scores are read (MintStatsSnapshot.stats). */
snapshot: { stats: { attention: number | null; depth: number; reach: number } };
/** Frozen by the host at match start. */
live: { trendPercent: number | null; dailyAverage: number | null };
/** §1.10, set by the host. Only 'unchecked' changes derivation (cost cap). */
check: 'verified' | 'unverified' | 'unchecked' | 'loaner';
}
/** 99 ascending cut points per stat (§1.1). */
export type PercentileTable = Record<Stat, readonly number[]>;
/** The rules config keys derivation reads (§9). */
export interface DerivationRules {
costThresholds: readonly number[];
powerByCost: readonly number[];
vanillaBonus: number;
keywordsEnabled: readonly string[];
keywordParams: Record<string, Record<string, number>>;
trendUp: number;
trendDown: number;
trendMinDaily: number;
uncheckedCostCap: number;
}
export const DEFAULT_DERIVATION: DerivationRules = {
costThresholds: [15, 35, 55, 75, 90],
powerByCost: [0, 1, 2, 4, 6, 8, 10],
vanillaBonus: 1,
keywordsEnabled: V1_KEYWORDS,
keywordParams: {},
trendUp: 25, trendDown: -25, trendMinDaily: 20,
uncheckedCostCap: 4,
};
/** §1.1: cut points strictly below, plus half of those equal, rounded down. */
export function percentile(score: number, cuts: readonly number[]): number {
let below = 0, equal = 0;
for (const cut of cuts) {
if (cut < score) below++;
else if (cut === score) equal++;
}
return Math.floor(below + equal / 2);
}
export function percentiles(stats: CardInput['snapshot']['stats'], table: PercentileTable): Record<Stat, number | null> {
return {
attention: stats.attention === null ? null : percentile(stats.attention, table.attention),
depth: percentile(stats.depth, table.depth),
reach: percentile(stats.reach, table.reach),
};
}
/** §1.2: integer mean of the non-null percentiles, rounded half up. */
export function fame(pct: Record<Stat, number | null>): number {
const values = STATS.map(stat => pct[stat]).filter((value): value is number => value !== null);
if (!values.length) return 0;
return Math.floor(values.reduce((total, value) => total + value, 0) / values.length + 0.5);
}
/** §1.2: 1 + the number of thresholds ≤ fame. */
export function costFor(fameValue: number, thresholds: readonly number[]): number {
return 1 + thresholds.filter(threshold => threshold <= fameValue).length;
}
/** §1.4: highest percentile, ties by depth > reach > attention; null never wins. */
export function homeStat(pct: Record<Stat, number | null>): Stat {
let best: Stat = HOME_TIE_ORDER[0];
for (const stat of HOME_TIE_ORDER) {
const value = pct[stat], current = pct[best];
if (value !== null && (current === null || value > current)) best = stat;
}
return best;
}
/** §1.6: ±1 past the thresholds; 0 for null or for articles under trendMinDaily views a day. */
export function trendFor(live: CardInput['live'], rules: Pick<DerivationRules, 'trendUp' | 'trendDown' | 'trendMinDaily'>): -1 | 0 | 1 {
const { trendPercent, dailyAverage } = live;
if (trendPercent === null || !Number.isFinite(trendPercent)) return 0;
if (dailyAverage === null || !(dailyAverage >= rules.trendMinDaily)) return 0;
if (trendPercent >= rules.trendUp) return 1;
if (trendPercent <= rules.trendDown) return -1;
return 0;
}
/**
* §10.1: cost 1 → vanilla (+vanillaBonus); edition if enabled and the deck has another
* copy; else the faction keyword if enabled; else vanilla without the bonus.
*/
export function keywordFor(faction: Faction, cost: number, hasCopyInDeck: boolean, rules: Pick<DerivationRules, 'keywordsEnabled'>):
{ keyword: string | null; vanilla: boolean } {
if (cost === 1) return { keyword: null, vanilla: true };
if (hasCopyInDeck && rules.keywordsEnabled.includes('edition')) return { keyword: 'edition', vanilla: false };
const keyword = FACTION_KEYWORD[faction];
return rules.keywordsEnabled.includes(keyword) ? { keyword, vanilla: false } : { keyword: null, vanilla: false };
}
export function deriveCard(input: CardInput, table: PercentileTable, rules: DerivationRules = DEFAULT_DERIVATION,
hasCopyInDeck = false): GameCard {
const pct = percentiles(input.snapshot.stats, table);
let cost = costFor(fame(pct), rules.costThresholds);
if (input.check === 'unchecked') cost = Math.min(cost, rules.uncheckedCostCap);
const base = rules.powerByCost[cost];
if (base === undefined) throw new RangeError(`powerByCost has no entry for cost ${cost}`);
const { keyword, vanilla } = keywordFor(input.category, cost, hasCopyInDeck, rules);
const delta = keyword ? Math.max(-3, Math.min(0, rules.keywordParams[keyword]?.powerDelta ?? 0)) : 0;
return {
cardId: input.cardId, pageId: input.pageId, title: input.title, faction: input.category, rarity: input.rarity,
cost, power: Math.max(0, base + (vanilla ? rules.vanillaBonus : 0) + delta),
home: homeStat(pct), trend: trendFor(input.live, rules), keyword,
source: input.check === 'loaner' ? 'loaner' : 'owned',
};
}
/** Derive a whole deck; Edition (if enabled) needs to know about copies of the same pageId. */
export function deriveDeck(inputs: readonly CardInput[], table: PercentileTable, rules: DerivationRules = DEFAULT_DERIVATION): GameCard[] {
const counts = new Map<number, number>();
for (const input of inputs) counts.set(input.pageId, (counts.get(input.pageId) ?? 0) + 1);
return inputs.map(input => deriveCard(input, table, rules, (counts.get(input.pageId) ?? 0) > 1));
}