Files
wikideck/shared/game/derive.ts
T

144 lines
7.0 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 } from './keywords.ts';
import { DEFAULT_RULESET } from './ruleset.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;
/** null for loaners without a known article (§2.1). */
pageId: number | null;
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';
/** Loaners only (§2.1): replaces §1.1–1.5. Ignored unless check === 'loaner'. */
pinned?: { cost: number; home: Stat; faction: Faction };
}
/** 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[];
/** v1.1 hook: 'home' gives Culture cards a home-stat keyword instead of viral (§10.1). Default 'faction' (v1). */
cultureKeyword?: 'faction' | 'home';
keywordParams: Record<string, Record<string, number>>;
trendUp: number;
trendDown: number;
trendMinDaily: number;
uncheckedCostCap: number;
}
/** Derivation defaults are the engine's DEFAULT_RULESET (a Ruleset is a DerivationRules). */
export const DEFAULT_DERIVATION: DerivationRules = DEFAULT_RULESET;
/** §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.
*/
/** v1.1 option (critic, #3): Culture keyword by home stat when `cultureKeyword: 'home'`. */
export const CULTURE_HOME_KEYWORD: Record<Stat, string> = { attention: 'viral', depth: 'encyclopedic', reach: 'translated' };
export function keywordFor(faction: Faction, cost: number, hasCopyInDeck: boolean,
rules: Pick<DerivationRules, 'keywordsEnabled' | 'cultureKeyword'>, home: Stat = 'attention'):
{ 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 === 'Culture' && rules.cultureKeyword === 'home' ? CULTURE_HOME_KEYWORD[home] : 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 pinned = input.check === 'loaner' ? input.pinned : undefined;
const pct = percentiles(input.snapshot.stats, table);
let cost = pinned ? pinned.cost : costFor(fame(pct), rules.costThresholds);
if (input.check === 'unchecked') cost = Math.min(cost, rules.uncheckedCostCap);
const faction = pinned ? pinned.faction : input.category;
const base = rules.powerByCost[cost];
if (base === undefined) throw new RangeError(`powerByCost has no entry for cost ${cost}`);
const home = pinned ? pinned.home : homeStat(pct);
const { keyword, vanilla } = keywordFor(faction, cost, hasCopyInDeck, rules, home);
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, rarity: pinned ? 'Common' : input.rarity,
cost, power: Math.max(0, base + (vanilla ? rules.vanillaBonus : 0) + delta),
home, trend: pinned ? 0 : trendFor(input.live, rules), keyword,
source: input.check === 'loaner' ? 'loaner' : 'owned', check: input.check,
};
}
/** 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 key = (input: CardInput) => input.pageId ?? `card:${input.cardId}`;
const counts = new Map<number | string, number>();
for (const input of inputs) counts.set(key(input), (counts.get(key(input)) ?? 0) + 1);
return inputs.map(input => deriveCard(input, table, rules, (counts.get(key(input)) ?? 0) > 1));
}