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

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

239 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Keyword and Portal registry (DESIGN §10, §10.3). Effects are code here; which
* ones a card/topic uses and their numbers are data (GameCard.keyword,
* TopicDef.portal, Ruleset.keywordParams / portalParams).
* Owner of the effects: engine-b (claude/wikideck#3). engine-a owns the hook contract:
*
* - Hooks get an EffectContext over the engine's *working copy* of the state and may
* mutate it (e.g. `bonus` on cards). Mutating is safe: applyAction already cloned.
* Any randomness must come from ctx.rng (the match RNG, in resolution order, §4.2.5).
* - onReveal: once, right after the card enters its lane (§5.4).
* - endOfTurn: every card in play, at §5.5, initiative player's cards first, lanes left→right,
* in play order.
* - ongoing: PURE. Returns a power delta for `target` while `self` is in play. Called for every
* (self, target) pair in play, including self === target. ctx.rng is a throwaway copy.
* - Portals: same shape; ongoing/canPlay/onReveal only apply while the Topic is revealed.
* onTopicReveal runs when the Topic flips face-up (§5.1).
* - Hooks must not throw, must not move/remove cards (§10 v1 constraint).
*/
import type { Rng } from './rng.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;
rng: Rng;
/** Tunable numbers for this keyword/portal from Ruleset.keywordParams / portalParams. */
params: Record<string, number>;
/** Lane the effect lives in. */
lane: number;
/** Add a line to the match log (attributed to this keyword/portal). */
log(text: string): void;
}
export interface KeywordDef {
id: string;
name: string;
/** One short line of reminder text with {param} placeholders. */
text: string;
onReveal?(ctx: EffectContext, self: CardInPlay): void;
endOfTurn?(ctx: EffectContext, self: CardInPlay): void;
ongoing?(ctx: EffectContext, self: CardInPlay, target: CardInPlay): number;
}
export interface PortalDef {
id: string;
name: string;
text: string;
onTopicReveal?(ctx: EffectContext): void;
/** Runs when any card is revealed in this Topic (after the card's own onReveal). */
onReveal?(ctx: EffectContext, card: CardInPlay): void;
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`. */
export function allies(state: MatchState, self: CardInPlay): CardInPlay[] {
return state.lanes[self.lane].cards[self.owner].filter(card => card !== self);
}
/** 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> = {
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 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> = {
'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)];
},
},
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,
},
};