forked from WikiDeck/wikideck
Night 1: engine v1 keywords, Portals, card derivation, starter decks, property and golden tests (#27)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit was merged in pull request #27.
This commit is contained in:
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* 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;
|
||||
/** 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[];
|
||||
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: -200, trendMinDaily: 20, // −200: no down arrow in v1 (§1.6)
|
||||
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 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 { keyword, vanilla } = keywordFor(faction, 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, rarity: pinned ? 'Common' : input.rarity,
|
||||
cost, power: Math.max(0, base + (vanilla ? rules.vanillaBonus : 0) + delta),
|
||||
home: pinned ? pinned.home : homeStat(pct), 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));
|
||||
}
|
||||
+11
-2
@@ -6,5 +6,14 @@ export {
|
||||
ENGINE_VERSION, createMatch, legalActions, applyAction, actionProblem, isOver, result, viewFor,
|
||||
serialize, deserialize, replay, validateDeck, cardPower, lanePower, laneLeader, laneCapacity, scoringPower, topicsLed, other, placeCard, revealPortal,
|
||||
} from './engine.ts';
|
||||
export { KEYWORDS, PORTALS, KEYWORD_IDS, PORTAL_IDS, allies, activePortal, isOnTopic, type KeywordDef, type PortalDef, type EffectContext } from './keywords.ts';
|
||||
export { STARTER_POOL, loanerCard, previewPool, starterDeck } from './starter.ts';
|
||||
export {
|
||||
KEYWORDS, PORTALS, KEYWORD_IDS, PORTAL_IDS, FACTION_KEYWORD, V1_KEYWORDS, OPTIONAL_KEYWORDS, allies, activePortal, isOnTopic, 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, STARTER_DECKS, loanerCard, loanerInput, previewPool, starterDeck, starterDeckById, type StarterDeckDef,
|
||||
} from './starter.ts';
|
||||
|
||||
+149
-5
@@ -23,7 +23,7 @@
|
||||
* - Hooks must not throw and must not move or remove cards (§10, v1).
|
||||
*/
|
||||
import type { Rng } from './rng.ts';
|
||||
import type { CardInPlay, GameCard, MatchState, PlayerId } from './types.ts';
|
||||
import type { CardInPlay, GameCard, MatchState, PlayerId, Stat } from './types.ts';
|
||||
|
||||
/** The 9 implemented keyword ids (§10.2; edition, obscure and wildcard are disabled by default). */
|
||||
export const KEYWORD_IDS = ['viral', 'rising', 'local', 'encyclopedic', 'nostalgic', 'translated', 'edition', 'obscure', 'wildcard'] as const;
|
||||
@@ -88,8 +88,152 @@ export function isOnTopic(state: MatchState, card: CardInPlay): boolean {
|
||||
return lane.topic.stat === card.card.home || activePortal(state, card.lane)?.allOnTopic === true;
|
||||
}
|
||||
|
||||
/** Filled in by engine-b (§10.2). Ids must be in KEYWORD_IDS. */
|
||||
export const KEYWORDS: Record<string, KeywordDef> = {};
|
||||
/** §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' && state.ruleset.keywordsEnabled.includes('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> = {
|
||||
viral: {
|
||||
id: 'viral', name: 'Viral', text: '+{amount} power for each other card you revealed earlier this turn (max +{cap}).',
|
||||
onReveal(ctx, self) {
|
||||
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}`); }
|
||||
},
|
||||
},
|
||||
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 && 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 [mine, theirs] = [self.owner, self.owner === 0 ? 1 : 0]
|
||||
.map(seat => ctx.state.lanes[self.lane].cards[seat].reduce((sum, card) => sum + ctx.power(card), 0));
|
||||
side.splice(index, 0, self);
|
||||
if (theirs > mine) {
|
||||
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;
|
||||
// Highest global reveal sequence number among your cards there (§10.2).
|
||||
const latest = lane.cards[self.owner].reduce<CardInPlay | undefined>((best, card) => (!best || card.seq > best.seq ? card : best), undefined);
|
||||
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 && self.card.pageId !== null && 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> = {
|
||||
'main-page': {
|
||||
id: 'main-page', name: 'Main Page', text: 'At scoring, each card here gets +{amount} power.',
|
||||
atScoring(ctx) {
|
||||
const [a, b] = ctx.state.lanes[ctx.lane].cards;
|
||||
return [a.length * amount(ctx, 1), b.length * amount(ctx, 1)];
|
||||
},
|
||||
},
|
||||
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}.',
|
||||
atScoring(ctx) {
|
||||
const best = ctx.state.lanes[ctx.lane].cards.map(side => Math.max(-1, ...side.map(card => ctx.power(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.',
|
||||
// Judged at scoring: in v1 Topic leads only matter at scoring (initiative alternates, underdog off).
|
||||
atScoring(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,
|
||||
},
|
||||
};
|
||||
|
||||
/** Filled in by engine-b (§10.3). Ids must be in PORTAL_IDS. */
|
||||
export const PORTALS: Record<string, PortalDef> = {};
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
* Loaners are off-chain preview cards: not NFTs, never minted or moved.
|
||||
* engine-b / council-data replace STARTER_POOL with derived cards (cards.ts).
|
||||
*/
|
||||
import { DEFAULT_DERIVATION, deriveCard, type CardInput, type DerivationRules } from './derive.ts';
|
||||
import { Rng } from './rng.ts';
|
||||
import type { Faction, GameCard, Stat } from './types.ts';
|
||||
|
||||
@@ -64,3 +65,63 @@ export function starterDeck(seed: number | string): GameCard[] {
|
||||
}
|
||||
return deck;
|
||||
}
|
||||
|
||||
// ---------- DESIGN §2.1 starter decks v1 (PR #18) ----------
|
||||
|
||||
type Pin = [cost: number, title: string, faction: Faction, home: Stat];
|
||||
|
||||
/** Real pageIds for the shared/catalog.ts cards; the others have none yet (§2.1), see loanerPageId. */
|
||||
const CATALOG_PAGE_IDS: Record<string, number> = { Moon: 19331, 'Periodic table': 23053, Octopus: 22780, 'Albert Einstein': 736 };
|
||||
|
||||
export interface StarterDeckDef { id: string; name: string; cards: readonly Pin[] }
|
||||
|
||||
/** Four 12-card loaner decks, each with the curve 1,1,2,2,3,3,3,4,4,5,5,6, 6+6 factions and 4 cards per home stat. */
|
||||
export const STARTER_DECKS: readonly StarterDeckDef[] = [
|
||||
{ id: 'stargazers', name: 'Stargazers', cards: [
|
||||
[1, 'Moon', 'Space', 'reach'], [1, 'Electron', 'Science', 'depth'], [2, 'Mars', 'Space', 'attention'],
|
||||
[2, 'Periodic table', 'Science', 'depth'], [3, 'Saturn', 'Space', 'reach'], [3, 'Photosynthesis', 'Science', 'attention'],
|
||||
[3, 'Black hole', 'Space', 'depth'], [4, 'Quantum mechanics', 'Science', 'reach'], [4, 'Milky Way', 'Space', 'attention'],
|
||||
[5, 'DNA', 'Science', 'attention'], [5, 'Sun', 'Space', 'reach'], [6, 'Theory of relativity', 'Science', 'depth'],
|
||||
] },
|
||||
{ id: 'field-guide', name: 'Field Guide', cards: [
|
||||
[1, 'Octopus', 'Nature', 'depth'], [1, 'Stonehenge', 'History', 'attention'], [2, 'Axolotl', 'Nature', 'attention'],
|
||||
[2, 'Rosetta Stone', 'History', 'reach'], [3, 'Coral reef', 'Nature', 'depth'], [3, 'Roman Empire', 'History', 'reach'],
|
||||
[3, 'Honey bee', 'Nature', 'attention'], [4, 'Ancient Egypt', 'History', 'depth'], [4, 'Amazon rainforest', 'Nature', 'reach'],
|
||||
[5, 'Blue whale', 'Nature', 'attention'], [5, 'Great Wall of China', 'History', 'reach'], [6, 'World War II', 'History', 'depth'],
|
||||
] },
|
||||
{ id: 'headliners', name: 'Headliners', cards: [
|
||||
[1, 'Haiku', 'Culture', 'attention'], [1, 'Ada Lovelace', 'People', 'depth'], [2, 'Jazz', 'Culture', 'attention'],
|
||||
[2, 'Marie Curie', 'People', 'reach'], [3, 'Mona Lisa', 'Culture', 'reach'], [3, 'Frida Kahlo', 'People', 'attention'],
|
||||
[3, 'Chess', 'Culture', 'depth'], [4, 'Leonardo da Vinci', 'People', 'reach'], [4, 'The Beatles', 'Culture', 'attention'],
|
||||
[5, 'William Shakespeare', 'People', 'depth'], [5, 'Olympic Games', 'Culture', 'reach'], [6, 'Wolfgang Amadeus Mozart', 'People', 'depth'],
|
||||
] },
|
||||
{ id: 'pioneers', name: 'Pioneers', cards: [
|
||||
[1, 'Sputnik 1', 'Space', 'reach'], [1, 'Nikola Tesla', 'People', 'attention'], [2, 'Hubble Space Telescope', 'Space', 'depth'],
|
||||
[2, 'Isaac Newton', 'People', 'reach'], [3, 'Neil Armstrong', 'People', 'attention'], [3, 'Jupiter', 'Space', 'reach'],
|
||||
[3, 'Galileo Galilei', 'People', 'depth'], [4, 'Albert Einstein', 'People', 'attention'], [4, 'International Space Station', 'Space', 'depth'],
|
||||
[5, 'Apollo 11', 'Space', 'attention'], [5, 'Charles Darwin', 'People', 'reach'], [6, 'Solar System', 'Space', 'depth'],
|
||||
] },
|
||||
];
|
||||
|
||||
const kebab = (title: string) => title.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
|
||||
|
||||
/** §2.1: the real pageId for the shared/catalog.ts cards, null for the rest (copies then count per cardId). */
|
||||
export function loanerPageId(title: string): number | null {
|
||||
return Object.hasOwn(CATALOG_PAGE_IDS, title) ? CATALOG_PAGE_IDS[title] : null;
|
||||
}
|
||||
|
||||
/** The §1 CardInput for a pinned loaner. Snapshot stats are unused (pinned replaces §1.1–1.5). */
|
||||
export function loanerInput([cost, title, faction, home]: Pin): CardInput {
|
||||
return { cardId: `loaner:${kebab(title)}`, pageId: loanerPageId(title), title, category: faction, rarity: 'Common',
|
||||
snapshot: { stats: { attention: null, depth: 0, reach: 0 } }, live: { trendPercent: null, dailyAverage: null },
|
||||
check: 'loaner', pinned: { cost, home, faction } };
|
||||
}
|
||||
|
||||
const NO_TABLE = { attention: [], depth: [], reach: [] };
|
||||
|
||||
/** A §2.1 starter deck by id, derived with the given rules (modes that change the curve change loaners too). */
|
||||
export function starterDeckById(id: string, rules: DerivationRules = DEFAULT_DERIVATION): GameCard[] {
|
||||
const def = STARTER_DECKS.find(deck => deck.id === id);
|
||||
if (!def) throw new RangeError(`Unknown starter deck: ${id}`);
|
||||
return def.cards.map(pin => deriveCard(loanerInput(pin), NO_TABLE, rules));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
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 modeRules = { ...RULES, trendDown: -25 }; // a mode that turns the down arrow back on
|
||||
const t = (trendPercent: number | null, dailyAverage: number | null = 100) => trendFor({ trendPercent, dailyAverage }, modeRules);
|
||||
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(trendFor({ trendPercent: -99, dailyAverage: 1000 }, RULES), 0, 'v1 default: no down arrow');
|
||||
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', check: 'verified' });
|
||||
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);
|
||||
});
|
||||
|
||||
test('pinned values replace §1.1–1.5 for loaners only (§2.1)', () => {
|
||||
const pinned = { cost: 5, home: 'reach' as const, faction: 'History' as const };
|
||||
const stats = { attention: 5, depth: 5, reach: 5 };
|
||||
const loaner = deriveCard(input(stats, { check: 'loaner', pinned, rarity: 'Epic', live: { trendPercent: 99, dailyAverage: 999 } }), TABLE);
|
||||
assert.deepEqual([loaner.cost, loaner.power, loaner.home, loaner.faction, loaner.keyword, loaner.rarity, loaner.trend, loaner.source],
|
||||
[5, 8, 'reach', 'History', 'nostalgic', 'Common', 0, 'loaner']);
|
||||
const owned = deriveCard(input(stats, { pinned }), TABLE);
|
||||
assert.deepEqual([owned.cost, owned.faction], [1, 'Science'], 'pinned is ignored when check !== loaner');
|
||||
const cheap = deriveCard(input(stats, { check: 'loaner', pinned: { ...pinned, cost: 1 } }), TABLE);
|
||||
assert.deepEqual([cheap.power, cheap.keyword], [2, null], 'vanillaBonus still applies to pinned cost-1');
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* Passes against night/engine/core e0ac157 (frozen §3–§7 rules).
|
||||
*/
|
||||
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 opts = {};
|
||||
|
||||
/** §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, portalRevealed: 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,229 @@
|
||||
// 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, atScoring } 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 (when enabled)', () => {
|
||||
const s = board();
|
||||
const a0 = place(s, 0, 1, card({ pageId: 41, power: 5, home: 'reach', keyword: 'edition' }));
|
||||
place(s, 0, 2, card({ pageId: 41, power: 5, home: 'depth', keyword: 'edition' }));
|
||||
assert.equal(cardPower(s, a0), 5, 'disabled by default');
|
||||
s.ruleset.keywordsEnabled = [...s.ruleset.keywordsEnabled, 'edition'];
|
||||
assert.equal(cardPower(s, a0), 7);
|
||||
s.lanes[1].cards[0] = []; s.lanes[2].cards[0] = [];
|
||||
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();
|
||||
s.ruleset.keywordsEnabled = [...s.ruleset.keywordsEnabled, 'wildcard'];
|
||||
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].portalRevealed = false;
|
||||
assert.ok(!isOnTopic(s, d), 'Portal not active while face down');
|
||||
});
|
||||
|
||||
test('Main Page: +1 per card at scoring', () => {
|
||||
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(atScoring(s, 1), [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(atScoring(s, 0), [2, 0]);
|
||||
bo.bonus = 1;
|
||||
assert.deepEqual(atScoring(s, 0), [0, 0], 'tied highest');
|
||||
bo.bonus = 3;
|
||||
assert.deepEqual(atScoring(s, 0), [0, 2]);
|
||||
assert.deepEqual(atScoring(board([topic('depth', 'featured-article')]), 0), [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(atScoring(s, 2), [1, 0]);
|
||||
assert.deepEqual(atScoring(s, 2), [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,52 @@
|
||||
// DESIGN §2.1 starter decks (PR #18). Owner: engine-b.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
DEFAULT_DERIVATION, DEFAULT_RULESET, FACTION_KEYWORD, STARTER_DECKS, createMatch, starterDeckById, validateDeck,
|
||||
} from '../shared/game/index.ts';
|
||||
|
||||
const countBy = (keys: string[]) => keys.reduce<Record<string, number>>((m, k) => ({ ...m, [k]: (m[k] ?? 0) + 1 }), {});
|
||||
|
||||
test('four starter decks, each with the frozen curve, 6+6 factions and 4 cards per home stat', () => {
|
||||
assert.deepEqual(STARTER_DECKS.map(d => d.id), ['stargazers', 'field-guide', 'headliners', 'pioneers']);
|
||||
for (const def of STARTER_DECKS) {
|
||||
const deck = starterDeckById(def.id);
|
||||
assert.deepEqual(deck.map(c => c.cost), [1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6], def.id);
|
||||
const factions = Object.values(countBy(deck.map(c => c.faction)));
|
||||
assert.deepEqual(factions, [6, 6], `${def.id} factions`);
|
||||
const homes = Object.values(countBy(deck.map(c => c.home)));
|
||||
assert.deepEqual(homes, [4, 4, 4], `${def.id} homes`);
|
||||
}
|
||||
});
|
||||
|
||||
test('starter cards follow §10.1 and the power curve like owned cards', () => {
|
||||
for (const def of STARTER_DECKS) for (const card of starterDeckById(def.id)) {
|
||||
assert.equal(card.source, 'loaner');
|
||||
assert.equal(card.rarity, 'Common');
|
||||
assert.equal(card.trend, 0);
|
||||
assert.match(card.cardId, /^loaner:[a-z0-9-]+$/);
|
||||
if (card.cost === 1) assert.deepEqual([card.keyword, card.power], [null, 2]);
|
||||
else assert.deepEqual([card.keyword, card.power], [FACTION_KEYWORD[card.faction], DEFAULT_DERIVATION.powerByCost[card.cost]]);
|
||||
}
|
||||
});
|
||||
|
||||
test('all 6 factions and all 4 shared/catalog.ts cards (with real pageIds) are covered', () => {
|
||||
const all = STARTER_DECKS.flatMap(d => starterDeckById(d.id));
|
||||
assert.equal(new Set(all.map(c => c.faction)).size, 6);
|
||||
const ids = Object.fromEntries(all.map(c => [c.title, c.pageId]));
|
||||
assert.deepEqual([ids.Moon, ids['Periodic table'], ids.Octopus, ids['Albert Einstein']], [19331, 23053, 22780, 736]);
|
||||
for (const c of all) if (!['Moon', 'Periodic table', 'Octopus', 'Albert Einstein'].includes(c.title)) assert.equal(c.pageId, null, c.title);
|
||||
});
|
||||
|
||||
test('every starter deck passes engine deck validation and starts a match against every other', () => {
|
||||
for (const a of STARTER_DECKS) {
|
||||
assert.deepEqual(validateDeck(DEFAULT_RULESET, starterDeckById(a.id)), [], a.id);
|
||||
for (const b of STARTER_DECKS) assert.doesNotThrow(() => createMatch(DEFAULT_RULESET, [starterDeckById(a.id), starterDeckById(b.id)], 1));
|
||||
}
|
||||
});
|
||||
|
||||
test('modes changing the curve change loaners too; unknown ids are rejected', () => {
|
||||
const flat = starterDeckById('pioneers', { ...DEFAULT_DERIVATION, powerByCost: [0, 3, 3, 3, 3, 3, 3], vanillaBonus: 0 });
|
||||
assert.ok(flat.every(c => c.power === 3));
|
||||
assert.throws(() => starterDeckById('nope'), RangeError);
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
/** 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, portalRevealed: 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 {
|
||||
state.revealSeq += 1;
|
||||
const inPlay: CardInPlay = { card: c, owner, lane, turn, seq: state.revealSeq, 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: () => {}, power: c => cardPower(state, c) };
|
||||
}
|
||||
|
||||
/** 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);
|
||||
}
|
||||
|
||||
/** A Portal's at-scoring Topic power for [seat 0, seat 1] (DESIGN §7). */
|
||||
export function atScoring(state: MatchState, lane: number): [number, number] {
|
||||
const id = state.lanes[lane].topic.portal;
|
||||
const portal = id ? PORTALS[id] : undefined;
|
||||
const params = state.ruleset.portalParams[state.lanes[lane].topic.id] ?? state.ruleset.portalParams[id!];
|
||||
return portal?.atScoring?.(ctxFor(state, params, lane)) ?? [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