/** * Files TCG rules engine (rules.md). The state is plain data. `decider` says who must act, * `legalActions` lists what they may do, and `applyAction` does it. Between decisions the engine * runs queued tasks (combat, captures, card triggers) until it needs a player again: a turn step, * a response window, or a choice a card asks for. */ import type { CardPool } from './cards.ts'; import { validateDeck, type DeckList } from './deck.ts'; import type { CardDef } from './cards.ts'; import { captureHooks, captureMain, combatStage, defeat, drawNow, drawTask, recallAvatar, resolveDeclaration, retireAvatar, } from './flow.ts'; import { GRID, LINES, LINES_AT, LINE_BY_ID, LOCATIONS, START_LOC, isStart, otherEnd, type LocId } from './map.ts'; import { avatarRoom, costOf, coresOf, desynced, emit, enemyFlagAt, hasRoom, pay, portsFree, programSlots, reachableRam, sources, stillActive, wears, } from './query.ts'; import { makeRng, randInt, shuffle } from './rng.ts'; import { DEFAULT_RULES, type RulesConfig } from './rules.ts'; import { scriptOf, type Fighter } from './scripts.ts'; import { avatar, avatarName, canAct, controls, defOf, defendersAt, endOf, firewallCost, gridCount, commanderOf, firstCommand, freshCopy, isCopy, isOpen, markUsed, nameOf, originalOf, other, fired, played, playerName, pushTasks, refsInPlay, removeFrom, roundOf, running, say, startOf, stat, toDiscard, usedThisTurn, } from './state.ts'; import { hardwareUsesLeft, useHardware } from './cards/hardware.ts'; import { STAT_KEYS, type Action, type Args, type AvatarRef, type AvatarState, type GameState, type GameStats, type LocationState, type PlayerId, type PlayerState, type Source, type StackItem, type Task, } from './types.ts'; export interface NewGame { pool: CardPool; decks: [DeckList, DeckList]; seed: number; rules?: RulesConfig; log?: boolean; } export { controls, defOf, firewallCost, gridCount, isOpen, nameOf, other } from './state.ts'; /** Combat Cores for an Avatar standing on `at`, outside any combat. For bots pricing an attack. */ export function avatarCores( s: GameState, p: PlayerId, slot: number, role: 'attack' | 'defend', at: LocId | null = s.players[p].avatars[slot - 1].at, loc: LocId | null = role === 'defend' ? at : null, ): number { const f: Fighter = { ref: { player: p, slot }, role, at, loc, combat: null }; return coresOf(s, f); } /** The first defender on a location, if any. */ export function defenderAt(s: GameState, loc: LocId): { player: PlayerId; slot: number } | null { return defendersAt(s, loc)[0] ?? null; } // --------------------------------------------------------------------------------------------- // Setup function newStats(): GameStats { return Object.fromEntries(STAT_KEYS.map((k) => [k, [0, 0]])) as GameStats; } /** Recruit rule: an Avatar's printed RAM is its price, which is also what it salvages for. */ function withPrice(def: CardDef, rules: RulesConfig): CardDef { if (!rules.recruit.on || def.kind !== 'avatar') return def; return { ...def, ram: rules.recruit.price + rules.recruit.pricePerCore * def.cores }; } /** Recruit rule: slots `p` can recruit into. The first empty one while there's room, or any Avatar to retire. */ export function recruitSlots(s: GameState, p: PlayerId): number[] { const avs = s.players[p].avatars.slice(0, 4); const out: number[] = []; const empty = avs.findIndex((a) => a.card < 0); if (empty >= 0 && avatarRoom(s, p)) out.push(empty + 1); avs.forEach((a, i) => { const declared = s.declarations.some((d) => d.ref.player === p && originalOf(d.ref).slot === i + 1); if (a.card >= 0 && !declared) out.push(i + 1); }); return out; } /** Buy-Avatars rule: the next Avatar `p` can buy (its slot) and its price, or null. */ export function avatarForSale(s: GameState, p: PlayerId): { slot: number; price: number } | null { if (!s.rules.buyAvatars.on) return null; const i = s.players[p].avatars.slice(0, 4).findIndex((a) => !a.faceUp); return i < 1 ? null : { slot: i + 1, price: s.rules.buyAvatars.prices[i - 1] }; } function newAvatar(card: number, faceUp: boolean, copyOf: number | null): AvatarState { return { card, faceUp, at: null, hardware: [], damage: 0, placed: false, advanced: false, attacks: 0, infection: 0, bugs: 0, permanentInfection: 0, mods: [], disabledUntil: 0, rootedUntil: 0, breachedTurn: 0, copyOf, createdTurn: 0, unlockedTurn: 0, }; } export function createGame({ pool, decks, seed, rules = DEFAULT_RULES, log = false }: NewGame): GameState { decks.forEach((deck, p) => { const errors = validateDeck(pool, deck, rules); if (errors.length) throw new Error(`${playerName(p as PlayerId)} deck is illegal:\n ${errors.join('\n ')}`); }); const rng = makeRng(seed); const s: GameState = { rules, rng, defs: {}, cards: [], players: [] as unknown as [PlayerState, PlayerState], locations: Object.fromEntries( LOCATIONS.map((loc): [LocId, LocationState] => [loc, { owner: null, server: null, programs: [], rootAccess: [0, 0] }]), ), firewalls: {}, firstPlayer: 0, active: 0, turn: 0, clock: 0, step: 'deploy', declarations: [], tasks: [], stack: [], choice: null, combat: null, virtuals: [], used: {}, seq: 0, over: false, winner: null, endReason: null, stats: newStats(), cardUse: {}, log: log ? [] : null, }; const add = (name: string, owner: PlayerId): number => { s.defs[name] = withPrice(pool.byName.get(name)!, rules); s.cards.push({ id: s.cards.length, name, owner, disabledUntil: 0, ignoredUntil: 0, installedTurn: 0 }); return s.cards.length - 1; }; for (const p of [0, 1] as const) { const deck = decks[p]; // Recruit rule: slots after the starting Avatar begin empty (-1). const avatars = shuffle(rng, deck.avatars.map((n) => add(n, p))); const slots = [0, 1, 2, 3].map((i) => avatars[i] ?? -1); s.players.push({ ram: 0, hand: [], deck: shuffle(rng, deck.main.map((n) => add(n, p))), discard: [], serverPile: shuffle(rng, deck.servers.map((n) => add(n, p))), avatars: [ ...slots.map((card, i) => newAvatar(card, card >= 0 && i < rules.startingAvatars, null)), ...slots.map((card, i) => newAvatar(card, false, i + 1)), ], unlockedLevel: 1, }); } for (const p of [0, 1] as const) { const me = s.players[p]; const start = s.locations[START_LOC[p]]; const server = me.serverPile.shift()!; start.owner = p; start.server = server; me.ram = rules.startingRam + (scriptOf(s.cards[server].name)?.ramOnPlace ?? 0); played(s, s.cards[server].name, p); for (let i = 0; i < rules.openingHand; i++) drawNow(s, p); say(s, `${playerName(p)} starts on ${nameOf(s, server)} with ${me.ram} RAM. Avatar 1: ${nameOf(s, me.avatars[0].card)}.`); } s.firstPlayer = randInt(rng, 2) as PlayerId; s.active = s.firstPlayer; const p2 = other(s.firstPlayer); const second = s.players[p2]; second.ram += rules.secondPlayer.ram; second.avatars.slice(0, rules.startingAvatars + rules.secondPlayer.avatars).forEach((av) => (av.faceUp = av.card >= 0)); for (let i = 0; i < rules.secondPlayer.cards; i++) drawNow(s, p2); if (rules.secondPlayer.locations > 0) { // The location next to the starting Server, with a Server from the pile: no RAM, no unlock. const line = LINES_AT.get(START_LOC[p2])![0]; const L = s.locations[otherEnd(line, START_LOC[p2])]; L.owner = p2; L.server = second.serverPile.shift()!; played(s, s.cards[L.server].name, p2); } s.stats.cardsDrawn = [0, 0]; say(s, `${playerName(s.firstPlayer)} goes first.`); beginTurn(s, !rules.firstTurn.draw); run(s); return s; } function beginTurn(s: GameState, skipDraw: boolean): void { const cmd = s.rules.commands.on; if (s.turn >= s.rules.maxTurns * (cmd ? s.rules.commands.perPlayer : 1)) { s.over = true; s.endReason = 'turnLimit'; say(s, `Turn limit reached: draw (South ${gridCount(s, 0)}, North ${gridCount(s, 1)} locations).`); return; } s.turn++; s.clock = startOf(s.turn); // Command rule: a player's turn is their commands in a round, so its refreshes come at the first. const fresh = !cmd || firstCommand(s, s.turn); if (!cmd || roundOf(s, s.turn) !== roundOf(s, s.turn - 1)) s.used = {}; tidy(s); const me = s.players[s.active]; if (fresh) { for (const av of me.avatars) { av.placed = false; av.advanced = false; av.attacks = 0; } } s.declarations = []; s.step = 'deploy'; const title = cmd ? `Round ${roundOf(s, s.turn)}, command ${s.turn}` : `Turn ${s.turn}`; say(s, `\n— ${title}: ${playerName(s.active)} (${me.ram} RAM, ${me.hand.length} cards, ${gridCount(s, s.active)} locations) —`); const draws = s.rules.drawPerTurn + (s.turn === 2 ? s.rules.secondPlayer.firstDraw : 0); if (fresh && !skipDraw) pushTasks(s, ...Array.from({ length: draws }, (): Task => ({ t: 'draw', player: s.active }))); if (fresh) emit(s, 'onTurnStart', null); } /** Command rule: this game turn's command is spent (an advance or attack is declared). */ const commandSpent = (s: GameState): boolean => s.rules.commands.on && s.declarations.length > 0; /** Command rule: an Avatar unlocked this round waits in its slot until the next round. */ const waitsForRound = (s: GameState, av: AvatarState): boolean => s.rules.commands.on && av.at === null && av.unlockedTurn > 0 && roundOf(s, av.unlockedTurn) === roundOf(s, s.turn); function endTurn(s: GameState): void { s.clock = endOf(s.turn); // Push Update: the extra Hardware leaves at the end of its controller's turn. for (const pl of s.players) { for (const av of pl.avatars) { for (const hw of [...av.hardware]) { const until = s.cards[hw].pushedUntil; if (until !== undefined && !running(s, until)) { removeFrom(av.hardware, hw); toDiscard(s, hw); say(s, `${nameOf(s, hw)} (Push Update) is discarded.`); } } } } tidy(s); s.active = s.rules.commands.on ? commanderOf(s, s.turn + 1) : other(s.active); beginTurn(s, false); } /** Drops expired statuses so the state stays small. Status checks don't rely on this. */ function tidy(s: GameState): void { s.virtuals = s.virtuals.filter((v) => running(s, v.until)); for (const pl of s.players) { for (const av of pl.avatars) av.mods = av.mods.filter((m) => m.combat !== undefined || running(s, m.until ?? 0)); } } // --------------------------------------------------------------------------------------------- // Who decides /** The player who must act now, or null when the game is over. */ export function decider(s: GameState): PlayerId | null { if (s.over) return null; if (s.choice) return s.choice.player; const front = s.tasks[0]; if (front?.t === 'window') return front.priority; return s.active; } /** The open response window, when the decider is responding. */ export function openWindow(s: GameState): Extract | null { const front = s.tasks[0]; return !s.choice && front?.t === 'window' ? front : null; } // --------------------------------------------------------------------------------------------- // Legal actions const targeted = (s: GameState, loc: LocId): boolean => s.declarations.some((d) => d.to === loc); /** Grid locations `p` may advance to: unowned or undefended enemy, next to its territory. */ export function advanceTargets(s: GameState, p: PlayerId): LocId[] { return GRID.filter((loc) => { const owner = s.locations[loc].owner; if (owner === p || targeted(s, loc)) return false; if (owner !== null && defendersAt(s, loc).length) return false; return LINES_AT.get(loc)!.some((line) => isOpen(s, line) && controls(s, p, otherEnd(line, loc))); }); } /** Infinite Loop lets an Avatar attacking from its location attack twice. */ export function maxAttacks(s: GameState, ref: AvatarRef): number { const at = avatar(s, ref).at; let extra = 0; for (const x of sources(s)) { if (x.at === at && x.controller === ref.player) extra = Math.max(extra, scriptOf(x.name)?.extraAttacks ?? 0); } return 1 + extra; } export function attackTargets(s: GameState, ref: AvatarRef): LocId[] { const av = avatar(s, ref); if (!av.faceUp || av.at === null || av.advanced || av.attacks >= maxAttacks(s, ref) || !canAct(s, ref) || freshCopy(s, ref)) return []; const opp = other(ref.player); return LINES_AT.get(av.at)! .filter((line) => isOpen(s, line)) .map((line) => otherEnd(line, av.at!)) .filter((to) => !isStart(to) && controls(s, opp, to) && defendersAt(s, to).length > 0 && !targeted(s, to)); } function pushClears(s: GameState, p: PlayerId, out: Action[]): void { for (const [line, level] of Object.entries(s.firewalls)) { const l = LINE_BY_ID.get(line)!; if ((controls(s, p, l.a) || controls(s, p, l.b)) && firewallCost(s, level) <= s.players[p].ram) { out.push({ type: 'clearFirewall', line }); } } } /** Latency Spike: the attacking player can't play Executions before the roll. */ /** Whether a first-turn rule variant stops p playing cards from hand right now. */ function cardsBlocked(s: GameState, p: PlayerId): boolean { return s.turn === 1 && p === s.firstPlayer && !s.rules.firstTurn.cards; } function latencyBlocked(s: GameState, p: PlayerId): boolean { const c = s.combat; const w = openWindow(s); if (!c || c.ended || w?.kind !== 'preRoll' || c.attacker.player !== p) return false; return enemyFlagAt(s, c.loc, p, (sc) => sc.blocksAttackerExecutions).length > 0; } /** Force Reboot: a Server that can't perform Executions for the rest of the turn. */ export const execBlocked = (s: GameState, loc: LocId): boolean => usedThisTurn(s, `noExec:${loc}`) > 0; /** * Servers worth naming as an Execution's performer: null (any of your Servers), plus each Server * where one of your Avatars wears Hardware that cares (Dedicated GPU, Quantum Coprocessor). */ function performers(s: GameState, p: PlayerId): (LocId | null)[] { const out = new Set([null]); for (const r of refsInPlay(s, p)) { const at = avatar(s, r).at!; if (isCopy(r) || !controls(s, p, at) || execBlocked(s, at)) continue; if (wears(s, r, (sc) => sc.executionPower || sc.copiesExecutions).length) out.add(at); } return [...out]; } /** Dedicated GPU: extra effect for Executions performed by `from`, from its Avatars' Hardware. */ export function executionPower(s: GameState, p: PlayerId, from: LocId | null): number { if (from === null) return 0; let n = 0; for (const r of refsInPlay(s, p)) { if (isCopy(r) || avatar(s, r).at !== from) continue; for (const hw of wears(s, r, (sc) => sc.executionPower)) n += scriptOf(s.cards[hw].name)!.executionPower!; } return n; } export const executionHostiles = (s: GameState, item: Pick): AvatarRef[] => (scriptOf(item.name)?.execution?.targetsAvatars?.(s, item) ?? []).filter((r) => r.player !== item.player); export function executionCost(s: GameState, p: PlayerId, card: number, target: LocId | null, args: Args, all?: Source[]): number { const hostile = executionHostiles(s, { player: p, target, args, name: s.cards[card].name }); return costOf(s, { kind: 'execution', player: p, card, at: target, hostile }, all); } /** * Execution plays for `p`. `budget` 'now' keeps plays affordable with current RAM; 'reachable' * also counts Salvage; 'any' ignores RAM. */ export function executionActions(s: GameState, p: PlayerId, budget: 'now' | 'reachable' | 'any', limit = Infinity): Action[] { const out: Action[] = []; if (latencyBlocked(s, p) || cardsBlocked(s, p)) return out; const seen = new Set(); let who: (LocId | null)[] | null = null; let all: Source[] | null = null; for (const card of s.players[p].hand) { const name = s.cards[card].name; if (seen.has(name)) continue; seen.add(name); const ex = scriptOf(name)?.execution; if (!ex) continue; const cap = budget === 'any' ? Infinity : budget === 'now' ? s.players[p].ram : reachableRam(s, p, card); if (defOf(s, card).ram - 3 > cap && budget !== 'any') continue; // no discount is bigger than 2 all ??= sources(s); for (const play of ex.plays(s, p)) { if (executionCost(s, p, card, play.target, play.args, all) > cap) continue; who ??= performers(s, p); for (const from of who) { out.push({ type: 'play', card, target: play.target, args: play.args, from }); if (out.length >= limit) return out; } } } return out; } export const abilitySource = (s: GameState, card: number, name: string): Source | undefined => sources(s).find((x) => x.id === card && x.name === name && activatable(x) && scriptOf(x.name)?.ability); export function abilityCost(s: GameState, src: Source): number { const script = scriptOf(src.name)!; if (src.kind === 'avatar') return defOf(s, src.id).ability?.cost ?? 0; return script.ability?.cost ?? 0; } /** Sources whose ability can be activated: real cards, plus Server abilities Duplicate Server copies. */ export const activatable = (src: Source): boolean => src.virtual === undefined || src.virtual === -2; export const abilityKey = (src: Source): string => `ability:${src.id}:${src.name}`; /** Whether an ability source may be used now (once per turn, not disabled, Desynchronization). */ export function abilityReady(s: GameState, src: Source): boolean { const ab = scriptOf(src.name)?.ability; if (!ab || !activatable(src)) return false; if (src.kind === 'avatar' && !canAct(s, src.ref!)) return false; if (src.kind === 'hardware') { if (hardwareUsesLeft(s, src.id) <= 0) return false; return !(ab.hardwareOncePerTurn && desynced(s, src.ref!)); } return usedThisTurn(s, abilityKey(src)) === 0; } export function abilityActions(s: GameState, p: PlayerId, budget: 'now' | 'reachable' | 'any', limit = Infinity): Action[] { const out: Action[] = []; const cap = budget === 'any' ? Infinity : budget === 'now' ? s.players[p].ram : reachableRam(s, p); for (const src of sources(s)) { if (src.controller !== p || !scriptOf(src.name)?.ability || !abilityReady(s, src)) continue; const ab = scriptOf(src.name)!.ability!; const base = abilityCost(s, src); if (base > cap) continue; for (const args of ab.uses(s, src)) { if (base + (ab.extraCost?.(s, src, args) ?? 0) > cap) continue; out.push({ type: 'activate', card: src.id, name: src.name, args }); if (out.length >= limit) return out; } } return out; } function hasResponse(s: GameState, p: PlayerId): boolean { return executionActions(s, p, 'reachable', 1).length > 0 || abilityActions(s, p, 'reachable', 1).length > 0; } export function hardwareCost(s: GameState, card: number, ref: AvatarRef, all?: Source[]): number { return costOf(s, { kind: 'hardware', player: ref.player, card, ref, at: avatar(s, ref).at }, all); } export function programCost(s: GameState, p: PlayerId, card: number, at: LocId, all?: Source[]): number { return costOf(s, { kind: 'program', player: p, card, at }, all); } export function placeFirewallCost(s: GameState, p: PlayerId, line: string, level: number, all?: Source[]): number { return costOf(s, { kind: 'firewall', player: p, line, level }, all); } /** Whether Hardware can go on an Avatar now (ports permitting). */ export function canWear(s: GameState, card: number, ref: AvatarRef): boolean { if (isCopy(ref) || avatar(s, ref).at === null) return false; return !!scriptOf(s.cards[card].name)?.noPort || portsFree(s, ref) > 0; } export function legalActions(s: GameState): Action[] { const p = decider(s); if (p === null) return []; const me = s.players[p]; const salvage: Action[] = me.hand.map((card) => ({ type: 'salvage', card })); if (s.choice) { const options = s.choice.options.flatMap((o, index): Action[] => (o.cost ?? 0) <= me.ram ? [{ type: 'choose', index }] : []); return [...options, ...salvage]; } if (openWindow(s)) { return [{ type: 'pass' }, ...salvage, ...executionActions(s, p, 'now'), ...abilityActions(s, p, 'now')]; } const out: Action[] = [{ type: 'end' }, ...salvage]; if (s.step === 'resolve') return out; out.push(...executionActions(s, p, 'now'), ...abilityActions(s, p, 'now')); const opp = other(p); if (s.step === 'deploy') { const placementOpen = s.declarations.length === 0; const targets = s.turn === 1 && !s.rules.firstTurn.advance ? [] : advanceTargets(s, p); me.avatars.forEach((av, i) => { const ref = { player: p, slot: i + 1 }; if (!av.faceUp || av.advanced || av.attacks > 0) return; if (av.at !== null && !canAct(s, ref)) return; if (placementOpen && !av.placed && !waitsForRound(s, av)) { for (const to of LOCATIONS) if (to !== av.at && hasRoom(s, p, to)) out.push({ type: 'place', slot: i + 1, to }); if (s.rules.health.on && s.rules.health.recall && av.at !== null && !isCopy(ref)) out.push({ type: 'recall', slot: i + 1 }); } if (av.at !== null && !freshCopy(s, ref) && !commandSpent(s)) for (const to of targets) out.push({ type: 'advance', slot: i + 1, to }); }); pushClears(s, p, out); } else if (s.step === 'attack') { me.avatars.forEach((_, i) => { if (commandSpent(s)) return; for (const to of attackTargets(s, { player: p, slot: i + 1 })) out.push({ type: 'attack', slot: i + 1, to }); }); pushClears(s, p, out); } else { const seen = new Set(); const all = sources(s); for (const card of cardsBlocked(s, p) ? [] : me.hand) { const def = defOf(s, card); if (seen.has(def.name)) continue; seen.add(def.name); if (def.kind === 'hardware') { for (const ref of refsInPlay(s, p)) { if (canWear(s, card, ref) && hardwareCost(s, card, ref, all) <= me.ram) { out.push({ type: 'installHardware', card, slot: ref.slot }); } } } else if (def.kind === 'avatar' && s.rules.recruit.on) { if (def.ram <= me.ram) for (const slot of recruitSlots(s, p)) out.push({ type: 'recruit', card, slot }); } else if (def.kind === 'program') { for (const at of LOCATIONS) { if (controls(s, p, at) && s.locations[at].programs.length < programSlots(s, at) && programCost(s, p, card, at, all) <= me.ram) { out.push({ type: 'installProgram', card, at }); } } } } const sale = avatarForSale(s, p); if (sale && sale.price <= me.ram) out.push({ type: 'buyAvatar', slot: sale.slot }); for (const line of LINES) { if (!line.gateway || !(controls(s, p, line.a) || controls(s, p, line.b))) continue; for (let level = (s.firewalls[line.id] ?? 0) + 1; level <= s.rules.firewallCost.length; level++) { if (placeFirewallCost(s, p, line.id, level, all) <= me.ram) out.push({ type: 'firewall', line: line.id, level }); } } } void opp; return out; } /** RAM an action costs, before any Salvage. */ export function actionCost(s: GameState, a: Action): number { const p = decider(s) ?? s.active; switch (a.type) { case 'firewall': return placeFirewallCost(s, p, a.line, a.level); case 'clearFirewall': return firewallCost(s, s.firewalls[a.line] ?? 0); case 'installHardware': return hardwareCost(s, a.card, { player: p, slot: a.slot }); case 'recruit': return defOf(s, a.card).ram; case 'buyAvatar': return avatarForSale(s, p)?.price ?? 0; case 'installProgram': return programCost(s, p, a.card, a.at); case 'play': return executionCost(s, p, a.card, a.target, a.args); case 'activate': { const src = abilitySource(s, a.card, a.name); return src ? abilityCost(s, src) + (scriptOf(src.name)!.ability!.extraCost?.(s, src, a.args) ?? 0) : 0; } case 'choose': return s.choice?.options[a.index]?.cost ?? 0; default: return 0; } } const argsKey = (a: Args): string => [a.ref ? `${a.ref.player}.${a.ref.slot}` : '', a.card ?? '', a.cards?.join(',') ?? '', a.to ?? '', a.mode ?? '', a.k ?? ''].join('|'); /** Stable identity for comparing actions. */ export function actionKey(a: Action): string { switch (a.type) { case 'end': case 'pass': return a.type; case 'choose': return `choose:${a.index}`; case 'place': case 'advance': case 'attack': return `${a.type}:${a.slot}:${a.to}`; case 'recall': return `recall:${a.slot}`; case 'clearFirewall': return `clear:${a.line}`; case 'firewall': return `firewall:${a.line}:${a.level}`; case 'salvage': return `salvage:${a.card}`; case 'installHardware': return `hw:${a.card}:${a.slot}`; case 'recruit': return `recruit:${a.card}:${a.slot}`; case 'buyAvatar': return `buy:${a.slot}`; case 'installProgram': return `prog:${a.card}:${a.at}`; case 'play': return `play:${a.card}:${a.target}:${argsKey(a.args)}:${a.from}`; case 'activate': return `act:${a.card}:${a.name}:${argsKey(a.args)}`; } } // --------------------------------------------------------------------------------------------- // Applying actions /** Opens (or continues) a response window after `actor` declares or plays something. */ function respondTo(s: GameState, actor: PlayerId, base: number): void { const w = openWindow(s); if (w) { w.passes = 1; w.priority = other(actor); return; } pushTasks(s, { t: 'window', kind: 'response', priority: other(actor), passes: 1, base, resolving: false }); } /** * Applies `a` for the deciding player, then runs the game until the next decision. Throws if it * isn't legal. Pass `legal` when you already have the current legal actions. */ export function applyAction(s: GameState, a: Action, legal: Action[] = legalActions(s)): void { const key = actionKey(a); if (!legal.some((x) => actionKey(x) === key)) throw new Error(`Illegal action at turn ${s.turn}: ${key}`); const p = decider(s)!; const me = s.players[p]; const who = playerName(p); const ref = (slot: number): AvatarRef => ({ player: p, slot }); switch (a.type) { case 'end': endStep(s); break; case 'pass': { const w = openWindow(s)!; w.passes++; w.priority = other(w.priority); break; } case 'choose': { const ch = s.choice!; const option = ch.options[a.index]; s.choice = null; say(s, `${who} chooses: ${option.label}.`); const fn = scriptOf(ch.resume.name)?.resume?.[ch.resume.fn]; if (!fn) throw new Error(`No resume ${ch.resume.name}.${ch.resume.fn}`); fn(s, ch.resume.data, option.value); break; } case 'buyAvatar': { const { price } = avatarForSale(s, p)!; const av = me.avatars[a.slot - 1]; me.ram -= price; stat(s, 'ramOnAvatars', p, price); stat(s, 'avatarsBought', p); av.faceUp = true; say(s, `${who} buys Avatar ${a.slot}: ${nameOf(s, av.card)} (-${price} RAM, now ${me.ram}).`); break; } case 'recruit': { const cost = defOf(s, a.card).ram; const av = me.avatars[a.slot - 1]; if (av.card >= 0) retireAvatar(s, ref(a.slot)); removeFrom(me.hand, a.card); me.ram -= cost; stat(s, 'ramOnCards', p, cost); stat(s, 'avatarsRecruited', p); played(s, nameOf(s, a.card), p); Object.assign(av, newAvatar(a.card, true, null)); me.avatars[a.slot + 3].card = a.card; say(s, `${who} recruits ${nameOf(s, a.card)} as Avatar ${a.slot} (-${cost} RAM, now ${me.ram}).`); break; } case 'salvage': { const gain = defOf(s, a.card).ram; removeFrom(me.hand, a.card); toDiscard(s, a.card); me.ram += gain; stat(s, 'ramFromSalvage', p, gain); stat(s, 'cardsSalvaged', p); say(s, `${who} salvages ${nameOf(s, a.card)} (+${gain} RAM, now ${me.ram}).`); break; } case 'place': { const av = me.avatars[a.slot - 1]; say(s, av.at === null ? `${who} places ${avatarName(s, ref(a.slot))} on ${a.to}.` : `${who} moves ${avatarName(s, ref(a.slot))} ${av.at} → ${a.to}.`); av.at = a.to; av.placed = true; break; } case 'recall': recallAvatar(s, ref(a.slot)); break; case 'advance': case 'attack': { const r = ref(a.slot); const av = avatar(s, r); const second = a.type === 'attack' && av.attacks > 0; if (a.type === 'advance') av.advanced = true; else av.attacks++; s.declarations.push({ kind: a.type, ref: r, to: a.to, from: av.at!, second }); say(s, a.type === 'advance' ? `${who}: ${avatarName(s, r)} advances to ${a.to}.` : `${who}: ${avatarName(s, r)} attacks ${a.to} from ${av.at}${second ? ' (Infinite Loop)' : ''}.`); respondTo(s, p, s.stack.length); if (a.type === 'attack') emit(s, 'onAttackDeclared', { ref: r, to: a.to }); break; } case 'clearFirewall': { const level = s.firewalls[a.line]; const cost = firewallCost(s, level); me.ram -= cost; stat(s, 'ramOnFirewalls', p, cost); delete s.firewalls[a.line]; stat(s, 'firewallsCleared', p); say(s, `${who} clears the Lv ${level} Firewall on ${a.line} (-${cost} RAM).`); break; } case 'firewall': { const before = s.firewalls[a.line] ?? 0; const cost = pay(s, { kind: 'firewall', player: p, line: a.line, level: a.level }, 'ramOnFirewalls'); s.firewalls[a.line] = a.level; stat(s, before ? 'firewallsUpgraded' : 'firewallsPlaced', p); say(s, before ? `${who} upgrades the Firewall on ${a.line} to Lv ${a.level} (-${cost} RAM).` : `${who} places a Lv ${a.level} Firewall on ${a.line} (-${cost} RAM).`); break; } case 'installHardware': { const r = ref(a.slot); const cost = pay(s, { kind: 'hardware', player: p, card: a.card, ref: r, at: avatar(s, r).at }, 'ramOnCards'); removeFrom(me.hand, a.card); avatar(s, r).hardware.push(a.card); s.cards[a.card].installedTurn = s.turn; stat(s, 'hardwareInstalled', p); played(s, nameOf(s, a.card), p); say(s, `${who} installs ${nameOf(s, a.card)} on ${avatarName(s, r)} (-${cost} RAM).`); respondTo(s, p, s.stack.length); emit(s, 'onInstall', { card: a.card, at: avatar(s, r).at, ref: r }); break; } case 'installProgram': { const cost = pay(s, { kind: 'program', player: p, card: a.card, at: a.at }, 'ramOnCards'); removeFrom(me.hand, a.card); s.locations[a.at].programs.push(a.card); s.cards[a.card].installedTurn = s.turn; stat(s, 'programsInstalled', p); played(s, nameOf(s, a.card), p); say(s, `${who} installs ${nameOf(s, a.card)} on ${a.at} (-${cost} RAM).`); respondTo(s, p, s.stack.length); emit(s, 'onInstall', { card: a.card, at: a.at, ref: null }); break; } case 'play': { const name = nameOf(s, a.card); const hostile = executionHostiles(s, { player: p, target: a.target, args: a.args, name }); const cost = pay(s, { kind: 'execution', player: p, card: a.card, at: a.target, hostile }, 'ramOnCards'); removeFrom(me.hand, a.card); const item: StackItem = { kind: 'execution', player: p, card: a.card, name, target: a.target, args: a.args, from: a.from, power: executionPower(s, p, a.from), }; s.stack.push(item); if (item.power > 0) fired(s, 'Dedicated GPU', p); stat(s, 'executionsPlayed', p); played(s, name, p); say(s, `${who} plays ${name}${a.target ? ` on ${a.target}` : ''}${a.from ? ` from ${a.from}` : ''} (-${cost} RAM).`); respondTo(s, p, s.stack.length - 1); if (hostile.length) pushTasks(s, { t: 'call', name: 'False Positive', fn: 'offer', data: { index: s.stack.length - 1 } }); break; } case 'activate': { const src = abilitySource(s, a.card, a.name)!; const cost = abilityCost(s, src) + (scriptOf(src.name)!.ability!.extraCost?.(s, src, a.args) ?? 0); me.ram -= cost; stat(s, 'ramOnAbilities', p, cost); if (src.kind === 'hardware') useHardware(s, src.id); else markUsed(s, abilityKey(src)); const label = src.kind === 'avatar' ? `${defOf(s, src.id).ability!.name} (${src.name})` : src.name; s.stack.push({ kind: 'ability', player: p, card: src.id, name: src.name, target: null, args: a.args, from: null, power: 0 }); stat(s, 'abilitiesUsed', p); if (src.kind === 'avatar') played(s, src.name, p); say(s, `${who} uses ${label}${cost ? ` (-${cost} RAM)` : ''}.`); respondTo(s, p, s.stack.length - 1); break; } } run(s); } function endStep(s: GameState): void { switch (s.step) { case 'deploy': s.step = 'play'; return; case 'play': s.step = 'attack'; return; case 'attack': s.step = 'resolve'; pushTasks(s, ...s.declarations.map((_, index): Task => ({ t: 'declaration', index })), { t: 'afterResolve' }); return; case 'resolve': return; case 'playAgain': pushTasks(s, { t: 'endTurn' }); return; } } // --------------------------------------------------------------------------------------------- // Running tasks const combatLive = (s: GameState): boolean => !!s.combat && !s.combat.ended; /** Runs queued tasks until a player must decide or the game ends. */ export function run(s: GameState): void { for (let guard = 0; !s.over && !s.choice; guard++) { if (guard > 100_000) throw new Error(`Engine stuck at turn ${s.turn}`); const task = s.tasks[0]; if (!task) return; if (task.t === 'window') { if (windowWaits(s, task)) return; continue; } s.tasks.shift(); execute(s, task); } } /** Advances a response window. Returns true when a player has priority and must decide. */ function windowWaits(s: GameState, w: Extract): boolean { const close = () => { s.tasks.shift(); return false; }; if (w.resolving) { if (s.stack.length > w.base) { resolveTop(s); return false; } w.resolving = false; if (w.kind === 'response' || !combatLive(s)) return close(); // Something changed the combat: both players may react again. w.passes = 0; w.priority = s.combat!.attacker.player; } if (w.passes >= 2 || (w.kind !== 'response' && !combatLive(s))) { if (s.stack.length > w.base) { w.resolving = true; return false; } return close(); } if (!hasResponse(s, w.priority)) { w.passes++; w.priority = other(w.priority); return false; } return true; } function resolveTop(s: GameState): void { const item = s.stack.pop()!; const script = scriptOf(item.name)!; if (item.kind === 'execution') { toDiscard(s, item.card); for (const src of sources(s)) { if (scriptOf(src.name)?.negates?.(s, src, item)) return; } if (item.from) pushTasks(s, { t: 'call', name: 'Quantum Coprocessor', fn: 'offer', data: { item: item as never } }); script.execution!.resolve(s, item); return; } const src = abilitySource(s, item.card, item.name); if (!src) { say(s, `${item.name}'s ability fizzles: it's no longer in play.`); return; } script.ability!.resolve(s, item, src); } function execute(s: GameState, task: Task): void { switch (task.t) { case 'declaration': return resolveDeclaration(s, task.index); case 'afterResolve': s.step = 'playAgain'; return; case 'combat': return combatStage(s, task.stage); case 'defeat': return defeat(s, task.ref, task.loc, task.role); case 'capture': return task.stage === 'hooks' ? captureHooks(s, task.ref, task.loc, task.how) : captureMain(s, task.ref, task.loc, task.how); case 'hook': { if (!stillActive(s, task.src)) return; const fn = scriptOf(task.src.name)?.[task.hook] as ((s: GameState, src: Source, data: unknown) => void) | undefined; fn?.(s, task.src, task.data); return; } case 'call': { const fn = scriptOf(task.name)?.resume?.[task.fn]; if (!fn) throw new Error(`No script function ${task.name}.${task.fn}`); fn(s, task.data, null); return; } case 'draw': return drawTask(s, task.player); case 'endTurn': return endTurn(s); case 'window': return; } } // --------------------------------------------------------------------------------------------- // Player views /** * What player `p` can see. Hidden cards become -1: the opponent's hand, both decks and Server * piles, and face-down Avatars. The RNG is blanked so bots can't predict dice, the opponent's * choices are hidden, and only open windows are kept from the task queue. Everything else is * shared with the real state, so treat a view as read-only. */ export function viewFor(s: GameState, p: PlayerId): GameState { const hide = (ids: number[]) => ids.map(() => -1); const players = s.players.map((pl, i): PlayerState => ({ ...pl, hand: i === p ? [...pl.hand] : hide(pl.hand), deck: hide(pl.deck), serverPile: hide(pl.serverPile), discard: [...pl.discard], avatars: pl.avatars.map((av) => ({ ...av, hardware: [...av.hardware], card: av.faceUp ? av.card : -1 })), })); const choice = s.choice && s.choice.player !== p ? { ...s.choice, options: s.choice.options.map(() => ({ label: '?', value: null })) } : s.choice; const combat = s.combat ? { ...s.combat, race: s.combat.race.map((r, i) => (i === p ? r : null)) as typeof s.combat.race } : null; return { ...s, rng: { s: 0 }, log: null, players: players as [PlayerState, PlayerState], choice, combat, tasks: s.tasks.filter((t) => t.t === 'window'), }; }