Files
wikideck/shared/game/keywords.ts
T

240 lines
12 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.2, §10.3). Effects are code here; which
* ones a card/topic uses and their numbers are data (GameCard.keyword,
* TopicDef.portal, Ruleset.keywordsEnabled / 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). Safe: applyAction already cloned.
* Any randomness must come from ctx.rng (match RNG, resolution order, §4.2.5).
* - A keyword's hooks run only if its id is in ruleset.keywordsEnabled.
* - onReveal(ctx, self): right after `self` is pushed into its lane (§5.4). Cards revealed
* earlier (any seat, any turn) are on the board; later ones are not. self.seq is its global
* reveal number; cards revealed this turn have `turn === ctx.state.turn`.
* - endOfTurn(ctx, self): §5.5 order: initiative seat's cards first, then lanes 1→N, then seq.
* Also runs on the last turn, before scoring (§7).
* - ongoing(ctx, self, target) → delta: PURE. Called for every (self, target) pair in play,
* including self === target. ctx.rng is a throwaway copy. Don't call ctx.power on a card from
* inside ongoing (infinite recursion); read base fields instead.
* - Portals: same, plus onPortalReveal(ctx), canPlay(ctx, card, seat), capacity(ctx) → number
* (lane capacity override), allOnTopic (Disambiguation) and atScoring(ctx) → [delta0, delta1]
* (Topic power added at scoring, §7). All Portal hooks apply only once the Portal is revealed.
* Params: ruleset.portalParams[topic.id], falling back to portalParams[portal id].
* - 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, 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;
/** The 6 Portal kinds (§10.3), named after their default Topic. */
export const PORTAL_IDS = ['main-page', 'trending', 'featured-article', 'stub', 'interwiki', 'disambiguation'] as const;
export interface EffectContext {
state: MatchState;
rng: Rng;
/** Tunable numbers for this keyword/portal from the ruleset. */
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;
/** Current lane power of a card in play (the engine's cardPower). Not for use inside `ongoing`. */
power(card: CardInPlay): number;
}
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;
onPortalReveal?(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 (replaces ruleset.laneCapacity). */
capacity?(ctx: EffectContext): number;
/** Every card here counts as on-topic. */
allOnTopic?: boolean;
/** Topic power added to [seat 0, seat 1] here at scoring. */
atScoring?(ctx: EffectContext): [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 lane's Portal, if it has one and it is revealed. */
export function activePortal(state: MatchState, lane: number): PortalDef | undefined {
const l = state.lanes[lane];
return l?.portalRevealed && l.topic.portal ? PORTALS[l.topic.portal] : undefined;
}
/** §1.4/§6 on-topic: home stat matches the Topic's stat, or an active Disambiguation-style Portal. */
export function isOnTopic(state: MatchState, card: CardInPlay): boolean {
const lane = state.lanes[card.lane];
return lane.topic.stat === card.card.home || activePortal(state, card.lane)?.allOnTopic === true;
}
/** §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,
},
};