This commit is contained in:
Forrest 2026-09-28 01:56:25 -04:00
parent 746d218eda
commit e590baf28d
44 changed files with 8308 additions and 0 deletions

912
sim/src/engine.ts Normal file
View file

@ -0,0 +1,912 @@
/**
* 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 {
captureHooks,
captureMain,
combatStage,
defeat,
drawNow,
drawTask,
resolveDeclaration,
} from './flow.ts';
import { GRID, LINES, LINES_AT, LINE_BY_ID, LOCATIONS, START_LOC, isStart, otherEnd, type LocId } from './map.ts';
import {
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,
isCopy,
isOpen,
markUsed,
nameOf,
other,
fired,
played,
playerName,
pushTasks,
refsInPlay,
removeFrom,
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;
}
function newAvatar(card: number, faceUp: boolean, copyOf: number | null): AvatarState {
return {
card,
faceUp,
at: null,
hardware: [],
placed: false,
advanced: false,
attacks: 0,
infection: 0,
bugs: 0,
permanentInfection: 0,
mods: [],
disabledUntil: 0,
rootedUntil: 0,
breachedTurn: 0,
copyOf,
};
}
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] = pool.byName.get(name)!;
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];
const avatars = shuffle(rng, deck.avatars.map((n) => add(n, p)));
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: [
...avatars.map((card, i) => newAvatar(card, i === 0, null)),
...avatars.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.stats.cardsDrawn = [0, 0];
s.firstPlayer = randInt(rng, 2) as PlayerId;
s.active = s.firstPlayer;
say(s, `${playerName(s.firstPlayer)} goes first.`);
beginTurn(s, true);
run(s);
return s;
}
function beginTurn(s: GameState, skipDraw: boolean): void {
if (s.turn >= s.rules.maxTurns) {
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);
s.used = {};
tidy(s);
const me = s.players[s.active];
for (const av of me.avatars) {
av.placed = false;
av.advanced = false;
av.attacks = 0;
}
s.declarations = [];
s.step = 'deploy';
say(s, `\n— Turn ${s.turn}: ${playerName(s.active)} (${me.ram} RAM, ${me.hand.length} cards, ${gridCount(s, s.active)} locations) —`);
if (!skipDraw) pushTasks(s, { t: 'draw', player: s.active });
emit(s, 'onTurnStart', null);
}
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 = 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<Task, { t: 'window' }> | 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)) 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. */
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<LocId | null>([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<StackItem, 'player' | 'target' | 'args' | 'name'>): 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)) return out;
const seen = new Set<string>();
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 = 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) {
for (const to of LOCATIONS) if (to !== av.at && hasRoom(s, p, to)) out.push({ type: 'place', slot: i + 1, to });
}
if (av.at !== null) 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) => {
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<string>();
const all = sources(s);
for (const card of 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 === '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 });
}
}
}
}
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 '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 '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 '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 '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 '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<Task, { t: 'window' }>): 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'),
};
}