forked from WikiDeck/wikideck
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>
This commit is contained in:
@@ -0,0 +1,136 @@
|
||||
/**
|
||||
* 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));
|
||||
}
|
||||
@@ -1,10 +1,17 @@
|
||||
/** Public entry point of the WikiDeck game engine. Other teams import only from here. See docs/game/ENGINE_API.md. */
|
||||
export * from './types.ts';
|
||||
export { Rng, seedFromString, normalizeSeed, type RngState } from './rng.ts';
|
||||
export { DEFAULT_RULESET, DEFAULT_TOPIC_POOL, RulesetSchema, TopicSchema, parseRuleset } from './ruleset.ts';
|
||||
export { DEFAULT_RULESET, DEFAULT_TOPIC_POOL, DEFAULT_KEYWORD_PARAMS, DEFAULT_PORTAL_PARAMS, RulesetSchema, TopicSchema, parseRuleset } from './ruleset.ts';
|
||||
export {
|
||||
ENGINE_VERSION, createMatch, legalActions, applyAction, actionProblem, isOver, result, viewFor,
|
||||
serialize, deserialize, replay, validateDeck, cardPower, lanePower, topicsLed, other, placeCard, revealTopic,
|
||||
} from './engine.ts';
|
||||
export { KEYWORDS, PORTALS, allies, type KeywordDef, type PortalDef, type EffectContext } from './keywords.ts';
|
||||
export {
|
||||
KEYWORDS, PORTALS, FACTION_KEYWORD, V1_KEYWORDS, OPTIONAL_KEYWORDS, allies, activePortal, isOnTopic, keywordEnabled, hiddenFrom,
|
||||
type KeywordDef, type PortalDef, type EffectContext,
|
||||
} from './keywords.ts';
|
||||
export {
|
||||
DEFAULT_DERIVATION, HOME_TIE_ORDER, percentile, percentiles, fame, costFor, homeStat, trendFor, keywordFor, deriveCard, deriveDeck,
|
||||
type CardInput, type PercentileTable, type DerivationRules,
|
||||
} from './derive.ts';
|
||||
export { STARTER_POOL, loanerCard, previewPool, starterDeck } from './starter.ts';
|
||||
|
||||
+167
-16
@@ -17,7 +17,9 @@
|
||||
* - Hooks must not throw, must not move/remove cards (§10 v1 constraint).
|
||||
*/
|
||||
import type { Rng } from './rng.ts';
|
||||
import type { CardInPlay, GameCard, MatchState, PlayerId } from './types.ts';
|
||||
// Cycle-safe: these are only called inside hooks, after both modules have loaded.
|
||||
import { cardPower, lanePower } from './engine.ts';
|
||||
import type { CardInPlay, GameCard, MatchState, PlayerId, Stat } from './types.ts';
|
||||
|
||||
export interface EffectContext {
|
||||
state: MatchState;
|
||||
@@ -50,6 +52,16 @@ export interface PortalDef {
|
||||
ongoing?(ctx: EffectContext, target: CardInPlay): number;
|
||||
/** Lets a Topic reject a card; checked when queuing and again at reveal. */
|
||||
canPlay?(ctx: EffectContext, card: GameCard, player: PlayerId): boolean;
|
||||
/** Per-player lane capacity in this Topic, overriding Ruleset.laneCapacity (Stub). */
|
||||
capacity?(ctx: EffectContext): number;
|
||||
/** Every card here counts as on-topic (Disambiguation). Read by isOnTopic. */
|
||||
allOnTopic?: boolean;
|
||||
/**
|
||||
* Topic-level power added to each seat's lane total (not to any card), e.g. Interwiki.
|
||||
* `scoring` is true only for the final judgement (§7), so "at scoring" Portals
|
||||
* (Main Page, Featured Article) return [0, 0] otherwise. PURE.
|
||||
*/
|
||||
topicBonus?(ctx: EffectContext, scoring: boolean): [number, number];
|
||||
}
|
||||
|
||||
/** Cards on the same side of the same lane, excluding `self`. */
|
||||
@@ -57,31 +69,170 @@ export function allies(state: MatchState, self: CardInPlay): CardInPlay[] {
|
||||
return state.lanes[self.lane].cards[self.owner].filter(card => card !== self);
|
||||
}
|
||||
|
||||
/** PLACEHOLDERS so the hook contract is exercised; engine-b replaces these per DESIGN §10. */
|
||||
/** The revealed Portal of a lane, if any. */
|
||||
export function activePortal(state: MatchState, lane: number): PortalDef | undefined {
|
||||
const l = state.lanes[lane];
|
||||
return l?.revealed && l.topic.portal ? PORTALS[l.topic.portal] : undefined;
|
||||
}
|
||||
|
||||
/** §1.4/§6: the card's home stat is the Topic's stat (stats are visible from turn 1), or a Disambiguation Portal applies. */
|
||||
export function isOnTopic(state: MatchState, card: CardInPlay): boolean {
|
||||
if (activePortal(state, card.lane)?.allOnTopic) return true;
|
||||
return state.lanes[card.lane].topic.stat === card.card.home;
|
||||
}
|
||||
|
||||
/** Whether a keyword runs in this ruleset (§9 keywordsEnabled; absent list = all enabled). */
|
||||
export function keywordEnabled(state: MatchState, id: string): boolean {
|
||||
const enabled = (state.ruleset as { keywordsEnabled?: string[] }).keywordsEnabled;
|
||||
return Object.hasOwn(KEYWORDS, id) && (!enabled || enabled.includes(id));
|
||||
}
|
||||
|
||||
/** §10.1 v1 faction keywords. */
|
||||
export const FACTION_KEYWORD = {
|
||||
Culture: 'viral', Nature: 'rising', People: 'local', Science: 'encyclopedic', History: 'nostalgic', Space: 'translated',
|
||||
} as const;
|
||||
export const V1_KEYWORDS: readonly string[] = Object.values(FACTION_KEYWORD);
|
||||
/** Implemented but off by default (modes only). */
|
||||
export const OPTIONAL_KEYWORDS: readonly string[] = ['edition', 'obscure', 'wildcard'];
|
||||
|
||||
/** True when `card` should be shown face down to `viewer` (Obscure). viewFor should use this. */
|
||||
export function hiddenFrom(state: MatchState, card: CardInPlay, viewer: PlayerId): boolean {
|
||||
return card.owner !== viewer && state.phase !== 'over' && card.card.keyword === 'obscure' && keywordEnabled(state, 'obscure');
|
||||
}
|
||||
|
||||
const amount = (ctx: EffectContext, fallback: number) => ctx.params.amount ?? fallback;
|
||||
|
||||
/**
|
||||
* DESIGN §10.2 (PR #17 @ cf2fceb). All keywords only add power, use no RNG, and
|
||||
* the largest single swing is +2. Every number comes from Ruleset.keywordParams.
|
||||
* `powerDelta` params are applied at derivation (derive.ts), not here.
|
||||
*/
|
||||
export const KEYWORDS: Record<string, KeywordDef> = {
|
||||
rally: {
|
||||
id: 'rally', name: 'Rally', text: 'On reveal: +{amount} to your other cards here.',
|
||||
viral: {
|
||||
id: 'viral', name: 'Viral', text: '+{amount} power for each other card you revealed earlier this turn (max +{cap}).',
|
||||
onReveal(ctx, self) {
|
||||
const amount = ctx.params.amount ?? 1;
|
||||
for (const ally of allies(ctx.state, self)) ally.bonus += amount;
|
||||
ctx.log(`${self.card.title}: Rally +${amount}`);
|
||||
let earlier = 0;
|
||||
for (const lane of ctx.state.lanes) for (const card of lane.cards[self.owner])
|
||||
if (card !== self && card.turn === ctx.state.turn) earlier++;
|
||||
const gain = Math.min(earlier * amount(ctx, 1), ctx.params.cap ?? 2);
|
||||
if (gain > 0) { self.bonus += gain; ctx.log(`${self.card.title}: Viral +${gain}`); }
|
||||
},
|
||||
},
|
||||
anchor: {
|
||||
id: 'anchor', name: 'Anchor', text: 'Ongoing: +{amount} if alone here.',
|
||||
rising: {
|
||||
id: 'rising', name: 'Rising', text: 'End of turn: +{amount} power (max +{cap} in total).',
|
||||
// Stateless: the gain so far is a function of how many ends of turn it has seen.
|
||||
endOfTurn(ctx, self) {
|
||||
const step = amount(ctx, 1), cap = ctx.params.cap ?? 2;
|
||||
const seen = ctx.state.turn - self.turn; // ends of turn before this one
|
||||
const gain = Math.min(cap, (seen + 1) * step) - Math.min(cap, seen * step);
|
||||
if (gain > 0) { self.bonus += gain; ctx.log(`${self.card.title}: Rising +${gain}`); }
|
||||
},
|
||||
},
|
||||
local: {
|
||||
id: 'local', name: 'Local', text: '+{amount} power while on-topic.',
|
||||
ongoing(ctx, self, target) {
|
||||
return target === self && allies(ctx.state, self).length === 0 ? ctx.params.amount ?? 2 : 0;
|
||||
return target === self && isOnTopic(ctx.state, self) ? amount(ctx, 1) : 0;
|
||||
},
|
||||
},
|
||||
encyclopedic: {
|
||||
id: 'encyclopedic', name: 'Encyclopedic', text: '+{amount} power if there are no other cards here.',
|
||||
onReveal(ctx, self) {
|
||||
const [mine, theirs] = ctx.state.lanes[self.lane].cards;
|
||||
if (mine.every(card => card === self) && theirs.length === 0) {
|
||||
self.bonus += amount(ctx, 2);
|
||||
ctx.log(`${self.card.title}: Encyclopedic +${amount(ctx, 2)}`);
|
||||
}
|
||||
},
|
||||
},
|
||||
nostalgic: {
|
||||
id: 'nostalgic', name: 'Nostalgic', text: '+{amount} power if you are losing here.',
|
||||
onReveal(ctx, self) {
|
||||
// Topic power just before this card was added (§10.2): take it out, measure, put it back.
|
||||
const side = ctx.state.lanes[self.lane].cards[self.owner];
|
||||
const index = side.indexOf(self);
|
||||
side.splice(index, 1);
|
||||
const power = lanePower(ctx.state, self.lane);
|
||||
side.splice(index, 0, self);
|
||||
if (power[self.owner === 0 ? 1 : 0] > power[self.owner]) {
|
||||
self.bonus += amount(ctx, 2);
|
||||
ctx.log(`${self.card.title}: Nostalgic +${amount(ctx, 2)}`);
|
||||
}
|
||||
},
|
||||
},
|
||||
translated: {
|
||||
id: 'translated', name: 'Translated', text: '+{amount} power to your most recently revealed card in each other Topic.',
|
||||
onReveal(ctx, self) {
|
||||
ctx.state.lanes.forEach((lane, index) => {
|
||||
if (index === self.lane) return;
|
||||
// Cards are appended in reveal order, so the last one is the most recently revealed.
|
||||
const latest = lane.cards[self.owner].at(-1);
|
||||
if (!latest) return;
|
||||
latest.bonus += amount(ctx, 1);
|
||||
ctx.log(`${self.card.title}: Translated +${amount(ctx, 1)} to ${latest.card.title}`);
|
||||
});
|
||||
},
|
||||
},
|
||||
|
||||
// Implemented, disabled by default (not in keywordsEnabled): modes only.
|
||||
edition: {
|
||||
id: 'edition', name: 'Edition', text: '+{amount} power for each other copy of this article on your side.',
|
||||
ongoing(ctx, self, target) {
|
||||
if (target !== self) return 0;
|
||||
let copies = 0;
|
||||
for (const lane of ctx.state.lanes) for (const card of lane.cards[self.owner])
|
||||
if (card !== self && card.card.pageId === self.card.pageId) copies++;
|
||||
return copies * amount(ctx, 2);
|
||||
},
|
||||
},
|
||||
obscure: {
|
||||
id: 'obscure', name: 'Obscure', text: 'Your opponent sees this card face down until the match ends.',
|
||||
},
|
||||
wildcard: {
|
||||
id: 'wildcard', name: 'Wildcard', text: "On reveal: its home stat becomes this Topic's stat.",
|
||||
onReveal(ctx, self) {
|
||||
const stat: Stat = ctx.state.lanes[self.lane].topic.stat;
|
||||
if (self.card.home !== stat) { self.card.home = stat; ctx.log(`${self.card.title}: Wildcard → ${stat}`); }
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
/** DESIGN §10.3 Portals, keyed by portal id (= Topic id). Numbers from Ruleset.portalParams. */
|
||||
export const PORTALS: Record<string, PortalDef> = {
|
||||
spotlight: {
|
||||
id: 'spotlight', name: 'Spotlight', text: 'Cards here get +{amount}.',
|
||||
ongoing(ctx) { return ctx.params.amount ?? 1; },
|
||||
'main-page': {
|
||||
id: 'main-page', name: 'Main Page', text: 'At scoring, each card here gets +{amount} power.',
|
||||
topicBonus(ctx, scoring) {
|
||||
if (!scoring) return [0, 0];
|
||||
const [a, b] = ctx.state.lanes[ctx.lane].cards;
|
||||
return [a.length * amount(ctx, 1), b.length * amount(ctx, 1)];
|
||||
},
|
||||
},
|
||||
paywall: {
|
||||
id: 'paywall', name: 'Paywall', text: 'Only cards costing {maxCost} or less.',
|
||||
canPlay(ctx, card) { return card.cost <= (ctx.params.maxCost ?? 3); },
|
||||
trending: {
|
||||
id: 'trending', name: 'Trending', text: 'Trend arrows count ×{factor} here.',
|
||||
ongoing(ctx, target) { return target.card.trend * ((ctx.params.factor ?? 2) - 1); },
|
||||
},
|
||||
'featured-article': {
|
||||
id: 'featured-article', name: 'Featured Article',
|
||||
text: 'At scoring, the player with the single highest-power card here gets +{amount}.',
|
||||
topicBonus(ctx, scoring) {
|
||||
if (!scoring) return [0, 0];
|
||||
const best = ctx.state.lanes[ctx.lane].cards.map(side => Math.max(-1, ...side.map(card => cardPower(ctx.state, card))));
|
||||
if (best[0] === best[1] || Math.max(best[0], best[1]) < 0) return [0, 0];
|
||||
return best[0] > best[1] ? [amount(ctx, 2), 0] : [0, amount(ctx, 2)];
|
||||
},
|
||||
},
|
||||
stub: {
|
||||
id: 'stub', name: 'Stub', text: 'Lane capacity here is {value} per player.',
|
||||
capacity(ctx) { return ctx.params.value ?? 2; },
|
||||
},
|
||||
interwiki: {
|
||||
id: 'interwiki', name: 'Interwiki', text: '+{amount} Topic power here if you have a card in every Topic.',
|
||||
topicBonus(ctx) {
|
||||
const lanes = ctx.state.lanes;
|
||||
return [0, 1].map(seat => lanes.every(lane => lane.cards[seat].length > 0) ? amount(ctx, 1) : 0) as [number, number];
|
||||
},
|
||||
},
|
||||
disambiguation: {
|
||||
id: 'disambiguation', name: 'Disambiguation', text: 'Every card here counts as on-topic.', allOnTopic: true,
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
+25
-12
@@ -76,19 +76,32 @@ export function parseRuleset(input: unknown): Ruleset {
|
||||
return RulesetSchema.parse(input) as Ruleset;
|
||||
}
|
||||
|
||||
/** DESIGN §3: 9 Topics, each stat 3 times: one plain and two with Portals (portals are placeholders until §10.3). */
|
||||
/** DESIGN §10.3: 9 Topics, one plain and two with Portals per stat. A Portal's id is its Topic's id. */
|
||||
export const DEFAULT_TOPIC_POOL: Ruleset['topicPool'] = [
|
||||
{ id: 'front-page', name: 'Front Page', stat: 'attention', portal: null },
|
||||
{ id: 'trending', name: 'Trending', stat: 'attention', portal: 'spotlight' },
|
||||
{ id: 'viral', name: 'Viral', stat: 'attention', portal: 'paywall' },
|
||||
{ id: 'deep-dive', name: 'Deep Dive', stat: 'depth', portal: null },
|
||||
{ id: 'archive', name: 'Archive', stat: 'depth', portal: 'spotlight' },
|
||||
{ id: 'citation-needed', name: 'Citation Needed', stat: 'depth', portal: 'paywall' },
|
||||
{ id: 'world-tour', name: 'World Tour', stat: 'reach', portal: null },
|
||||
{ id: 'translation', name: 'Translation', stat: 'reach', portal: 'spotlight' },
|
||||
{ id: 'interwiki', name: 'Interwiki', stat: 'reach', portal: 'paywall' },
|
||||
{ id: 'current-events', name: 'Current Events', stat: 'attention', portal: null },
|
||||
{ id: 'main-page', name: 'Main Page', stat: 'attention', portal: 'main-page' },
|
||||
{ id: 'trending', name: 'Trending', stat: 'attention', portal: 'trending' },
|
||||
{ id: 'archive', name: 'Archive', stat: 'depth', portal: null },
|
||||
{ id: 'featured-article', name: 'Featured Article', stat: 'depth', portal: 'featured-article' },
|
||||
{ id: 'stub', name: 'Stub', stat: 'depth', portal: 'stub' },
|
||||
{ id: 'translations', name: 'Translations', stat: 'reach', portal: null },
|
||||
{ id: 'interwiki', name: 'Interwiki', stat: 'reach', portal: 'interwiki' },
|
||||
{ id: 'disambiguation', name: 'Disambiguation', stat: 'reach', portal: 'disambiguation' },
|
||||
];
|
||||
|
||||
/** DESIGN §10.2 keywordParams defaults. */
|
||||
export const DEFAULT_KEYWORD_PARAMS: Ruleset['keywordParams'] = {
|
||||
viral: { amount: 1, cap: 2, powerDelta: 0 }, rising: { amount: 1, cap: 2, powerDelta: 0 },
|
||||
local: { amount: 1, powerDelta: 0 }, encyclopedic: { amount: 2, powerDelta: 0 },
|
||||
nostalgic: { amount: 2, powerDelta: 0 }, translated: { amount: 1, powerDelta: 0 },
|
||||
edition: { amount: 2, powerDelta: 0 }, obscure: { powerDelta: 0 }, wildcard: { powerDelta: 0 },
|
||||
};
|
||||
|
||||
/** DESIGN §10.3 portalParams defaults. */
|
||||
export const DEFAULT_PORTAL_PARAMS: Ruleset['portalParams'] = {
|
||||
'main-page': { amount: 1 }, trending: { factor: 2 }, 'featured-article': { amount: 2 }, stub: { value: 2 }, interwiki: { amount: 1 },
|
||||
};
|
||||
|
||||
/** DESIGN §9 defaults. */
|
||||
export const DEFAULT_RULESET: Ruleset = {
|
||||
version: '1.0',
|
||||
@@ -106,6 +119,6 @@ export const DEFAULT_RULESET: Ruleset = {
|
||||
verifyStats: true,
|
||||
percentiles: 'card-sample-2026-11-16',
|
||||
starterDecks: 'default',
|
||||
keywordParams: { rally: { amount: 1 }, anchor: { amount: 2 } },
|
||||
portalParams: { spotlight: { amount: 1 }, paywall: { maxCost: 3 } },
|
||||
keywordParams: DEFAULT_KEYWORD_PARAMS,
|
||||
portalParams: DEFAULT_PORTAL_PARAMS,
|
||||
};
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
* engine-b / council-data replace STARTER_POOL with derived cards (cards.ts).
|
||||
*/
|
||||
import { Rng } from './rng.ts';
|
||||
import { FACTION_KEYWORD } from './keywords.ts';
|
||||
import type { Faction, GameCard, Stat } from './types.ts';
|
||||
|
||||
type Spec = [pageId: number, title: string, faction: Faction, cost: number, home: Stat, keyword: string | null];
|
||||
@@ -40,7 +41,9 @@ export const STARTER_POOL: readonly Spec[] = [
|
||||
];
|
||||
|
||||
export function loanerCard(spec: Spec, copy = 0): GameCard {
|
||||
const [pageId, title, faction, cost, home, keyword] = spec;
|
||||
const [pageId, title, faction, cost, home, spec5] = spec;
|
||||
// §10.1: cost-1 cards are vanilla; a placeholder keyword marks "gets its faction's keyword".
|
||||
const keyword = cost > 1 && spec5 !== null ? FACTION_KEYWORD[faction] : null;
|
||||
return { cardId: `loaner:${pageId}:${copy}`, pageId, title, faction, rarity: 'Common', cost, power: POWER_BY_COST[cost], home, trend: 0, keyword, source: 'loaner' };
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
DEFAULT_DERIVATION, percentile, percentiles, fame, costFor, homeStat, trendFor, keywordFor, deriveCard, deriveDeck,
|
||||
type CardInput, type PercentileTable, type DerivationRules, type Faction,
|
||||
} from '../shared/game/index.ts';
|
||||
import { forAll } from './game/property.ts';
|
||||
|
||||
/** Cut points 1..99: score s sits at percentile ~s, which makes examples readable. */
|
||||
const LINEAR = Array.from({ length: 99 }, (_, i) => i + 1);
|
||||
const TABLE: PercentileTable = { attention: LINEAR, depth: LINEAR, reach: LINEAR };
|
||||
const RULES = DEFAULT_DERIVATION;
|
||||
const LIVE = { trendPercent: null, dailyAverage: null };
|
||||
|
||||
function input(stats: CardInput['snapshot']['stats'], overrides: Partial<CardInput> = {}): CardInput {
|
||||
return { cardId: 'c1', pageId: 1, title: 'T', category: 'Science', rarity: 'Common',
|
||||
snapshot: { stats }, live: LIVE, check: 'verified', ...overrides };
|
||||
}
|
||||
|
||||
test('percentile counts cuts strictly below plus half of equal ones, rounded down (§1.1)', () => {
|
||||
assert.equal(percentile(0, LINEAR), 0);
|
||||
assert.equal(percentile(50, LINEAR), 49);
|
||||
assert.equal(percentile(50.5, LINEAR), 50);
|
||||
assert.equal(percentile(1000, LINEAR), 99);
|
||||
assert.equal(percentile(5, [5, 5, 5, 5]), 2);
|
||||
assert.equal(percentile(5, [1, 5, 5, 9]), 2);
|
||||
});
|
||||
|
||||
test('null attention gives a null percentile and is ignored by fame (§1.1, §1.2)', () => {
|
||||
const pct = percentiles({ attention: null, depth: 61, reach: 31 }, TABLE);
|
||||
assert.deepEqual(pct, { attention: null, depth: 60, reach: 30 });
|
||||
assert.equal(fame(pct), 45);
|
||||
});
|
||||
|
||||
test('fame rounds half up', () => {
|
||||
assert.equal(fame({ attention: 10, depth: 11, reach: null }), 11);
|
||||
assert.equal(fame({ attention: 10, depth: 10, reach: 11 }), 10);
|
||||
assert.equal(fame({ attention: 10, depth: 11, reach: 11 }), 11);
|
||||
});
|
||||
|
||||
test('cost is 1 + thresholds ≤ fame, spanning 1–6 (§1.2)', () => {
|
||||
const t = RULES.costThresholds;
|
||||
assert.deepEqual([0, 14, 15, 54, 55, 89, 90, 100].map(f => costFor(f, t)), [1, 1, 2, 3, 4, 5, 6, 6]);
|
||||
});
|
||||
|
||||
test('home stat: highest percentile, ties depth > reach > attention, never null (§1.4)', () => {
|
||||
assert.equal(homeStat({ attention: 90, depth: 10, reach: 10 }), 'attention');
|
||||
assert.equal(homeStat({ attention: 50, depth: 50, reach: 50 }), 'depth');
|
||||
assert.equal(homeStat({ attention: 50, depth: 40, reach: 50 }), 'reach');
|
||||
assert.equal(homeStat({ attention: null, depth: 0, reach: 0 }), 'depth');
|
||||
assert.equal(homeStat({ attention: null, depth: 0, reach: 1 }), 'reach');
|
||||
});
|
||||
|
||||
test('trend: ±1 at inclusive thresholds, 0 for null, 0 under trendMinDaily (§1.6)', () => {
|
||||
const t = (trendPercent: number | null, dailyAverage: number | null = 100) => trendFor({ trendPercent, dailyAverage }, RULES);
|
||||
assert.deepEqual([t(25), t(24.9), t(-25), t(-24.9), t(null), t(Number.NaN), t(1e9)], [1, 0, -1, 0, 0, 0, 1]);
|
||||
assert.equal(t(80, 19.9), 0);
|
||||
assert.equal(t(80, 20), 1);
|
||||
assert.equal(t(80, null), 0);
|
||||
});
|
||||
|
||||
test('keyword choice: cost 1 vanilla, faction keyword otherwise, disabled → plain vanilla (§10.1)', () => {
|
||||
const expected: Record<Faction, string> = { Culture: 'viral', Nature: 'rising', People: 'local',
|
||||
Science: 'encyclopedic', History: 'nostalgic', Space: 'translated' };
|
||||
for (const [faction, keyword] of Object.entries(expected) as [Faction, string][]) {
|
||||
assert.deepEqual(keywordFor(faction, 1, false, RULES), { keyword: null, vanilla: true });
|
||||
assert.deepEqual(keywordFor(faction, 3, false, RULES), { keyword, vanilla: false });
|
||||
assert.deepEqual(keywordFor(faction, 3, false, { keywordsEnabled: [] }), { keyword: null, vanilla: false });
|
||||
}
|
||||
assert.equal(keywordFor('Culture', 3, true, RULES).keyword, 'viral', 'edition is off by default');
|
||||
assert.equal(keywordFor('Culture', 3, true, { keywordsEnabled: ['edition', 'viral'] }).keyword, 'edition');
|
||||
assert.equal(keywordFor('Culture', 1, true, { keywordsEnabled: ['edition'] }).keyword, null, 'cost 1 stays vanilla');
|
||||
});
|
||||
|
||||
test('deriveCard: cost, power, vanillaBonus, home, trend and source', () => {
|
||||
// pct 80/70/60 → fame 70 → cost 4 → power 6, Science → encyclopedic
|
||||
const card = deriveCard(input({ attention: 81, depth: 71, reach: 61 }, { live: { trendPercent: 40, dailyAverage: 50 } }), TABLE);
|
||||
assert.deepEqual(card, { cardId: 'c1', pageId: 1, title: 'T', faction: 'Science', rarity: 'Common',
|
||||
cost: 4, power: 6, home: 'attention', trend: 1, keyword: 'encyclopedic', source: 'owned' });
|
||||
const cheap = deriveCard(input({ attention: 5, depth: 5, reach: 5 }, { check: 'loaner' }), TABLE);
|
||||
assert.deepEqual([cheap.cost, cheap.power, cheap.keyword, cheap.source], [1, 2, null, 'loaner']);
|
||||
const disabled = deriveCard(input({ attention: 81, depth: 71, reach: 61 }), TABLE, { ...RULES, keywordsEnabled: [] });
|
||||
assert.deepEqual([disabled.power, disabled.keyword], [6, null]);
|
||||
});
|
||||
|
||||
test('rarity is cosmetic: it never changes cost, power or keyword (§1.7)', () => {
|
||||
const stats = { attention: 40, depth: 60, reach: 20 };
|
||||
const cards = (['Common', 'Rare', 'Epic', 'Legendary'] as const).map(rarity => deriveCard(input(stats, { rarity }), TABLE));
|
||||
for (const card of cards) assert.deepEqual({ ...card, rarity: 'Common' }, { ...cards[0], rarity: 'Common' });
|
||||
});
|
||||
|
||||
test('unchecked cards are capped at uncheckedCostCap and keep their home stat (§1.10)', () => {
|
||||
const stats = { attention: 100, depth: 100, reach: 99 };
|
||||
const checked = deriveCard(input(stats), TABLE);
|
||||
const unchecked = deriveCard(input(stats, { check: 'unchecked' }), TABLE);
|
||||
assert.equal(checked.cost, 6);
|
||||
assert.equal(unchecked.cost, 4);
|
||||
assert.equal(unchecked.power, RULES.powerByCost[4]);
|
||||
assert.equal(unchecked.home, checked.home);
|
||||
});
|
||||
|
||||
test('powerDelta from keywordParams lowers keyword cards only, clamped to −3..0', () => {
|
||||
const rules: DerivationRules = { ...RULES, keywordParams: { encyclopedic: { powerDelta: -2 }, viral: { powerDelta: -9 } } };
|
||||
assert.equal(deriveCard(input({ attention: 81, depth: 71, reach: 61 }), TABLE, rules).power, 4);
|
||||
assert.equal(deriveCard(input({ attention: 81, depth: 71, reach: 61 }, { category: 'Culture' }), TABLE, rules).power, 3);
|
||||
assert.equal(deriveCard(input({ attention: 5, depth: 5, reach: 5 }), TABLE, rules).power, 2);
|
||||
});
|
||||
|
||||
test('deriveDeck marks copies for Edition when it is enabled', () => {
|
||||
const a = input({ attention: 50, depth: 50, reach: 50 }, { cardId: 'a', pageId: 7, category: 'Culture' });
|
||||
const b = { ...a, cardId: 'b' };
|
||||
const c = { ...a, cardId: 'c', pageId: 8 };
|
||||
const rules = { ...RULES, keywordsEnabled: [...RULES.keywordsEnabled, 'edition'] };
|
||||
assert.deepEqual(deriveDeck([a, b, c], TABLE, rules).map(card => card.keyword), ['edition', 'edition', 'viral']);
|
||||
assert.deepEqual(deriveDeck([a, b, c], TABLE).map(card => card.keyword), ['viral', 'viral', 'viral']);
|
||||
});
|
||||
|
||||
test('power depends only on cost: forged stats only move a card up the curve (§1.3)', () => {
|
||||
forAll(300, g => {
|
||||
const stats = { attention: g.bool(0.1) ? null : g.int(0, 100), depth: g.int(0, 100), reach: g.int(0, 100) };
|
||||
const card = deriveCard(input(stats, { category: g.pick(['Space', 'Nature', 'People', 'Science', 'History', 'Culture'] as const) }), TABLE);
|
||||
assert.ok(card.cost >= 1 && card.cost <= 6);
|
||||
assert.equal(card.power, RULES.powerByCost[card.cost] + (card.cost === 1 ? RULES.vanillaBonus : 0));
|
||||
assert.ok(stats[card.home] !== null, 'home is never a null stat');
|
||||
const bumped = { ...stats, depth: Math.min(100, stats.depth + g.int(1, 30)) };
|
||||
assert.ok(deriveCard(input(bumped), TABLE).cost >= card.cost, 'raising a stat never lowers cost');
|
||||
});
|
||||
});
|
||||
|
||||
test('deriveCard rejects a rules config with no power for the derived cost', () => {
|
||||
assert.throws(() => deriveCard(input({ attention: 100, depth: 100, reach: 100 }), TABLE, { ...RULES, powerByCost: [0, 1, 2] }), RangeError);
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* Golden test: DESIGN.md §12 worked example (PR #17 @ cf2fceb), encoded exactly.
|
||||
* The Topic order, hands and initiative are injected; each player's per-turn
|
||||
* commit list is the table's, in the listed queue order. Owner: engine-b.
|
||||
*
|
||||
* Until the core implements the frozen §3–§7 rules (3 slots, energy carry,
|
||||
* interleaved reveals, alternating initiative, per-cost on-topic bonus,
|
||||
* consensus tie-break, at-scoring Portals), these run as `todo`: they report
|
||||
* but do not fail the suite. Flip GOLDEN_READY when core lands (#3).
|
||||
*/
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
DEFAULT_RULESET, applyAction, createMatch, isOver, lanePower, result, starterDeck, topicsLed,
|
||||
type Action, type GameCard, type MatchState, type PlayerId, type Ruleset, type Stat, type Faction,
|
||||
} from '../shared/game/index.ts';
|
||||
|
||||
const GOLDEN_READY = process.env.GOLDEN_READY === '1';
|
||||
const opts = GOLDEN_READY ? {} : { todo: 'core rules from DESIGN cf2fceb §3–§7 not landed yet' };
|
||||
|
||||
/** §9 defaults the example depends on. */
|
||||
const FROZEN = {
|
||||
laneCapacity: 3, powerByCost: [0, 1, 2, 4, 6, 8, 10], onTopicBonus: [0, 1, 1, 2, 2, 3, 3],
|
||||
vanillaBonus: 1, energyCarryMax: 1, underdog: false, portalReveal: [2, 3, 4],
|
||||
};
|
||||
|
||||
const c = (owner: string, title: string, faction: Faction, cost: number, power: number, home: Stat, keyword: string | null): GameCard =>
|
||||
({ cardId: `${owner}:${title}`, pageId: title.length * 1000 + cost, title, faction, rarity: 'Common',
|
||||
cost, power, home, trend: 0, keyword, source: 'loaner' });
|
||||
|
||||
const ANA = [
|
||||
c('ana', 'Octopus', 'Nature', 1, 2, 'depth', null),
|
||||
c('ana', 'Moon', 'Space', 2, 2, 'reach', 'translated'),
|
||||
c('ana', 'Coral reef', 'Nature', 2, 2, 'depth', 'rising'),
|
||||
c('ana', 'Albert Einstein', 'People', 4, 6, 'attention', 'local'),
|
||||
c('ana', 'Ancient Rome', 'History', 5, 8, 'depth', 'nostalgic'),
|
||||
c('ana', 'Library of Alexandria', 'History', 4, 6, 'depth', 'nostalgic'),
|
||||
c('ana', 'Periodic table', 'Science', 3, 4, 'depth', 'encyclopedic'),
|
||||
];
|
||||
const BO = [
|
||||
c('bo', 'Haiku', 'Culture', 1, 2, 'attention', null),
|
||||
c('bo', 'Mars', 'Space', 2, 2, 'reach', 'translated'),
|
||||
c('bo', 'Jazz', 'Culture', 2, 2, 'attention', 'viral'),
|
||||
c('bo', 'Pop music', 'Culture', 4, 6, 'attention', 'viral'),
|
||||
c('bo', 'Jupiter', 'Space', 5, 8, 'reach', 'translated'),
|
||||
c('bo', 'Fern', 'Nature', 3, 4, 'depth', 'rising'),
|
||||
c('bo', 'Mona Lisa', 'Culture', 3, 4, 'attention', 'viral'),
|
||||
];
|
||||
|
||||
const T1 = 0, T2 = 1, T3 = 2;
|
||||
/** [player, title, lane] in queue order, per turn (§12 table). */
|
||||
const PLAN: [PlayerId, string, number][][] = [
|
||||
[[0, 'Octopus', T1], [1, 'Haiku', T2]],
|
||||
[[0, 'Moon', T3]], // Bo passes to carry 1
|
||||
[[0, 'Coral reef', T1], [1, 'Mars', T3], [1, 'Jazz', T2]],
|
||||
[[1, 'Pop music', T3], [0, 'Albert Einstein', T2]],
|
||||
[[0, 'Ancient Rome', T3], [1, 'Jupiter', T1]],
|
||||
[[1, 'Fern', T1], [0, 'Library of Alexandria', T1], [1, 'Mona Lisa', T2], [0, 'Periodic table', T2]],
|
||||
];
|
||||
|
||||
function setup(): MatchState {
|
||||
const rules: Ruleset = { ...DEFAULT_RULESET };
|
||||
const state = createMatch(rules, [starterDeck('golden-a'), starterDeck('golden-b')], 1);
|
||||
const pool = state.ruleset.topicPool;
|
||||
const find = (id: string) => pool.find(t => t.id === id) ?? assert.fail(`topic ${id} missing from the default pool`);
|
||||
const topics = [find('archive'), find('main-page'), find('translations')];
|
||||
state.lanes = topics.map(topic => ({ topic, revealed: false, cards: [[], []] }));
|
||||
// Inject: every card the example plays starts in hand, nothing left to draw.
|
||||
state.players[0].hand = structuredClone(ANA);
|
||||
state.players[1].hand = structuredClone(BO);
|
||||
for (const p of state.players) p.deck = [];
|
||||
state.initiative = 0; // Ana has initiative on odd turns
|
||||
return state;
|
||||
}
|
||||
|
||||
const id = (player: PlayerId, title: string) => `${player === 0 ? 'ana' : 'bo'}:${title}`;
|
||||
|
||||
function playTurn(state: MatchState, plays: [PlayerId, string, number][]): MatchState {
|
||||
for (const [player, title, lane] of plays) state = applyAction(state, { type: 'play', player, cardId: id(player, title), lane } as Action);
|
||||
state = applyAction(state, { type: 'commit', player: 0 });
|
||||
return applyAction(state, { type: 'commit', player: 1 });
|
||||
}
|
||||
|
||||
test('§12 golden: rules defaults match the frozen §9 values', opts, () => {
|
||||
for (const [key, value] of Object.entries(FROZEN)) assert.deepEqual((DEFAULT_RULESET as unknown as Record<string, unknown>)[key], value, key);
|
||||
});
|
||||
|
||||
test('§12 golden: final Topic powers 19–15, 15–19, 13–10; Ana (p0) wins 2–1', opts, () => {
|
||||
let state = setup();
|
||||
const energyAtStart: [number, number][] = [];
|
||||
const snapshots: MatchState[] = [];
|
||||
for (const plays of PLAN) {
|
||||
energyAtStart.push([state.players[0].energy, state.players[1].energy]);
|
||||
state = playTurn(state, plays);
|
||||
snapshots.push(state);
|
||||
}
|
||||
assert.ok(isOver(state));
|
||||
const r = result(state)!;
|
||||
assert.deepEqual(r.lanePower, [[19, 15], [15, 19], [13, 10]]);
|
||||
assert.equal(r.winner, 0);
|
||||
assert.deepEqual(r.topicsLed, [2, 1]);
|
||||
|
||||
// Carry-over: Bo 4 at the start of turn 3; Ana 5, 6, 7 at the start of turns 4, 5, 6.
|
||||
assert.equal(energyAtStart[2][1], 4);
|
||||
assert.deepEqual(energyAtStart.slice(3).map(e => e[0]), [5, 6, 7]);
|
||||
|
||||
// After turn 5: T2 is 9–9 and Bo leads it by consensus (2 on-topic cards to 1).
|
||||
const afterFive = snapshots[4];
|
||||
assert.deepEqual(lanePower(afterFive, T2), [9, 9]);
|
||||
assert.deepEqual(lanePower(afterFive, T1), [9, 8]);
|
||||
assert.deepEqual(lanePower(afterFive, T3), [13, 10]);
|
||||
assert.deepEqual(topicsLed(afterFive), [2, 1]);
|
||||
});
|
||||
|
||||
test('§12 golden: per-turn Topic powers match the table', opts, () => {
|
||||
const expected = [
|
||||
[[3, 0], [0, 3], [0, 0]],
|
||||
[[4, 0], [0, 3], [3, 0]],
|
||||
[[8, 0], [0, 8], [3, 3]],
|
||||
[[9, 0], [9, 8], [3, 9]],
|
||||
[[9, 8], [9, 9], [13, 10]],
|
||||
];
|
||||
let state = setup();
|
||||
PLAN.slice(0, 5).forEach((plays, turn) => {
|
||||
state = playTurn(state, plays);
|
||||
assert.deepEqual(state.lanes.map((_, lane) => lanePower(state, lane)), expected[turn], `after turn ${turn + 1}`);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,224 @@
|
||||
// Keyword and Portal unit tests (DESIGN §10.2, §10.3 — PR #17 @ cf2fceb). Owner: engine-b.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
DEFAULT_RULESET, FACTION_KEYWORD, KEYWORDS, OPTIONAL_KEYWORDS, PORTALS, V1_KEYWORDS, hiddenFrom, isOnTopic, parseRuleset,
|
||||
} from '../shared/game/index.ts';
|
||||
import { board, card, cardPower, ctxFor, endOfTurn, place, reveal, topic, topicBonus } from './game/build.ts';
|
||||
|
||||
|
||||
test('registry: ids match keys, every entry has name and text, v1 set is one keyword per faction', () => {
|
||||
for (const [id, def] of [...Object.entries(KEYWORDS), ...Object.entries(PORTALS)]) {
|
||||
assert.equal(def.id, id);
|
||||
assert.ok(def.name && def.text, `${id} needs name and text`);
|
||||
}
|
||||
assert.deepEqual([...V1_KEYWORDS].sort(), ['encyclopedic', 'local', 'nostalgic', 'rising', 'translated', 'viral']);
|
||||
assert.equal(new Set(Object.values(FACTION_KEYWORD)).size, 6);
|
||||
for (const id of [...V1_KEYWORDS, ...OPTIONAL_KEYWORDS]) assert.ok(KEYWORDS[id], `${id} implemented`);
|
||||
});
|
||||
|
||||
test('the default ruleset (topic pool and params) validates', () => {
|
||||
assert.doesNotThrow(() => parseRuleset(DEFAULT_RULESET));
|
||||
for (const t of DEFAULT_RULESET.topicPool) if (t.portal) assert.equal(t.portal, t.id, 'portal id = topic id');
|
||||
assert.equal(DEFAULT_RULESET.topicPool.length, 9);
|
||||
});
|
||||
|
||||
// ---- viral ----
|
||||
test('viral: +1 per other own card revealed earlier this turn, any Topic, capped at +2', () => {
|
||||
const s = board();
|
||||
place(s, 0, 0, card(), s.turn - 1); // an older card does not count
|
||||
place(s, 1, 1, card()); // nor do the opponent's
|
||||
assert.equal(reveal(s, 0, 1, card({ keyword: 'viral' })).bonus, 0);
|
||||
place(s, 0, 2, card());
|
||||
// two earlier this turn now (the first viral card and this one) → +2
|
||||
assert.equal(reveal(s, 0, 2, card({ keyword: 'viral' })).bonus, 2);
|
||||
for (let i = 0; i < 3; i++) place(s, 0, 0, card());
|
||||
assert.equal(reveal(s, 0, 0, card({ keyword: 'viral' })).bonus, 2, 'cap');
|
||||
});
|
||||
|
||||
test('viral: the §12 example (Mars then Jazz → +1)', () => {
|
||||
const s = board();
|
||||
place(s, 1, 2, card({ title: 'Mars' }));
|
||||
assert.equal(reveal(s, 1, 1, card({ title: 'Jazz', keyword: 'viral' })).bonus, 1);
|
||||
});
|
||||
|
||||
// ---- rising ----
|
||||
test('rising: +1 at each end of turn, stopping after +2 in total', () => {
|
||||
const s = board();
|
||||
const r = place(s, 0, 0, card({ power: 2, keyword: 'rising' }));
|
||||
const seen: number[] = [];
|
||||
for (let i = 0; i < 4; i++) { endOfTurn(s, r); seen.push(r.bonus); s.turn++; }
|
||||
assert.deepEqual(seen, [1, 2, 2, 2]);
|
||||
});
|
||||
|
||||
test('rising: other bonuses do not count toward its cap', () => {
|
||||
const s = board();
|
||||
const r = place(s, 0, 0, card({ keyword: 'rising' }));
|
||||
r.bonus = 5;
|
||||
endOfTurn(s, r); s.turn++; endOfTurn(s, r); s.turn++; endOfTurn(s, r);
|
||||
assert.equal(r.bonus, 7);
|
||||
});
|
||||
|
||||
test('rising: respects keywordParams amount and cap', () => {
|
||||
const s = board();
|
||||
s.ruleset.keywordParams.rising = { amount: 2, cap: 3 };
|
||||
const r = place(s, 0, 0, card({ keyword: 'rising' }));
|
||||
endOfTurn(s, r); s.turn++; endOfTurn(s, r); s.turn++; endOfTurn(s, r);
|
||||
assert.equal(r.bonus, 3);
|
||||
});
|
||||
|
||||
// ---- local ----
|
||||
test('local: +1 only while on-topic, on top of the on-topic bonus', () => {
|
||||
const s = board();
|
||||
const on = place(s, 0, 1, card({ cost: 4, power: 6, home: 'attention', keyword: 'local' }));
|
||||
const off = place(s, 0, 0, card({ cost: 4, power: 6, home: 'attention', keyword: 'local' }));
|
||||
const plain = place(s, 1, 1, card({ cost: 4, power: 6, home: 'attention' }));
|
||||
assert.equal(cardPower(s, on) - cardPower(s, plain), 1);
|
||||
assert.equal(cardPower(s, off), 6);
|
||||
assert.equal(KEYWORDS.local.ongoing!(ctxFor(s, {}, 1), on, plain), 0, 'only buffs itself');
|
||||
});
|
||||
|
||||
// ---- encyclopedic ----
|
||||
test('encyclopedic: +2 only into a completely empty Topic (either side)', () => {
|
||||
const s = board();
|
||||
assert.equal(reveal(s, 0, 0, card({ keyword: 'encyclopedic' })).bonus, 2);
|
||||
place(s, 1, 1, card());
|
||||
assert.equal(reveal(s, 0, 1, card({ keyword: 'encyclopedic' })).bonus, 0, 'opponent card here');
|
||||
place(s, 0, 2, card());
|
||||
assert.equal(reveal(s, 0, 2, card({ keyword: 'encyclopedic' })).bonus, 0, 'own card here');
|
||||
});
|
||||
|
||||
// ---- nostalgic ----
|
||||
test('nostalgic: +2 when strictly losing, counted before this card is added', () => {
|
||||
const s = board();
|
||||
place(s, 0, 2, card({ power: 3, home: 'attention' }));
|
||||
place(s, 1, 2, card({ power: 9, home: 'attention' }));
|
||||
const n = reveal(s, 0, 2, card({ power: 8, home: 'depth', keyword: 'nostalgic' }));
|
||||
assert.equal(n.bonus, 2);
|
||||
assert.equal(s.lanes[2].cards[0].indexOf(n), 1, 'card is back in place, in reveal order');
|
||||
});
|
||||
|
||||
test('nostalgic: a tie is not losing, and neither is an empty Topic', () => {
|
||||
const s = board();
|
||||
place(s, 0, 2, card({ power: 4 }));
|
||||
place(s, 1, 2, card({ power: 4 }));
|
||||
assert.equal(reveal(s, 0, 2, card({ keyword: 'nostalgic' })).bonus, 0);
|
||||
assert.equal(reveal(s, 1, 0, card({ keyword: 'nostalgic' })).bonus, 0);
|
||||
});
|
||||
|
||||
// ---- translated ----
|
||||
test('translated: +1 to your most recently revealed card in each other Topic', () => {
|
||||
const s = board();
|
||||
const first = place(s, 0, 0, card());
|
||||
const latest = place(s, 0, 0, card());
|
||||
const enemy = place(s, 1, 2, card());
|
||||
const t = reveal(s, 0, 1, card({ keyword: 'translated' }));
|
||||
assert.deepEqual([first.bonus, latest.bonus, enemy.bonus, t.bonus], [0, 1, 0, 0]);
|
||||
});
|
||||
|
||||
test('translated: the §12 example (Jupiter → Jazz in T2 and Pop music in T3)', () => {
|
||||
const s = board();
|
||||
const haiku = place(s, 1, 1, card({ title: 'Haiku' }));
|
||||
const jazz = place(s, 1, 1, card({ title: 'Jazz' }));
|
||||
const mars = place(s, 1, 2, card({ title: 'Mars' }));
|
||||
const pop = place(s, 1, 2, card({ title: 'Pop music' }));
|
||||
reveal(s, 1, 0, card({ title: 'Jupiter', keyword: 'translated' }));
|
||||
assert.deepEqual([haiku.bonus, jazz.bonus, mars.bonus, pop.bonus], [0, 1, 0, 1]);
|
||||
});
|
||||
|
||||
// ---- optional keywords ----
|
||||
test('edition: +2 per other copy of the same pageId on your side', () => {
|
||||
const s = board();
|
||||
const a = place(s, 0, 0, card({ pageId: 42, power: 5, home: 'reach', keyword: 'edition' }));
|
||||
assert.equal(cardPower(s, a), 5);
|
||||
place(s, 0, 2, card({ pageId: 42, power: 5, home: 'depth', keyword: 'edition' }));
|
||||
place(s, 1, 0, card({ pageId: 42 }));
|
||||
assert.equal(cardPower(s, a), 7);
|
||||
});
|
||||
|
||||
test('wildcard: its home stat becomes the Topic stat on reveal', () => {
|
||||
const s = board();
|
||||
const w = reveal(s, 0, 2, card({ home: 'attention', keyword: 'wildcard' }));
|
||||
assert.equal(w.card.home, 'reach');
|
||||
assert.ok(isOnTopic(s, w));
|
||||
});
|
||||
|
||||
test('obscure: hidden only from the opponent, only while running, only when enabled', () => {
|
||||
const s = board();
|
||||
const o = place(s, 0, 1, card({ keyword: 'obscure' }));
|
||||
(s.ruleset as unknown as { keywordsEnabled: string[] }).keywordsEnabled = ['obscure'];
|
||||
assert.equal(hiddenFrom(s, o, 1), true);
|
||||
assert.equal(hiddenFrom(s, o, 0), false);
|
||||
(s.ruleset as unknown as { keywordsEnabled: string[] }).keywordsEnabled = [...V1_KEYWORDS];
|
||||
assert.equal(hiddenFrom(s, o, 1), false, 'disabled by default');
|
||||
(s.ruleset as unknown as { keywordsEnabled: string[] }).keywordsEnabled = ['obscure'];
|
||||
s.phase = 'over';
|
||||
assert.equal(hiddenFrom(s, o, 1), false);
|
||||
});
|
||||
|
||||
// ---- Portals (§10.3) ----
|
||||
test('isOnTopic: home stat matches the Topic stat; Disambiguation makes everything on-topic once revealed', () => {
|
||||
const s = board([topic('depth'), topic('reach', 'disambiguation'), topic('reach')]);
|
||||
assert.ok(isOnTopic(s, place(s, 0, 0, card({ home: 'depth' }))));
|
||||
assert.ok(!isOnTopic(s, place(s, 0, 2, card({ home: 'depth' }))));
|
||||
const d = place(s, 0, 1, card({ home: 'attention' }));
|
||||
assert.ok(isOnTopic(s, d));
|
||||
s.lanes[1].revealed = false;
|
||||
assert.ok(!isOnTopic(s, d), 'Portal not active while face down');
|
||||
});
|
||||
|
||||
test('Main Page: +1 per card at scoring only', () => {
|
||||
const s = board([topic('depth'), topic('attention', 'main-page'), topic('reach')]);
|
||||
place(s, 0, 1, card()); place(s, 0, 1, card()); place(s, 1, 1, card());
|
||||
assert.deepEqual(topicBonus(s, 1, false), [0, 0]);
|
||||
assert.deepEqual(topicBonus(s, 1, true), [2, 1]);
|
||||
});
|
||||
|
||||
test('Trending: trend arrows count double', () => {
|
||||
const s = board([topic('depth'), topic('attention', 'trending'), topic('reach')]);
|
||||
const up = place(s, 0, 1, card({ trend: 1 }));
|
||||
const down = place(s, 1, 1, card({ trend: -1 }));
|
||||
const flat = place(s, 1, 1, card({ trend: 0 }));
|
||||
const portal = PORTALS.trending;
|
||||
const ctx = ctxFor(s, s.ruleset.portalParams.trending, 1);
|
||||
assert.deepEqual([portal.ongoing!(ctx, up), portal.ongoing!(ctx, down), portal.ongoing!(ctx, flat)], [1, -1, 0]);
|
||||
});
|
||||
|
||||
test('Featured Article: +2 to the owner of the single highest card at scoring; tie → nobody', () => {
|
||||
const s = board([topic('depth', 'featured-article'), topic('attention'), topic('reach')]);
|
||||
place(s, 0, 0, card({ power: 6, home: 'reach' }));
|
||||
const bo = place(s, 1, 0, card({ power: 5, home: 'reach' }));
|
||||
assert.deepEqual(topicBonus(s, 0, false), [0, 0]);
|
||||
assert.deepEqual(topicBonus(s, 0, true), [2, 0]);
|
||||
bo.bonus = 1;
|
||||
assert.deepEqual(topicBonus(s, 0, true), [0, 0], 'tied highest');
|
||||
bo.bonus = 3;
|
||||
assert.deepEqual(topicBonus(s, 0, true), [0, 2]);
|
||||
assert.deepEqual(topicBonus(board([topic('depth', 'featured-article')]), 0, true), [0, 0], 'empty');
|
||||
});
|
||||
|
||||
test('Stub: lane capacity 2', () => {
|
||||
const s = board([topic('depth', 'stub'), topic('attention'), topic('reach')]);
|
||||
assert.equal(PORTALS.stub.capacity!(ctxFor(s, s.ruleset.portalParams.stub, 0)), 2);
|
||||
});
|
||||
|
||||
test('Interwiki: +1 Topic power to a player with a card in every Topic', () => {
|
||||
const s = board([topic('depth'), topic('attention'), topic('reach', 'interwiki')]);
|
||||
for (const lane of [0, 1, 2]) place(s, 0, lane, card());
|
||||
place(s, 1, 2, card());
|
||||
assert.deepEqual(topicBonus(s, 2, false), [1, 0]);
|
||||
assert.deepEqual(topicBonus(s, 2, true), [1, 0]);
|
||||
});
|
||||
|
||||
test('no keyword or Portal hook moves or removes cards (§10 v1 constraint)', () => {
|
||||
const s = board([topic('depth', 'featured-article'), topic('attention', 'main-page'), topic('reach', 'interwiki')]);
|
||||
for (const lane of [0, 1, 2]) { place(s, 0, lane, card()); place(s, 1, lane, card()); }
|
||||
const count = () => s.lanes.map(l => l.cards.map(side => side.map(c => c.card.cardId)));
|
||||
for (const id of [...V1_KEYWORDS, ...OPTIONAL_KEYWORDS]) {
|
||||
const before = count();
|
||||
const c = reveal(s, 0, 1, card({ keyword: id }));
|
||||
endOfTurn(s, c);
|
||||
s.lanes[1].cards[0].pop();
|
||||
assert.deepEqual(count(), before, id);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
// Property tests over random legal play (engine-b). Failures print a seed: rerun with PROP_SEED=<seed>.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
DEFAULT_RULESET, FACTION_KEYWORD, PLAYERS, applyAction, createMatch, deserialize, isOver, legalActions, replay, result,
|
||||
serialize, starterDeck, viewFor, type Action, type Faction, type GameCard, type MatchState,
|
||||
} from '../shared/game/index.ts';
|
||||
import { forAll, type Gen } from './game/property.ts';
|
||||
|
||||
const MAX_ACTIONS = 2000;
|
||||
const FACTIONS = Object.keys(FACTION_KEYWORD) as Faction[];
|
||||
const STATS = ['attention', 'depth', 'reach'] as const;
|
||||
|
||||
/** A starter deck with random factions, homes and trend, keywords per §10.1, so every keyword and Portal gets exercised. */
|
||||
function randomDeck(g: Gen, tag: string): GameCard[] {
|
||||
return starterDeck(tag).map(card => {
|
||||
const faction = g.pick(FACTIONS);
|
||||
return { ...card, cardId: `${tag}:${card.cardId}`, faction, home: g.pick(STATS), trend: g.pick([-1, 0, 0, 1] as const),
|
||||
keyword: card.cost === 1 ? null : FACTION_KEYWORD[faction] };
|
||||
});
|
||||
}
|
||||
|
||||
function decksFor(g: Gen, seed: number): [GameCard[], GameCard[]] {
|
||||
return [randomDeck(g, `a-${seed}`), randomDeck(g, `b-${seed}`)];
|
||||
}
|
||||
|
||||
/** Random legal play; commits come out at random so queues of every length happen. Concede is rare. */
|
||||
function playOut(g: Gen, state: MatchState, check?: (s: MatchState) => void) {
|
||||
const log: Action[] = [];
|
||||
for (let steps = 0; !isOver(state); steps++) {
|
||||
assert.ok(steps <= MAX_ACTIONS, `match did not terminate within ${MAX_ACTIONS} actions`);
|
||||
const options = PLAYERS.flatMap(player => legalActions(state, player));
|
||||
assert.ok(options.length > 0, `no legal actions in a live match (turn ${state.turn})`);
|
||||
const action: Action = g.bool(0.002) ? { type: 'concede', player: g.pick(PLAYERS) } : g.pick(options);
|
||||
log.push(action);
|
||||
state = applyAction(state, action);
|
||||
check?.(state);
|
||||
}
|
||||
return { state, log };
|
||||
}
|
||||
|
||||
test('random legal play never crashes, always terminates within the turn cap, and has a result', () => {
|
||||
forAll(200, (g, seed) => {
|
||||
const { state } = playOut(g, createMatch(DEFAULT_RULESET, decksFor(g, seed), seed));
|
||||
const r = result(state);
|
||||
assert.ok(r, 'finished match has a result');
|
||||
assert.ok(r.turns <= DEFAULT_RULESET.turns);
|
||||
if (r.reason !== 'concede' && r.reason !== 'afk') {
|
||||
const led = r.topicsLed;
|
||||
if (r.winner === null) assert.equal(led[0], led[1]);
|
||||
else assert.ok(led[r.winner] > led[1 - r.winner] || r.reason === 'totalPower');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test('same seed, decks and actions give the same match (replay)', () => {
|
||||
forAll(50, (g, seed) => {
|
||||
const decks = decksFor(g, seed);
|
||||
const first = playOut(g, createMatch(DEFAULT_RULESET, decks, seed));
|
||||
const again = replay(DEFAULT_RULESET, decks, seed, first.log);
|
||||
assert.deepEqual(again, first.state);
|
||||
});
|
||||
});
|
||||
|
||||
test('createMatch is deterministic per seed and varies across seeds', () => {
|
||||
const decks = (): [GameCard[], GameCard[]] => [starterDeck('x'), starterDeck('y')];
|
||||
assert.deepEqual(createMatch(DEFAULT_RULESET, decks(), 7), createMatch(DEFAULT_RULESET, decks(), 7));
|
||||
const distinct = new Set(Array.from({ length: 20 }, (_, i) => JSON.stringify(createMatch(DEFAULT_RULESET, decks(), i))));
|
||||
assert.ok(distinct.size > 1);
|
||||
});
|
||||
|
||||
test('serialize/deserialize round-trips after every action', () => {
|
||||
forAll(30, (g, seed) => {
|
||||
playOut(g, createMatch(DEFAULT_RULESET, decksFor(g, seed), seed), s => assert.deepEqual(deserialize(serialize(s)), s));
|
||||
});
|
||||
});
|
||||
|
||||
test('applyAction never mutates its input', () => {
|
||||
forAll(30, (g, seed) => {
|
||||
let state = createMatch(DEFAULT_RULESET, decksFor(g, seed), seed);
|
||||
for (let steps = 0; !isOver(state) && steps < MAX_ACTIONS; steps++) {
|
||||
const before = serialize(state);
|
||||
const next = applyAction(state, g.pick(PLAYERS.flatMap(player => legalActions(state, player))));
|
||||
assert.equal(serialize(state), before);
|
||||
state = next;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test('every listed legal action is accepted; a finished match lists none', () => {
|
||||
forAll(30, (g, seed) => {
|
||||
const { state } = playOut(g, createMatch(DEFAULT_RULESET, decksFor(g, seed), seed), s => {
|
||||
for (const player of PLAYERS) for (const action of legalActions(s, player)) assert.doesNotThrow(() => applyAction(s, action));
|
||||
});
|
||||
for (const player of PLAYERS) assert.deepEqual(legalActions(state, player), []);
|
||||
});
|
||||
});
|
||||
|
||||
test('lane power is never negative and lanes never exceed capacity', () => {
|
||||
forAll(50, (g, seed) => {
|
||||
playOut(g, createMatch(DEFAULT_RULESET, decksFor(g, seed), seed), s => {
|
||||
for (const player of PLAYERS) {
|
||||
const view = viewFor(s, player);
|
||||
for (const lane of view.lanes) {
|
||||
assert.ok(lane.power[0] >= 0 && lane.power[1] >= 0);
|
||||
for (const side of lane.cardPower) for (const p of side) assert.ok(p >= 0);
|
||||
}
|
||||
}
|
||||
for (const lane of s.lanes) for (const side of lane.cards) assert.ok(side.length <= s.ruleset.laneCapacity);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('a view never shows the opponent hand or queue', () => {
|
||||
forAll(30, (g, seed) => {
|
||||
playOut(g, createMatch(DEFAULT_RULESET, decksFor(g, seed), seed), s => {
|
||||
for (const player of PLAYERS) {
|
||||
const text = JSON.stringify(viewFor(s, player));
|
||||
for (const card of s.players[1 - player].hand) assert.ok(!text.includes(`"${card.cardId}"`), `p${player} sees ${card.cardId}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
/** Hand-built boards for keyword and Portal unit tests (engine-b). */
|
||||
import {
|
||||
DEFAULT_RULESET, KEYWORDS, PORTALS, Rng, cardPower, createMatch, lanePower, starterDeck,
|
||||
type CardInPlay, type EffectContext, type GameCard, type MatchState, type PlayerId, type Stat, type TopicDef,
|
||||
} from '../../shared/game/index.ts';
|
||||
|
||||
export const topic = (stat: Stat, portal: string | null = null, id = portal ?? `plain-${stat}`): TopicDef =>
|
||||
({ id, name: id, stat, portal });
|
||||
|
||||
/** Empty board, turn 1; lanes are depth / attention / reach plain Topics unless given. */
|
||||
export function board(topics: TopicDef[] = [topic('depth'), topic('attention'), topic('reach')], revealed = true): MatchState {
|
||||
const state = createMatch(DEFAULT_RULESET, [starterDeck('a'), starterDeck('b')], 'keyword-test');
|
||||
state.lanes = topics.map(t => ({ topic: t, revealed, cards: [[], []] as [CardInPlay[], CardInPlay[]] }));
|
||||
return state;
|
||||
}
|
||||
|
||||
let serial = 0;
|
||||
export function card(overrides: Partial<GameCard> = {}): GameCard {
|
||||
serial++;
|
||||
return { cardId: `t${serial}`, pageId: 1000 + serial, title: `Card ${serial}`, faction: 'Culture', rarity: 'Common',
|
||||
cost: 2, power: 2, home: 'attention', trend: 0, keyword: null, source: 'loaner', ...overrides };
|
||||
}
|
||||
|
||||
/** Put a card in a lane with no effects (mutates). */
|
||||
export function place(state: MatchState, owner: PlayerId, lane: number, c: GameCard, turn = state.turn): CardInPlay {
|
||||
const inPlay: CardInPlay = { card: c, owner, lane, turn, bonus: 0 };
|
||||
state.lanes[lane].cards[owner].push(inPlay);
|
||||
return inPlay;
|
||||
}
|
||||
|
||||
export function ctxFor(state: MatchState, params: Record<string, number> | undefined, lane: number): EffectContext {
|
||||
return { state, rng: new Rng(1), params: params ?? {}, lane, log: () => {} };
|
||||
}
|
||||
|
||||
/** Place a card and fire its keyword's onReveal, as the engine does at reveal (mutates). */
|
||||
export function reveal(state: MatchState, owner: PlayerId, lane: number, c: GameCard): CardInPlay {
|
||||
const inPlay = place(state, owner, lane, c);
|
||||
const keyword = c.keyword ? KEYWORDS[c.keyword] : undefined;
|
||||
keyword?.onReveal?.(ctxFor(state, state.ruleset.keywordParams[keyword.id], lane), inPlay);
|
||||
return inPlay;
|
||||
}
|
||||
|
||||
export function endOfTurn(state: MatchState, self: CardInPlay): void {
|
||||
const keyword = self.card.keyword ? KEYWORDS[self.card.keyword] : undefined;
|
||||
keyword?.endOfTurn?.(ctxFor(state, state.ruleset.keywordParams[keyword.id], self.lane), self);
|
||||
}
|
||||
|
||||
export function topicBonus(state: MatchState, lane: number, scoring: boolean): [number, number] {
|
||||
const id = state.lanes[lane].topic.portal;
|
||||
const portal = id ? PORTALS[id] : undefined;
|
||||
return portal?.topicBonus?.(ctxFor(state, state.ruleset.portalParams[id!], lane), scoring) ?? [0, 0];
|
||||
}
|
||||
|
||||
export { cardPower, lanePower };
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Tiny dependency-free property-testing helper. Each case gets its own seed
|
||||
* so a failure reports a reproducible seed: rerun with PROP_SEED=<seed>.
|
||||
*/
|
||||
export function mulberry32(seed: number): () => number {
|
||||
let a = seed >>> 0;
|
||||
return () => {
|
||||
a = (a + 0x6d2b79f5) >>> 0;
|
||||
let t = a;
|
||||
t = Math.imul(t ^ (t >>> 15), t | 1);
|
||||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
export interface Gen {
|
||||
rand: () => number;
|
||||
int(min: number, max: number): number;
|
||||
pick<T>(items: readonly T[]): T;
|
||||
bool(p?: number): boolean;
|
||||
}
|
||||
|
||||
export function gen(seed: number): Gen {
|
||||
const rand = mulberry32(seed);
|
||||
return {
|
||||
rand,
|
||||
int: (min, max) => min + Math.floor(rand() * (max - min + 1)),
|
||||
pick: items => {
|
||||
if (!items.length) throw new Error('pick from empty list');
|
||||
return items[Math.floor(rand() * items.length)];
|
||||
},
|
||||
bool: (p = 0.5) => rand() < p,
|
||||
};
|
||||
}
|
||||
|
||||
export function forAll(runs: number, property: (g: Gen, seed: number) => void, baseSeed = 0x5eed): void {
|
||||
const fixed = process.env.PROP_SEED;
|
||||
const seeds = fixed ? [Number(fixed)] : Array.from({ length: runs }, (_, i) => (baseSeed + i * 2654435761) >>> 0);
|
||||
for (const seed of seeds) {
|
||||
try {
|
||||
property(gen(seed), seed);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
throw new Error(`Property failed for seed ${seed} (rerun with PROP_SEED=${seed}): ${message}`, { cause: error });
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user