sim
This commit is contained in:
parent
746d218eda
commit
e590baf28d
44 changed files with 8308 additions and 0 deletions
10
sim/src/bots/bot.ts
Normal file
10
sim/src/bots/bot.ts
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import type { Action, GameState, PlayerId } from '../types.ts';
|
||||
|
||||
export interface Bot {
|
||||
readonly name: string;
|
||||
/** Picks one of `actions` for player `me`, seeing only `view` (see viewFor). */
|
||||
choose(view: GameState, actions: Action[], me: PlayerId): Action;
|
||||
}
|
||||
|
||||
/** Bots are created per game so they can keep per-game memory. */
|
||||
export type BotFactory = (seed: number) => Bot;
|
||||
169
sim/src/bots/eval.ts
Normal file
169
sim/src/bots/eval.ts
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
/** Scoring helpers the greedy bot shares: board values, combat odds and what a combat is worth. */
|
||||
import { isStart, levelFor, type LocId } from '../map.ts';
|
||||
import { winChance } from '../odds.ts';
|
||||
import { bugImmune, coresOf, fighterOf, hardwareActive, sources } from '../query.ts';
|
||||
import { scriptOf } from '../scripts.ts';
|
||||
import { avatar, defOf, defendersAt, fightersOf, hardwareOf, refKey } from '../state.ts';
|
||||
import type { AvatarRef, GameState, PlayerId } from '../types.ts';
|
||||
|
||||
// A location is worth about 10 points, plus 8 more when it's taken from the opponent. RAM counts
|
||||
// half a point per RAM, a card in hand about 2.
|
||||
export const LOCATION_POINTS = 10;
|
||||
export const ENEMY_LOCATION_POINTS = 8;
|
||||
export const RAM_POINTS = 0.5;
|
||||
export const LOSS_POINTS = 4;
|
||||
export const CARD_POINTS = 2;
|
||||
|
||||
export function locationValue(v: GameState, p: PlayerId, loc: LocId): number {
|
||||
if (isStart(loc)) return 0; // starting Servers can't be captured
|
||||
const taken = v.locations[loc].owner === null ? 0 : ENEMY_LOCATION_POINTS;
|
||||
return LOCATION_POINTS + taken + v.rules.levelRam[levelFor(p, loc)] * RAM_POINTS;
|
||||
}
|
||||
|
||||
/** What losing an Avatar costs: the tempo, plus its Hardware. */
|
||||
export function avatarStake(v: GameState, r: AvatarRef): number {
|
||||
return LOSS_POINTS + hardwareOf(v, r).reduce((t, h) => t + (h < 0 ? 0 : defOf(v, h).ram), 0) * RAM_POINTS;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Dice
|
||||
|
||||
const sumDist: number[][] = [[1]];
|
||||
/** Probability of each total for k six-sided dice. */
|
||||
export function diceSum(k: number): number[] {
|
||||
while (sumDist.length <= k) {
|
||||
const prev = sumDist[sumDist.length - 1];
|
||||
const next = new Array(prev.length + 6).fill(0);
|
||||
prev.forEach((p, s) => {
|
||||
for (let f = 1; f <= 6; f++) next[s + f] += p / 6;
|
||||
});
|
||||
sumDist.push(next);
|
||||
}
|
||||
return sumDist[k];
|
||||
}
|
||||
|
||||
/** P(a > b) where a = fa + k d6 and b = fb + m d6, ties rerolled at `tie` odds. */
|
||||
function beats(fa: number, ka: number, fb: number, kb: number, tie: number): number {
|
||||
const da = diceSum(ka);
|
||||
const db = diceSum(kb);
|
||||
let win = 0;
|
||||
let draw = 0;
|
||||
da.forEach((pa, a) => {
|
||||
if (!pa) return;
|
||||
db.forEach((pb, b) => {
|
||||
if (!pb) return;
|
||||
const x = fa + a;
|
||||
const y = fb + b;
|
||||
if (x > y) win += pa * pb;
|
||||
else if (x === y) draw += pa * pb;
|
||||
});
|
||||
});
|
||||
return win + draw * tie;
|
||||
}
|
||||
|
||||
/**
|
||||
* Chance the attacker wins the current combat. Before the roll that's the Core odds. After it,
|
||||
* the dice on the table count: Core changes add dice or drop the highest ones, and `reroll` lets a
|
||||
* fighter reroll its dice showing k or less (Bit Flip).
|
||||
*/
|
||||
export function combatOdds(v: GameState, reroll?: { ref: AvatarRef; k: number }): number {
|
||||
const c = v.combat!;
|
||||
let atk = 0;
|
||||
let def = 0;
|
||||
for (const r of fightersOf(c)) {
|
||||
const n = coresOf(v, fighterOf(v, r));
|
||||
if (r === c.attacker) atk += n;
|
||||
else def += n;
|
||||
}
|
||||
const tie = winChance(atk, def);
|
||||
if (!c.rolled) return tie;
|
||||
let fa = 0;
|
||||
let ka = 0;
|
||||
let fd = 0;
|
||||
let kd = 0;
|
||||
for (const r of fightersOf(c)) {
|
||||
const want = coresOf(v, fighterOf(v, r));
|
||||
let dice = [...(c.dice[refKey(r)] ?? [])].sort((a, b) => a - b);
|
||||
if (dice.length > want) dice = dice.slice(0, want);
|
||||
let extra = want - dice.length;
|
||||
if (reroll && refKey(reroll.ref) === refKey(r)) {
|
||||
extra += dice.filter((d) => d <= reroll.k).length;
|
||||
dice = dice.filter((d) => d > reroll.k);
|
||||
}
|
||||
const fixed = dice.reduce((a, b) => a + b, 0);
|
||||
if (r === c.attacker) {
|
||||
fa += fixed;
|
||||
ka += extra;
|
||||
} else {
|
||||
fd += fixed;
|
||||
kd += extra;
|
||||
}
|
||||
}
|
||||
return beats(fa, ka, fd, kd, tie);
|
||||
}
|
||||
|
||||
/**
|
||||
* Chance an attack would win if declared now, counting what the target's Programs do when a
|
||||
* combat starts there (Memory Leak, Visual Artifact, Race Condition, Memory Parasite).
|
||||
*/
|
||||
export function attackOdds(v: GameState, ref: AvatarRef, origin: LocId, target: LocId, bonus = 0): number {
|
||||
let atk = coresOf(v, { ref, role: 'attack', at: origin, loc: target, combat: null }) + bonus;
|
||||
const defs = defendersAt(v, target);
|
||||
let def = defs.reduce((t, d) => t + coresOf(v, { ref: d, role: 'defend', at: target, loc: target, combat: null }), 0);
|
||||
let race = false;
|
||||
for (const x of sources(v)) {
|
||||
if (x.at !== target || x.controller === ref.player) continue;
|
||||
const hw = hardwareOf(v, ref);
|
||||
if (x.name === 'Memory Leak' && !bugImmune(v, ref, x.controller)) atk -= hw.length;
|
||||
if (x.name === 'Visual Artifact' && !v.cards[x.id].spent) atk -= 1;
|
||||
if (x.name === 'Race Condition') race = true;
|
||||
if (x.name === 'Memory Parasite') {
|
||||
const bonuses = hw.filter((h) => hardwareActive(v, h)).map((h) => hardwareCores(v, h));
|
||||
if (bonuses.length) atk -= Math.min(...bonuses);
|
||||
}
|
||||
}
|
||||
atk = Math.max(1, atk);
|
||||
def = Math.max(1, def);
|
||||
return race ? (winChance(atk, def) + winChance(atk, def + 2)) / 2 : winChance(atk, def);
|
||||
}
|
||||
|
||||
/** Rough Cores a Hardware card adds in combat. */
|
||||
export function hardwareCores(v: GameState, hw: number): number {
|
||||
const name = v.cards[hw].name;
|
||||
return { 'Additional Core': 1, 'RAM Expansion': 2, 'Overclocked CPU': 2, 'Packet Accelerator': 1 }[name] ?? 0;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// What the current combat is worth
|
||||
|
||||
/** Points for `me` if the combat goes each way. */
|
||||
export function stakes(v: GameState, me: PlayerId): { win: number; lose: number } {
|
||||
const c = v.combat!;
|
||||
const loc = locationValue(v, c.attacker.player, c.loc);
|
||||
const atk = avatarStake(v, c.attacker);
|
||||
const def = c.defenders.reduce((t, d) => t + avatarStake(v, d), 0);
|
||||
return c.attacker.player === me
|
||||
? { win: loc + def / 2, lose: -atk }
|
||||
: { win: atk / 2, lose: -(loc + def) };
|
||||
}
|
||||
|
||||
/** Expected points for `me` from the current combat, or from how it ended. */
|
||||
export function combatValue(v: GameState, me: PlayerId): number {
|
||||
const c = v.combat;
|
||||
if (!c) return 0;
|
||||
const iAttack = c.attacker.player === me;
|
||||
if (c.ended) {
|
||||
// Ended early: the attacker takes the location only if every defender left.
|
||||
const taken = c.defenders.length === 0 && avatar(v, c.attacker).at !== null;
|
||||
if (!taken) return 0;
|
||||
return iAttack ? locationValue(v, me, c.loc) : -locationValue(v, c.attacker.player, c.loc);
|
||||
}
|
||||
const s = stakes(v, me);
|
||||
const pAtk = combatOdds(v);
|
||||
const p = iAttack ? pAtk : 1 - pAtk;
|
||||
return p * s.win + (1 - p) * s.lose;
|
||||
}
|
||||
|
||||
export const cardName = (v: GameState, id: number): string => (id < 0 ? '' : v.cards[id].name);
|
||||
export const printedRam = (v: GameState, id: number): number => (id < 0 ? 0 : defOf(v, id).ram);
|
||||
export const scriptFor = (v: GameState, id: number) => scriptOf(cardName(v, id));
|
||||
912
sim/src/bots/greedy.ts
Normal file
912
sim/src/bots/greedy.ts
Normal file
|
|
@ -0,0 +1,912 @@
|
|||
import {
|
||||
abilityActions,
|
||||
abilitySource,
|
||||
actionCost,
|
||||
actionKey,
|
||||
executionActions,
|
||||
executionPower,
|
||||
firewallCost,
|
||||
hardwareCost,
|
||||
openWindow,
|
||||
programCost,
|
||||
} from '../engine.ts';
|
||||
import { GRID, LINES_AT, LOCATIONS, otherEnd, type LocId } from '../map.ts';
|
||||
import { coresOf, hardwareActive, hasRoom, portsFree, programSlots, sources } from '../query.ts';
|
||||
import { scriptOf } from '../scripts.ts';
|
||||
import {
|
||||
avatar,
|
||||
canAct,
|
||||
controls,
|
||||
defendersAt,
|
||||
defOf,
|
||||
hardwareOf,
|
||||
isCopy,
|
||||
isOpen,
|
||||
other,
|
||||
programLocation,
|
||||
refsInPlay,
|
||||
removeFrom,
|
||||
} from '../state.ts';
|
||||
import type { Action, AvatarRef, Choice, GameState, PlayerId, StackItem } from '../types.ts';
|
||||
import type { Bot } from './bot.ts';
|
||||
import {
|
||||
CARD_POINTS,
|
||||
RAM_POINTS,
|
||||
attackOdds,
|
||||
avatarStake,
|
||||
cardName,
|
||||
combatOdds,
|
||||
combatValue,
|
||||
hardwareCores,
|
||||
locationValue,
|
||||
printedRam,
|
||||
stakes,
|
||||
} from './eval.ts';
|
||||
|
||||
export interface GreedyParams {
|
||||
/** Only attack when the chance to win is at least this. */
|
||||
minWinChance: number;
|
||||
/** Firewall level used to wall off undefended frontier locations; 0 = never place Firewalls. */
|
||||
firewallLevel: number;
|
||||
maxFirewallsPerTurn: number;
|
||||
/** RAM, counting salvageable cards, kept back after spending in step 6. */
|
||||
ramReserve: number;
|
||||
/** Play Programs, Executions and Abilities. Off plays like the Phase 2 bot: Core Hardware only. */
|
||||
useCards: boolean;
|
||||
}
|
||||
|
||||
export const DEFAULT_GREEDY: GreedyParams = {
|
||||
minWinChance: 0.6,
|
||||
firewallLevel: 1,
|
||||
maxFirewallsPerTurn: 2,
|
||||
ramReserve: 6,
|
||||
useCards: true,
|
||||
};
|
||||
|
||||
/**
|
||||
* Board order as seen from `me`'s side. North gets South's order rotated 180°, which maps the
|
||||
* board onto itself, so tie-breaks never favor a seat.
|
||||
*/
|
||||
const REVERSED_GRID = [...GRID].reverse();
|
||||
const REVERSED_LOCATIONS = [...LOCATIONS].reverse();
|
||||
const gridFrom = (me: PlayerId) => (me === 0 ? GRID : REVERSED_GRID);
|
||||
const locationsFrom = (me: PlayerId) => (me === 0 ? LOCATIONS : REVERSED_LOCATIONS);
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// How much the bot wants each card
|
||||
|
||||
/** Programs by how much they help where they're installed, roughly in points per turn. */
|
||||
const PROGRAM_WEIGHT: Record<string, number> = {
|
||||
'Stack Overflow': 4, 'Race Condition': 3, 'Memory Leak': 3, 'Visual Artifact': 2, 'Memory Parasite': 2,
|
||||
'Recursive Infection': 2, 'Resource Leech': 2, 'Overflow Error': 2, 'Persistent Infection': 1, 'Stock Rice': 1.5,
|
||||
'Packet Loss': 1.5, 'Null Pointer': 1.5, Fragmentation: 1, 'Latency Spike': 1, Desynchronization: 0.5,
|
||||
'False Positive': 0.5, Hotfix: 0.5, 'Version Control': 1.5, 'Compatibility Layer': 1.5, 'Replication Routine': 1,
|
||||
'Worm Protocol': 1.5, 'Payload Injector': 0.5, 'Ghost Process': 0.5, 'Garbage Collection': 1, 'Error Correction': 0.5,
|
||||
'Rollback Routine': 1, 'Undefined Behavior': 1.5, 'Infinite Loop': 2,
|
||||
};
|
||||
/** Programs that only matter when an enemy attacks their location. */
|
||||
const DEFENSIVE = new Set([
|
||||
'Stack Overflow', 'Race Condition', 'Memory Leak', 'Visual Artifact', 'Memory Parasite', 'Recursive Infection',
|
||||
'Resource Leech', 'Overflow Error', 'Persistent Infection', 'Stock Rice', 'Packet Loss', 'Null Pointer',
|
||||
'Fragmentation', 'Latency Spike', 'Desynchronization', 'False Positive', 'Version Control', 'Undefined Behavior',
|
||||
]);
|
||||
const UTILITY_HARDWARE: Record<string, number> = {
|
||||
'Redundant Power Supply': 2, 'RAID Array': 1.5, 'Diagnostic Module': 1.5, 'Firewall Appliance': 1, 'ECC Memory': 1,
|
||||
'Hardware Sandbox': 1, 'Dedicated GPU': 1, 'Quantum Coprocessor': 1, 'Hot-Swap Bay': 1, 'Solid-State Cache': 1,
|
||||
'Cooling System': 0.5, 'Network Interface Upgrade': 1.5,
|
||||
};
|
||||
/** Executions worth holding for the opponent's turn. */
|
||||
const HELD = new Set(['Execute: Emergency Shutdown', 'Execute: Disconnect', 'Execute: Sabotage', 'Execute: Packet Flood']);
|
||||
/** Executions and Abilities that can change a combat already under way. */
|
||||
const COMBAT_TRICKS = new Set([
|
||||
'Execute: Disconnect', 'Execute: Sabotage', 'Execute: Kill Process', 'Execute: Force Reboot', 'Execute: Fork',
|
||||
'Execute: Override', 'Execute: Emergency Shutdown', 'Execute: Process Clone', 'Execute: Defragment',
|
||||
'Execute: Remote Access', 'Execute: Purge', 'Corrupt Driver', 'Pixelated Picture', 'Beta Version 1.0', 'Code Zero',
|
||||
'Broken Bits', 'Hot-Swap Bay', 'Rollback Routine', 'Undefined Behavior',
|
||||
]);
|
||||
|
||||
/** How much the bot wants to keep a card rather than salvage it. Below 3 is fodder. */
|
||||
function keepScore(v: GameState, id: number): number {
|
||||
const def = defOf(v, id);
|
||||
if (def.kind === 'hardware') {
|
||||
if (hardwareCores(v, id) > 0) return 6;
|
||||
return (UTILITY_HARDWARE[def.name] ?? 0) * 2;
|
||||
}
|
||||
if (def.kind === 'program') return PROGRAM_WEIGHT[def.name] ?? 1;
|
||||
if (HELD.has(def.name)) return 4;
|
||||
return 1.5;
|
||||
}
|
||||
|
||||
/** RAM available this turn, counting cards the bot is willing to salvage. */
|
||||
function spendable(v: GameState, me: PlayerId): number {
|
||||
const pl = v.players[me];
|
||||
return pl.ram + pl.hand.filter((id) => keepScore(v, id) < 3).reduce((t, id) => t + printedRam(v, id), 0);
|
||||
}
|
||||
|
||||
/** The salvage that best covers `cost`, never the card being paid for. Null if none is needed or possible. */
|
||||
function salvageFor(v: GameState, me: PlayerId, cost: number, except: number | null = null): Action | null {
|
||||
const pl = v.players[me];
|
||||
const need = cost - pl.ram;
|
||||
if (need <= 0) return null;
|
||||
const hand = pl.hand.filter((id) => id !== except && id >= 0);
|
||||
if (hand.reduce((t, id) => t + printedRam(v, id), 0) < need) return null;
|
||||
const order = [...hand].sort((a, b) => keepScore(v, a) - keepScore(v, b) || printedRam(v, b) - printedRam(v, a));
|
||||
const fodder = order.filter((id) => keepScore(v, id) < 3);
|
||||
const from = fodder.reduce((t, id) => t + printedRam(v, id), 0) >= need ? fodder : order;
|
||||
const card = from.find((id) => printedRam(v, id) >= need) ?? from[0];
|
||||
return { type: 'salvage', card };
|
||||
}
|
||||
|
||||
/** The card an action spends from hand, so Salvage doesn't use it. */
|
||||
const spentCard = (a: Action): number | null =>
|
||||
a.type === 'play' || a.type === 'installHardware' || a.type === 'installProgram' ? a.card : null;
|
||||
|
||||
const reach = (v: GameState, me: PlayerId) =>
|
||||
v.players[me].ram + v.players[me].hand.reduce((t, id) => t + printedRam(v, id), 0);
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// The board
|
||||
|
||||
/** My grid locations the opponent could advance into or attack, most valuable to them first. */
|
||||
function threatened(v: GameState, me: PlayerId): LocId[] {
|
||||
const opp = other(me);
|
||||
const worth = (loc: LocId) => locationValue(v, opp, loc);
|
||||
return gridFrom(me).filter(
|
||||
(loc) => controls(v, me, loc) && LINES_AT.get(loc)!.some((l) => isOpen(v, l) && controls(v, opp, otherEnd(l, loc))),
|
||||
).sort((a, b) => worth(b) - worth(a));
|
||||
}
|
||||
|
||||
/** Avatars `me` can place, advance or attack with this turn. */
|
||||
function readyAvatars(v: GameState, me: PlayerId): { at: LocId | null; slot: number }[] {
|
||||
return v.players[me].avatars
|
||||
.map((a, i) => ({ a, slot: i + 1 }))
|
||||
.filter(({ a, slot }) => a.faceUp && !a.advanced && a.attacks === 0 &&
|
||||
(a.at === null || canAct(v, { player: me, slot })))
|
||||
.map(({ a, slot }) => ({ at: a.at, slot }));
|
||||
}
|
||||
|
||||
const advanceCount = (v: GameState, me: PlayerId): number =>
|
||||
GRID.filter((loc) => !controls(v, me, loc) && defendersAt(v, loc).length === 0 &&
|
||||
LINES_AT.get(loc)!.some((l) => isOpen(v, l) && controls(v, me, otherEnd(l, loc)))).length;
|
||||
|
||||
interface Option {
|
||||
kind: 'advance' | 'attack';
|
||||
slot: number;
|
||||
to: LocId;
|
||||
/** Where an attacker must stand. */
|
||||
origin?: LocId;
|
||||
/** Firewall to clear first. */
|
||||
clear?: string;
|
||||
score: number;
|
||||
}
|
||||
|
||||
interface TurnPlan {
|
||||
turn: number;
|
||||
deploy: Action[];
|
||||
attacks: Action[];
|
||||
attackers: Set<number>;
|
||||
}
|
||||
|
||||
/** Infinite Loop: extra attacks for my Avatars attacking from `loc`. */
|
||||
const extraAttacksAt = (v: GameState, me: PlayerId, loc: LocId): number =>
|
||||
Math.max(0, ...sources(v).filter((x) => x.at === loc && x.controller === me).map((x) => scriptOf(x.name)?.extraAttacks ?? 0));
|
||||
|
||||
/**
|
||||
* Deploy-step plan for the whole turn: which Avatars advance, which attack and from where, and
|
||||
* where the rest stand guard.
|
||||
*/
|
||||
function planTurn(v: GameState, me: PlayerId, params: GreedyParams): TurnPlan {
|
||||
const pl = v.players[me];
|
||||
const mine = locationsFrom(me).filter((l) => controls(v, me, l));
|
||||
const ready = readyAvatars(v, me);
|
||||
const occupant = new Map<LocId, number>();
|
||||
pl.avatars.forEach((a, i) => {
|
||||
if (a.at) occupant.set(a.at, i + 1);
|
||||
});
|
||||
for (const { at, slot } of ready) if (at) occupant.set(at, slot);
|
||||
let budget = spendable(v, me);
|
||||
|
||||
const options: Option[] = [];
|
||||
for (const to of gridFrom(me)) {
|
||||
if (controls(v, me, to)) continue;
|
||||
const defended = defendersAt(v, to).length > 0;
|
||||
const value = locationValue(v, me, to);
|
||||
for (const line of LINES_AT.get(to)!) {
|
||||
const from = otherEnd(line, to);
|
||||
if (!controls(v, me, from)) continue;
|
||||
const level = v.firewalls[line.id] ?? 0;
|
||||
const clearCost = firewallCost(v, level);
|
||||
if (clearCost > budget) continue;
|
||||
const clear = level ? line.id : undefined;
|
||||
for (const { slot } of ready) {
|
||||
const ref = { player: me, slot };
|
||||
if (!defended) {
|
||||
// Advancing needs no dice, so prefer weak Avatars and save strong ones for attacks.
|
||||
const weakness = 0.01 * coresOf(v, { ref, role: 'attack', at: null, loc: null, combat: null });
|
||||
options.push({ kind: 'advance', slot, to, clear, score: value - clearCost * RAM_POINTS - weakness });
|
||||
continue;
|
||||
}
|
||||
const holder = occupant.get(from);
|
||||
if (holder !== undefined && holder !== slot) continue;
|
||||
const chance = attackOdds(v, ref, from, to);
|
||||
if (chance < params.minWinChance) continue;
|
||||
const score = chance * value - (1 - chance) * avatarStake(v, ref) - clearCost * RAM_POINTS;
|
||||
options.push({ kind: 'attack', slot, to, origin: from, clear, score });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
options.sort((x, y) => y.score - x.score);
|
||||
const chosen: Option[] = [];
|
||||
const uses = new Map<number, number>();
|
||||
const usedTargets = new Set<LocId>();
|
||||
const origins = new Map<LocId, number>();
|
||||
const clears = new Set<string>();
|
||||
for (const o of options) {
|
||||
if (o.score <= 0) break;
|
||||
if (usedTargets.has(o.to)) continue;
|
||||
const n = uses.get(o.slot) ?? 0;
|
||||
if (n > 0) {
|
||||
// A second attack only from an Infinite Loop location, from the same origin.
|
||||
const first = chosen.find((c) => c.slot === o.slot)!;
|
||||
if (first.kind !== 'attack' || o.kind !== 'attack' || o.origin !== first.origin) continue;
|
||||
if (n > extraAttacksAt(v, me, o.origin!)) continue;
|
||||
} else if (o.origin && origins.has(o.origin) && origins.get(o.origin) !== o.slot) continue;
|
||||
const cost = o.clear && !clears.has(o.clear) ? firewallCost(v, v.firewalls[o.clear]) : 0;
|
||||
if (cost > budget) continue;
|
||||
budget -= cost;
|
||||
if (o.clear) clears.add(o.clear);
|
||||
uses.set(o.slot, n + 1);
|
||||
usedTargets.add(o.to);
|
||||
if (o.origin) origins.set(o.origin, o.slot);
|
||||
chosen.push(o);
|
||||
}
|
||||
|
||||
const deploy: Action[] = [...clears].map((line): Action => ({ type: 'clearFirewall', line }));
|
||||
const pos = new Map<number, LocId | null>(ready.map((x) => [x.slot, x.at]));
|
||||
const occupied = new Map(occupant);
|
||||
const move = (slot: number, to: LocId) => {
|
||||
const from = pos.get(slot);
|
||||
if (from) occupied.delete(from);
|
||||
occupied.set(to, slot);
|
||||
pos.set(slot, to);
|
||||
deploy.push({ type: 'place', slot, to });
|
||||
};
|
||||
const freeSpot = (prefer: LocId[]) => prefer.find((l) => !occupied.has(l) && !origins.has(l));
|
||||
const risky = threatened(v, me);
|
||||
const final: Option[] = [];
|
||||
|
||||
for (const o of chosen) {
|
||||
if (o.kind !== 'attack') continue;
|
||||
if (pos.get(o.slot) === o.origin) final.push(o);
|
||||
else if (!occupied.has(o.origin!)) {
|
||||
move(o.slot, o.origin!);
|
||||
final.push(o);
|
||||
} else if (final.some((f) => f.slot === o.slot && f.origin === o.origin)) final.push(o);
|
||||
}
|
||||
// Advancers still in their slot must enter play first; put them where nobody threatens.
|
||||
const safeFirst = [...mine.filter((l) => !risky.includes(l)), ...risky];
|
||||
for (const o of chosen) {
|
||||
if (o.kind !== 'advance') continue;
|
||||
if (pos.get(o.slot) !== null) final.push(o);
|
||||
else {
|
||||
const spot = freeSpot(safeFirst);
|
||||
if (spot) {
|
||||
move(o.slot, spot);
|
||||
final.push(o);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Everyone else guards the most threatened free location.
|
||||
const busy = new Set(final.map((o) => o.slot));
|
||||
for (const { slot } of ready) {
|
||||
if (busy.has(slot)) continue;
|
||||
const cur = pos.get(slot) ?? null;
|
||||
if (cur && risky.includes(cur)) continue;
|
||||
const spot = freeSpot(risky) ?? (cur === null ? freeSpot(mine) : undefined);
|
||||
if (spot) move(slot, spot);
|
||||
}
|
||||
|
||||
for (const o of final) if (o.kind === 'advance') deploy.push({ type: 'advance', slot: o.slot, to: o.to });
|
||||
const attacks = final
|
||||
.filter((o) => o.kind === 'attack')
|
||||
.map((o): Action => ({ type: 'attack', slot: o.slot, to: o.to }));
|
||||
return { turn: v.turn, deploy, attacks, attackers: new Set(final.filter((o) => o.kind === 'attack').map((o) => o.slot)) };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Playing cards on your own turn
|
||||
|
||||
const inHand = (v: GameState, me: PlayerId, name: string): number | undefined =>
|
||||
v.players[me].hand.find((id) => cardName(v, id) === name);
|
||||
|
||||
/** How much a performing Server adds: Dedicated GPU power, and a Quantum Coprocessor copy. */
|
||||
function fromValue(v: GameState, me: PlayerId, from: LocId | null): number {
|
||||
if (from === null) return 0;
|
||||
const qc = refsInPlay(v, me).some((r) => avatar(v, r).at === from &&
|
||||
hardwareOf(v, r).some((h) => cardName(v, h) === 'Quantum Coprocessor' && hardwareActive(v, h)));
|
||||
return executionPower(v, me, from) + (qc ? 0.5 : 0);
|
||||
}
|
||||
|
||||
/** A legal play of a named Execution matching `pick`, ignoring RAM, from the best Server. */
|
||||
function findPlay(v: GameState, me: PlayerId, name: string, pick: (a: Extract<Action, { type: 'play' }>) => boolean): Action | null {
|
||||
if (inHand(v, me, name) === undefined) return null;
|
||||
let best: Extract<Action, { type: 'play' }> | null = null;
|
||||
for (const a of executionActions(v, me, 'any')) {
|
||||
if (a.type !== 'play' || cardName(v, a.card) !== name || !pick(a)) continue;
|
||||
if (!best || fromValue(v, me, a.from) > fromValue(v, me, best.from)) best = a;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** A legal use of a named card's Ability matching `pick`, ignoring RAM. */
|
||||
function findUse(v: GameState, me: PlayerId, name: string, pick: (a: Extract<Action, { type: 'activate' }>) => boolean = () => true): Action | null {
|
||||
for (const a of abilityActions(v, me, 'any')) if (a.type === 'activate' && a.name === name && pick(a)) return a;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Deploy: make a copy (Replicate, Backup Server) before planning, so it can advance too. */
|
||||
function copyAction(v: GameState, me: PlayerId): Action | null {
|
||||
if (advanceCount(v, me) === 0) return null;
|
||||
const risky = threatened(v, me);
|
||||
const spot = locationsFrom(me).find((l) => hasRoom(v, me, l) && !risky.includes(l)) ??
|
||||
locationsFrom(me).find((l) => hasRoom(v, me, l));
|
||||
if (!spot) return null;
|
||||
const backup = findUse(v, me, 'Backup Server', (a) => a.args.to === spot);
|
||||
if (backup) return backup;
|
||||
if (spendable(v, me) >= 5 + 4) return findUse(v, me, 'Carbon NanoBots', (a) => a.args.to === spot);
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Hardware worth installing now: Core Hardware on fighters, useful utility Hardware anywhere. */
|
||||
function hardwarePlan(v: GameState, me: PlayerId, attackers: Set<number>, budget: number, useCards: boolean): Action[] {
|
||||
const pl = v.players[me];
|
||||
const risky = threatened(v, me);
|
||||
const out: Action[] = [];
|
||||
const wearers = refsInPlay(v, me).filter((r) => !isCopy(r))
|
||||
.sort((x, y) => Number(attackers.has(y.slot)) - Number(attackers.has(x.slot)));
|
||||
const ports = new Map(wearers.map((r) => [r.slot, portsFree(v, r)]));
|
||||
const fights = (r: AvatarRef) => attackers.has(r.slot) || risky.includes(avatar(v, r).at!);
|
||||
const hasExecutions = pl.hand.some((id) => defOf(v, id).kind === 'execution');
|
||||
// Network Interface Upgrade first, since it opens a port for the rest.
|
||||
const niuFirst = (id: number) => (cardName(v, id) === 'Network Interface Upgrade' ? 1 : 0);
|
||||
const hand = [...pl.hand].sort((a, b) => niuFirst(b) - niuFirst(a) || hardwareCores(v, b) - hardwareCores(v, a));
|
||||
for (const card of hand) {
|
||||
const def = defOf(v, card);
|
||||
if (def.kind !== 'hardware') continue;
|
||||
const cores = hardwareCores(v, card);
|
||||
let target: AvatarRef | undefined;
|
||||
if (cores > 0) {
|
||||
const attackOnly = def.name === 'Packet Accelerator';
|
||||
target = wearers.find((r) => ports.get(r.slot)! > 0 && fights(r) && (!attackOnly || attackers.has(r.slot)));
|
||||
} else if (def.name === 'Network Interface Upgrade') {
|
||||
// Adds a port: best on a fighter whose ports are full.
|
||||
target = [...wearers].sort((x, y) => ports.get(x.slot)! - ports.get(y.slot)!).find((r) => fights(r)) ?? wearers[0];
|
||||
} else if (useCards && (UTILITY_HARDWARE[def.name] ?? 0) > 0) {
|
||||
if (['Dedicated GPU', 'Quantum Coprocessor'].includes(def.name) && !hasExecutions) continue;
|
||||
const protects = ['Redundant Power Supply', 'RAID Array'].includes(def.name);
|
||||
target = wearers.find((r) => (protects ? avatar(v, r).hardware.length > 0 && ports.get(r.slot)! > 0 : ports.get(r.slot)! > 1));
|
||||
}
|
||||
if (!target) continue;
|
||||
const cost = hardwareCost(v, card, target);
|
||||
if (cost > budget) continue;
|
||||
budget -= cost;
|
||||
ports.set(target.slot, ports.get(target.slot)! + (def.name === 'Network Interface Upgrade' ? 1 : -1));
|
||||
out.push({ type: 'installHardware', card, slot: target.slot });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Negative effects on an Avatar that Error Correction or Purge could clear. */
|
||||
const afflicted = (v: GameState, r: AvatarRef): boolean => {
|
||||
const av = avatar(v, r);
|
||||
return av.infection + av.permanentInfection > 0 || hardwareOf(v, r).some((h) => !hardwareActive(v, h));
|
||||
};
|
||||
|
||||
/** How much installing Program `name` on my location `at` is worth, in points. */
|
||||
function programValue(v: GameState, me: PlayerId, name: string, at: LocId, risky: LocId[]): number {
|
||||
const opp = other(me);
|
||||
const w = PROGRAM_WEIGHT[name] ?? 1;
|
||||
const guarded = defendersAt(v, at).length > 0;
|
||||
const threat = risky.includes(at) ? (guarded ? 1 : 0.4) : 0.1;
|
||||
const here = v.locations[at].programs.map((id) => cardName(v, id));
|
||||
const hand = v.players[me].hand.map((id) => cardName(v, id));
|
||||
const enemyNear = LINES_AT.get(at)!.filter((l) => isOpen(v, l) && controls(v, opp, otherEnd(l, at))).map((l) => otherEnd(l, at));
|
||||
const slots = programSlots(v, at) - here.length;
|
||||
switch (name) {
|
||||
case 'Infinite Loop':
|
||||
return enemyNear.filter((l) => defendersAt(v, l).length).length >= 2 && guarded ? w : 0;
|
||||
case 'Compatibility Layer':
|
||||
return risky.includes(at) ? w : 0.3;
|
||||
case 'Replication Routine': {
|
||||
const viruses = v.players[me].hand.filter((id) => defOf(v, id).type === 'V' && defOf(v, id).kind === 'program' && cardName(v, id) !== name);
|
||||
if (slots < 2 || viruses.length === 0) return 0;
|
||||
return 0.5 + Math.max(...viruses.map((id) => programValue(v, me, cardName(v, id), at, risky)));
|
||||
}
|
||||
case 'Garbage Collection':
|
||||
case 'Hotfix':
|
||||
return here.length > 0 ? w * threat : 0;
|
||||
case 'Error Correction':
|
||||
return refsInPlay(v, me).some((r) => avatar(v, r).at === at && afflicted(v, r)) ? 2 : 0;
|
||||
case 'Rollback Routine': {
|
||||
// Helps my Avatars attacking from here into Programs that cut Cores.
|
||||
const cutters = enemyNear.some((l) => v.locations[l].programs.some((id) => ['Memory Leak', 'Visual Artifact'].includes(cardName(v, id))));
|
||||
return guarded && cutters ? w * 1.5 : 0;
|
||||
}
|
||||
case 'Payload Injector':
|
||||
return hand.filter((n) => ['Execute: Memory Dump', 'Execute: Process Clone', 'Execute: Purge', 'Execute: Hard Reset'].includes(n)).length >= 1 ? w * 1.5 : 0;
|
||||
case 'Ghost Process':
|
||||
return hand.some((n) => ['Execute: Kill Process', 'Execute: Override', 'Execute: Sabotage'].includes(n)) &&
|
||||
enemyNear.some((l) => v.locations[l].programs.length) ? 1 : 0;
|
||||
case 'Worm Protocol':
|
||||
return here.some((n) => DEFENSIVE.has(n)) && neighborsMine(v, me, at).some((l) => risky.includes(l)) ? w : 0;
|
||||
default:
|
||||
return DEFENSIVE.has(name) ? w * threat * (locationValue(v, opp, at) / 18) : w * 0.4;
|
||||
}
|
||||
}
|
||||
|
||||
const neighborsMine = (v: GameState, me: PlayerId, at: LocId): LocId[] =>
|
||||
LINES_AT.get(at)!.filter((l) => isOpen(v, l) && controls(v, me, otherEnd(l, at))).map((l) => otherEnd(l, at));
|
||||
|
||||
/** Programs worth installing, best first. */
|
||||
function programPlan(v: GameState, me: PlayerId, budget: number): Action[] {
|
||||
const pl = v.players[me];
|
||||
const risky = threatened(v, me);
|
||||
const mine = locationsFrom(me).filter((l) => controls(v, me, l));
|
||||
const room = new Map(mine.map((l) => [l, programSlots(v, l) - v.locations[l].programs.length]));
|
||||
const picks: { card: number; at: LocId; value: number }[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const card of pl.hand) {
|
||||
const name = cardName(v, card);
|
||||
if (PROGRAM_WEIGHT[name] === undefined || seen.has(name)) continue;
|
||||
seen.add(name);
|
||||
for (const at of mine) {
|
||||
if (room.get(at)! <= 0 || v.locations[at].programs.some((id) => cardName(v, id) === name)) continue;
|
||||
const value = programValue(v, me, name, at, risky);
|
||||
picks.push({ card, at, value: value - programCost(v, me, card, at) * RAM_POINTS * 0.3 });
|
||||
}
|
||||
}
|
||||
picks.sort((a, b) => b.value - a.value);
|
||||
const out: Action[] = [];
|
||||
const used = new Set<number>();
|
||||
for (const p of picks) {
|
||||
if (p.value <= 0.3 || used.has(p.card) || room.get(p.at)! <= 0) continue;
|
||||
const cost = programCost(v, me, p.card, p.at);
|
||||
if (cost > budget) continue;
|
||||
budget -= cost;
|
||||
used.add(p.card);
|
||||
room.set(p.at, room.get(p.at)! - 1);
|
||||
out.push({ type: 'installProgram', card: p.card, at: p.at });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Enemy Programs that make an attack on `target` harder. */
|
||||
const HARD_TARGET = new Set(['Stack Overflow', 'Race Condition', 'Memory Leak', 'Visual Artifact', 'Memory Parasite', 'Stock Rice']);
|
||||
|
||||
/** Step 3: switch off a Program that guards a location I'm about to attack, when it's worth it. */
|
||||
function clearTheWay(v: GameState, me: PlayerId, plan: TurnPlan | null): Action[] {
|
||||
if (plan?.turn !== v.turn) return [];
|
||||
const out: Action[] = [];
|
||||
for (const a of plan.attacks) {
|
||||
if (a.type !== 'attack') continue;
|
||||
const ref = { player: me, slot: a.slot };
|
||||
const origin = [...plan.deploy].reverse().find((d) => d.type === 'place' && d.slot === a.slot);
|
||||
const from = origin?.type === 'place' ? origin.to : avatar(v, ref).at;
|
||||
if (!from) continue;
|
||||
const before = attackOdds(v, ref, from, a.to);
|
||||
let best: { play: Action; gain: number } | null = null;
|
||||
for (const name of ['Execute: Kill Process', 'Execute: Override']) {
|
||||
if (inHand(v, me, name) === undefined) continue;
|
||||
for (const play of executionActions(v, me, 'any')) {
|
||||
if (play.type !== 'play' || cardName(v, play.card) !== name) continue;
|
||||
const prog = play.args.card!;
|
||||
if (programLocation(v, prog) !== a.to || !HARD_TARGET.has(cardName(v, prog))) continue;
|
||||
const after = simulate(v, me, play);
|
||||
if (!after) continue;
|
||||
const gain = attackOdds(after, ref, from, a.to) - before;
|
||||
if (gain > 0.08 && (!best || gain > best.gain)) best = { play, gain };
|
||||
}
|
||||
}
|
||||
if (best) out.push(best.play);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Step 3: extra captures with Trace Route, and cleaning up Avatars before they fight. */
|
||||
function preAttackPlays(v: GameState, me: PlayerId, plan: TurnPlan | null): Action[] {
|
||||
const out: Action[] = [];
|
||||
const planned = new Set(plan?.turn === v.turn ? [...plan.attackers] : []);
|
||||
const trace = inHand(v, me, 'Execute: Trace Route');
|
||||
if (trace !== undefined && spendable(v, me) >= 5) {
|
||||
let best: { a: Action; score: number } | null = null;
|
||||
for (const a of executionActions(v, me, 'any')) {
|
||||
if (a.type !== 'play' || a.card !== trace) continue;
|
||||
const ref = a.args.ref!;
|
||||
const av = avatar(v, ref);
|
||||
const t = a.target!;
|
||||
if (planned.has(ref.slot) || av.advanced || av.attacks > 0 || controls(v, me, t)) continue;
|
||||
// Don't pull a guard off a threatened location.
|
||||
if (threatened(v, me).includes(av.at!) && defendersAt(v, av.at!).length < 2) continue;
|
||||
if (v.declarations.some((d) => d.to === t)) continue;
|
||||
const value = locationValue(v, me, t);
|
||||
const chance = defendersAt(v, t).length ? attackOdds(v, ref, av.at!, t, 1 + executionPower(v, me, a.from)) : 1;
|
||||
const score = chance * value - (1 - chance) * avatarStake(v, ref) - 5 * RAM_POINTS - CARD_POINTS;
|
||||
if (chance >= 0.6 && score > 0 && (!best || score > best.score)) best = { a, score };
|
||||
}
|
||||
if (best) out.push(best.a);
|
||||
}
|
||||
// Clean up Avatars carrying Infection or disabled Hardware.
|
||||
for (const r of refsInPlay(v, me)) {
|
||||
const av = avatar(v, r);
|
||||
const disabled = hardwareOf(v, r).filter((h) => !hardwareActive(v, h));
|
||||
if (av.infection + av.permanentInfection < 2 && disabled.length === 0) continue;
|
||||
const purge = findPlay(v, me, 'Execute: Purge', (a) => (a.args.to ?? a.target) === av.at);
|
||||
if (purge) out.push(purge);
|
||||
else if (disabled.length) {
|
||||
const defrag = findPlay(v, me, 'Execute: Defragment', (a) => a.args.card === disabled[0]);
|
||||
if (defrag) out.push(defrag);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Step 6: card draw, Exfiltrate, Restore Point and Undefined Behavior, when RAM is spare. */
|
||||
function utilityPlays(v: GameState, me: PlayerId, budget: number): Action[] {
|
||||
const out: Action[] = [];
|
||||
const add = (a: Action | null, cost: number) => {
|
||||
if (a && cost <= budget) {
|
||||
out.push(a);
|
||||
budget -= cost;
|
||||
}
|
||||
};
|
||||
add(findPlay(v, me, 'Execute: Memory Dump', (a) => controls(v, me, a.target!)), 4);
|
||||
add(findPlay(v, me, 'Execute: Ping Sweep', () => true), 4);
|
||||
if (v.players[other(me)].hand.length > 0) add(findUse(v, me, 'Data Leaker'), 3);
|
||||
add(findUse(v, me, 'Backup Machine', (a) => {
|
||||
const id = a.args.card!;
|
||||
return hardwareCores(v, id) > 0 || (PROGRAM_WEIGHT[cardName(v, id)] ?? 0) >= 2;
|
||||
}), 5);
|
||||
// Undefined Behavior: copy a strong defensive Program onto its own location.
|
||||
add(findUse(v, me, 'Undefined Behavior', (a) =>
|
||||
['Stack Overflow', 'Race Condition', 'Memory Leak'].includes(cardName(v, a.args.card!))), 0);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Firewalls around undefended threatened locations whose every enemy line has a gateway. */
|
||||
function firewallPlan(v: GameState, me: PlayerId, params: GreedyParams, budget: number): Action[] {
|
||||
if (params.firewallLevel <= 0) return [];
|
||||
const pl = v.players[me];
|
||||
const opp = other(me);
|
||||
const out: Action[] = [];
|
||||
const cost = firewallCost(v, params.firewallLevel);
|
||||
let left = params.maxFirewallsPerTurn;
|
||||
for (const loc of threatened(v, me)) {
|
||||
if (pl.avatars.some((a) => a.at === loc)) continue;
|
||||
const exposed = LINES_AT.get(loc)!.filter((l) => isOpen(v, l) && controls(v, opp, otherEnd(l, loc)));
|
||||
// A location reachable along a gateway-free line can't be walled off.
|
||||
if (exposed.some((l) => !l.gateway) || exposed.length > left) continue;
|
||||
if (budget - cost * exposed.length < params.ramReserve) break;
|
||||
for (const line of exposed) out.push({ type: 'firewall', line: line.id, level: params.firewallLevel });
|
||||
budget -= cost * exposed.length;
|
||||
left -= exposed.length;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** RAM to keep for the opponent's turn: enough for the best trick held. */
|
||||
function heldReserve(v: GameState, me: PlayerId, params: GreedyParams): number {
|
||||
if (!params.useCards) return 0;
|
||||
const held = v.players[me].hand.filter((id) => HELD.has(cardName(v, id))).map((id) => printedRam(v, id));
|
||||
return Math.max(0, ...held);
|
||||
}
|
||||
|
||||
const totalCost = (v: GameState, list: Action[]) => list.reduce((t, a) => t + actionCost(v, a), 0);
|
||||
|
||||
function planPlay(v: GameState, me: PlayerId, params: GreedyParams, plan: TurnPlan | null): Action[] {
|
||||
const budget = spendable(v, me);
|
||||
const attackers = v.step === 'play' && plan?.turn === v.turn ? plan.attackers : new Set<number>();
|
||||
if (v.step === 'play') {
|
||||
const early = params.useCards ? [...clearTheWay(v, me, plan), ...preAttackPlays(v, me, plan)] : [];
|
||||
return [...early, ...hardwarePlan(v, me, attackers, budget - totalCost(v, early), params.useCards)];
|
||||
}
|
||||
const keep = heldReserve(v, me, params);
|
||||
const hw = hardwarePlan(v, me, attackers, budget - keep, params.useCards);
|
||||
let left = budget - keep - totalCost(v, hw);
|
||||
const progs = params.useCards ? programPlan(v, me, left - params.ramReserve) : [];
|
||||
left -= totalCost(v, progs);
|
||||
const walls = firewallPlan(v, me, params, left);
|
||||
left -= totalCost(v, walls);
|
||||
const extra = params.useCards ? utilityPlays(v, me, left - params.ramReserve) : [];
|
||||
return [...hw, ...progs, ...walls, ...extra];
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Responding
|
||||
|
||||
/** Plays out an Execution or Ability on a copy of the view, to see what it would do. */
|
||||
function simulate(v: GameState, me: PlayerId, a: Action): GameState | null {
|
||||
// Copy only what card effects change; card definitions and rules are shared read-only.
|
||||
const c: GameState = {
|
||||
...v,
|
||||
players: structuredClone(v.players),
|
||||
locations: structuredClone(v.locations),
|
||||
cards: v.cards.map((x) => ({ ...x })),
|
||||
firewalls: { ...v.firewalls },
|
||||
declarations: [...v.declarations],
|
||||
tasks: [...v.tasks],
|
||||
stack: [...v.stack],
|
||||
combat: v.combat && structuredClone(v.combat),
|
||||
virtuals: v.virtuals.map((x) => ({ ...x })),
|
||||
used: { ...v.used },
|
||||
stats: Object.fromEntries(Object.entries(v.stats).map(([k, x]) => [k, [...x]])) as GameState['stats'],
|
||||
cardUse: {},
|
||||
log: null,
|
||||
};
|
||||
try {
|
||||
if (a.type === 'play') {
|
||||
const name = cardName(c, a.card);
|
||||
removeFrom(c.players[me].hand, a.card);
|
||||
const item: StackItem = {
|
||||
kind: 'execution', player: me, card: a.card, name, target: a.target, args: a.args, from: a.from, power: executionPower(c, me, a.from),
|
||||
};
|
||||
scriptOf(name)!.execution!.resolve(c, item);
|
||||
} else if (a.type === 'activate') {
|
||||
const src = abilitySource(c, a.card, a.name);
|
||||
if (!src) return null;
|
||||
const item: StackItem = { kind: 'ability', player: me, card: a.card, name: a.name, target: null, args: a.args, from: null, power: 0 };
|
||||
scriptOf(src.name)!.ability!.resolve(c, item, src);
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
c.choice = null;
|
||||
return c;
|
||||
}
|
||||
|
||||
/** Whether a candidate touches the current combat at all, to skip pointless simulations. */
|
||||
function touchesCombat(v: GameState, a: Action): boolean {
|
||||
const c = v.combat!;
|
||||
const near = [c.loc, c.origin];
|
||||
if (a.type === 'activate') return COMBAT_TRICKS.has(a.name);
|
||||
if (a.type !== 'play' || !COMBAT_TRICKS.has(cardName(v, a.card))) return false;
|
||||
if (a.args.ref) return true;
|
||||
if (a.args.card !== undefined) {
|
||||
const loc = programLocation(v, a.args.card);
|
||||
return loc ? near.includes(loc) : true;
|
||||
}
|
||||
return near.includes(a.target!) || near.includes(a.args.to ?? '');
|
||||
}
|
||||
|
||||
/** The best combat trick for `me` once the dice are down, if one is worth its cost. */
|
||||
function combatTrick(v: GameState, me: PlayerId): Action | null {
|
||||
const c = v.combat!;
|
||||
if (!c.rolled) return null;
|
||||
const base = combatValue(v, me);
|
||||
const price = (a: Action) => actionCost(v, a) * RAM_POINTS +
|
||||
(a.type === 'play' || (a.type === 'activate' && a.name === 'Beta Version 1.0') ? CARD_POINTS : 0);
|
||||
let best: Action | null = null;
|
||||
let bestGain = 0.25;
|
||||
const consider = (a: Action, value: number) => {
|
||||
const gain = value - base - price(a);
|
||||
if (gain > bestGain) {
|
||||
best = a;
|
||||
bestGain = gain;
|
||||
}
|
||||
};
|
||||
for (const a of [...executionActions(v, me, 'reachable'), ...abilityActions(v, me, 'reachable')]) {
|
||||
if (!touchesCombat(v, a)) continue;
|
||||
if (a.type === 'activate' && a.name === 'Broken Bits') {
|
||||
const ref = refsInPlay(v, me).find((r) => avatar(v, r).card === a.card && !isCopy(r))!;
|
||||
const pAtk = combatOdds(v, { ref, k: a.args.k! });
|
||||
const s = stakes(v, me);
|
||||
const p = c.attacker.player === me ? pAtk : 1 - pAtk;
|
||||
consider(a, p * s.win + (1 - p) * s.lose);
|
||||
continue;
|
||||
}
|
||||
const after = simulate(v, me, a);
|
||||
if (after) consider(a, combatValue(after, me) + (a.type === 'play' ? fromValue(v, me, a.from) * 0.1 : 0));
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** Outside combat: try to stop the opponent's newest advance or attack on one of my locations. */
|
||||
function stopDeclaration(v: GameState, me: PlayerId): Action | null {
|
||||
const d = v.declarations[v.declarations.length - 1];
|
||||
if (!d || d.ref.player === me || !controls(v, me, d.to)) return null;
|
||||
const at = avatar(v, d.ref).at;
|
||||
if (at === null) return null;
|
||||
const defended = defendersAt(v, d.to).length > 0;
|
||||
const risk = defended ? attackOdds(v, d.ref, d.from, d.to) : 1;
|
||||
const stake = risk * locationValue(v, d.ref.player, d.to);
|
||||
// Root the Avatar that declared, so it can't move.
|
||||
const flood = findPlay(v, me, 'Execute: Packet Flood', (a) => (a.args.to ?? a.target) === at);
|
||||
if (flood && stake > 5 * RAM_POINTS + CARD_POINTS + 2) return flood;
|
||||
if (defended) return null;
|
||||
// Put a copy in the way.
|
||||
const copy = findUse(v, me, 'Backup Server', (a) => a.args.to === d.to) ??
|
||||
(reach(v, me) >= 5 ? findUse(v, me, 'Carbon NanoBots', (a) => a.args.to === d.to) : null);
|
||||
if (copy) return copy;
|
||||
// Or cash in the Programs there before they're lost.
|
||||
const progs = v.locations[d.to].programs;
|
||||
if (progs.length === 0) return null;
|
||||
const top = Math.max(...progs.map((p) => printedRam(v, p)));
|
||||
const gc = findUse(v, me, 'Garbage Collection', (a) => programLocation(v, a.args.card!) === d.to && printedRam(v, a.args.card!) === top);
|
||||
if (gc) return gc;
|
||||
const reset = findPlay(v, me, 'Execute: Hard Reset', (a) => a.target === d.to && a.args.cards!.length === progs.length);
|
||||
return reset && progs.reduce((t, p) => t + printedRam(v, p), 0) >= 8 ? reset : null;
|
||||
}
|
||||
|
||||
/** Sends back an expensive enemy Program or Hardware installed this turn. */
|
||||
function rollbackInstall(v: GameState, me: PlayerId): Action | null {
|
||||
return findPlay(v, me, 'Execute: Rollback', (a) => v.cards[a.args.card!].owner !== me && printedRam(v, a.args.card!) >= 7);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Choices
|
||||
|
||||
function choose(v: GameState, me: PlayerId, ch: Choice): number {
|
||||
const opts = ch.options;
|
||||
const val = (i: number) => opts[i].value;
|
||||
const best = (score: (i: number) => number) => {
|
||||
let b = 0;
|
||||
for (let i = 1; i < opts.length; i++) if (score(i) > score(b)) b = i;
|
||||
return b;
|
||||
};
|
||||
const cardVal = (id: number) => keepScore(v, id) + printedRam(v, id) * 0.2;
|
||||
const yesIfAffordable = (yes: unknown) => {
|
||||
const i = opts.findIndex((o) => o.value === yes);
|
||||
return i >= 0 && (opts[i].cost ?? 0) <= v.players[me].ram ? i : opts.findIndex((o) => o.value !== yes);
|
||||
};
|
||||
switch (ch.kind) {
|
||||
case 'Callable Server:redraw': {
|
||||
const card = v.players[me].hand[v.players[me].hand.length - 1];
|
||||
return opts.findIndex((o) => o.value === (keepScore(v, card) < 2));
|
||||
}
|
||||
case 'Diagnostic Module:bottom': {
|
||||
const weak = opts.some((o) => /Network Interface|Root Access|Execute: Rollback|Ping Sweep/.test(o.label));
|
||||
return opts.findIndex((o) => o.value === weak);
|
||||
}
|
||||
case 'Duplicate Server:copy': {
|
||||
const rank = ['Cloud Compute', 'Server Farm', 'MultiCore Server', 'High Efficiency RAM Server', 'Power Server',
|
||||
'Cluster Server', 'Pingable Server', 'Backup Server', 'Protected Server'];
|
||||
return best((i) => -((rank.indexOf(String(val(i))) + 1) || 99));
|
||||
}
|
||||
case 'Memory Parasite:disable':
|
||||
case 'Overclocked CPU:disable':
|
||||
return best((i) => -(hardwareCores(v, val(i) as number) * 10 + cardVal(val(i) as number)));
|
||||
case 'Replication Routine:install':
|
||||
return best((i) => (val(i) === null ? 0.5 : PROGRAM_WEIGHT[cardName(v, val(i) as number)] ?? 1));
|
||||
case 'Worm Protocol:spread': {
|
||||
const risky = threatened(v, me);
|
||||
return best((i) => (risky.includes(val(i) as string) ? 2 : controls(v, me, val(i) as string) ? 1 : 0));
|
||||
}
|
||||
case 'Race Condition:pick':
|
||||
return (v.seq + v.turn + me) % 2;
|
||||
case 'Overflow Error:hit':
|
||||
return best((i) => {
|
||||
const x = val(i) as { card: number; mode: string };
|
||||
return printedRam(v, x.card) + (x.mode === 'destroy' ? 0.5 : 0);
|
||||
});
|
||||
case 'Error Correction:remove':
|
||||
return best((i) => {
|
||||
const x = String(val(i));
|
||||
if (x.startsWith('hw:')) return 4 + hardwareCores(v, Number(x.slice(3)));
|
||||
return x === 'permanent' ? 3 : x === 'infection' ? 2 : 1;
|
||||
});
|
||||
case 'Version Control:save':
|
||||
case 'Hardware Sandbox:protect':
|
||||
return best((i) => printedRam(v, val(i) as number) + (PROGRAM_WEIGHT[cardName(v, val(i) as number)] ?? 0));
|
||||
case 'RAID Array:keep':
|
||||
return yesIfAffordable(true);
|
||||
case 'Backup Machine:install':
|
||||
return yesIfAffordable(true);
|
||||
case 'Quantum Coprocessor:copy':
|
||||
case 'False Positive:redirect':
|
||||
return opts.length > 1 ? 1 : 0;
|
||||
case 'Execute: Memory Dump:discard':
|
||||
return best((i) => -cardVal(val(i) as number));
|
||||
case 'Data Leaker:discard':
|
||||
return best((i) => printedRam(v, val(i) as number));
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Plans each turn up front: grabs the best open locations, attacks when the odds clear
|
||||
* `minWinChance`, guards threatened locations, installs Hardware and Programs, and walls off
|
||||
* undefended locations. On the opponent's turn it answers with combat tricks after the roll and
|
||||
* tries to stop advances into its locations.
|
||||
*/
|
||||
export function greedyBot(params: GreedyParams = DEFAULT_GREEDY): Bot {
|
||||
let plan: TurnPlan | null = null;
|
||||
let queueFor = '';
|
||||
let queue: Action[] = [];
|
||||
let copiedTurn = -1;
|
||||
/** Responses already tried in this window, so one that can't be paid for isn't retried forever. */
|
||||
let tried = new Set<string>();
|
||||
let triedFor = '';
|
||||
|
||||
/** The next action toward `a`: a Salvage to afford it, or `a` itself. Null if it can't happen. */
|
||||
function toward(v: GameState, me: PlayerId, a: Action, legal: Map<string, Action>): Action | null {
|
||||
const cost = actionCost(v, a);
|
||||
if (cost > v.players[me].ram) return salvageFor(v, me, cost, spentCard(a));
|
||||
return legal.get(actionKey(a)) ?? null;
|
||||
}
|
||||
|
||||
return {
|
||||
name: params.useCards ? 'greedy' : 'greedy-nocards',
|
||||
choose(v, actions, me) {
|
||||
const legal = new Map(actions.map((a) => [actionKey(a), a]));
|
||||
|
||||
if (v.choice) {
|
||||
const pick = legal.get(`choose:${choose(v, me, v.choice)}`);
|
||||
return pick ?? actions.find((a) => a.type === 'choose') ?? actions[0];
|
||||
}
|
||||
|
||||
const w = openWindow(v);
|
||||
if (w) {
|
||||
if (!params.useCards) return { type: 'pass' };
|
||||
const key = `${v.turn}:${w.kind}:${v.stack.length}:${v.combat?.id ?? 0}:${v.combat?.ties ?? 0}`;
|
||||
if (key !== triedFor) {
|
||||
triedFor = key;
|
||||
tried = new Set();
|
||||
}
|
||||
let want: Action | null = null;
|
||||
if (v.combat && !v.combat.ended) {
|
||||
if (w.kind === 'postRoll') want = combatTrick(v, me);
|
||||
} else if (w.kind === 'response' && v.active !== me && v.stack.length === 0) {
|
||||
want = stopDeclaration(v, me) ?? rollbackInstall(v, me);
|
||||
}
|
||||
if (want && !tried.has(actionKey(want))) {
|
||||
const next = toward(v, me, want, legal);
|
||||
if (next) {
|
||||
if (next.type !== 'salvage') tried.add(actionKey(want));
|
||||
return next;
|
||||
}
|
||||
tried.add(actionKey(want));
|
||||
}
|
||||
return { type: 'pass' };
|
||||
}
|
||||
|
||||
const stepKey = `${v.turn}:${v.step}`;
|
||||
if (stepKey !== queueFor) {
|
||||
if (v.step === 'deploy' && params.useCards && copiedTurn !== v.turn) {
|
||||
copiedTurn = v.turn;
|
||||
const copy = copyAction(v, me);
|
||||
const next = copy && toward(v, me, copy, legal);
|
||||
if (next) {
|
||||
if (next.type === 'salvage') copiedTurn = -1;
|
||||
return next;
|
||||
}
|
||||
}
|
||||
queueFor = stepKey;
|
||||
if (v.step === 'deploy') {
|
||||
plan = planTurn(v, me, params);
|
||||
queue = [...plan.deploy];
|
||||
} else if (v.step === 'attack') {
|
||||
queue = plan?.turn === v.turn ? [...plan.attacks] : [];
|
||||
} else {
|
||||
queue = planPlay(v, me, params, plan);
|
||||
}
|
||||
}
|
||||
while (queue.length > 0) {
|
||||
const next = queue[0];
|
||||
const cost = actionCost(v, next);
|
||||
if (cost > v.players[me].ram) {
|
||||
const salvage = salvageFor(v, me, cost, spentCard(next));
|
||||
if (salvage) return salvage;
|
||||
queue.shift();
|
||||
continue;
|
||||
}
|
||||
queue.shift();
|
||||
const action = legal.get(actionKey(next));
|
||||
if (action) return action;
|
||||
}
|
||||
return { type: 'end' };
|
||||
},
|
||||
};
|
||||
}
|
||||
21
sim/src/bots/random.ts
Normal file
21
sim/src/bots/random.ts
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import { makeRng, nextFloat, pick } from '../rng.ts';
|
||||
import type { Bot } from './bot.ts';
|
||||
|
||||
/**
|
||||
* Baseline: ends the step or passes 30% of the time, otherwise picks any legal action. Choices
|
||||
* are picked at random too.
|
||||
*/
|
||||
export function randomBot(seed: number): Bot {
|
||||
const rng = makeRng(seed);
|
||||
return {
|
||||
name: 'random',
|
||||
choose(_view, actions) {
|
||||
const stop = actions.find((a) => a.type === 'end' || a.type === 'pass');
|
||||
const others = actions.filter((a) => a.type !== 'end' && a.type !== 'pass');
|
||||
if (others.length === 0) return stop ?? actions[0];
|
||||
if (stop && nextFloat(rng) < 0.3) return stop;
|
||||
const choices = others.filter((a) => a.type === 'choose');
|
||||
return pick(rng, choices.length && nextFloat(rng) < 0.8 ? choices : others);
|
||||
},
|
||||
};
|
||||
}
|
||||
69
sim/src/cards.ts
Normal file
69
sim/src/cards.ts
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
import { readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { parseCsvObjects } from './csv.ts';
|
||||
|
||||
export type CardKind = 'avatar' | 'server' | 'program' | 'hardware' | 'execution';
|
||||
|
||||
export interface CardDef {
|
||||
name: string;
|
||||
kind: CardKind;
|
||||
/** Printed RAM: play cost and salvage value. Avatars and Servers print none. */
|
||||
ram: number;
|
||||
cores: number;
|
||||
/** Expansion Slots (Hardware ports). */
|
||||
slots: number;
|
||||
/** V / B / G / P, when printed. */
|
||||
type: string;
|
||||
/** Card text; flavor text for Avatars. */
|
||||
text: string;
|
||||
ability?: { name: string; cost: number; text: string };
|
||||
}
|
||||
|
||||
export interface CardPool {
|
||||
all: CardDef[];
|
||||
byName: Map<string, CardDef>;
|
||||
}
|
||||
|
||||
const KIND_BY_TEMPLATE: Record<string, CardKind> = {
|
||||
'Avatar Front': 'avatar',
|
||||
'Server Front': 'server',
|
||||
'Program Front': 'program',
|
||||
'Hardware Front': 'hardware',
|
||||
'Execution Front': 'execution',
|
||||
};
|
||||
|
||||
export const DEFAULT_CARDS_CSV = fileURLToPath(
|
||||
new URL('../../decks/files-deck-1/cards.csv', import.meta.url),
|
||||
);
|
||||
|
||||
const num = (s: string | undefined): number => (s ? Number(s) : 0);
|
||||
|
||||
/** Loads the Cider deck CSV. Reference cards (Turn Sequence) are skipped. */
|
||||
export function loadCards(path = DEFAULT_CARDS_CSV): CardPool {
|
||||
const all: CardDef[] = [];
|
||||
const byName = new Map<string, CardDef>();
|
||||
for (const row of parseCsvObjects(readFileSync(path, 'utf8'))) {
|
||||
const kind = KIND_BY_TEMPLATE[row['Front Template']];
|
||||
if (!kind) continue;
|
||||
const card: CardDef = {
|
||||
name: row['Name'],
|
||||
kind,
|
||||
ram: num(row['RAM']),
|
||||
cores: num(row['Cores']),
|
||||
slots: num(row['Expansion Slots']),
|
||||
type: row['Type'],
|
||||
text: row['Description'],
|
||||
};
|
||||
if (row['Ability Name']) {
|
||||
card.ability = {
|
||||
name: row['Ability Name'],
|
||||
cost: num(row['Ability Cost']),
|
||||
text: row['Ability Description'],
|
||||
};
|
||||
}
|
||||
if (byName.has(card.name)) throw new Error(`Duplicate card name in ${path}: ${card.name}`);
|
||||
all.push(card);
|
||||
byName.set(card.name, card);
|
||||
}
|
||||
return { all, byName };
|
||||
}
|
||||
217
sim/src/cards/avatars.ts
Normal file
217
sim/src/cards/avatars.ts
Normal file
|
|
@ -0,0 +1,217 @@
|
|||
/**
|
||||
* Avatar Abilities. Each costs the RAM printed on the card, can be used once per turn at
|
||||
* Execution timing, and only while the Avatar is in play. For Abilities, "a combat at this
|
||||
* Server" means any combat the Avatar is fighting in, attacking or defending.
|
||||
*/
|
||||
import { createCopy, drawCards } from '../flow.ts';
|
||||
import { LOCATIONS } from '../map.ts';
|
||||
import { costOf, hardwareActive, hasRoom, portsFree } from '../query.ts';
|
||||
import type { Script } from '../scripts.ts';
|
||||
import {
|
||||
addMod,
|
||||
ask,
|
||||
avatar,
|
||||
avatarName,
|
||||
copyOf,
|
||||
defOf,
|
||||
endOf,
|
||||
fired,
|
||||
hardwareOf,
|
||||
inCombat,
|
||||
infectionOf,
|
||||
nameOf,
|
||||
nextTurnOf,
|
||||
opponentsInCombat,
|
||||
other,
|
||||
playerName,
|
||||
refKey,
|
||||
removeFrom,
|
||||
rollDie,
|
||||
say,
|
||||
toDiscard,
|
||||
toHand,
|
||||
} from '../state.ts';
|
||||
import type { AvatarRef, GameState } from '../types.ts';
|
||||
import { attachHardware } from './hardware.ts';
|
||||
import { cardOptions } from './util.ts';
|
||||
|
||||
/** Hardware cost after discounts (Upgraded Hardware), for Abilities that install Hardware. */
|
||||
const installCost = (s: GameState, card: number, ref: AvatarRef) =>
|
||||
costOf(s, { kind: 'hardware', player: ref.player, card, ref, at: avatar(s, ref).at });
|
||||
|
||||
export const AVATARS: Record<string, Script> = {
|
||||
// The copy has the same Cores and uses the original's Hardware bonuses, but no Hardware or
|
||||
// Ability of its own. It enters play on a location you control with room.
|
||||
'Carbon NanoBots': {
|
||||
text: 'Avatar may create a copy of itself. Only one copy is allowed at a time. If the copy is defeated the original does not lose any hardware upgrades. If the original is defeated the replicate is as well.',
|
||||
ability: {
|
||||
uses(s, src) {
|
||||
if (avatar(s, copyOf(src.ref!)).at !== null) return [];
|
||||
return LOCATIONS.filter((l) => hasRoom(s, src.controller, l)).map((to) => ({ to }));
|
||||
},
|
||||
resolve(s, item, src) {
|
||||
const to = item.args.to!;
|
||||
if (avatar(s, copyOf(src.ref!)).at !== null || !hasRoom(s, src.controller, to)) return;
|
||||
fired(s, 'Carbon NanoBots', src.controller);
|
||||
createCopy(s, src.ref!, to);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
'Corrupt Driver': {
|
||||
text: 'Choose one Hardware on an enemy Avatar in combat with this Avatar. It is disabled until the end of your next turn.',
|
||||
ability: {
|
||||
uses: (s, src) =>
|
||||
[...new Set(opponentsInCombat(s, src.ref!).flatMap((r) => hardwareOf(s, r)))]
|
||||
.filter((hw) => hardwareActive(s, hw))
|
||||
.map((card) => ({ card })),
|
||||
resolve(s, item, src) {
|
||||
const hw = item.args.card!;
|
||||
s.cards[hw].disabledUntil = Math.max(s.cards[hw].disabledUntil, endOf(nextTurnOf(s, src.controller)));
|
||||
fired(s, 'Corrupt Driver', src.controller);
|
||||
say(s, `Driver Fault disables ${nameOf(s, hw)} until the end of ${playerName(src.controller)}'s next turn.`);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
'Pixelated Picture': {
|
||||
text: 'Attacking Avatars have -1 cores against this Avatar.',
|
||||
ability: {
|
||||
uses: (s, src) => (inCombat(s, src.ref!) && s.combat!.defenders.some((d) => refKey(d) === refKey(src.ref!)) ? [{}] : []),
|
||||
resolve(s, _item, src) {
|
||||
const c = s.combat;
|
||||
if (!c || c.ended) return;
|
||||
addMod(s, c.attacker, -1, 'Low Resolution', src.controller, { combat: c.id });
|
||||
fired(s, 'Pixelated Picture', src.controller);
|
||||
say(s, `Low Resolution: ${avatarName(s, c.attacker)} gets -1 Core.`);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
// Reading: during a combat it's in, install one Hardware from hand on it (paying its cost),
|
||||
// ignoring ports. That Hardware is discarded at the end of your turn.
|
||||
'Beta Version 1.0': {
|
||||
text: 'While in combat an additional piece of hardware can be placed on this avatar until the end of your turn. If there no ports available this can still be attached.',
|
||||
ability: {
|
||||
uses: (s, src) =>
|
||||
inCombat(s, src.ref!)
|
||||
? cardOptions(s, s.players[src.controller].hand.filter((id) => defOf(s, id).kind === 'hardware')).map((o) => ({ card: o.value as number }))
|
||||
: [],
|
||||
extraCost: (s, src, args) => installCost(s, args.card!, src.ref!),
|
||||
resolve(s, item, src) {
|
||||
const card = item.args.card!;
|
||||
if (!s.players[src.controller].hand.includes(card) || !inCombat(s, src.ref!)) return;
|
||||
attachHardware(s, card, src.ref!);
|
||||
const turn = s.active === src.controller ? s.turn : nextTurnOf(s, src.controller);
|
||||
s.cards[card].pushedUntil = endOf(turn);
|
||||
fired(s, 'Beta Version 1.0', src.controller);
|
||||
say(s, `Push Update attaches ${nameOf(s, card)} to ${avatarName(s, src.ref!)} until the end of ${playerName(src.controller)}'s turn.`);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
'Code Zero': {
|
||||
text: 'Place an Infection counter on every enemy Avatar in combat at this Server. While this Avatar is in play, an Avatar with 2+ Infection counters has -1 Core.',
|
||||
globalCores: (s, f) => (infectionOf(avatar(s, f.ref)) >= 2 ? -1 : 0),
|
||||
ability: {
|
||||
uses: (s, src) => (opponentsInCombat(s, src.ref!).length ? [{}] : []),
|
||||
resolve(s, _item, src) {
|
||||
const foes = opponentsInCombat(s, src.ref!);
|
||||
for (const r of foes) avatar(s, r).infection++;
|
||||
fired(s, 'Code Zero', src.controller);
|
||||
say(s, `Patient Zero infects ${foes.map((r) => `${avatarName(s, r)} (${infectionOf(avatar(s, r))})`).join(', ')}.`);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
// "Breached a Server" = captured an enemy location this turn.
|
||||
'Data Leaker': {
|
||||
text: "Look at your opponent's hand and choose one card in it. They must discard that card without gaining RAM. If this Avatar breached a Server this turn, draw a card.",
|
||||
ability: {
|
||||
uses: (s, src) => (s.players[other(src.controller)].hand.length ? [{}] : []),
|
||||
resolve(s, _item, src) {
|
||||
const hand = s.players[other(src.controller)].hand;
|
||||
if (hand.length === 0) return;
|
||||
fired(s, 'Data Leaker', src.controller);
|
||||
ask(s, {
|
||||
player: src.controller,
|
||||
kind: 'Data Leaker:discard',
|
||||
prompt: "Exfiltrate: choose a card from your opponent's hand for them to discard.",
|
||||
options: cardOptions(s, hand),
|
||||
resume: { name: 'Data Leaker', fn: 'discard', data: { ref: src.ref! as never } },
|
||||
});
|
||||
},
|
||||
},
|
||||
resume: {
|
||||
discard(s, data: { ref: AvatarRef }, card: number) {
|
||||
const p = data.ref.player;
|
||||
if (removeFrom(s.players[other(p)].hand, card)) {
|
||||
toDiscard(s, card);
|
||||
say(s, `Exfiltrate: ${playerName(other(p))} discards ${nameOf(s, card)}.`);
|
||||
}
|
||||
if (avatar(s, data.ref).breachedTurn === s.turn) drawCards(s, p, 1);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
'Backup Machine': {
|
||||
text: 'Return one Hardware or Program from your discard pile to your hand. If it is a Hardware and this Avatar has an open port, you may install it immediately for 2 less RAM.',
|
||||
ability: {
|
||||
uses: (s, src) =>
|
||||
cardOptions(s, s.players[src.controller].discard.filter((id) => ['hardware', 'program'].includes(defOf(s, id).kind)))
|
||||
.map((o) => ({ card: o.value as number })),
|
||||
resolve(s, item, src) {
|
||||
const card = item.args.card!;
|
||||
const p = src.controller;
|
||||
if (!removeFrom(s.players[p].discard, card)) return;
|
||||
toHand(s, card);
|
||||
fired(s, 'Backup Machine', p);
|
||||
say(s, `Restore Point returns ${nameOf(s, card)} to ${playerName(p)}'s hand.`);
|
||||
if (defOf(s, card).kind !== 'hardware' || portsFree(s, src.ref!) <= 0) return;
|
||||
const cost = Math.max(0, installCost(s, card, src.ref!) - 2);
|
||||
ask(s, {
|
||||
player: p,
|
||||
kind: 'Backup Machine:install',
|
||||
prompt: `Restore Point: install ${nameOf(s, card)} on ${avatarName(s, src.ref!)} now for ${cost} RAM?`,
|
||||
options: [
|
||||
{ label: 'Keep it in hand', value: false },
|
||||
{ label: `Install it for ${cost} RAM`, value: true, cost },
|
||||
],
|
||||
resume: { name: 'Backup Machine', fn: 'install', data: { card, ref: src.ref! as never, cost } },
|
||||
});
|
||||
},
|
||||
},
|
||||
resume: {
|
||||
install(s, data: { card: number; ref: AvatarRef; cost: number }, yes: boolean) {
|
||||
if (!yes || avatar(s, data.ref).at === null || !s.players[data.ref.player].hand.includes(data.card)) return;
|
||||
s.players[data.ref.player].ram -= data.cost;
|
||||
s.stats.ramOnCards[data.ref.player] += data.cost;
|
||||
attachHardware(s, data.card, data.ref);
|
||||
say(s, `${nameOf(s, data.card)} is installed on ${avatarName(s, data.ref)}.`);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
// Rerolls this Avatar's dice showing k or less; that's always the best way to pick dice.
|
||||
'Broken Bits': {
|
||||
text: "During a combat at this Server, reroll any number of this Avatar's Core dice.",
|
||||
ability: {
|
||||
uses(s, src) {
|
||||
const c = s.combat;
|
||||
if (!c || c.ended || !c.rolled || !inCombat(s, src.ref!)) return [];
|
||||
const dice = c.dice[refKey(src.ref!)] ?? [];
|
||||
const ks = [...new Set(dice)].filter((v) => v < 6).sort((a, b) => a - b);
|
||||
return ks.map((k) => ({ k }));
|
||||
},
|
||||
resolve(s, item, src) {
|
||||
const c = s.combat;
|
||||
if (!c || c.ended || !c.rolled) return;
|
||||
const key = refKey(src.ref!);
|
||||
const before = [...(c.dice[key] ?? [])];
|
||||
c.dice[key] = before.map((v) => (v <= item.args.k! ? rollDie(s) : v));
|
||||
fired(s, 'Broken Bits', src.controller);
|
||||
say(s, `Bit Flip rerolls ${before.filter((v) => v <= item.args.k!).length} dice: [${before.join(',')}] → [${c.dice[key].join(',')}].`);
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
481
sim/src/cards/executions.ts
Normal file
481
sim/src/cards/executions.ts
Normal file
|
|
@ -0,0 +1,481 @@
|
|||
/**
|
||||
* Executions. Each targets a location (the "target Server") and resolves there, then goes to the
|
||||
* discard pile. Ghost Process lets its controller's Executions reach one adjacent location too.
|
||||
*/
|
||||
import { dropFromCombat, endCombat, moveAvatar } from '../flow.ts';
|
||||
import { LOCATIONS, isStart } from '../map.ts';
|
||||
import { canTargetProgram, emit, hardwareActive, hasRoom, programActive } from '../query.ts';
|
||||
import type { Play, Script } from '../scripts.ts';
|
||||
import {
|
||||
activeMods,
|
||||
addMod,
|
||||
adjacent,
|
||||
ask,
|
||||
avatar,
|
||||
avatarName,
|
||||
avatarsAt,
|
||||
canAct,
|
||||
controls,
|
||||
defendersAt,
|
||||
endOfTurn,
|
||||
fightersOf,
|
||||
fired,
|
||||
gainRam,
|
||||
hardwareOf,
|
||||
inCombat,
|
||||
later,
|
||||
markUsed,
|
||||
nameOf,
|
||||
neighbors,
|
||||
nextTurnOf,
|
||||
ownerOf,
|
||||
playerName,
|
||||
programLocation,
|
||||
pushCapture,
|
||||
pushTasks,
|
||||
refKey,
|
||||
refsInPlay,
|
||||
removeFrom,
|
||||
running,
|
||||
say,
|
||||
startCombat,
|
||||
startOf,
|
||||
stat,
|
||||
toDiscard,
|
||||
toHand,
|
||||
uninstallHardware,
|
||||
uninstallProgram,
|
||||
wearerOf,
|
||||
} from '../state.ts';
|
||||
import { FOREVER, type AvatarRef, type GameState, type PlayerId, type Task } from '../types.ts';
|
||||
import { cardOptions, ghostsOf, mine, programsOn, scopeOf, subsets } from './util.ts';
|
||||
|
||||
const liveCombat = (s: GameState) => (s.combat && !s.combat.ended ? s.combat : null);
|
||||
|
||||
/** Unique Avatar refs. */
|
||||
function uniq(refs: AvatarRef[]): AvatarRef[] {
|
||||
const seen = new Set<string>();
|
||||
return refs.filter((r) => !seen.has(refKey(r)) && !!seen.add(refKey(r)));
|
||||
}
|
||||
|
||||
/** Plays for every target whose reach includes a location, with the args that location allows. */
|
||||
function acrossScope(s: GameState, p: PlayerId, argsAt: (loc: string) => Play['args'][]): Play[] {
|
||||
const out: Play[] = [];
|
||||
const ghosts = ghostsOf(s, p);
|
||||
const at = new Map<string, Play['args'][]>();
|
||||
for (const target of LOCATIONS) {
|
||||
for (const loc of scopeOf(s, p, target, ghosts)) {
|
||||
if (!at.has(loc)) at.set(loc, argsAt(loc));
|
||||
for (const args of at.get(loc)!) out.push({ target, args });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const wearerList = (s: GameState, hw: number | undefined): AvatarRef[] => {
|
||||
const r = hw === undefined ? null : wearerOf(s, hw);
|
||||
return r ? [r] : [];
|
||||
};
|
||||
|
||||
export const EXECUTIONS: Record<string, Script> = {
|
||||
// Reading: the Avatar moves to a location you control with room. An attacker "at" the target
|
||||
// (attacking it) can retreat back to where it stands.
|
||||
'Execute: Disconnect': {
|
||||
text: 'Move one Avatar you control at the target Server to an adjacent Server, removing it from any combat there.',
|
||||
execution: {
|
||||
plays: (s, p) =>
|
||||
acrossScope(s, p, (loc) =>
|
||||
mine(s, p, loc)
|
||||
.filter((ref) => canAct(s, ref))
|
||||
.flatMap((ref) => {
|
||||
const at = avatar(s, ref).at!;
|
||||
const dests = neighbors(s, loc).filter((d) => d !== at && hasRoom(s, p, d));
|
||||
if (inCombat(s, ref) && at !== loc) dests.push(at);
|
||||
return dests.map((to) => ({ ref, to }));
|
||||
})),
|
||||
targetsAvatars: (_s, item) => (item.args.ref ? [item.args.ref] : []),
|
||||
resolve(s, item) {
|
||||
const { ref, to } = item.args as { ref: AvatarRef; to: string };
|
||||
const av = avatar(s, ref);
|
||||
if (av.at === null || !canAct(s, ref) || (to !== av.at && !hasRoom(s, ref.player, to))) return;
|
||||
fired(s, item.name, item.player);
|
||||
if (inCombat(s, ref)) dropFromCombat(s, ref);
|
||||
if (to !== av.at) moveAvatar(s, ref, to);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
// Reading: an unspecified disable lasts until something re-enables it (Execute: Defragment).
|
||||
'Execute: Sabotage': {
|
||||
text: 'Destroy or disable one Hardware on an enemy Avatar in combat at the target Server.',
|
||||
execution: {
|
||||
plays(s, p) {
|
||||
const c = liveCombat(s);
|
||||
if (!c) return [];
|
||||
const hws = [...new Set(fightersOf(c).filter((r) => r.player !== p).flatMap((r) => hardwareOf(s, r)))];
|
||||
return LOCATIONS.filter((t) => scopeOf(s, p, t).includes(c.loc)).flatMap((target) =>
|
||||
hws.flatMap((card) => [
|
||||
{ target, args: { card, mode: 'destroy' as const } },
|
||||
...(hardwareActive(s, card) ? [{ target, args: { card, mode: 'disable' as const } }] : []),
|
||||
]));
|
||||
},
|
||||
targetsAvatars: (s, item) => wearerList(s, item.args.card),
|
||||
resolve(s, item) {
|
||||
const hw = item.args.card!;
|
||||
const owner = wearerOf(s, hw);
|
||||
if (!owner) return;
|
||||
fired(s, item.name, item.player);
|
||||
if (item.args.mode === 'destroy') {
|
||||
uninstallHardware(s, hw);
|
||||
toDiscard(s, hw);
|
||||
stat(s, 'hardwareLost', owner.player);
|
||||
say(s, `Sabotage destroys ${nameOf(s, hw)}.`);
|
||||
} else {
|
||||
s.cards[hw].disabledUntil = FOREVER;
|
||||
say(s, `Sabotage disables ${nameOf(s, hw)}.`);
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
'Execute: Kill Process': {
|
||||
text: "Disable one Program installed on the target Server until its controller's next turn.",
|
||||
execution: {
|
||||
plays: (s, p) =>
|
||||
acrossScope(s, p, (loc) => programsOn(s, loc).filter((id) => canTargetProgram(s, id, p)).map((card) => ({ card }))),
|
||||
resolve(s, item) {
|
||||
const card = item.args.card!;
|
||||
if (!programLocation(s, card)) return;
|
||||
const until = startOf(nextTurnOf(s, ownerOf(s, card)));
|
||||
s.cards[card].disabledUntil = Math.max(s.cards[card].disabledUntil, until);
|
||||
fired(s, item.name, item.player);
|
||||
say(s, `Kill Process disables ${nameOf(s, card)} until ${playerName(ownerOf(s, card))}'s next turn.`);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
// Ruling: Servers perform Executions, so "that Avatar cannot play another Execution" stops the
|
||||
// Server it stands on from performing Executions for the rest of the turn.
|
||||
'Execute: Force Reboot': {
|
||||
text: 'Remove all temporary bonuses and penalties from one Avatar you control at the target Server, or one Avatar attacking it. That Avatar cannot play another Execution this turn.',
|
||||
execution: {
|
||||
plays: (s, p) =>
|
||||
acrossScope(s, p, (loc) => {
|
||||
const c = liveCombat(s);
|
||||
const attacker = c && c.loc === loc ? [c.attacker] : [];
|
||||
return uniq([...mine(s, p, loc), ...attacker]).map((ref) => ({ ref }));
|
||||
}),
|
||||
targetsAvatars: (_s, item) => (item.args.ref ? [item.args.ref] : []),
|
||||
resolve(s, item) {
|
||||
const ref = item.args.ref!;
|
||||
const av = avatar(s, ref);
|
||||
if (av.at === null) return;
|
||||
const live = activeMods(s, av);
|
||||
av.mods = av.mods.filter((m) => !live.includes(m));
|
||||
// Servers perform Executions: the Server this Avatar stands on can't for the rest of the turn.
|
||||
markUsed(s, `noExec:${av.at}`);
|
||||
fired(s, item.name, item.player);
|
||||
say(s, `Force Reboot clears ${live.length} temporary effect(s) from ${avatarName(s, ref)}.`);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
'Execute: Fork': {
|
||||
text: 'Copy the localized effect of one Program installed on the target Server until end of turn.',
|
||||
execution: {
|
||||
plays: (s, p) =>
|
||||
acrossScope(s, p, (loc) => programsOn(s, loc).filter((id) => canTargetProgram(s, id, p)).map((card) => ({ card }))),
|
||||
resolve(s, item) {
|
||||
const card = item.args.card!;
|
||||
if (!programLocation(s, card) || !programActive(s, card)) return;
|
||||
s.virtuals.push({
|
||||
id: ++s.seq, name: nameOf(s, card), controller: item.player, at: item.target!, until: endOfTurn(s), installed: false, from: card,
|
||||
});
|
||||
fired(s, item.name, item.player);
|
||||
say(s, `Fork copies ${nameOf(s, card)} on ${item.target} for ${playerName(item.player)} until end of turn.`);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
'Execute: Ping Sweep': {
|
||||
text: 'You may draw 2 cards from the top of your deck.',
|
||||
execution: {
|
||||
plays: () => [{ target: null, args: {} }],
|
||||
resolve(s, item) {
|
||||
fired(s, item.name, item.player);
|
||||
drawN(s, item.player, 2 + item.power);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
// Reading: resolves right away, only while no combat is going on. Into your own location it's a
|
||||
// move; into an unowned or undefended one it's a capture; into a defended one it's an attack.
|
||||
'Execute: Trace Route': {
|
||||
text: 'Move one Avatar you control from an adjacent Server to the target Server. If the target Server is enemy-controlled, your Avatar attacks it with +1 Core for the resulting combat.',
|
||||
execution: {
|
||||
plays(s, p) {
|
||||
if (liveCombat(s)) return [];
|
||||
const out: Play[] = [];
|
||||
for (const target of LOCATIONS) {
|
||||
if (isStart(target) && !controls(s, p, target)) continue;
|
||||
const mineThere = controls(s, p, target);
|
||||
if (mineThere && !hasRoom(s, p, target)) continue;
|
||||
for (const ref of refsInPlay(s, p)) {
|
||||
const at = avatar(s, ref).at!;
|
||||
if (at !== target && canAct(s, ref) && adjacent(s, at, target)) out.push({ target, args: { ref } });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
},
|
||||
targetsAvatars: (_s, item) => (item.args.ref ? [item.args.ref] : []),
|
||||
resolve(s, item) {
|
||||
const ref = item.args.ref!;
|
||||
const t = item.target!;
|
||||
const av = avatar(s, ref);
|
||||
if (av.at === null || !canAct(s, ref) || !adjacent(s, av.at, t) || liveCombat(s)) return;
|
||||
const owner = s.locations[t].owner;
|
||||
fired(s, item.name, item.player);
|
||||
if (owner === item.player) {
|
||||
if (hasRoom(s, item.player, t)) moveAvatar(s, ref, t);
|
||||
} else if (owner === null) {
|
||||
pushCapture(s, ref, t, 'capturesUnowned');
|
||||
} else if (defendersAt(s, t).length === 0) {
|
||||
pushCapture(s, ref, t, 'capturesUndefended');
|
||||
} else {
|
||||
const c = startCombat(s, ref, av.at, t, 'traceRoute');
|
||||
addMod(s, ref, 1 + item.power, 'Trace Route', item.player, { combat: c.id });
|
||||
emit(s, 'onAttackDeclared', { ref: ref as never, to: t });
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
'Execute: Override': {
|
||||
text: 'Choose one enemy Program installed on the target Server. Ignore its text until the end of turn.',
|
||||
execution: {
|
||||
plays: (s, p) =>
|
||||
acrossScope(s, p, (loc) =>
|
||||
programsOn(s, loc).filter((id) => ownerOf(s, id) !== p && canTargetProgram(s, id, p)).map((card) => ({ card }))),
|
||||
resolve(s, item) {
|
||||
const card = item.args.card!;
|
||||
if (!programLocation(s, card)) return;
|
||||
s.cards[card].ignoredUntil = endOfTurn(s);
|
||||
fired(s, item.name, item.player);
|
||||
say(s, `Override: ${nameOf(s, card)}'s text is ignored until end of turn.`);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
'Execute: Memory Dump': {
|
||||
text: 'Draw 2 cards, then discard 1. If you control the target Server, draw 1 extra card instead of discarding.',
|
||||
execution: {
|
||||
plays: () => LOCATIONS.map((target) => ({ target, args: {} })),
|
||||
resolve(s, item) {
|
||||
const p = item.player;
|
||||
fired(s, item.name, p);
|
||||
if (controls(s, p, item.target!)) {
|
||||
drawN(s, p, 3 + item.power);
|
||||
return;
|
||||
}
|
||||
const draws = Array.from({ length: 2 + item.power }, (): Task => ({ t: 'draw', player: p }));
|
||||
pushTasks(s, ...draws, later('Execute: Memory Dump', 'discard', { player: p }));
|
||||
},
|
||||
},
|
||||
resume: {
|
||||
discard(s, data: { player: PlayerId }) {
|
||||
const hand = s.players[data.player].hand;
|
||||
if (hand.length === 0) return;
|
||||
ask(s, {
|
||||
player: data.player,
|
||||
kind: 'Execute: Memory Dump:discard',
|
||||
prompt: 'Memory Dump: discard a card.',
|
||||
options: cardOptions(s, hand),
|
||||
resume: { name: 'Execute: Memory Dump', fn: 'drop', data: { player: data.player } },
|
||||
});
|
||||
},
|
||||
drop(s, data: { player: PlayerId }, card: number) {
|
||||
if (removeFrom(s.players[data.player].hand, card)) toDiscard(s, card);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
'Execute: Rollback': {
|
||||
text: "Return one Program or Hardware installed at the target Server this turn to its owner's hand.",
|
||||
execution: {
|
||||
plays: (s, p) =>
|
||||
acrossScope(s, p, (loc) => {
|
||||
const progs = s.locations[loc].programs.filter((id) => s.cards[id].installedTurn === s.turn && canTargetProgram(s, id, p));
|
||||
const hws = [...new Set(avatarsAt(s, loc).flatMap((r) => avatar(s, r).hardware))].filter((id) => s.cards[id].installedTurn === s.turn);
|
||||
return [...progs, ...hws].map((card) => ({ card }));
|
||||
}),
|
||||
targetsAvatars: (s, item) => wearerList(s, item.args.card),
|
||||
resolve(s, item) {
|
||||
const card = item.args.card!;
|
||||
if (!uninstallProgram(s, card) && !uninstallHardware(s, card)) return;
|
||||
toHand(s, card);
|
||||
fired(s, item.name, item.player);
|
||||
say(s, `Rollback returns ${nameOf(s, card)} to ${playerName(ownerOf(s, card))}'s hand.`);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
// Protected = Hardware Sandbox's Program. No card protects Hardware yet.
|
||||
'Execute: Root Access': {
|
||||
text: 'Until end of turn, your Programs and Executions at the target Server may target protected Programs and Hardware as though they were unprotected.',
|
||||
execution: {
|
||||
plays: () => LOCATIONS.map((target) => ({ target, args: {} })),
|
||||
resolve(s, item) {
|
||||
s.locations[item.target!].rootAccess[item.player] = endOfTurn(s);
|
||||
fired(s, item.name, item.player);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
// Rooted Avatars can't advance, attack, reposition, or be moved; their declared moves fail.
|
||||
'Execute: Packet Flood': {
|
||||
text: "Avatars based at the target Server cannot move or retreat until the start of their controller's next turn.",
|
||||
execution: {
|
||||
plays: (s, p) => acrossScope(s, p, (loc) => (avatarsAt(s, loc).length ? [{ to: loc }] : [])),
|
||||
resolve(s, item) {
|
||||
const loc = item.args.to ?? item.target!;
|
||||
const here = avatarsAt(s, loc);
|
||||
if (here.length === 0) return;
|
||||
for (const r of here) {
|
||||
const av = avatar(s, r);
|
||||
av.rootedUntil = Math.max(av.rootedUntil, startOf(nextTurnOf(s, r.player)));
|
||||
}
|
||||
fired(s, item.name, item.player);
|
||||
say(s, `Packet Flood: ${here.map((r) => avatarName(s, r)).join(', ')} can't move.`);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
// Reading: Disabled Avatars still defend, but can't advance, attack, move or use Abilities.
|
||||
'Execute: Emergency Shutdown': {
|
||||
text: 'End any combat at the target Server immediately. All Avatars there remain and become Disabled until end of turn.',
|
||||
execution: {
|
||||
plays(s, p) {
|
||||
const c = liveCombat(s);
|
||||
return c ? LOCATIONS.filter((t) => scopeOf(s, p, t).includes(c.loc)).map((target) => ({ target, args: {} })) : [];
|
||||
},
|
||||
resolve(s, item) {
|
||||
const c = liveCombat(s);
|
||||
if (!c || !scopeOf(s, item.player, item.target!).includes(c.loc)) return;
|
||||
const everyone = uniq([...fightersOf(c), ...avatarsAt(s, c.loc)]);
|
||||
endCombat(s, 'Emergency Shutdown');
|
||||
for (const r of everyone) avatar(s, r).disabledUntil = Math.max(avatar(s, r).disabledUntil, endOfTurn(s));
|
||||
fired(s, item.name, item.player);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
'Execute: Process Clone': {
|
||||
text: 'Choose one Program installed on the target Server you control. Treat it as though a second copy were installed there until end of turn.',
|
||||
execution: {
|
||||
plays: (s, p) =>
|
||||
LOCATIONS.filter((t) => controls(s, p, t)).flatMap((target) =>
|
||||
scopeOf(s, p, target).flatMap((loc) => (controls(s, p, loc) ? programsOn(s, loc) : []).map((card) => ({ target, args: { card } })))),
|
||||
resolve(s, item) {
|
||||
const card = item.args.card!;
|
||||
if (!programLocation(s, card) || !controls(s, item.player, item.target!)) return;
|
||||
s.virtuals.push({
|
||||
id: ++s.seq, name: nameOf(s, card), controller: item.player, at: item.target!, until: endOfTurn(s), installed: true, from: card,
|
||||
});
|
||||
fired(s, item.name, item.player);
|
||||
say(s, `Process Clone: a second ${nameOf(s, card)} runs on ${item.target} until end of turn.`);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
'Execute: Defragment': {
|
||||
text: 'Re-enable one Disabled Program on the target Server, or one Disabled Hardware on an Avatar there.',
|
||||
execution: {
|
||||
plays: (s, p) =>
|
||||
acrossScope(s, p, (loc) => {
|
||||
const progs = s.locations[loc].programs.filter((id) => running(s, s.cards[id].disabledUntil));
|
||||
const hws = [...new Set(avatarsAt(s, loc).flatMap((r) => hardwareOf(s, r)))].filter((id) => !hardwareActive(s, id));
|
||||
return [...progs, ...hws].map((card) => ({ card }));
|
||||
}),
|
||||
resolve(s, item) {
|
||||
const card = item.args.card!;
|
||||
if (!running(s, s.cards[card].disabledUntil)) return;
|
||||
s.cards[card].disabledUntil = 0;
|
||||
fired(s, item.name, item.player);
|
||||
say(s, `Defragment re-enables ${nameOf(s, card)}.`);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
// Reading: the Program keeps its owner, and runs at both locations until end of turn.
|
||||
'Execute: Remote Access': {
|
||||
text: 'Activate one Program installed on a Server adjacent to the target Server as though it were installed on the target Server, until end of turn.',
|
||||
execution: {
|
||||
plays: (s, p) =>
|
||||
LOCATIONS.flatMap((target) =>
|
||||
neighbors(s, target).flatMap((n) => programsOn(s, n).filter((id) => canTargetProgram(s, id, p)).map((card) => ({ target, args: { card } })))),
|
||||
resolve(s, item) {
|
||||
const card = item.args.card!;
|
||||
if (!programLocation(s, card)) return;
|
||||
s.virtuals.push({
|
||||
id: ++s.seq, name: nameOf(s, card), controller: ownerOf(s, card), at: item.target!, until: endOfTurn(s), installed: true, from: card,
|
||||
});
|
||||
fired(s, item.name, item.player);
|
||||
say(s, `Remote Access: ${nameOf(s, card)} also runs on ${item.target} until end of turn.`);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
'Execute: Purge': {
|
||||
text: 'Remove all Virus/Infection counters and hostile persistent effects from every Avatar you control at the target Server.',
|
||||
execution: {
|
||||
plays: (s, p) =>
|
||||
acrossScope(s, p, (loc) => (mine(s, p, loc).some((r) => hasNegatives(s, r)) ? [{ to: loc }] : [])),
|
||||
resolve(s, item) {
|
||||
const loc = item.args.to ?? item.target!;
|
||||
const here = mine(s, item.player, loc);
|
||||
for (const r of here) {
|
||||
const av = avatar(s, r);
|
||||
av.infection = 0;
|
||||
av.permanentInfection = 0;
|
||||
av.mods = av.mods.filter((m) => m.cores >= 0 || m.by === item.player);
|
||||
av.rootedUntil = 0;
|
||||
av.disabledUntil = 0;
|
||||
for (const hw of hardwareOf(s, r)) s.cards[hw].disabledUntil = 0;
|
||||
}
|
||||
fired(s, item.name, item.player);
|
||||
say(s, `Purge cleans ${here.map((r) => avatarName(s, r)).join(', ')}.`);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
'Execute: Hard Reset': {
|
||||
text: 'Uninstall any number of Programs from the target Server you control. For each card returned to your hand this way, recover 1 RAM.',
|
||||
execution: {
|
||||
plays: (s, p) =>
|
||||
LOCATIONS.filter((t) => controls(s, p, t) && s.locations[t].programs.length > 0).flatMap((target) =>
|
||||
subsets(s.locations[target].programs).map((cards) => ({ target, args: { cards } }))),
|
||||
resolve(s, item) {
|
||||
const back = item.args.cards!.filter((id) => programLocation(s, id) === item.target);
|
||||
for (const id of back) {
|
||||
uninstallProgram(s, id);
|
||||
toHand(s, id);
|
||||
}
|
||||
gainRam(s, item.player, back.length * (1 + item.power));
|
||||
fired(s, item.name, item.player);
|
||||
say(s, `Hard Reset returns ${back.map((id) => nameOf(s, id)).join(', ')} to hand (+${back.length * (1 + item.power)} RAM).`);
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
function drawN(s: GameState, p: PlayerId, n: number): void {
|
||||
pushTasks(s, ...Array.from({ length: n }, (): Task => ({ t: 'draw', player: p })));
|
||||
}
|
||||
|
||||
function hasNegatives(s: GameState, r: AvatarRef): boolean {
|
||||
const av = avatar(s, r);
|
||||
return av.infection > 0 || av.permanentInfection > 0 || running(s, av.rootedUntil) || running(s, av.disabledUntil) ||
|
||||
activeMods(s, av).some((m) => m.cores < 0) || hardwareOf(s, r).some((hw) => !hardwareActive(s, hw));
|
||||
}
|
||||
|
||||
|
||||
362
sim/src/cards/hardware.ts
Normal file
362
sim/src/cards/hardware.ts
Normal file
|
|
@ -0,0 +1,362 @@
|
|||
/**
|
||||
* Hardware. It works while its wearer is in play. "The occupied Server" is the location the
|
||||
* wearer stands on.
|
||||
*/
|
||||
import { knockOut } from '../flow.ts';
|
||||
import { desynced, hardwareActive } from '../query.ts';
|
||||
import { scriptOf, type Script } from '../scripts.ts';
|
||||
import {
|
||||
ask,
|
||||
avatar,
|
||||
avatarName,
|
||||
defOf,
|
||||
fired,
|
||||
isCopy,
|
||||
markUsed,
|
||||
nameOf,
|
||||
nextTurnOf,
|
||||
ownerOf,
|
||||
played,
|
||||
programLocation,
|
||||
refsInPlay,
|
||||
removeFrom,
|
||||
say,
|
||||
startOf,
|
||||
endOf,
|
||||
stat,
|
||||
toHand,
|
||||
uninstallHardware,
|
||||
usedThisTurn,
|
||||
wearerOf,
|
||||
} from '../state.ts';
|
||||
import type { AvatarRef, GameState, LocationState, PlayerId, StackItem } from '../types.ts';
|
||||
import { cardOptions, programsOn } from './util.ts';
|
||||
|
||||
/**
|
||||
* Uses a Hardware card has left this turn. Its "once per turn" or "first ... each turn" effect gets
|
||||
* one use, or two when Cooling System on the same Avatar picks it (Cooling helps one Hardware a turn).
|
||||
*/
|
||||
export function hardwareUsesLeft(s: GameState, hw: number): number {
|
||||
const used = usedThisTurn(s, `hw:${hw}`);
|
||||
const cooler = coolerFor(s, hw);
|
||||
return (cooler === null ? 1 : 2) - used;
|
||||
}
|
||||
|
||||
function coolerFor(s: GameState, hw: number): number | null {
|
||||
const ref = wearerOf(s, hw);
|
||||
if (!ref) return null;
|
||||
for (const id of avatar(s, ref).hardware) {
|
||||
if (id === hw || s.cards[id].name !== 'Cooling System' || !hardwareActive(s, id)) continue;
|
||||
const pickedFor = s.used[`cool:${id}`];
|
||||
if (pickedFor === undefined || pickedFor === hw) return id;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function useHardware(s: GameState, hw: number): void {
|
||||
const cooler = coolerFor(s, hw);
|
||||
markUsed(s, `hw:${hw}`);
|
||||
if (usedThisTurn(s, `hw:${hw}`) >= 2 && cooler !== null) {
|
||||
s.used[`cool:${cooler}`] = hw;
|
||||
fired(s, 'Cooling System', ownerOf(s, hw));
|
||||
}
|
||||
}
|
||||
|
||||
const wearing = (ref: AvatarRef | undefined, f: { ref: AvatarRef }) =>
|
||||
!!ref && ref.player === f.ref.player && (ref.slot === f.ref.slot || ref.slot + 4 === f.ref.slot);
|
||||
|
||||
/** Installs a Hardware card from its owner's hand onto an Avatar, without paying. */
|
||||
export function attachHardware(s: GameState, card: number, ref: AvatarRef): void {
|
||||
removeFrom(s.players[ref.player].hand, card);
|
||||
avatar(s, ref).hardware.push(card);
|
||||
s.cards[card].installedTurn = s.turn;
|
||||
stat(s, 'hardwareInstalled', ref.player);
|
||||
played(s, nameOf(s, card), ref.player);
|
||||
}
|
||||
|
||||
export const HARDWARE: Record<string, Script> = {
|
||||
// Reading: "+2 Core capacity" means +2 Cores.
|
||||
'RAM Expansion': {
|
||||
text: 'Avatar gains +2 Core capacity.',
|
||||
cores: () => 2,
|
||||
},
|
||||
'Additional Core': {
|
||||
text: 'Avatar gains +1 Core.',
|
||||
cores: () => 1,
|
||||
},
|
||||
|
||||
// Reading: the Program is one on the location the wearer fought from, the owner picks it, and it
|
||||
// stays disabled through the end of the next turn.
|
||||
'Overclocked CPU': {
|
||||
text: 'Avatar gains +2 Cores during combat, but one installed Program at the current server becomes disabled afterward for 2 turns.',
|
||||
cores: (_s, _src, f) => (f.role !== null ? 2 : 0),
|
||||
onCombatEnd(s, src) {
|
||||
const c = s.combat!;
|
||||
const role = wearing(src.ref, { ref: c.attacker }) ? 'attack' : c.defenders.some((d) => wearing(src.ref, { ref: d })) ? 'defend' : null;
|
||||
if (!role) return;
|
||||
const loc = role === 'attack' ? c.origin : c.loc;
|
||||
if (s.locations[loc].owner !== src.controller) return;
|
||||
const progs = programsOn(s, loc);
|
||||
if (progs.length === 0) return;
|
||||
fired(s, 'Overclocked CPU', src.controller);
|
||||
if (progs.length === 1) {
|
||||
disableForTwoTurns(s, progs[0]);
|
||||
return;
|
||||
}
|
||||
ask(s, {
|
||||
player: src.controller,
|
||||
kind: 'Overclocked CPU:disable',
|
||||
prompt: `Overclocked CPU: which Program on ${loc} is disabled for 2 turns?`,
|
||||
options: progs.map((id) => ({ label: nameOf(s, id), value: id })),
|
||||
resume: { name: 'Overclocked CPU', fn: 'disable', data: null },
|
||||
});
|
||||
},
|
||||
resume: {
|
||||
disable: (s, _data, id: number) => disableForTwoTurns(s, id),
|
||||
},
|
||||
},
|
||||
|
||||
'Solid-State Cache': {
|
||||
text: 'The first Program installed on the occupied Server each turn costs 3 less RAM.',
|
||||
costMod: (s, src, pay) =>
|
||||
pay.kind === 'program' && pay.player === src.controller && pay.at === src.at && hardwareUsesLeft(s, src.id) > 0 ? -3 : 0,
|
||||
onPaid(s, src) {
|
||||
useHardware(s, src.id);
|
||||
fired(s, 'Solid-State Cache', src.controller);
|
||||
},
|
||||
},
|
||||
|
||||
// Reading: the first time the wearer is defeated with this installed, all its Hardware stays on
|
||||
// it (in its slot) instead of being discarded.
|
||||
'Redundant Power Supply': {
|
||||
text: 'The first time this Avatar would be destroyed, do not destroy the Hardware.',
|
||||
savePriority: 0,
|
||||
onWearerDefeated(s, hw, ev) {
|
||||
if (s.cards[hw].spent) return false;
|
||||
s.cards[hw].spent = true;
|
||||
fired(s, 'Redundant Power Supply', ev.ref.player);
|
||||
say(s, `Redundant Power Supply: ${avatarName(s, ev.ref)} keeps its Hardware.`);
|
||||
knockOut(s, ev.ref, ev.loc, ev.role, true);
|
||||
return true;
|
||||
},
|
||||
},
|
||||
|
||||
// Ruling: it takes no port and adds one, so the wearer nets +1 Expansion Slot.
|
||||
'Network Interface Upgrade': {
|
||||
text: 'This Hardware can be played without taking an upgrade port on the Avatar.',
|
||||
noPort: true,
|
||||
extraSlots: 1,
|
||||
},
|
||||
|
||||
// Ruling: Servers perform Executions, so this works for Executions performed by the Server the
|
||||
// wearer stands on. +1 to the number the Execution uses (cards drawn, Cores, RAM recovered).
|
||||
'Dedicated GPU': {
|
||||
text: 'Executions performed by this Avatar receive +1 effectiveness or combat strength.',
|
||||
executionPower: 1,
|
||||
},
|
||||
|
||||
// Blocks opponents' Bug counters (see addBugs in util.ts; no card places them yet) and their
|
||||
// Bug Program effects on the wearer (Memory Leak, Stock Rice).
|
||||
'ECC Memory': {
|
||||
text: 'Opponents cannot place Bug counters or Bug status effects on this Avatar.',
|
||||
bugImmunity: true,
|
||||
},
|
||||
|
||||
// Works through hardwareUsesLeft() above.
|
||||
'Cooling System': {
|
||||
text: 'Allow one Hardware to activate twice per turn.',
|
||||
},
|
||||
|
||||
// Reading: half the combined printed RAM of its Hardware, rounded up.
|
||||
'RAID Array': {
|
||||
text: 'When this Avatar is destroyed, all hardware can be kept by paying half the RAM cost.',
|
||||
savePriority: 1,
|
||||
onWearerDefeated(s, hw, ev) {
|
||||
const av = avatar(s, ev.ref);
|
||||
const cost = Math.ceil(av.hardware.reduce((t, h) => t + defOf(s, h).ram, 0) / 2);
|
||||
ask(s, {
|
||||
player: ev.ref.player,
|
||||
kind: 'RAID Array:keep',
|
||||
prompt: `RAID Array: pay ${cost} RAM to keep ${av.hardware.map((h) => nameOf(s, h)).join(', ')}?`,
|
||||
options: [
|
||||
{ label: `Keep all Hardware for ${cost} RAM`, value: true, cost },
|
||||
{ label: 'Lose the Hardware', value: false },
|
||||
],
|
||||
resume: { name: 'RAID Array', fn: 'keep', data: { ref: ev.ref as never, loc: ev.loc, role: ev.role, cost } },
|
||||
});
|
||||
return true;
|
||||
},
|
||||
resume: {
|
||||
keep(s, data: { ref: AvatarRef; loc: string; role: 'attack' | 'defend'; cost: number }, keep: boolean) {
|
||||
if (keep) {
|
||||
s.players[data.ref.player].ram -= data.cost;
|
||||
stat(s, 'ramOnCards', data.ref.player, data.cost);
|
||||
fired(s, 'RAID Array', data.ref.player);
|
||||
}
|
||||
knockOut(s, data.ref, data.loc, data.role, keep);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
'Packet Accelerator': {
|
||||
text: 'This Avatar gains +1 Core hen attacking.',
|
||||
cores: (_s, _src, f) => (f.role === 'attack' ? 1 : 0),
|
||||
},
|
||||
|
||||
// Programs never target Avatars, so this taxes Executions (and Hardware they hit).
|
||||
'Firewall Appliance': {
|
||||
text: 'The first hostile Program or Execution targeting this Avatar each turn costs the opponent +3 RAM.',
|
||||
costMod: (s, src, pay) =>
|
||||
pay.kind === 'execution' && pay.player !== src.controller && hardwareUsesLeft(s, src.id) > 0 &&
|
||||
(pay.hostile ?? []).some((r) => wearing(src.ref, { ref: r })) ? 3 : 0,
|
||||
onPaid(s, src) {
|
||||
useHardware(s, src.id);
|
||||
fired(s, 'Firewall Appliance', src.controller);
|
||||
},
|
||||
},
|
||||
|
||||
// Reading: pick the Program on install, and again at the start of your turn if the wearer has
|
||||
// moved. Protection only holds while the wearer stands on that Program's location.
|
||||
'Hardware Sandbox': {
|
||||
text: 'Choose one Program installed on the occupied Server. It cannot be targeted by opponents.',
|
||||
onInstall(s, src, ev: { card: number }) {
|
||||
if (ev.card === src.id) askSandbox(s, src.id);
|
||||
},
|
||||
onTurnStart(s, src) {
|
||||
if (s.active !== src.controller) return;
|
||||
const p = s.cards[src.id].protects;
|
||||
if (p === undefined || programLocation(s, p) !== src.at) askSandbox(s, src.id);
|
||||
},
|
||||
resume: {
|
||||
protect(s, data: { card: number }, program: number) {
|
||||
s.cards[data.card].protects = program;
|
||||
fired(s, 'Hardware Sandbox', ownerOf(s, data.card));
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
// Reading: at the start of your turn, look at the top card and you may put it on the bottom.
|
||||
'Diagnostic Module': {
|
||||
text: 'Look at one face down card in your draw pile. You may place it at the bottom and draw another to start your turn.',
|
||||
onTurnStart(s, src) {
|
||||
if (s.active !== src.controller || hardwareUsesLeft(s, src.id) <= 0) return;
|
||||
const deck = s.players[src.controller].deck;
|
||||
if (deck.length < 2) return;
|
||||
useHardware(s, src.id);
|
||||
fired(s, 'Diagnostic Module', src.controller);
|
||||
ask(s, {
|
||||
player: src.controller,
|
||||
kind: 'Diagnostic Module:bottom',
|
||||
prompt: `Diagnostic Module: the top card of your deck is ${nameOf(s, deck[0])}. Put it on the bottom?`,
|
||||
options: [
|
||||
{ label: `Keep ${nameOf(s, deck[0])} on top`, value: false },
|
||||
{ label: `Put ${nameOf(s, deck[0])} on the bottom`, value: true },
|
||||
],
|
||||
resume: { name: 'Diagnostic Module', fn: 'bottom', data: { player: src.controller } },
|
||||
});
|
||||
},
|
||||
resume: {
|
||||
bottom(s, data: { player: PlayerId }, bottom: boolean) {
|
||||
const deck = s.players[data.player].deck;
|
||||
if (bottom && deck.length) deck.push(deck.shift()!);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
// Reading: swap Hardware on this Avatar, paying the difference in printed RAM (no refund).
|
||||
'Hot-Swap Bay': {
|
||||
text: 'Once per turn, return one Hardware to your hand and install another Hardware from your hand, paying the difference in cost.',
|
||||
ability: {
|
||||
hardwareOncePerTurn: true,
|
||||
uses(s, src) {
|
||||
const av = avatar(s, src.ref!);
|
||||
const hand = s.players[src.controller].hand.filter((id) => defOf(s, id).kind === 'hardware');
|
||||
return av.hardware.flatMap((out) => cardOptions(s, hand).map((o) => ({ card: out, cards: [o.value as number] })));
|
||||
},
|
||||
extraCost: (s, _src, args) => Math.max(0, defOf(s, args.cards![0]).ram - defOf(s, args.card!).ram),
|
||||
resolve(s, item, src) {
|
||||
const out = item.args.card!;
|
||||
const into = item.args.cards![0];
|
||||
const ref = src.ref!;
|
||||
if (!avatar(s, ref).hardware.includes(out) || !s.players[src.controller].hand.includes(into)) return;
|
||||
uninstallHardware(s, out);
|
||||
toHand(s, out);
|
||||
attachHardware(s, into, ref);
|
||||
fired(s, 'Hot-Swap Bay', src.controller);
|
||||
say(s, `Hot-Swap Bay swaps ${nameOf(s, out)} for ${nameOf(s, into)} on ${avatarName(s, ref)}.`);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
// Ruling: Servers perform Executions, so "this Avatar uses an Execution" means one performed by
|
||||
// the Server the wearer stands on. "Disable this Hardware" lasts until your next turn.
|
||||
'Quantum Coprocessor': {
|
||||
text: "Once per turn when this Avatar uses an Execution, you may copy that Execution's effect with a different legal target, then disable this Hardware.",
|
||||
copiesExecutions: true,
|
||||
resume: {
|
||||
offer(s, data: { item: StackItem }) {
|
||||
const item = data.item;
|
||||
const wearers = refsInPlay(s, item.player).filter((r) => !isCopy(r) && avatar(s, r).at === item.from && !desynced(s, r));
|
||||
const qc = wearers.flatMap((r) => avatar(s, r).hardware)
|
||||
.find((hw) => s.cards[hw].name === 'Quantum Coprocessor' && hardwareActive(s, hw) && hardwareUsesLeft(s, hw) > 0);
|
||||
if (qc === undefined) return;
|
||||
const ex = scriptOf(item.name)?.execution;
|
||||
if (!ex) return;
|
||||
const same = JSON.stringify({ t: item.target, a: item.args });
|
||||
const plays = ex.plays(s, item.player).filter((p) => JSON.stringify({ t: p.target, a: p.args }) !== same);
|
||||
if (plays.length === 0) return;
|
||||
ask(s, {
|
||||
player: item.player,
|
||||
kind: 'Quantum Coprocessor:copy',
|
||||
prompt: `Quantum Coprocessor: copy ${item.name} with a different target?`,
|
||||
options: [
|
||||
{ label: "Don't copy", value: null },
|
||||
...plays.map((p) => ({ label: `${p.target ?? 'no target'} ${describeArgs(s, p.args)}`, value: { target: p.target, args: p.args as never } })),
|
||||
],
|
||||
resume: { name: 'Quantum Coprocessor', fn: 'copy', data: { item: item as never, qc } },
|
||||
});
|
||||
},
|
||||
copy(s, data: { item: StackItem; qc: number }, v: { target: string | null; args: never } | null) {
|
||||
if (!v) return;
|
||||
useHardware(s, data.qc);
|
||||
s.cards[data.qc].disabledUntil = startOf(nextTurnOf(s, data.item.player));
|
||||
fired(s, 'Quantum Coprocessor', data.item.player);
|
||||
say(s, `Quantum Coprocessor copies ${data.item.name} onto ${v.target ?? 'a new target'}.`);
|
||||
scriptOf(data.item.name)!.execution!.resolve(s, { ...data.item, target: v.target, args: v.args, from: null });
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
function describeArgs(s: GameState, a: StackItem['args']): string {
|
||||
const parts: string[] = [];
|
||||
if (a.ref) parts.push(avatarName(s, a.ref));
|
||||
if (a.card !== undefined) parts.push(nameOf(s, a.card));
|
||||
if (a.to) parts.push(`→ ${a.to}`);
|
||||
if (a.mode) parts.push(a.mode);
|
||||
return parts.join(' ');
|
||||
}
|
||||
|
||||
function disableForTwoTurns(s: GameState, id: number): void {
|
||||
s.cards[id].disabledUntil = Math.max(s.cards[id].disabledUntil, endOf(s.turn + 1));
|
||||
say(s, `Overclocked CPU: ${nameOf(s, id)} is disabled for 2 turns.`);
|
||||
}
|
||||
|
||||
function askSandbox(s: GameState, card: number): void {
|
||||
const ref = wearerOf(s, card);
|
||||
const at = ref ? avatar(s, ref).at : null;
|
||||
if (!ref || !at) return;
|
||||
const progs = (s.locations[at] as LocationState).programs.filter((id) => ownerOf(s, id) === ref.player);
|
||||
if (progs.length === 0) return;
|
||||
if (progs.length === 1) {
|
||||
s.cards[card].protects = progs[0];
|
||||
return;
|
||||
}
|
||||
ask(s, {
|
||||
player: ref.player,
|
||||
kind: 'Hardware Sandbox:protect',
|
||||
prompt: `Hardware Sandbox: protect which Program on ${at}?`,
|
||||
options: progs.map((id) => ({ label: nameOf(s, id), value: id })),
|
||||
resume: { name: 'Hardware Sandbox', fn: 'protect', data: { card } },
|
||||
});
|
||||
}
|
||||
599
sim/src/cards/programs.ts
Normal file
599
sim/src/cards/programs.ts
Normal file
|
|
@ -0,0 +1,599 @@
|
|||
/**
|
||||
* Programs. A Program sits on a location its owner controls and its effect is local: "this
|
||||
* Server" is the location it's on (or where Worm Protocol spreads it). Enemy Avatars are only
|
||||
* ever "at" your location while attacking or capturing it.
|
||||
*/
|
||||
import { LOCATIONS, type LocId } from '../map.ts';
|
||||
import {
|
||||
bugImmune,
|
||||
canTargetProgram,
|
||||
emit,
|
||||
hardwareActive,
|
||||
installedCount,
|
||||
programSlots,
|
||||
sameSource,
|
||||
sources,
|
||||
sourcesNamed,
|
||||
} from '../query.ts';
|
||||
import { scriptOf, type Script } from '../scripts.ts';
|
||||
import {
|
||||
activeMods,
|
||||
addMod,
|
||||
ask,
|
||||
avatar,
|
||||
avatarName,
|
||||
controls,
|
||||
defOf,
|
||||
fired,
|
||||
gainRam,
|
||||
hardwareOf,
|
||||
infectionOf,
|
||||
isCopy,
|
||||
later,
|
||||
markUsed,
|
||||
nameOf,
|
||||
neighbors,
|
||||
nextTurnOf,
|
||||
ownerOf,
|
||||
played,
|
||||
playerName,
|
||||
programLocation,
|
||||
pushTasks,
|
||||
refsInPlay,
|
||||
removeFrom,
|
||||
running,
|
||||
sameRef,
|
||||
say,
|
||||
startOf,
|
||||
stat,
|
||||
toDiscard,
|
||||
toHand,
|
||||
uninstallProgram,
|
||||
usedThisTurn,
|
||||
} from '../state.ts';
|
||||
import { randInt } from '../rng.ts';
|
||||
import { FOREVER, type AvatarRef, type GameState, type PlayerId, type Source, type Task } from '../types.ts';
|
||||
import { cardOptions, infect, isPatch, isVirus, programsOn } from './util.ts';
|
||||
|
||||
const enemyOf = (src: Source, ref: AvatarRef) => ref.player !== src.controller;
|
||||
/** The first active source with this name at the location, so duplicates don't double up. */
|
||||
const firstHere = (s: GameState, src: Source, loc: LocId) => {
|
||||
const first = sourcesNamed(s, src.name, loc)[0];
|
||||
return !!first && sameSource(first, src);
|
||||
};
|
||||
|
||||
/**
|
||||
* Destroys an installed Program. Hotfix (first each turn) disables it instead; otherwise Version
|
||||
* Control returns it to its owner's hand.
|
||||
*/
|
||||
export function destroyProgram(s: GameState, id: number): void {
|
||||
const loc = programLocation(s, id);
|
||||
if (!loc) return;
|
||||
const owner = ownerOf(s, id);
|
||||
const here = sources(s).filter((x) => x.at === loc && x.controller === owner && x.virtual === undefined);
|
||||
const hotfix = here.find((x) => x.name === 'Hotfix' && usedThisTurn(s, `hotfix:${x.id}`) === 0);
|
||||
if (hotfix) {
|
||||
markUsed(s, `hotfix:${hotfix.id}`);
|
||||
s.cards[id].disabledUntil = Math.max(s.cards[id].disabledUntil, startOf(nextTurnOf(s, owner)));
|
||||
fired(s, 'Hotfix', owner);
|
||||
say(s, `Hotfix: ${nameOf(s, id)} is disabled instead of destroyed.`);
|
||||
return;
|
||||
}
|
||||
uninstallProgram(s, id);
|
||||
stat(s, 'programsLost', owner);
|
||||
if (here.some((x) => x.name === 'Version Control')) {
|
||||
fired(s, 'Version Control', owner);
|
||||
toHand(s, id);
|
||||
say(s, `Version Control: ${nameOf(s, id)} returns to ${playerName(owner)}'s hand.`);
|
||||
return;
|
||||
}
|
||||
toDiscard(s, id);
|
||||
say(s, `${nameOf(s, id)} is destroyed.`);
|
||||
}
|
||||
|
||||
/** Installs a Program for free (Replication Routine). */
|
||||
function installFree(s: GameState, card: number, at: LocId): void {
|
||||
const p = ownerOf(s, card);
|
||||
removeFrom(s.players[p].hand, card);
|
||||
s.locations[at].programs.push(card);
|
||||
s.cards[card].installedTurn = s.turn;
|
||||
stat(s, 'programsInstalled', p);
|
||||
played(s, nameOf(s, card), p);
|
||||
say(s, `${playerName(p)} installs ${nameOf(s, card)} on ${at} for free.`);
|
||||
emit(s, 'onInstall', { card, at, ref: null });
|
||||
}
|
||||
|
||||
/** Negative things on an Avatar that Error Correction can remove, one at a time. */
|
||||
function negatives(s: GameState, ref: AvatarRef): { label: string; value: string }[] {
|
||||
const av = avatar(s, ref);
|
||||
const out: { label: string; value: string }[] = [];
|
||||
if (av.infection > 0) out.push({ label: 'an Infection counter', value: 'infection' });
|
||||
if (av.bugs > 0) out.push({ label: 'a Bug counter', value: 'bug' });
|
||||
if (av.permanentInfection > 0) out.push({ label: 'a permanent Infection counter', value: 'permanent' });
|
||||
for (const hw of hardwareOf(s, ref)) {
|
||||
if (!hardwareActive(s, hw)) out.push({ label: `disabled ${nameOf(s, hw)}`, value: `hw:${hw}` });
|
||||
}
|
||||
const worst = activeMods(s, av).filter((m) => m.cores < 0).sort((a, b) => b.seq - a.seq)[0];
|
||||
if (worst) out.push({ label: `${worst.cores} Cores from ${worst.source}`, value: `mod:${worst.seq}` });
|
||||
if (running(s, av.rootedUntil)) out.push({ label: 'Packet Flood', value: 'rooted' });
|
||||
if (running(s, av.disabledUntil)) out.push({ label: 'Disabled', value: 'disabled' });
|
||||
return out;
|
||||
}
|
||||
|
||||
function removeNegative(s: GameState, ref: AvatarRef, what: string): void {
|
||||
const av = avatar(s, ref);
|
||||
if (what === 'infection') av.infection--;
|
||||
else if (what === 'bug') av.bugs--;
|
||||
else if (what === 'permanent') av.permanentInfection--;
|
||||
else if (what === 'rooted') av.rootedUntil = 0;
|
||||
else if (what === 'disabled') av.disabledUntil = 0;
|
||||
else if (what.startsWith('hw:')) s.cards[Number(what.slice(3))].disabledUntil = 0;
|
||||
else if (what.startsWith('mod:')) av.mods = av.mods.filter((m) => m.seq !== Number(what.slice(4)));
|
||||
}
|
||||
|
||||
export const PROGRAMS: Record<string, Script> = {
|
||||
// Reading: one counter per attack declared on this Server, or per capture of it that wasn't an
|
||||
// attack. The -2 applies anywhere while this Program is in play, and doesn't stack with copies.
|
||||
'Recursive Infection': {
|
||||
text: 'Whenever an enemy Avatar attacks or breaches this Server, place an Infection counter on it. An Avatar with 3+ Infection counters has -2 Core.',
|
||||
onAttackDeclared(s, src, ev: { ref: AvatarRef; to: LocId }) {
|
||||
if (ev.to === src.at && enemyOf(src, ev.ref)) infect(s, ev.ref, 1, 'Recursive Infection', src.controller);
|
||||
},
|
||||
onBreach(s, src, ev: { ref: AvatarRef; loc: LocId }) {
|
||||
if (ev.loc !== src.at || !enemyOf(src, ev.ref)) return;
|
||||
const attacked = s.declarations.some((d) => d.kind === 'attack' && sameRef(d.ref, ev.ref) && d.to === ev.loc);
|
||||
if (!attacked) infect(s, ev.ref, 1, 'Recursive Infection', src.controller);
|
||||
},
|
||||
globalCores: (s, f) => (infectionOf(avatar(s, f.ref)) >= 3 ? -2 : 0),
|
||||
},
|
||||
|
||||
// Reading: "owner" is the attacking Avatar's owner, who picks which of its Hardware is disabled
|
||||
// for that combat.
|
||||
'Memory Parasite': {
|
||||
text: "Enemy Avatars attacking this Server have 1 hardware component disabled of the owners choosing.",
|
||||
onCombatStart(s, src) {
|
||||
const c = s.combat!;
|
||||
if (c.loc !== src.at || !enemyOf(src, c.attacker)) return;
|
||||
const hw = hardwareOf(s, c.attacker).filter((h) => hardwareActive(s, h) && !c.suppressed.includes(h));
|
||||
if (hw.length === 0) return;
|
||||
fired(s, 'Memory Parasite', src.controller);
|
||||
if (hw.length === 1) {
|
||||
c.suppressed.push(hw[0]);
|
||||
say(s, `Memory Parasite disables ${nameOf(s, hw[0])} for this combat.`);
|
||||
return;
|
||||
}
|
||||
ask(s, {
|
||||
player: c.attacker.player,
|
||||
kind: 'Memory Parasite:disable',
|
||||
prompt: 'Memory Parasite: which of your Hardware is disabled for this combat?',
|
||||
options: hw.map((h) => ({ label: nameOf(s, h), value: h })),
|
||||
resume: { name: 'Memory Parasite', fn: 'disable', data: null },
|
||||
});
|
||||
},
|
||||
resume: {
|
||||
disable(s, _data, hw: number) {
|
||||
s.combat?.suppressed.push(hw);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
// Reading: installing this card counts, so it can bring a second Virus with it.
|
||||
'Replication Routine': {
|
||||
text: 'When you install a Virus Program on this Server, you may install a second Virus Program from your hand here for no RAM cost.',
|
||||
onInstall(s, src, ev: { card: number; at: LocId | null }) {
|
||||
if (!src.at || ev.at !== src.at || src.virtual !== undefined || !isVirus(s, ev.card)) return;
|
||||
if (s.locations[src.at].programs.length >= programSlots(s, src.at)) return;
|
||||
const hand = s.players[src.controller].hand.filter((id) => isVirus(s, id));
|
||||
if (hand.length === 0) return;
|
||||
ask(s, {
|
||||
player: src.controller,
|
||||
kind: 'Replication Routine:install',
|
||||
prompt: `Replication Routine: install a second Virus Program on ${src.at} for free?`,
|
||||
options: [{ label: 'No', value: null }, ...cardOptions(s, hand)],
|
||||
resume: { name: 'Replication Routine', fn: 'install', data: { at: src.at } },
|
||||
});
|
||||
},
|
||||
resume: {
|
||||
install(s, data: { at: LocId }, card: number | null) {
|
||||
if (card === null || !controls(s, ownerOf(s, card), data.at)) return;
|
||||
if (s.locations[data.at].programs.length >= programSlots(s, data.at)) return;
|
||||
fired(s, 'Replication Routine', ownerOf(s, card));
|
||||
installFree(s, card, data.at);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
'Resource Leech': {
|
||||
text: 'Whenever an enemy Avatar is destroyed while attacking this Server, gain 5 RAM.',
|
||||
onDefeat(s, src, ev: { ref: AvatarRef; loc: LocId; role: string }) {
|
||||
if (ev.loc !== src.at || ev.role !== 'attack' || !enemyOf(src, ev.ref)) return;
|
||||
gainRam(s, src.controller, 5);
|
||||
fired(s, 'Resource Leech', src.controller);
|
||||
say(s, `Resource Leech: ${playerName(src.controller)} gains 5 RAM.`);
|
||||
},
|
||||
},
|
||||
|
||||
'Worm Protocol': {
|
||||
text: 'The localized effects of your other Programs on this Server also apply at one adjacent Server you choose when this is installed.',
|
||||
onInstall(s, src, ev: { card: number }) {
|
||||
if (ev.card !== src.id || src.virtual !== undefined) return;
|
||||
const near = neighbors(s, src.at!);
|
||||
if (near.length === 0) return;
|
||||
ask(s, {
|
||||
player: src.controller,
|
||||
kind: 'Worm Protocol:spread',
|
||||
prompt: `Worm Protocol on ${src.at}: spread your other Programs' effects to which adjacent location?`,
|
||||
options: near.map((l) => ({ label: l, value: l })),
|
||||
resume: { name: 'Worm Protocol', fn: 'spread', data: { card: src.id } },
|
||||
});
|
||||
},
|
||||
resume: {
|
||||
spread(s, data: { card: number }, to: LocId) {
|
||||
s.cards[data.card].wormTo = to;
|
||||
fired(s, 'Worm Protocol', ownerOf(s, data.card));
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
'Payload Injector': {
|
||||
text: 'The first Execution you play targeting this Server each turn costs 2 less RAM.',
|
||||
costMod: (s, src, pay) =>
|
||||
pay.kind === 'execution' && pay.player === src.controller && pay.at === src.at &&
|
||||
usedThisTurn(s, `payload:${src.id}`) === 0 ? -2 : 0,
|
||||
onPaid(s, src) {
|
||||
markUsed(s, `payload:${src.id}`);
|
||||
fired(s, 'Payload Injector', src.controller);
|
||||
},
|
||||
},
|
||||
|
||||
// Reading: enemy Avatars only (Virus Programs hit attackers). The counter survives defeat.
|
||||
'Persistent Infection': {
|
||||
text: 'If an Avatar is defeated at this Server, place an Infection Counter on it permanently.',
|
||||
onDefeat(s, src, ev: { ref: AvatarRef; loc: LocId }) {
|
||||
if (ev.loc !== src.at || !enemyOf(src, ev.ref) || isCopy(ev.ref)) return;
|
||||
infect(s, ev.ref, 1, 'Persistent Infection', src.controller, true);
|
||||
},
|
||||
},
|
||||
|
||||
// Reading: your Avatar attacking from this Server may declare a second attack on another
|
||||
// adjacent location. Both come from this Server, even if the first one moved it.
|
||||
'Infinite Loop': {
|
||||
text: 'If the attacking Avatar is controlled by the owner of this Program, it may attack a second adjacent Server in the same turn.',
|
||||
extraAttacks: 1,
|
||||
},
|
||||
|
||||
'Stack Overflow': {
|
||||
text: 'Avatars you control defending this Server gain +1 Core for each Program installed on this Server (including this one).',
|
||||
cores: (s, src, f) =>
|
||||
f.role === 'defend' && f.at === src.at && f.ref.player === src.controller ? installedCount(s, src.at!) : 0,
|
||||
},
|
||||
|
||||
// Both players pick at the same time; the attacker's pick stays hidden from the defender.
|
||||
'Race Condition': {
|
||||
text: 'During any combat at this Server, both players secretly choose Attack or Defend. If the choices differ, the defender gains a combat bonus of +2 Cores.',
|
||||
onCombatStart(s, src) {
|
||||
const c = s.combat!;
|
||||
if (c.loc !== src.at || !firstHere(s, src, c.loc)) return;
|
||||
fired(s, 'Race Condition', src.controller);
|
||||
askRace(s, c.attacker.player);
|
||||
},
|
||||
resume: {
|
||||
pick(s, data: { player: PlayerId }, pick: 'attack' | 'defend') {
|
||||
const c = s.combat;
|
||||
if (!c || c.ended) return;
|
||||
c.race[data.player] = pick;
|
||||
const defender = c.defenders[0]?.player ?? (c.attacker.player === 0 ? 1 : 0);
|
||||
if (data.player === c.attacker.player) {
|
||||
askRace(s, defender);
|
||||
return;
|
||||
}
|
||||
const [a, d] = [c.race[c.attacker.player], c.race[defender]];
|
||||
say(s, `Race Condition: attacker chose ${a}, defender chose ${d}.`);
|
||||
if (a !== d && c.defenders.length) {
|
||||
addMod(s, c.defenders[0], 2, 'Race Condition', defender, { combat: c.id });
|
||||
say(s, 'The choices differ: the defender gets +2 Cores.');
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
'Memory Leak': {
|
||||
text: 'At the start of any combat at this Server, the attacking Avatar loses 1 Core for each Hardware installed on it.',
|
||||
onCombatStart(s, src) {
|
||||
const c = s.combat!;
|
||||
if (c.loc !== src.at || !enemyOf(src, c.attacker) || bugImmune(s, c.attacker, src.controller)) return;
|
||||
const n = hardwareOf(s, c.attacker).length;
|
||||
if (n === 0) return;
|
||||
addMod(s, c.attacker, -n, 'Memory Leak', src.controller, { combat: c.id });
|
||||
fired(s, 'Memory Leak', src.controller);
|
||||
say(s, `Memory Leak: ${avatarName(s, c.attacker)} loses ${n} Core${n === 1 ? '' : 's'}.`);
|
||||
},
|
||||
},
|
||||
|
||||
'Null Pointer': {
|
||||
text: "Once per turn, when an enemy Execution would resolve at this Server, it's effect does not occur.",
|
||||
negates(s, src, item) {
|
||||
if (item.player === src.controller || item.target !== src.at || usedThisTurn(s, `null:${src.id}`) > 0) return false;
|
||||
markUsed(s, `null:${src.id}`);
|
||||
fired(s, 'Null Pointer', src.controller);
|
||||
say(s, `Null Pointer: ${item.name} has no effect.`);
|
||||
return true;
|
||||
},
|
||||
},
|
||||
|
||||
// Reading: "Hardware bonuses" are the Cores Hardware adds.
|
||||
'Stock Rice': {
|
||||
text: 'Neither Avatar in a combat that takes place at this Server may use any Hardware bonuses.',
|
||||
blocksHardwareInCombat: true,
|
||||
onCombatStart(s, src) {
|
||||
if (s.combat!.loc === src.at) fired(s, 'Stock Rice', src.controller);
|
||||
},
|
||||
},
|
||||
|
||||
// Reading: an unspecified disable lasts until something re-enables it (Execute: Defragment).
|
||||
'Overflow Error': {
|
||||
text: "When an enemy Avatar is destroyed while attacking this Server, destroy or disable one Program that Avatar's controller has in play.",
|
||||
onDefeat(s, src, ev: { ref: AvatarRef; loc: LocId; role: string }) {
|
||||
if (ev.loc !== src.at || ev.role !== 'attack' || !enemyOf(src, ev.ref)) return;
|
||||
const theirs = LOCATIONS.flatMap((l) => (controls(s, ev.ref.player, l) ? programsOn(s, l) : []))
|
||||
.filter((id) => canTargetProgram(s, id, src.controller));
|
||||
if (theirs.length === 0) return;
|
||||
fired(s, 'Overflow Error', src.controller);
|
||||
ask(s, {
|
||||
player: src.controller,
|
||||
kind: 'Overflow Error:hit',
|
||||
prompt: 'Overflow Error: destroy or disable one of their Programs.',
|
||||
options: theirs.flatMap((id) => [
|
||||
{ label: `Destroy ${nameOf(s, id)} on ${programLocation(s, id)}`, value: { card: id, mode: 'destroy' } },
|
||||
{ label: `Disable ${nameOf(s, id)} on ${programLocation(s, id)}`, value: { card: id, mode: 'disable' } },
|
||||
]),
|
||||
resume: { name: 'Overflow Error', fn: 'hit', data: null },
|
||||
});
|
||||
},
|
||||
resume: {
|
||||
hit(s, _data, v: { card: number; mode: string }) {
|
||||
if (!programLocation(s, v.card)) return;
|
||||
if (v.mode === 'destroy') destroyProgram(s, v.card);
|
||||
else s.cards[v.card].disabledUntil = FOREVER;
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
// Reading: the copy lasts until your next turn, while this Program is disabled.
|
||||
'Undefined Behavior': {
|
||||
text: 'Once per turn, copy the localized effect of another Program on another Server. Then disable this Program until your next turn.',
|
||||
ability: {
|
||||
uses(s, src) {
|
||||
if (src.kind !== 'program' || src.virtual !== undefined) return [];
|
||||
return LOCATIONS.filter((l) => l !== src.at)
|
||||
.flatMap((l) => programsOn(s, l))
|
||||
.filter((id) => nameOf(s, id) !== 'Undefined Behavior' && canTargetProgram(s, id, src.controller))
|
||||
.map((card) => ({ card }));
|
||||
},
|
||||
resolve(s, item, src) {
|
||||
const card = item.args.card!;
|
||||
if (!programLocation(s, card)) return;
|
||||
const until = startOf(nextTurnOf(s, src.controller));
|
||||
s.virtuals.push({ id: ++s.seq, name: nameOf(s, card), controller: src.controller, at: src.at!, until, installed: false, from: card });
|
||||
s.cards[src.id].disabledUntil = Math.max(s.cards[src.id].disabledUntil, until);
|
||||
fired(s, 'Undefined Behavior', src.controller);
|
||||
say(s, `Undefined Behavior on ${src.at} copies ${nameOf(s, card)} and shuts itself off until ${playerName(src.controller)}'s next turn.`);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
'Packet Loss': {
|
||||
text: 'When an enemy successfully breaches this Server, its controller discards a card at random.',
|
||||
onBreach(s, src, ev: { ref: AvatarRef; loc: LocId }) {
|
||||
if (ev.loc !== src.at || !enemyOf(src, ev.ref)) return;
|
||||
const hand = s.players[ev.ref.player].hand;
|
||||
if (hand.length === 0) return;
|
||||
const card = hand[randInt(s.rng, hand.length)];
|
||||
removeFrom(hand, card);
|
||||
toDiscard(s, card);
|
||||
fired(s, 'Packet Loss', src.controller);
|
||||
say(s, `Packet Loss: ${playerName(ev.ref.player)} discards ${nameOf(s, card)} at random.`);
|
||||
},
|
||||
},
|
||||
|
||||
// The once-per-turn Hardware abilities are Hot-Swap Bay's and Quantum Coprocessor's.
|
||||
Desynchronization: {
|
||||
text: 'Enemy Avatars attacking this Server cannot use their Hardware\'s "once per turn" abilities during that combat.',
|
||||
blocksHardwareAbilities: true,
|
||||
},
|
||||
|
||||
// Reading: "each turn" was removed from the card, so this works once per installation.
|
||||
'Visual Artifact': {
|
||||
text: 'The first attack made against an Avatar you control at this Server suffers -1 Core.',
|
||||
onCombatStart(s, src) {
|
||||
const c = s.combat!;
|
||||
if (c.loc !== src.at || s.cards[src.id].spent || c.defenders.every((d) => d.player !== src.controller)) return;
|
||||
s.cards[src.id].spent = true;
|
||||
addMod(s, c.attacker, -1, 'Visual Artifact', src.controller, { combat: c.id });
|
||||
fired(s, 'Visual Artifact', src.controller);
|
||||
say(s, `Visual Artifact: ${avatarName(s, c.attacker)} gets -1 Core.`);
|
||||
},
|
||||
},
|
||||
|
||||
// Executions check for this through scopeOf() in util.ts.
|
||||
'Ghost Process': {
|
||||
text: 'Your Executions played targeting this Server may also affect Avatars, Programs, and Hardware at one adjacent Server.',
|
||||
},
|
||||
|
||||
// Runs from the engine right after an enemy Execution that targets an Avatar is played.
|
||||
'False Positive': {
|
||||
text: 'When an enemy Execution targets an Avatar you control at this Server, you may redirect it to another legal Avatar at another Server.',
|
||||
resume: {
|
||||
offer(s, data: { index: number }) {
|
||||
const item = s.stack[data.index];
|
||||
if (!item) return;
|
||||
const ex = scriptOf(item.name)?.execution;
|
||||
const hit = ex?.targetsAvatars?.(s, item) ?? [];
|
||||
const guarded = hit.find((r) => {
|
||||
if (r.player === item.player) return false;
|
||||
const at = avatar(s, r).at;
|
||||
return sources(s).some((x) => x.name === 'False Positive' && x.at === at && x.controller === r.player);
|
||||
});
|
||||
if (!ex || !guarded) return;
|
||||
const from = avatar(s, guarded).at;
|
||||
const options = ex.plays(s, item.player).filter((play) => {
|
||||
const refs = ex.targetsAvatars?.(s, { player: item.player, target: play.target, args: play.args }) ?? [];
|
||||
return refs.length > 0 && refs.every((r) => avatar(s, r).at !== from && !sameRef(r, guarded));
|
||||
});
|
||||
if (options.length === 0) return;
|
||||
ask(s, {
|
||||
player: guarded.player,
|
||||
kind: 'False Positive:redirect',
|
||||
prompt: `False Positive: redirect ${item.name} away from ${avatarName(s, guarded)}?`,
|
||||
options: [
|
||||
{ label: 'Leave it', value: null },
|
||||
...options.map((play) => ({
|
||||
label: `Redirect to ${play.args.ref ? avatarName(s, play.args.ref) : nameOf(s, play.args.card ?? -1)} on ${play.target}`,
|
||||
value: { index: data.index, target: play.target, args: play.args as never },
|
||||
})),
|
||||
],
|
||||
resume: { name: 'False Positive', fn: 'redirect', data: null },
|
||||
});
|
||||
},
|
||||
redirect(s, _data, v: { index: number; target: LocId; args: never } | null) {
|
||||
if (!v) return;
|
||||
const item = s.stack[v.index];
|
||||
if (!item) return;
|
||||
item.target = v.target;
|
||||
item.args = v.args;
|
||||
fired(s, 'False Positive', item.player === 0 ? 1 : 0);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
Fragmentation: {
|
||||
text: 'Executions your opponents play targeting this Server cost +2 RAM.',
|
||||
costMod: (s, src, pay) => (pay.kind === 'execution' && pay.player !== src.controller && pay.at === src.at ? 2 : 0),
|
||||
onPaid: (s, src) => fired(s, 'Fragmentation', src.controller),
|
||||
},
|
||||
|
||||
'Latency Spike': {
|
||||
text: 'The attacking player cannot play Executions during the first step of any combat at this Server.',
|
||||
blocksAttackerExecutions: true,
|
||||
},
|
||||
|
||||
// Destroyed means destroyed by an effect (Overflow Error). A captured location's Programs aren't
|
||||
// destroyed; they're discarded (see Version Control).
|
||||
Hotfix: {
|
||||
text: 'The first Program on this Server that would be destroyed each turn is instead disabled until your next turn.',
|
||||
},
|
||||
|
||||
'Error Correction': {
|
||||
text: 'At the beginning of your turn, remove one negative counter or status from each Avatar you control at this Server.',
|
||||
onTurnStart(s, src) {
|
||||
if (s.active !== src.controller) return;
|
||||
const tasks: Task[] = refsInPlay(s, src.controller)
|
||||
.filter((r) => avatar(s, r).at === src.at)
|
||||
.map((r) => later('Error Correction', 'fix', { ref: r as never }));
|
||||
pushTasks(s, ...tasks);
|
||||
},
|
||||
resume: {
|
||||
fix(s, data: { ref: AvatarRef }) {
|
||||
const list = negatives(s, data.ref);
|
||||
if (list.length === 0) return;
|
||||
fired(s, 'Error Correction', data.ref.player);
|
||||
if (list.length === 1) {
|
||||
removeNegative(s, data.ref, list[0].value);
|
||||
say(s, `Error Correction removes ${list[0].label} from ${avatarName(s, data.ref)}.`);
|
||||
return;
|
||||
}
|
||||
ask(s, {
|
||||
player: data.ref.player,
|
||||
kind: 'Error Correction:remove',
|
||||
prompt: `Error Correction: remove what from ${avatarName(s, data.ref)}?`,
|
||||
options: list,
|
||||
resume: { name: 'Error Correction', fn: 'remove', data: { ref: data.ref as never } },
|
||||
});
|
||||
},
|
||||
remove(s, data: { ref: AvatarRef }, what: string) {
|
||||
removeNegative(s, data.ref, what);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
// Reading: it can sacrifice itself.
|
||||
'Garbage Collection': {
|
||||
text: 'Once per turn, sacrifice one Program installed on this Server to recover its printed RAM value.',
|
||||
ability: {
|
||||
uses: (s, src) => (src.kind === 'program' ? s.locations[src.at!].programs.map((card) => ({ card })) : []),
|
||||
resolve(s, item, src) {
|
||||
const card = item.args.card!;
|
||||
if (programLocation(s, card) !== src.at) return;
|
||||
uninstallProgram(s, card);
|
||||
toDiscard(s, card);
|
||||
stat(s, 'programsLost', src.controller);
|
||||
gainRam(s, src.controller, defOf(s, card).ram);
|
||||
fired(s, 'Garbage Collection', src.controller);
|
||||
say(s, `Garbage Collection sacrifices ${nameOf(s, card)} for ${defOf(s, card).ram} RAM.`);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
'Version Control': {
|
||||
text: 'When a Program on this Server would be destroyed, or when this Server is captured, return one Program from this Server to your hand instead of discarding it.',
|
||||
onCaptured(s, src, ev: { loc: LocId }) {
|
||||
if (ev.loc !== src.at || src.virtual !== undefined) return;
|
||||
const here = s.locations[ev.loc].programs;
|
||||
if (here.length === 0) return;
|
||||
ask(s, {
|
||||
player: src.controller,
|
||||
kind: 'Version Control:save',
|
||||
prompt: `Version Control: ${ev.loc} is being captured. Return which Program to your hand?`,
|
||||
options: here.map((id) => ({ label: nameOf(s, id), value: id })),
|
||||
resume: { name: 'Version Control', fn: 'save', data: null },
|
||||
});
|
||||
},
|
||||
resume: {
|
||||
save(s, _data, card: number) {
|
||||
if (!uninstallProgram(s, card)) return;
|
||||
toHand(s, card);
|
||||
fired(s, 'Version Control', ownerOf(s, card));
|
||||
say(s, `Version Control returns ${nameOf(s, card)} to ${playerName(ownerOf(s, card))}'s hand.`);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
'Rollback Routine': {
|
||||
text: 'Once per turn, undo the most recent temporary stat reduction applied to an Avatar you control at this Server.',
|
||||
ability: {
|
||||
uses(s, src) {
|
||||
if (src.kind !== 'program') return [];
|
||||
return refsInPlay(s, src.controller)
|
||||
.filter((r) => avatar(s, r).at === src.at && activeMods(s, avatar(s, r)).some((m) => m.cores < 0))
|
||||
.map((ref) => ({ ref }));
|
||||
},
|
||||
resolve(s, item, src) {
|
||||
const av = avatar(s, item.args.ref!);
|
||||
if (av.at !== src.at) return;
|
||||
const last = activeMods(s, av).filter((m) => m.cores < 0).sort((a, b) => b.seq - a.seq)[0];
|
||||
if (!last) return;
|
||||
av.mods = av.mods.filter((m) => m !== last);
|
||||
fired(s, 'Rollback Routine', src.controller);
|
||||
say(s, `Rollback Routine undoes ${last.cores} Cores from ${last.source} on ${avatarName(s, item.args.ref!)}.`);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
'Compatibility Layer': {
|
||||
text: 'This Server may hold one additional Program beyond the normal limit, and Patch Programs installed here cost 2 less RAM.',
|
||||
programSlots: 1,
|
||||
costMod: (s, src, pay) =>
|
||||
pay.kind === 'program' && pay.player === src.controller && pay.at === src.at && isPatch(s, pay.card!) ? -2 : 0,
|
||||
onPaid: (s, src) => fired(s, 'Compatibility Layer', src.controller),
|
||||
},
|
||||
};
|
||||
|
||||
function askRace(s: GameState, player: PlayerId): void {
|
||||
ask(s, {
|
||||
player,
|
||||
kind: 'Race Condition:pick',
|
||||
prompt: 'Race Condition: secretly choose Attack or Defend.',
|
||||
options: [{ label: 'Attack', value: 'attack' }, { label: 'Defend', value: 'defend' }],
|
||||
resume: { name: 'Race Condition', fn: 'pick', data: { player } },
|
||||
});
|
||||
}
|
||||
160
sim/src/cards/servers.ts
Normal file
160
sim/src/cards/servers.ts
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
/**
|
||||
* Servers. A Server's ability belongs to the player who controls its location and applies at that
|
||||
* location, unless the text says otherwise.
|
||||
*/
|
||||
import { createCopy, drawNow } from '../flow.ts';
|
||||
import { LINE_BY_ID } from '../map.ts';
|
||||
import { hasRoom, sameSource, sourcesNamed } from '../query.ts';
|
||||
import type { Fighter, Script } from '../scripts.ts';
|
||||
import {
|
||||
ask,
|
||||
avatar,
|
||||
copyOf,
|
||||
defendersAt,
|
||||
fired,
|
||||
gainRam,
|
||||
isCopy,
|
||||
nameOf,
|
||||
neighbors,
|
||||
playerName,
|
||||
refsInPlay,
|
||||
removeFrom,
|
||||
say,
|
||||
} from '../state.ts';
|
||||
import { LOCATIONS } from '../map.ts';
|
||||
import type { GameState, PlayerId, Source } from '../types.ts';
|
||||
|
||||
/** Core bonus for the controller's Avatar standing on this Server (attacking from it or defending it). */
|
||||
const coreBonus = (n: number) => (s: GameState, src: Source, f: Fighter) =>
|
||||
f.at === src.at && f.ref.player === src.controller ? n : 0;
|
||||
|
||||
export const SERVERS: Record<string, Script> = {
|
||||
'High Efficiency RAM Server': { text: 'Add additional 4 RAM to resource total', ramOnPlace: 4 },
|
||||
'Power Server': { text: 'Add additional 4 RAM to resource total', ramOnPlace: 4 },
|
||||
'Server Farm': {
|
||||
text: 'Add 4 RAM to resource total and 2 Cores to any Avatar',
|
||||
ramOnPlace: 4,
|
||||
cores: coreBonus(2),
|
||||
},
|
||||
'MultiCore Server': { text: 'Add 2 Cores to any Avatars', cores: coreBonus(2) },
|
||||
'Cloud Compute': { text: 'Add 4 Cores to any Avatars', cores: coreBonus(4) },
|
||||
'Cluster Server': { text: 'Up to 2 Avatars can defend this Server', capacity: 2 },
|
||||
'Pingable Server': { text: 'Up to 2 Avatars can defend this Server', capacity: 2 },
|
||||
|
||||
// Reading: once per turn, at any time, make a copy of your Avatar based here (Carbon NanoBots'
|
||||
// copy rules). The copy enters play on any location you control with room.
|
||||
'Backup Server': {
|
||||
text: 'Duplicate Avatar based at this Server',
|
||||
ability: {
|
||||
uses(s, src) {
|
||||
const p = src.controller;
|
||||
const spots = LOCATIONS.filter((l) => hasRoom(s, p, l));
|
||||
return refsInPlay(s, p)
|
||||
.filter((r) => !isCopy(r) && avatar(s, r).at === src.at && avatar(s, copyOf(r)).at === null)
|
||||
.flatMap((r) => spots.map((to) => ({ ref: r, to })));
|
||||
},
|
||||
resolve(s, item) {
|
||||
const r = item.args.ref!;
|
||||
const to = item.args.to!;
|
||||
if (avatar(s, r).at === null || avatar(s, copyOf(r)).at !== null || !hasRoom(s, r.player, to)) return;
|
||||
fired(s, 'Backup Server', r.player);
|
||||
createCopy(s, r, to);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
'Upgraded Hardware': {
|
||||
text: 'Hardware upgrades cost 2 less RAM to install',
|
||||
costMod: (s, src, pay) => (pay.kind === 'hardware' && pay.player === src.controller && pay.at === src.at ? -2 : 0),
|
||||
onPaid: (s, src) => fired(s, 'Upgraded Hardware', src.controller),
|
||||
},
|
||||
|
||||
'Network Throttle': {
|
||||
text: 'Firewalls cost 1 less RAM to install',
|
||||
costMod(s, src, pay) {
|
||||
if (pay.kind !== 'firewall' || pay.player !== src.controller) return 0;
|
||||
const line = LINE_BY_ID.get(pay.line!)!;
|
||||
return line.a === src.at || line.b === src.at ? -1 : 0;
|
||||
},
|
||||
onPaid: (s, src) => fired(s, 'Network Throttle', src.controller),
|
||||
},
|
||||
|
||||
// Reading: when placed, pick one adjacent Server (either player's) and gain its ability for as
|
||||
// long as this card stays. A copied RAM bonus is paid right away.
|
||||
'Duplicate Server': {
|
||||
text: 'Copy one adjacent Server ability',
|
||||
onPlaced(s, src, ev: { card: number }) {
|
||||
if (ev.card !== src.id || src.virtual !== undefined) return;
|
||||
const names = new Set<string>();
|
||||
for (const n of neighbors(s, src.at!)) {
|
||||
const sv = s.locations[n].server;
|
||||
if (sv !== null && nameOf(s, sv) !== 'Duplicate Server') names.add(nameOf(s, sv));
|
||||
}
|
||||
if (names.size === 0) return;
|
||||
ask(s, {
|
||||
player: src.controller,
|
||||
kind: 'Duplicate Server:copy',
|
||||
prompt: `Duplicate Server on ${src.at}: copy which adjacent Server?`,
|
||||
options: [...names].map((n) => ({ label: n, value: n })),
|
||||
resume: { name: 'Duplicate Server', fn: 'copy', data: { card: src.id, player: src.controller } },
|
||||
});
|
||||
},
|
||||
resume: {
|
||||
copy(s, data: { card: number; player: PlayerId }, name: string) {
|
||||
s.cards[data.card].copies = name;
|
||||
const p = data.player;
|
||||
fired(s, 'Duplicate Server', p);
|
||||
say(s, `Duplicate Server copies ${name}.`);
|
||||
const bonus = SERVERS[name]?.ramOnPlace ?? 0;
|
||||
if (bonus) {
|
||||
gainRam(s, p, bonus, 'ramFromCaptures');
|
||||
say(s, `${playerName(p)} gains ${bonus} RAM from the copied ability.`);
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
'Protected Server': {
|
||||
text: 'Add 2 RAM if defending this Server',
|
||||
onCombatStart(s, src) {
|
||||
const c = s.combat!;
|
||||
if (c.loc !== src.at || defendersAt(s, c.loc).every((d) => d.player !== src.controller)) return;
|
||||
gainRam(s, src.controller, 2);
|
||||
fired(s, 'Protected Server', src.controller);
|
||||
say(s, `Protected Server: ${playerName(src.controller)} gains 2 RAM for defending.`);
|
||||
},
|
||||
},
|
||||
|
||||
// Reading: applies to every draw after the opening hand, once per card drawn.
|
||||
'Callable Server': {
|
||||
text: 'When drawing a card, you may choose to place it on the bottom of the deck and draw another',
|
||||
onDraw(s, src, ev: { player: PlayerId; card: number }) {
|
||||
if (ev.player !== src.controller || s.players[ev.player].deck.length === 0) return;
|
||||
const first = sourcesNamed(s, 'Callable Server').find((x) => x.controller === ev.player);
|
||||
if (!first || !sameSource(first, src)) return;
|
||||
if (!s.players[ev.player].hand.includes(ev.card)) return;
|
||||
ask(s, {
|
||||
player: ev.player,
|
||||
kind: 'Callable Server:redraw',
|
||||
prompt: `Callable Server: keep ${nameOf(s, ev.card)}, or put it on the bottom and draw another?`,
|
||||
options: [
|
||||
{ label: `Keep ${nameOf(s, ev.card)}`, value: false },
|
||||
{ label: `Bottom ${nameOf(s, ev.card)} and draw again`, value: true },
|
||||
],
|
||||
resume: { name: 'Callable Server', fn: 'redraw', data: { player: ev.player, card: ev.card } },
|
||||
});
|
||||
},
|
||||
resume: {
|
||||
redraw(s, data: { player: PlayerId; card: number }, again: boolean) {
|
||||
if (!again) return;
|
||||
const pl = s.players[data.player];
|
||||
if (!removeFrom(pl.hand, data.card)) return;
|
||||
pl.deck.push(data.card);
|
||||
fired(s, 'Callable Server', data.player);
|
||||
drawNow(s, data.player);
|
||||
s.stats.cardsDrawn[data.player]--;
|
||||
say(s, `${playerName(data.player)} bottoms a card and draws again.`);
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
89
sim/src/cards/util.ts
Normal file
89
sim/src/cards/util.ts
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
/** Helpers shared by card scripts. */
|
||||
import type { LocId } from '../map.ts';
|
||||
import { bugImmune, hardwareActive, programActive, sources } from '../query.ts';
|
||||
import {
|
||||
atServer,
|
||||
avatar,
|
||||
avatarName,
|
||||
defOf,
|
||||
fired,
|
||||
nameOf,
|
||||
neighbors,
|
||||
playerName,
|
||||
refsInPlay,
|
||||
say,
|
||||
} from '../state.ts';
|
||||
import type { AvatarRef, ChoiceOption, GameState, PlayerId, Source } from '../types.ts';
|
||||
|
||||
/** Locations where `p` has Ghost Process working. */
|
||||
export const ghostsOf = (s: GameState, p: PlayerId): Set<LocId> =>
|
||||
new Set(sources(s).filter((x) => x.name === 'Ghost Process' && x.controller === p).map((x) => x.at!));
|
||||
|
||||
/** Locations an Execution played on `target` can reach: Ghost Process adds one adjacent location. */
|
||||
export function scopeOf(s: GameState, p: PlayerId, target: LocId, ghosts = ghostsOf(s, p)): LocId[] {
|
||||
return ghosts.has(target) ? [target, ...neighbors(s, target)] : [target];
|
||||
}
|
||||
|
||||
export const mine = (s: GameState, p: PlayerId, loc: LocId): AvatarRef[] =>
|
||||
atServer(s, loc).filter((r) => r.player === p);
|
||||
|
||||
/** Active, installed Programs on a location. */
|
||||
export const programsOn = (s: GameState, loc: LocId): number[] =>
|
||||
s.locations[loc].programs.filter((id) => programActive(s, id));
|
||||
|
||||
export const activeHardware = (s: GameState, ids: number[]): number[] => ids.filter((id) => hardwareActive(s, id));
|
||||
|
||||
/**
|
||||
* Places Bug counters: like Infection counters, for Bug cards. No card places them yet. ECC Memory
|
||||
* stops opponents from placing them.
|
||||
*/
|
||||
export function addBugs(s: GameState, ref: AvatarRef, n: number, source: string, by: PlayerId): boolean {
|
||||
if (bugImmune(s, ref, by)) {
|
||||
say(s, `ECC Memory blocks ${source}'s Bug counters on ${avatarName(s, ref)}.`);
|
||||
fired(s, 'ECC Memory', ref.player);
|
||||
return false;
|
||||
}
|
||||
avatar(s, ref).bugs += n;
|
||||
fired(s, source, by);
|
||||
say(s, `${source}: ${avatarName(s, ref)} gets ${n} Bug counter${n === 1 ? '' : 's'} (${avatar(s, ref).bugs} total).`);
|
||||
return true;
|
||||
}
|
||||
|
||||
export function infect(s: GameState, ref: AvatarRef, n: number, source: string, by: PlayerId, permanent = false): void {
|
||||
const av = avatar(s, ref);
|
||||
if (permanent) av.permanentInfection += n;
|
||||
else av.infection += n;
|
||||
fired(s, source, by);
|
||||
say(s, `${source}: ${avatarName(s, ref)} gets ${n === 1 ? 'an' : n} ${permanent ? 'permanent ' : ''}Infection counter${n === 1 ? '' : 's'} (${av.infection + av.permanentInfection} total).`);
|
||||
}
|
||||
|
||||
/** One option per distinct card name. */
|
||||
export function cardOptions(s: GameState, ids: number[]): ChoiceOption[] {
|
||||
const seen = new Set<string>();
|
||||
const out: ChoiceOption[] = [];
|
||||
for (const id of ids) {
|
||||
const name = nameOf(s, id);
|
||||
if (seen.has(name)) continue;
|
||||
seen.add(name);
|
||||
out.push({ label: name, value: id });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export const isVirus = (s: GameState, id: number): boolean => defOf(s, id).kind === 'program' && defOf(s, id).type === 'V';
|
||||
export const isPatch = (s: GameState, id: number): boolean => defOf(s, id).kind === 'program' && defOf(s, id).type === 'P';
|
||||
|
||||
export const whose = (p: PlayerId): string => playerName(p);
|
||||
|
||||
/** Distinct non-empty subsets of up to 3 items. */
|
||||
export function subsets<T>(items: T[]): T[][] {
|
||||
const out: T[][] = [];
|
||||
const n = Math.min(items.length, 3);
|
||||
for (let mask = 1; mask < 1 << n; mask++) out.push(items.slice(0, n).filter((_, i) => mask & (1 << i)));
|
||||
return out;
|
||||
}
|
||||
|
||||
export const srcLabel = (s: GameState, src: Source): string =>
|
||||
src.kind === 'avatar' ? `${defOf(s, src.id).ability?.name} (${src.name})` : src.name;
|
||||
|
||||
export const everyAvatarInPlay = (s: GameState): AvatarRef[] => [...refsInPlay(s, 0), ...refsInPlay(s, 1)];
|
||||
120
sim/src/cli.ts
Normal file
120
sim/src/cli.ts
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
import { mkdirSync, writeFileSync } from 'node:fs';
|
||||
import { dirname } from 'node:path';
|
||||
import { parseArgs } from 'node:util';
|
||||
import type { BotFactory } from './bots/bot.ts';
|
||||
import { DEFAULT_GREEDY, greedyBot } from './bots/greedy.ts';
|
||||
import { randomBot } from './bots/random.ts';
|
||||
import { DEFAULT_CARDS_CSV, loadCards, type CardKind } from './cards.ts';
|
||||
import { playGame } from './play.ts';
|
||||
import { DEFAULT_RULES } from './rules.ts';
|
||||
import { isImplemented, staleScripts } from './scripts.ts';
|
||||
import { cardReport, formatCardReport, formatSummary, recordOf, summarize, type GameRecord } from './stats.ts';
|
||||
import { PLAYER_NAMES } from './types.ts';
|
||||
|
||||
const BOTS: Record<string, { about: string; make: BotFactory }> = {
|
||||
greedy: { about: 'grabs open locations, attacks at 60%+ odds, walls with Lv 1 Firewalls, plays its cards', make: () => greedyBot() },
|
||||
nocards: { about: 'greedy, but only uses Core Hardware (the Phase 2 bot)', make: () => greedyBot({ ...DEFAULT_GREEDY, useCards: false }) },
|
||||
bold: { about: 'greedy, but attacks at 50%+ odds', make: () => greedyBot({ ...DEFAULT_GREEDY, minWinChance: 0.5 }) },
|
||||
cautious: { about: 'greedy, but attacks only at 75%+ odds', make: () => greedyBot({ ...DEFAULT_GREEDY, minWinChance: 0.75 }) },
|
||||
nowall: { about: 'greedy, but never places Firewalls', make: () => greedyBot({ ...DEFAULT_GREEDY, firewallLevel: 0 }) },
|
||||
wall3: { about: 'greedy, but walls with Lv 3 Firewalls', make: () => greedyBot({ ...DEFAULT_GREEDY, firewallLevel: 3 }) },
|
||||
random: { about: 'picks any legal action', make: randomBot },
|
||||
};
|
||||
|
||||
const USAGE = `Files TCG simulator
|
||||
|
||||
node src/cli.ts [options]
|
||||
|
||||
-n, --games N games to play (default 1000)
|
||||
--seed N first game's seed; game i uses seed + i (default 1)
|
||||
--south BOT South's bot (default greedy)
|
||||
--north BOT North's bot (default greedy)
|
||||
--max-turns N player turns before a draw (default ${DEFAULT_RULES.maxTurns})
|
||||
--log play one game and print the play-by-play
|
||||
--check check rule invariants after every action (slow)
|
||||
--json FILE also write the summary and every game's result as JSON
|
||||
--card-report also print each card's win rate (decks holding it) and how often bots played it
|
||||
--cards FILE card CSV (default decks/files-deck-1/cards.csv)
|
||||
|
||||
Bots:
|
||||
${Object.entries(BOTS).map(([name, b]) => ` ${name.padEnd(10)} ${b.about}`).join('\n')}
|
||||
`;
|
||||
|
||||
const { values: opt } = parseArgs({
|
||||
options: {
|
||||
games: { type: 'string', short: 'n', default: '1000' },
|
||||
seed: { type: 'string', default: '1' },
|
||||
south: { type: 'string', default: 'greedy' },
|
||||
north: { type: 'string', default: 'greedy' },
|
||||
'max-turns': { type: 'string' },
|
||||
log: { type: 'boolean', default: false },
|
||||
check: { type: 'boolean', default: false },
|
||||
json: { type: 'string' },
|
||||
'card-report': { type: 'boolean', default: false },
|
||||
cards: { type: 'string', default: DEFAULT_CARDS_CSV },
|
||||
help: { type: 'boolean', short: 'h', default: false },
|
||||
},
|
||||
});
|
||||
|
||||
if (opt.help) {
|
||||
console.log(USAGE);
|
||||
process.exit(0);
|
||||
}
|
||||
for (const side of [opt.south, opt.north]) {
|
||||
if (!BOTS[side]) {
|
||||
console.error(`Unknown bot "${side}". Choose from: ${Object.keys(BOTS).join(', ')}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
function count(name: string, value: string | undefined): number | undefined {
|
||||
if (value === undefined) return undefined;
|
||||
const n = Number(value);
|
||||
if (!Number.isInteger(n) || n < 0) {
|
||||
console.error(`--${name} needs a whole number, got "${value}"`);
|
||||
process.exit(1);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
const games = count('games', opt.games)!;
|
||||
const seed = count('seed', opt.seed)!;
|
||||
const maxTurns = count('max-turns', opt['max-turns']);
|
||||
|
||||
const pool = loadCards(opt.cards);
|
||||
const rules = maxTurns === undefined ? DEFAULT_RULES : { ...DEFAULT_RULES, maxTurns };
|
||||
const bots: [BotFactory, BotFactory] = [BOTS[opt.south].make, BOTS[opt.north].make];
|
||||
|
||||
for (const warning of staleScripts(pool)) console.warn(`warning: ${warning}`);
|
||||
const KIND_LABELS: [CardKind, string][] = [
|
||||
['avatar', 'Avatars'], ['server', 'Servers'], ['hardware', 'Hardware'], ['program', 'Programs'], ['execution', 'Executions'],
|
||||
];
|
||||
const coverage = KIND_LABELS.map(([kind, label]) => {
|
||||
const cards = pool.all.filter((c) => c.kind === kind);
|
||||
return `${label} ${cards.filter(isImplemented).length}/${cards.length}`;
|
||||
});
|
||||
console.log(`Card effects simulated: ${coverage.join(', ')}.\n`);
|
||||
|
||||
if (opt.log) {
|
||||
const s = playGame({ pool, bots, seed, rules, log: true, check: opt.check });
|
||||
console.log(s.log!.join('\n'));
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const labels: [string, string] = [`${PLAYER_NAMES[0]} (${opt.south})`, `${PLAYER_NAMES[1]} (${opt.north})`];
|
||||
const started = performance.now();
|
||||
const records: GameRecord[] = [];
|
||||
for (let i = 0; i < games; i++) {
|
||||
records.push(recordOf(seed + i, playGame({ pool, bots, seed: seed + i, rules, check: opt.check })));
|
||||
}
|
||||
const seconds = (performance.now() - started) / 1000;
|
||||
const summary = summarize(records);
|
||||
|
||||
console.log(`${games} games, ${labels[0]} vs ${labels[1]}, seeds ${seed}–${seed + games - 1} (${seconds.toFixed(1)}s)\n`);
|
||||
console.log(formatSummary(summary, labels));
|
||||
if (opt['card-report']) console.log(`\n${formatCardReport(cardReport(pool, records))}`);
|
||||
|
||||
if (opt.json) {
|
||||
mkdirSync(dirname(opt.json), { recursive: true });
|
||||
writeFileSync(opt.json, JSON.stringify({ south: opt.south, north: opt.north, summary, games: records }, null, 2));
|
||||
console.log(`\nWrote ${opt.json}`);
|
||||
}
|
||||
40
sim/src/csv.ts
Normal file
40
sim/src/csv.ts
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
/** Minimal RFC 4180 parser: quoted fields, "" escapes, and commas or newlines inside quotes. */
|
||||
export function parseCsv(text: string): string[][] {
|
||||
const rows: string[][] = [];
|
||||
let row: string[] = [];
|
||||
let field = '';
|
||||
let quoted = false;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const ch = text[i];
|
||||
if (quoted) {
|
||||
if (ch !== '"') field += ch;
|
||||
else if (text[i + 1] === '"') {
|
||||
field += '"';
|
||||
i++;
|
||||
} else quoted = false;
|
||||
} else if (ch === '"') quoted = true;
|
||||
else if (ch === ',') {
|
||||
row.push(field);
|
||||
field = '';
|
||||
} else if (ch === '\n' || ch === '\r') {
|
||||
if (ch === '\r' && text[i + 1] === '\n') i++;
|
||||
row.push(field);
|
||||
rows.push(row);
|
||||
row = [];
|
||||
field = '';
|
||||
} else field += ch;
|
||||
}
|
||||
if (field !== '' || row.length > 0) {
|
||||
row.push(field);
|
||||
rows.push(row);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** Rows keyed by header name, skipping blank lines. */
|
||||
export function parseCsvObjects(text: string): Record<string, string>[] {
|
||||
const [header, ...rows] = parseCsv(text);
|
||||
return rows
|
||||
.filter((r) => r.some((f) => f !== ''))
|
||||
.map((r) => Object.fromEntries(header.map((h, i) => [h, r[i] ?? ''])));
|
||||
}
|
||||
57
sim/src/deck.ts
Normal file
57
sim/src/deck.ts
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
import type { CardDef, CardKind, CardPool } from './cards.ts';
|
||||
import { shuffle, type Rng } from './rng.ts';
|
||||
import type { RulesConfig } from './rules.ts';
|
||||
|
||||
export interface DeckList {
|
||||
avatars: string[];
|
||||
servers: string[];
|
||||
/** Executions, Hardware and Programs. */
|
||||
main: string[];
|
||||
}
|
||||
|
||||
const MAIN_KINDS: CardKind[] = ['program', 'hardware', 'execution'];
|
||||
|
||||
/** Problems with a deck list; empty when it's legal. */
|
||||
export function validateDeck(pool: CardPool, deck: DeckList, rules: RulesConfig): string[] {
|
||||
const errors: string[] = [];
|
||||
const part = (label: string, names: string[], kinds: CardKind[], size: number) => {
|
||||
if (names.length !== size) errors.push(`${label}: ${names.length} cards, needs ${size}`);
|
||||
for (const name of names) {
|
||||
const card = pool.byName.get(name);
|
||||
if (!card) errors.push(`${label}: unknown card "${name}"`);
|
||||
else if (!kinds.includes(card.kind)) errors.push(`${label}: "${name}" is a ${card.kind}`);
|
||||
}
|
||||
};
|
||||
part('Avatars', deck.avatars, ['avatar'], rules.deck.avatars);
|
||||
part('Servers', deck.servers, ['server'], rules.deck.servers);
|
||||
part('Deck', deck.main, MAIN_KINDS, rules.deck.main);
|
||||
const copies = new Map<string, number>();
|
||||
for (const name of [...deck.avatars, ...deck.servers, ...deck.main]) {
|
||||
copies.set(name, (copies.get(name) ?? 0) + 1);
|
||||
}
|
||||
for (const [name, n] of copies) {
|
||||
if (n > rules.deck.maxCopies) errors.push(`${n} copies of "${name}", max ${rules.deck.maxCopies}`);
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
/** A random legal deck: every card in the pool is equally likely, up to the copy limit. */
|
||||
export function randomDeck(
|
||||
pool: CardPool,
|
||||
rng: Rng,
|
||||
rules: RulesConfig,
|
||||
include: (card: CardDef) => boolean = () => true,
|
||||
): DeckList {
|
||||
const sample = (kinds: CardKind[], size: number): string[] => {
|
||||
const names = pool.all
|
||||
.filter((c) => kinds.includes(c.kind) && include(c))
|
||||
.flatMap((c) => Array<string>(rules.deck.maxCopies).fill(c.name));
|
||||
if (names.length < size) throw new Error(`Not enough ${kinds.join('/')} cards for a deck`);
|
||||
return shuffle(rng, names).slice(0, size);
|
||||
};
|
||||
return {
|
||||
avatars: sample(['avatar'], rules.deck.avatars),
|
||||
servers: sample(['server'], rules.deck.servers),
|
||||
main: sample(MAIN_KINDS, rules.deck.main),
|
||||
};
|
||||
}
|
||||
912
sim/src/engine.ts
Normal file
912
sim/src/engine.ts
Normal 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'),
|
||||
};
|
||||
}
|
||||
403
sim/src/flow.ts
Normal file
403
sim/src/flow.ts
Normal file
|
|
@ -0,0 +1,403 @@
|
|||
/**
|
||||
* The parts of a turn that run on their own once started: resolving declarations, combat,
|
||||
* defeat, capture and drawing. Card scripts call into these too (Trace Route starts a combat,
|
||||
* Disconnect pulls an Avatar out of one).
|
||||
*/
|
||||
import { isStart, levelFor, type LocId } from './map.ts';
|
||||
import { scriptOf } from './scripts.ts';
|
||||
import { coresOf, emit, fighterOf, hardwareActive, sideCores } from './query.ts';
|
||||
import {
|
||||
adjacent,
|
||||
avatar,
|
||||
avatarName,
|
||||
controls,
|
||||
copyOf,
|
||||
defendersAt,
|
||||
fightersOf,
|
||||
fired,
|
||||
gainRam,
|
||||
gridCount,
|
||||
isCopy,
|
||||
isDisabledAvatar,
|
||||
isRooted,
|
||||
nameOf,
|
||||
neighbors,
|
||||
played,
|
||||
playerName,
|
||||
pushCapture,
|
||||
pushTasks,
|
||||
refKey,
|
||||
resetCard,
|
||||
rollDie,
|
||||
sameRef,
|
||||
say,
|
||||
startCombat,
|
||||
stat,
|
||||
toDiscard,
|
||||
} from './state.ts';
|
||||
import type { AvatarRef, AvatarState, CaptureStat, Combat, GameState, PlayerId, Task } from './types.ts';
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Drawing
|
||||
|
||||
export function drawCards(s: GameState, p: PlayerId, n: number): void {
|
||||
pushTasks(s, ...Array.from({ length: n }, (): Task => ({ t: 'draw', player: p })));
|
||||
}
|
||||
|
||||
/** Draws one card without "when drawing" effects. Returns it, or null for an empty deck. */
|
||||
export function drawNow(s: GameState, p: PlayerId): number | null {
|
||||
const pl = s.players[p];
|
||||
const card = pl.deck.shift();
|
||||
if (card === undefined) return null;
|
||||
pl.hand.push(card);
|
||||
stat(s, 'cardsDrawn', p);
|
||||
return card;
|
||||
}
|
||||
|
||||
export function drawTask(s: GameState, p: PlayerId): void {
|
||||
const card = drawNow(s, p);
|
||||
if (card !== null) emit(s, 'onDraw', { player: p, card });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Avatars leaving and entering play
|
||||
|
||||
function clearStatus(av: AvatarState): void {
|
||||
av.infection = 0;
|
||||
av.bugs = 0;
|
||||
av.mods = [];
|
||||
av.disabledUntil = 0;
|
||||
av.rootedUntil = 0;
|
||||
}
|
||||
|
||||
/** A copy leaves play. It has no Hardware of its own. */
|
||||
export function removeCopy(s: GameState, ref: AvatarRef): void {
|
||||
const cp = avatar(s, ref);
|
||||
if (cp.at === null) return;
|
||||
say(s, `${avatarName(s, ref)} is removed.`);
|
||||
clearStatus(cp);
|
||||
cp.permanentInfection = 0;
|
||||
cp.at = null;
|
||||
cp.faceUp = false;
|
||||
dropFromCombat(s, ref);
|
||||
}
|
||||
|
||||
/**
|
||||
* The loser of a combat goes back to its slot. Its Hardware is discarded unless `keepHardware`,
|
||||
* and its counters and effects are removed (Persistent Infection's counters stay).
|
||||
*/
|
||||
export function knockOut(s: GameState, ref: AvatarRef, loc: LocId, role: 'attack' | 'defend', keepHardware: boolean): void {
|
||||
const av = avatar(s, ref);
|
||||
if (av.at === null) return;
|
||||
if (isCopy(ref)) {
|
||||
removeCopy(s, ref);
|
||||
} else {
|
||||
if (!keepHardware && av.hardware.length) {
|
||||
say(s, `${playerName(ref.player)} loses ${av.hardware.map((h) => nameOf(s, h)).join(', ')}.`);
|
||||
stat(s, 'hardwareLost', ref.player, av.hardware.length);
|
||||
for (const hw of av.hardware) toDiscard(s, hw);
|
||||
av.hardware = [];
|
||||
}
|
||||
clearStatus(av);
|
||||
av.at = null;
|
||||
say(s, `${avatarName(s, ref)} returns to its slot.`);
|
||||
removeCopy(s, copyOf(ref));
|
||||
}
|
||||
emit(s, 'onDefeat', { ref, loc, role });
|
||||
}
|
||||
|
||||
/** Places a copy of `original` on `to`. */
|
||||
export function createCopy(s: GameState, original: AvatarRef, to: LocId): void {
|
||||
const ref = copyOf(original);
|
||||
const cp = avatar(s, ref);
|
||||
Object.assign(cp, {
|
||||
card: avatar(s, original).card,
|
||||
faceUp: true,
|
||||
at: to,
|
||||
hardware: [],
|
||||
placed: false,
|
||||
advanced: false,
|
||||
attacks: 0,
|
||||
infection: 0,
|
||||
bugs: 0,
|
||||
permanentInfection: 0,
|
||||
mods: [],
|
||||
disabledUntil: 0,
|
||||
rootedUntil: 0,
|
||||
breachedTurn: 0,
|
||||
} satisfies Partial<AvatarState>);
|
||||
say(s, `${playerName(ref.player)} creates ${avatarName(s, ref)} on ${to}.`);
|
||||
}
|
||||
|
||||
/** Moves an Avatar by a card effect. Callers check the move is legal. */
|
||||
export function moveAvatar(s: GameState, ref: AvatarRef, to: LocId): void {
|
||||
const av = avatar(s, ref);
|
||||
say(s, `${avatarName(s, ref)} moves ${av.at} → ${to}.`);
|
||||
av.at = to;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Step 5: declarations
|
||||
|
||||
export function resolveDeclaration(s: GameState, index: number): void {
|
||||
const d = s.declarations[index];
|
||||
const p = d.ref.player;
|
||||
const av = avatar(s, d.ref);
|
||||
const who = avatarName(s, d.ref);
|
||||
if (av.at === null) return;
|
||||
if (isRooted(s, d.ref) || isDisabledAvatar(s, d.ref)) {
|
||||
say(s, `${who} can't move, so its ${d.kind} on ${d.to} fails.`);
|
||||
return;
|
||||
}
|
||||
if (controls(s, p, d.to)) return;
|
||||
const defended = defendersAt(s, d.to).length > 0;
|
||||
const how: CaptureStat = s.locations[d.to].owner === null ? 'capturesUnowned' : 'capturesUndefended';
|
||||
if (d.kind === 'advance') {
|
||||
if (!neighbors(s, d.to).some((n) => controls(s, p, n))) {
|
||||
say(s, `${who} can no longer reach ${d.to}.`);
|
||||
return;
|
||||
}
|
||||
if (defended) startCombat(s, d.ref, av.at, d.to, 'advance');
|
||||
else pushCapture(s, d.ref, d.to, how);
|
||||
return;
|
||||
}
|
||||
if ((!d.second && av.at !== d.from) || !controls(s, p, d.from) || !adjacent(s, d.from, d.to)) {
|
||||
say(s, `${who}'s attack on ${d.to} fails: it's no longer in position.`);
|
||||
return;
|
||||
}
|
||||
if (defended) startCombat(s, d.ref, d.from, d.to, 'attack');
|
||||
else pushCapture(s, d.ref, d.to, how);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Combat
|
||||
|
||||
const total = (dice: number[]) => dice.reduce((a, b) => a + b, 0);
|
||||
const roll = (s: GameState, n: number) => Array.from({ length: n }, () => rollDie(s));
|
||||
|
||||
function sideTotals(c: Combat): { atk: number; def: number } {
|
||||
return {
|
||||
atk: total(c.dice[refKey(c.attacker)] ?? []),
|
||||
def: c.defenders.reduce((t, d) => t + total(c.dice[refKey(d)] ?? []), 0),
|
||||
};
|
||||
}
|
||||
|
||||
function diceText(s: GameState, c: Combat): string {
|
||||
const one = (r: AvatarRef) => `${nameOf(s, avatar(s, r).card)} [${(c.dice[refKey(r)] ?? []).join(',')}]`;
|
||||
const t = sideTotals(c);
|
||||
return `${one(c.attacker)}=${t.atk} vs ${c.defenders.map(one).join(' + ')}=${t.def}`;
|
||||
}
|
||||
|
||||
/** Rolls every fighter's dice, rerolling all of them on a tie. */
|
||||
function rollAll(s: GameState, c: Combat): void {
|
||||
do {
|
||||
for (const r of fightersOf(c)) c.dice[refKey(r)] = roll(s, coresOf(s, fighterOf(s, r)));
|
||||
const t = sideTotals(c);
|
||||
if (t.atk !== t.def) break;
|
||||
c.ties++;
|
||||
} while (true);
|
||||
c.rolled = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cores that change after the roll change the dice: each Core gained rolls one more die, and each
|
||||
* Core lost removes that Avatar's highest die.
|
||||
*/
|
||||
export function syncDice(s: GameState, c: Combat): void {
|
||||
if (!c.rolled) return;
|
||||
for (const r of fightersOf(c)) {
|
||||
const key = refKey(r);
|
||||
const dice = c.dice[key] ?? [];
|
||||
const want = coresOf(s, fighterOf(s, r));
|
||||
while (dice.length < want) dice.push(rollDie(s));
|
||||
if (dice.length > want) {
|
||||
dice.sort((a, b) => a - b);
|
||||
dice.length = want;
|
||||
}
|
||||
c.dice[key] = dice;
|
||||
}
|
||||
}
|
||||
|
||||
/** Current dice totals, after syncing to Core changes. */
|
||||
export function combatTotals(s: GameState): { atk: number; def: number } {
|
||||
const c = s.combat!;
|
||||
syncDice(s, c);
|
||||
return sideTotals(c);
|
||||
}
|
||||
|
||||
/** Stops the current combat with no winner. */
|
||||
export function endCombat(s: GameState, why: string): void {
|
||||
const c = s.combat;
|
||||
if (!c || c.ended) return;
|
||||
c.ended = true;
|
||||
stat(s, 'combatsEnded', c.attacker.player);
|
||||
say(s, `The combat at ${c.loc} ends: ${why}.`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes an Avatar out of the current combat. If the attacker leaves, the combat ends. If the last
|
||||
* defender leaves, the attacker takes the location as undefended.
|
||||
*/
|
||||
export function dropFromCombat(s: GameState, ref: AvatarRef): void {
|
||||
const c = s.combat;
|
||||
if (!c || c.ended) return;
|
||||
if (sameRef(c.attacker, ref)) {
|
||||
endCombat(s, `${avatarName(s, ref)} left it`);
|
||||
return;
|
||||
}
|
||||
const i = c.defenders.findIndex((d) => sameRef(d, ref));
|
||||
if (i < 0) return;
|
||||
c.defenders.splice(i, 1);
|
||||
delete c.dice[refKey(ref)];
|
||||
if (c.defenders.length === 0) {
|
||||
endCombat(s, 'no defender is left');
|
||||
if (avatar(s, c.attacker).at !== null) pushCapture(s, c.attacker, c.loc, 'capturesUndefended');
|
||||
}
|
||||
}
|
||||
|
||||
export function combatStage(s: GameState, stage: 'start' | 'roll' | 'result' | 'end' | 'cleanup'): void {
|
||||
const c = s.combat;
|
||||
if (!c) return;
|
||||
if (stage === 'cleanup') {
|
||||
for (const r of fightersOf(c)) {
|
||||
const av = avatar(s, r);
|
||||
av.mods = av.mods.filter((m) => m.combat !== c.id);
|
||||
}
|
||||
s.combat = null;
|
||||
return;
|
||||
}
|
||||
if (stage === 'end') {
|
||||
pushTasks(s, { t: 'combat', stage: 'cleanup' });
|
||||
if (c.rolled || c.ended) emit(s, 'onCombatEnd', null);
|
||||
return;
|
||||
}
|
||||
if (c.ended) return;
|
||||
if (stage === 'start') {
|
||||
stat(s, 'attacks', c.attacker.player);
|
||||
const { atk, def } = sideCores(s);
|
||||
const defs = c.defenders.map((d) => avatarName(s, d)).join(' and ');
|
||||
say(s, `Combat at ${c.loc}: ${avatarName(s, c.attacker)} (${atk} Cores, from ${c.origin}) vs ${defs} (${def} Cores).`);
|
||||
emit(s, 'onCombatStart', null);
|
||||
return;
|
||||
}
|
||||
if (stage === 'roll') {
|
||||
// Static Core effects count as firing once per combat.
|
||||
const credited = new Set<string>();
|
||||
for (const r of fightersOf(c)) {
|
||||
coresOf(s, fighterOf(s, r), (name, p) => {
|
||||
if (!credited.has(`${name}:${p}`)) {
|
||||
credited.add(`${name}:${p}`);
|
||||
fired(s, name, p);
|
||||
}
|
||||
});
|
||||
}
|
||||
rollAll(s, c);
|
||||
say(s, `Roll: ${diceText(s, c)}${c.ties ? ` after ${c.ties} tie reroll(s)` : ''}.`);
|
||||
return;
|
||||
}
|
||||
// result
|
||||
const t = combatTotals(s);
|
||||
if (t.atk === t.def) {
|
||||
c.ties++;
|
||||
rollAll(s, c);
|
||||
say(s, `Tie, so both sides reroll: ${diceText(s, c)}.`);
|
||||
pushTasks(
|
||||
s,
|
||||
{ t: 'window', kind: 'postRoll', priority: c.attacker.player, passes: 0, base: s.stack.length, resolving: false },
|
||||
{ t: 'combat', stage: 'result' },
|
||||
);
|
||||
return;
|
||||
}
|
||||
const attackerWins = t.atk > t.def;
|
||||
const winner = attackerWins ? c.attacker.player : s.locations[c.loc].owner!;
|
||||
say(s, `${playerName(winner)} wins the combat, ${t.atk} to ${t.def}.`);
|
||||
if (attackerWins) {
|
||||
stat(s, 'attacksWon', c.attacker.player);
|
||||
pushTasks(
|
||||
s,
|
||||
...c.defenders.map((ref): Task => ({ t: 'defeat', ref, loc: c.loc, role: 'defend' })),
|
||||
{ t: 'capture', ref: c.attacker, loc: c.loc, stage: 'hooks', how: 'capturesInCombat' },
|
||||
);
|
||||
} else {
|
||||
pushTasks(s, { t: 'defeat', ref: c.attacker, loc: c.loc, role: 'attack' });
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Defeat
|
||||
|
||||
export function defeat(s: GameState, ref: AvatarRef, loc: LocId, role: 'attack' | 'defend'): void {
|
||||
const av = avatar(s, ref);
|
||||
if (av.at === null) return;
|
||||
if (!isCopy(ref)) {
|
||||
// Redundant Power Supply, then RAID Array, may save the Hardware.
|
||||
const savers = av.hardware
|
||||
.filter((hw) => hardwareActive(s, hw) && scriptOf(s.cards[hw].name)?.onWearerDefeated)
|
||||
.sort((a, b) => (scriptOf(s.cards[a].name)!.savePriority ?? 0) - (scriptOf(s.cards[b].name)!.savePriority ?? 0));
|
||||
for (const hw of savers) {
|
||||
if (scriptOf(s.cards[hw].name)!.onWearerDefeated!(s, hw, { ref, loc, role })) return;
|
||||
}
|
||||
}
|
||||
knockOut(s, ref, loc, role, false);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Capture
|
||||
|
||||
export function captureHooks(s: GameState, ref: AvatarRef, loc: LocId, how: CaptureStat): void {
|
||||
const p = ref.player;
|
||||
if (avatar(s, ref).at === null || controls(s, p, loc) || isStart(loc)) return;
|
||||
pushTasks(s, { t: 'capture', ref, loc, stage: 'main', how });
|
||||
const prev = s.locations[loc].owner;
|
||||
if (prev !== null && prev !== p) {
|
||||
avatar(s, ref).breachedTurn = s.turn;
|
||||
emit(s, 'onCaptured', { ref, loc });
|
||||
emit(s, 'onBreach', { ref, loc });
|
||||
}
|
||||
}
|
||||
|
||||
export function captureMain(s: GameState, ref: AvatarRef, loc: LocId, how: CaptureStat): void {
|
||||
const p = ref.player;
|
||||
const me = s.players[p];
|
||||
const L = s.locations[loc];
|
||||
if (avatar(s, ref).at === null || controls(s, p, loc)) return;
|
||||
const previous = L.owner;
|
||||
if (L.server !== null) {
|
||||
resetCard(s, L.server);
|
||||
s.players[s.cards[L.server].owner].serverPile.push(L.server);
|
||||
}
|
||||
if (previous !== null && L.programs.length) stat(s, 'programsLost', previous, L.programs.length);
|
||||
for (const prog of L.programs) toDiscard(s, prog);
|
||||
L.programs = [];
|
||||
L.owner = p;
|
||||
L.server = me.serverPile.shift() ?? null;
|
||||
avatar(s, ref).at = loc;
|
||||
|
||||
const level = levelFor(p, loc);
|
||||
const bonus = L.server === null ? 0 : (scriptOf(s.cards[L.server].name)?.ramOnPlace ?? 0);
|
||||
gainRam(s, p, s.rules.levelRam[level] + bonus, 'ramFromCaptures');
|
||||
stat(s, how, p);
|
||||
const from = previous === null ? '' : ` from ${playerName(previous)}`;
|
||||
say(s, `${playerName(p)} captures ${loc}${from} (Lv ${level}) with ${L.server === null ? 'no Server' : nameOf(s, L.server)}: +${s.rules.levelRam[level] + bonus} RAM (now ${me.ram}).`);
|
||||
|
||||
if (level > me.unlockedLevel) {
|
||||
me.unlockedLevel = level;
|
||||
me.avatars.slice(0, 4).forEach((av, i) => {
|
||||
if (i < level && !av.faceUp) {
|
||||
av.faceUp = true;
|
||||
say(s, `${playerName(p)} unlocks Avatar ${i + 1}: ${nameOf(s, av.card)}.`);
|
||||
}
|
||||
});
|
||||
}
|
||||
if (gridCount(s, p) >= s.rules.winLocations) {
|
||||
s.over = true;
|
||||
s.winner = p;
|
||||
s.endReason = 'win';
|
||||
say(s, `${playerName(p)} wins with ${gridCount(s, p)} locations.`);
|
||||
return;
|
||||
}
|
||||
if (L.server !== null) {
|
||||
played(s, nameOf(s, L.server), p);
|
||||
emit(s, 'onPlaced', { card: L.server });
|
||||
}
|
||||
}
|
||||
63
sim/src/invariants.ts
Normal file
63
sim/src/invariants.ts
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
import { LOCATIONS } from './map.ts';
|
||||
import { capacity, portsTotal } from './query.ts';
|
||||
import { scriptOf } from './scripts.ts';
|
||||
import { controls } from './state.ts';
|
||||
import type { GameState } from './types.ts';
|
||||
|
||||
/** Rule violations in a state; empty when it's consistent. Used by tests and `--check`. */
|
||||
export function checkInvariants(s: GameState): string[] {
|
||||
const errors: string[] = [];
|
||||
const zone = new Map<number, string>();
|
||||
const put = (id: number, where: string) => {
|
||||
const prev = zone.get(id);
|
||||
if (prev) errors.push(`card ${id} (${s.cards[id]?.name}) is in both ${prev} and ${where}`);
|
||||
zone.set(id, where);
|
||||
};
|
||||
|
||||
s.players.forEach((pl, p) => {
|
||||
const own = (ids: number[], where: string) => {
|
||||
for (const id of ids) {
|
||||
put(id, `p${p}.${where}`);
|
||||
if (s.cards[id].owner !== p) errors.push(`p${p}.${where} holds the opponent's card ${id}`);
|
||||
}
|
||||
};
|
||||
own(pl.hand, 'hand');
|
||||
own(pl.deck, 'deck');
|
||||
own(pl.discard, 'discard');
|
||||
own(pl.serverPile, 'serverPile');
|
||||
if (pl.ram < 0) errors.push(`p${p} has ${pl.ram} RAM`);
|
||||
const count = new Map<string, number>();
|
||||
pl.avatars.forEach((av, i) => {
|
||||
const slot = i + 1;
|
||||
const copy = slot > 4;
|
||||
if (!copy) {
|
||||
own([av.card], `avatar${slot}`);
|
||||
own(av.hardware, `avatar${slot}.hardware`);
|
||||
const ported = av.hardware.filter((h) => !scriptOf(s.cards[h].name)?.noPort && s.cards[h].pushedUntil === undefined);
|
||||
if (ported.length > portsTotal(s, { player: p as 0 | 1, slot })) errors.push(`p${p} Avatar ${slot} is over its slots`);
|
||||
} else {
|
||||
if (av.hardware.length) errors.push(`p${p} copy ${slot - 4} has Hardware of its own`);
|
||||
if (av.at !== null && pl.avatars[i - 4].at === null) errors.push(`p${p} copy ${slot - 4} is in play without its original`);
|
||||
if (av.card !== pl.avatars[i - 4].card) errors.push(`p${p} copy ${slot - 4} doesn't match its original`);
|
||||
}
|
||||
if (av.at === null) return;
|
||||
if (!av.faceUp) errors.push(`p${p} Avatar ${slot} is in play face down`);
|
||||
if (!controls(s, p as 0 | 1, av.at)) errors.push(`p${p} Avatar ${slot} is on ${av.at}, which it doesn't control`);
|
||||
count.set(av.at, (count.get(av.at) ?? 0) + 1);
|
||||
});
|
||||
for (const [loc, n] of count) if (n > capacity(s, loc)) errors.push(`p${p} has ${n} Avatars on ${loc}`);
|
||||
});
|
||||
|
||||
for (const loc of LOCATIONS) {
|
||||
const L = s.locations[loc];
|
||||
if (L.server !== null) put(L.server, `${loc}.server`);
|
||||
for (const id of L.programs) put(id, `${loc}.programs`);
|
||||
if (L.owner === null && (L.server !== null || L.programs.length > 0)) errors.push(`${loc} is unowned but has cards`);
|
||||
const layers = L.programs.filter((id) => s.cards[id].name === 'Compatibility Layer').length;
|
||||
if (L.programs.length > s.rules.maxProgramsPerLocation + layers) errors.push(`${loc} has too many Programs`);
|
||||
}
|
||||
for (const item of s.stack) if (item.kind === 'execution') put(item.card, 'stack');
|
||||
if (zone.size !== s.cards.length) errors.push(`${s.cards.length - zone.size} cards are missing from every zone`);
|
||||
if (s.choice && s.choice.options.length === 0) errors.push(`choice ${s.choice.kind} has no options`);
|
||||
return errors;
|
||||
}
|
||||
62
sim/src/map.ts
Normal file
62
sim/src/map.ts
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
import type { PlayerId } from './types.ts';
|
||||
|
||||
/** Location ids follow the diagram in rules.md: S1 is South's start, S2 is North's. */
|
||||
export type LocId = string;
|
||||
|
||||
export const START_LOC: readonly [LocId, LocId] = ['S1', 'S2'];
|
||||
export const GRID: readonly LocId[] = [
|
||||
'A1', 'A2', 'A3', 'B1', 'B2', 'C1', 'C2', 'C3', 'D1', 'D2', 'E1', 'E2', 'E3',
|
||||
];
|
||||
export const LOCATIONS: readonly LocId[] = [START_LOC[0], ...GRID, START_LOC[1]];
|
||||
|
||||
export interface Line {
|
||||
id: string;
|
||||
a: LocId;
|
||||
b: LocId;
|
||||
/** Lines with a gateway can hold a Firewall. */
|
||||
gateway: boolean;
|
||||
}
|
||||
|
||||
const LINE_DEFS: [LocId, LocId, boolean][] = [
|
||||
['S1', 'A2', false],
|
||||
['A1', 'A2', true], ['A2', 'A3', true],
|
||||
['A1', 'B1', true], ['A2', 'B1', true], ['A2', 'B2', true], ['A3', 'B2', true],
|
||||
['A2', 'C2', false],
|
||||
['B1', 'C1', true], ['B1', 'C2', true], ['B2', 'C2', true], ['B2', 'C3', true],
|
||||
['C1', 'D1', true], ['C2', 'D1', true], ['C2', 'D2', true], ['C3', 'D2', true],
|
||||
['C2', 'E2', false],
|
||||
['D1', 'E1', true], ['D1', 'E2', true], ['D2', 'E2', true], ['D2', 'E3', true],
|
||||
['E1', 'E2', true], ['E2', 'E3', true],
|
||||
['S2', 'E2', false],
|
||||
];
|
||||
|
||||
export const LINES: readonly Line[] = LINE_DEFS.map(([a, b, gateway]) => ({
|
||||
id: `${a}-${b}`,
|
||||
a,
|
||||
b,
|
||||
gateway,
|
||||
}));
|
||||
|
||||
export const LINE_BY_ID: ReadonlyMap<string, Line> = new Map(LINES.map((l) => [l.id, l]));
|
||||
|
||||
export const LINES_AT: ReadonlyMap<LocId, readonly Line[]> = new Map(
|
||||
LOCATIONS.map((loc) => [loc, LINES.filter((l) => l.a === loc || l.b === loc)]),
|
||||
);
|
||||
|
||||
export const otherEnd = (line: Line, loc: LocId): LocId => (line.a === loc ? line.b : line.a);
|
||||
|
||||
export const isStart = (loc: LocId): boolean => loc === START_LOC[0] || loc === START_LOC[1];
|
||||
|
||||
/** Level by row letter, from each player's side of the mat. */
|
||||
const LEVEL_BY_ROW: readonly [Record<string, number>, Record<string, number>] = [
|
||||
{ A: 2, B: 2, C: 3, D: 4, E: 5 },
|
||||
{ A: 5, B: 4, C: 3, D: 2, E: 2 },
|
||||
];
|
||||
|
||||
/** A location's level for the player capturing it. Your own start is Lv 1. */
|
||||
export function levelFor(p: PlayerId, loc: LocId): number {
|
||||
if (loc === START_LOC[p]) return 1;
|
||||
const level = LEVEL_BY_ROW[p][loc[0]];
|
||||
if (level === undefined) throw new Error(`No level for ${loc} from player ${p}`);
|
||||
return level;
|
||||
}
|
||||
36
sim/src/odds.ts
Normal file
36
sim/src/odds.ts
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
/** Distribution of the sum of n d6, as probability by total. */
|
||||
function sumDistribution(n: number): Map<number, number> {
|
||||
let dist = new Map([[0, 1]]);
|
||||
for (let i = 0; i < n; i++) {
|
||||
const next = new Map<number, number>();
|
||||
for (const [total, p] of dist) {
|
||||
for (let face = 1; face <= 6; face++) {
|
||||
next.set(total + face, (next.get(total + face) ?? 0) + p / 6);
|
||||
}
|
||||
}
|
||||
dist = next;
|
||||
}
|
||||
return dist;
|
||||
}
|
||||
|
||||
const cache = new Map<string, number>();
|
||||
|
||||
/** Exact chance that `atk` Cores beat `def` Cores, with ties rerolled. */
|
||||
export function winChance(atk: number, def: number): number {
|
||||
const key = `${atk}:${def}`;
|
||||
const hit = cache.get(key);
|
||||
if (hit !== undefined) return hit;
|
||||
let win = 0;
|
||||
let lose = 0;
|
||||
const a = sumDistribution(Math.max(1, atk));
|
||||
const d = sumDistribution(Math.max(1, def));
|
||||
for (const [sa, pa] of a) {
|
||||
for (const [sd, pd] of d) {
|
||||
if (sa > sd) win += pa * pd;
|
||||
else if (sa < sd) lose += pa * pd;
|
||||
}
|
||||
}
|
||||
const chance = win / (win + lose);
|
||||
cache.set(key, chance);
|
||||
return chance;
|
||||
}
|
||||
44
sim/src/play.ts
Normal file
44
sim/src/play.ts
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import type { BotFactory } from './bots/bot.ts';
|
||||
import type { CardPool } from './cards.ts';
|
||||
import { randomDeck, type DeckList } from './deck.ts';
|
||||
import { applyAction, createGame, decider, legalActions, viewFor } from './engine.ts';
|
||||
import { checkInvariants } from './invariants.ts';
|
||||
import { makeRng } from './rng.ts';
|
||||
import { DEFAULT_RULES, type RulesConfig } from './rules.ts';
|
||||
import type { GameState } from './types.ts';
|
||||
|
||||
export interface MatchOptions {
|
||||
pool: CardPool;
|
||||
/** Bot for South (index 0) and North (index 1). */
|
||||
bots: [BotFactory, BotFactory];
|
||||
seed: number;
|
||||
/** Random legal decks when omitted. */
|
||||
decks?: [DeckList, DeckList];
|
||||
rules?: RulesConfig;
|
||||
log?: boolean;
|
||||
/** Check invariants after every action (slow). */
|
||||
check?: boolean;
|
||||
}
|
||||
|
||||
const MAX_ACTIONS = 200_000;
|
||||
|
||||
/** Plays one game to the end. The same options and seed always produce the same game. */
|
||||
export function playGame(o: MatchOptions): GameState {
|
||||
const rules = o.rules ?? DEFAULT_RULES;
|
||||
const deckRng = makeRng(o.seed ^ 0x9e3779b9);
|
||||
const decks = o.decks ?? [randomDeck(o.pool, deckRng, rules), randomDeck(o.pool, deckRng, rules)];
|
||||
const s = createGame({ pool: o.pool, decks, seed: o.seed, rules, log: o.log });
|
||||
const bots = [o.bots[0](o.seed * 2 + 1), o.bots[1](o.seed * 2 + 2)];
|
||||
for (let n = 0; !s.over; n++) {
|
||||
if (n > MAX_ACTIONS) throw new Error(`Game with seed ${o.seed} didn't finish in ${MAX_ACTIONS} actions`);
|
||||
const p = decider(s)!;
|
||||
const legal = legalActions(s);
|
||||
const action = bots[p].choose(viewFor(s, p), legal, p);
|
||||
applyAction(s, action, legal);
|
||||
if (o.check) {
|
||||
const errors = checkInvariants(s);
|
||||
if (errors.length) throw new Error(`Seed ${o.seed}, turn ${s.turn}:\n ${errors.join('\n ')}`);
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
269
sim/src/query.ts
Normal file
269
sim/src/query.ts
Normal file
|
|
@ -0,0 +1,269 @@
|
|||
/**
|
||||
* Questions about the current state that depend on card effects: what's in play, Cores, costs,
|
||||
* capacity and protection.
|
||||
*/
|
||||
import { LOCATIONS, type LocId } from './map.ts';
|
||||
import { scriptOf, type Fighter, type Payment, type Script } from './scripts.ts';
|
||||
import {
|
||||
activeMods,
|
||||
avatar,
|
||||
controls,
|
||||
defOf,
|
||||
firewallCost,
|
||||
hardwareOf,
|
||||
isCopy,
|
||||
pushTasks,
|
||||
refsInPlay,
|
||||
running,
|
||||
sameRef,
|
||||
stat,
|
||||
} from './state.ts';
|
||||
import type { AvatarRef, GameState, HookName, Json, PlayerId, Source, Task } from './types.ts';
|
||||
|
||||
export const programActive = (s: GameState, id: number): boolean =>
|
||||
!running(s, s.cards[id].disabledUntil) && !running(s, s.cards[id].ignoredUntil);
|
||||
export const hardwareActive = (s: GameState, id: number): boolean => !running(s, s.cards[id].disabledUntil);
|
||||
|
||||
/** Everything with an effect in play right now. */
|
||||
export function sources(s: GameState): Source[] {
|
||||
const out: Source[] = [];
|
||||
for (const loc of LOCATIONS) {
|
||||
const L = s.locations[loc];
|
||||
if (L.owner === null) continue;
|
||||
if (L.server !== null) {
|
||||
const c = s.cards[L.server];
|
||||
out.push({ kind: 'server', id: L.server, name: c.name, controller: L.owner, at: loc });
|
||||
if (c.copies) out.push({ kind: 'server', id: L.server, name: c.copies, controller: L.owner, at: loc, virtual: -2 });
|
||||
}
|
||||
const live = L.programs.filter((id) => programActive(s, id));
|
||||
for (const id of live) out.push({ kind: 'program', id, name: s.cards[id].name, controller: L.owner, at: loc });
|
||||
for (const w of live) {
|
||||
const to = s.cards[w].name === 'Worm Protocol' ? s.cards[w].wormTo : undefined;
|
||||
if (!to) continue;
|
||||
for (const id of live) {
|
||||
if (id !== w) out.push({ kind: 'program', id, name: s.cards[id].name, controller: L.owner, at: to, virtual: -1 });
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const v of s.virtuals) {
|
||||
if (running(s, v.until)) {
|
||||
out.push({ kind: 'program', id: v.from, name: v.name, controller: v.controller, at: v.at, virtual: v.id });
|
||||
}
|
||||
}
|
||||
for (const p of [0, 1] as const) {
|
||||
for (const r of refsInPlay(s, p)) {
|
||||
if (isCopy(r)) continue;
|
||||
const av = avatar(s, r);
|
||||
out.push({ kind: 'avatar', id: av.card, name: s.cards[av.card].name, controller: p, at: av.at, ref: r });
|
||||
for (const hw of av.hardware) {
|
||||
if (hardwareActive(s, hw)) out.push({ kind: 'hardware', id: hw, name: s.cards[hw].name, controller: p, at: av.at, ref: r });
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export const sameSource = (a: Source, b: Source): boolean =>
|
||||
a.id === b.id && a.name === b.name && a.at === b.at && a.virtual === b.virtual && sameRefOrNone(a.ref, b.ref);
|
||||
const sameRefOrNone = (a?: AvatarRef, b?: AvatarRef) => (!a && !b) || sameRef(a, b);
|
||||
|
||||
export const stillActive = (s: GameState, src: Source): boolean => sources(s).some((x) => sameSource(x, src));
|
||||
|
||||
/** Active sources with this card name (including copies) applying at `loc`, when given. */
|
||||
export function sourcesNamed(s: GameState, name: string, loc?: LocId | null): Source[] {
|
||||
return sources(s).filter((x) => x.name === name && (loc === undefined || x.at === loc));
|
||||
}
|
||||
|
||||
/** Queues `hook` for every source whose script has it. */
|
||||
export function emit(s: GameState, hook: HookName, data: Json): void {
|
||||
const tasks: Task[] = [];
|
||||
for (const src of sources(s)) if (scriptOf(src.name)?.[hook]) tasks.push({ t: 'hook', hook, src, data });
|
||||
pushTasks(s, ...tasks);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Capacity
|
||||
|
||||
/** How many of its owner's Avatars a location holds (Cluster Server, Pingable Server: 2). */
|
||||
export function capacity(s: GameState, loc: LocId): number {
|
||||
const sv = s.locations[loc].server;
|
||||
if (sv === null || s.locations[loc].owner === null) return 1;
|
||||
const c = s.cards[sv];
|
||||
return Math.max(1, scriptOf(c.name)?.capacity ?? 1, c.copies ? scriptOf(c.copies)?.capacity ?? 1 : 1);
|
||||
}
|
||||
|
||||
/** Whether `p` can put another Avatar on `loc`. */
|
||||
export function hasRoom(s: GameState, p: PlayerId, loc: LocId): boolean {
|
||||
if (!controls(s, p, loc)) return false;
|
||||
return refsInPlay(s, p).filter((r) => avatar(s, r).at === loc).length < capacity(s, loc);
|
||||
}
|
||||
|
||||
/** Program slots on a location: 2, plus active Programs that add slots (Compatibility Layer). */
|
||||
export function programSlots(s: GameState, loc: LocId): number {
|
||||
let n = s.rules.maxProgramsPerLocation;
|
||||
for (const id of s.locations[loc].programs) if (programActive(s, id)) n += scriptOf(s.cards[id].name)?.programSlots ?? 0;
|
||||
return n;
|
||||
}
|
||||
|
||||
/** Programs installed on a location, counting copies that count as installed (Process Clone). */
|
||||
export function installedCount(s: GameState, loc: LocId): number {
|
||||
return s.locations[loc].programs.length +
|
||||
s.virtuals.filter((v) => v.installed && v.at === loc && running(s, v.until)).length;
|
||||
}
|
||||
|
||||
export function portsUsed(s: GameState, r: AvatarRef): number {
|
||||
return avatar(s, r).hardware.filter((id) => !scriptOf(s.cards[id].name)?.noPort).length;
|
||||
}
|
||||
|
||||
/** Expansion Slots an Avatar has: printed, plus Hardware that adds ports (Network Interface Upgrade). */
|
||||
export const portsTotal = (s: GameState, r: AvatarRef): number =>
|
||||
defOf(s, avatar(s, r).card).slots +
|
||||
avatar(s, r).hardware.reduce((t, id) => t + (scriptOf(s.cards[id].name)?.extraSlots ?? 0), 0);
|
||||
|
||||
export const portsFree = (s: GameState, r: AvatarRef): number => portsTotal(s, r) - portsUsed(s, r);
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Cores
|
||||
|
||||
/** Where an Avatar would fight from, as a fighter. `combat` is the current one, if it's in it. */
|
||||
export function fighterOf(s: GameState, ref: AvatarRef): Fighter {
|
||||
const c = s.combat;
|
||||
const av = avatar(s, ref);
|
||||
if (c && !c.ended) {
|
||||
if (sameRef(c.attacker, ref)) return { ref, role: 'attack', at: c.origin, loc: c.loc, combat: c };
|
||||
if (c.defenders.some((d) => sameRef(d, ref))) return { ref, role: 'defend', at: c.loc, loc: c.loc, combat: c };
|
||||
}
|
||||
return { ref, role: null, at: av.at, loc: null, combat: null };
|
||||
}
|
||||
|
||||
/** Hardware on an Avatar (a copy uses its original's) with a script flag, if active. */
|
||||
export const wears = (s: GameState, ref: AvatarRef, flag: (sc: Script) => unknown): number[] =>
|
||||
hardwareOf(s, ref).filter((hw) => hardwareActive(s, hw) && flag(scriptOf(s.cards[hw].name) ?? { text: '' }));
|
||||
|
||||
/** Opponents' Bug effects can't touch an Avatar wearing ECC Memory. */
|
||||
export const bugImmune = (s: GameState, ref: AvatarRef, by: PlayerId): boolean =>
|
||||
by !== ref.player && wears(s, ref, (sc) => sc.bugImmunity).length > 0;
|
||||
|
||||
/** An active Program flag at a location, from a player other than `p`. */
|
||||
export const enemyFlagAt = (s: GameState, loc: LocId, p: PlayerId, flag: (sc: Script) => unknown): Source[] =>
|
||||
sources(s).filter((x) => x.at === loc && x.controller !== p && flag(scriptOf(x.name) ?? { text: '' }));
|
||||
|
||||
/** Stock Rice: no Hardware bonuses in a combat at its location. */
|
||||
function hardwareBlocked(s: GameState, f: Fighter, all: Source[]): boolean {
|
||||
if (!f.loc || f.role === null) return false;
|
||||
return all.some((x) => x.at === f.loc && scriptOf(x.name)?.blocksHardwareInCombat && !bugImmune(s, f.ref, x.controller));
|
||||
}
|
||||
|
||||
/** Desynchronization: an attacker can't use once-per-turn Hardware abilities in a combat there. */
|
||||
export function desynced(s: GameState, ref: AvatarRef): boolean {
|
||||
const c = s.combat;
|
||||
if (!c || c.ended || !sameRef(c.attacker, ref)) return false;
|
||||
return enemyFlagAt(s, c.loc, ref.player, (sc) => sc.blocksHardwareAbilities).length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Combat Cores for a fighter. `credit` is told about every card that changed the total, so the
|
||||
* card report can count static effects (Stack Overflow, Server bonuses) as firing.
|
||||
*/
|
||||
export function coresOf(s: GameState, f: Fighter, credit?: (name: string, p: PlayerId) => void): number {
|
||||
const av = avatar(s, f.ref);
|
||||
let n = defOf(s, av.card).cores;
|
||||
const all = sources(s);
|
||||
const add = (d: number, name: string, p: PlayerId) => {
|
||||
n += d;
|
||||
if (d !== 0) credit?.(name, p);
|
||||
};
|
||||
if (!hardwareBlocked(s, f, all)) {
|
||||
for (const hw of hardwareOf(s, f.ref)) {
|
||||
if (!hardwareActive(s, hw) || f.combat?.suppressed.includes(hw)) continue;
|
||||
const name = s.cards[hw].name;
|
||||
const sc = scriptOf(name);
|
||||
if (sc?.cores) add(sc.cores(s, { kind: 'hardware', id: hw, name, controller: f.ref.player, at: f.at, ref: f.ref }, f), name, f.ref.player);
|
||||
}
|
||||
}
|
||||
const counted = new Set<string>();
|
||||
for (const src of all) {
|
||||
if (src.kind === 'hardware') continue;
|
||||
const sc = scriptOf(src.name);
|
||||
if (sc?.cores) add(sc.cores(s, src, f), src.name, src.controller);
|
||||
if (sc?.globalCores && !counted.has(src.name)) {
|
||||
counted.add(src.name);
|
||||
add(sc.globalCores(s, f), src.name, src.controller);
|
||||
}
|
||||
}
|
||||
for (const m of activeMods(s, av)) n += m.cores;
|
||||
return Math.max(1, n);
|
||||
}
|
||||
|
||||
/** Cores for each side of the current combat. */
|
||||
export function sideCores(s: GameState): { atk: number; def: number } {
|
||||
const c = s.combat!;
|
||||
return {
|
||||
atk: coresOf(s, fighterOf(s, c.attacker)),
|
||||
def: c.defenders.reduce((t, d) => t + coresOf(s, fighterOf(s, d)), 0),
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Costs
|
||||
|
||||
function baseCost(s: GameState, pay: Payment): number {
|
||||
if (pay.kind === 'firewall') return firewallCost(s, pay.level ?? 0);
|
||||
return pay.card === undefined ? 0 : defOf(s, pay.card).ram;
|
||||
}
|
||||
|
||||
/**
|
||||
* RAM a payment costs after every discount and surcharge in play. Pass `all` (the current
|
||||
* sources) when pricing many payments against the same state.
|
||||
*/
|
||||
export function costOf(s: GameState, pay: Payment, all: Source[] = sources(s)): number {
|
||||
let n = baseCost(s, pay);
|
||||
for (const src of all) {
|
||||
const mod = scriptOf(src.name)?.costMod;
|
||||
if (mod) n += mod(s, src, pay);
|
||||
}
|
||||
return Math.max(0, n);
|
||||
}
|
||||
|
||||
/** Pays for something, using up once-per-turn discounts. Returns the amount paid. */
|
||||
export function pay(s: GameState, payment: Payment, statKey: 'ramOnCards' | 'ramOnFirewalls' | 'ramOnAbilities'): number {
|
||||
let n = baseCost(s, payment);
|
||||
const touched: Source[] = [];
|
||||
for (const src of sources(s)) {
|
||||
const d = scriptOf(src.name)?.costMod?.(s, src, payment) ?? 0;
|
||||
if (d !== 0) {
|
||||
n += d;
|
||||
touched.push(src);
|
||||
}
|
||||
}
|
||||
const cost = Math.max(0, n);
|
||||
if (cost > s.players[payment.player].ram) throw new Error(`Can't afford ${cost} RAM`);
|
||||
s.players[payment.player].ram -= cost;
|
||||
stat(s, statKey, payment.player, cost);
|
||||
for (const src of touched) scriptOf(src.name)?.onPaid?.(s, src, payment);
|
||||
return cost;
|
||||
}
|
||||
|
||||
/** RAM a player could have for a payment: current RAM plus the Salvage value of the rest of the hand. */
|
||||
export function reachableRam(s: GameState, p: PlayerId, except: number | null = null): number {
|
||||
const pl = s.players[p];
|
||||
return pl.ram + pl.hand.reduce((t, id) => t + (id === except || id < 0 ? 0 : defOf(s, id).ram), 0);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Protection
|
||||
|
||||
/** Hardware Sandbox: opponents can't target the Program it protects (Execute: Root Access lifts it). */
|
||||
export function isProtected(s: GameState, program: number, by: PlayerId): boolean {
|
||||
const owner = s.cards[program].owner;
|
||||
if (by === owner) return false;
|
||||
const loc = LOCATIONS.find((l) => s.locations[l].programs.includes(program));
|
||||
if (loc && running(s, s.locations[loc].rootAccess[by])) return false;
|
||||
return sources(s).some(
|
||||
(x) => x.kind === 'hardware' && x.name === 'Hardware Sandbox' && s.cards[x.id].protects === program &&
|
||||
x.at === loc && x.controller === owner,
|
||||
);
|
||||
}
|
||||
|
||||
export const canTargetProgram = (s: GameState, program: number, by: PlayerId): boolean =>
|
||||
!isProtected(s, program, by);
|
||||
31
sim/src/rng.ts
Normal file
31
sim/src/rng.ts
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
/**
|
||||
* Seeded Mulberry32. The state is a plain object so a cloned GameState carries its RNG along,
|
||||
* which keeps every game reproducible from its seed.
|
||||
*/
|
||||
export interface Rng {
|
||||
s: number;
|
||||
}
|
||||
|
||||
export const makeRng = (seed: number): Rng => ({ s: seed >>> 0 });
|
||||
|
||||
export function nextFloat(r: Rng): number {
|
||||
r.s = (r.s + 0x6d2b79f5) >>> 0;
|
||||
let t = r.s;
|
||||
t = Math.imul(t ^ (t >>> 15), t | 1);
|
||||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
}
|
||||
|
||||
export const randInt = (r: Rng, n: number): number => Math.floor(nextFloat(r) * n);
|
||||
|
||||
export const d6 = (r: Rng): number => 1 + randInt(r, 6);
|
||||
|
||||
export const pick = <T>(r: Rng, items: readonly T[]): T => items[randInt(r, items.length)];
|
||||
|
||||
export function shuffle<T>(r: Rng, items: T[]): T[] {
|
||||
for (let i = items.length - 1; i > 0; i--) {
|
||||
const j = randInt(r, i + 1);
|
||||
[items[i], items[j]] = [items[j], items[i]];
|
||||
}
|
||||
return items;
|
||||
}
|
||||
29
sim/src/rules.ts
Normal file
29
sim/src/rules.ts
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
/**
|
||||
* Every number from rules.md that a rule variant might change. Pass a modified copy to
|
||||
* createGame to A/B test a rule.
|
||||
*/
|
||||
export interface RulesConfig {
|
||||
startingRam: number;
|
||||
openingHand: number;
|
||||
/** Grid locations needed to win (starting Servers don't count). */
|
||||
winLocations: number;
|
||||
/** Player turns before the game is called a draw. */
|
||||
maxTurns: number;
|
||||
/** RAM paid on capture, by level. */
|
||||
levelRam: Record<number, number>;
|
||||
/** Cost to place, upgrade to, or clear a Firewall of each level; index 0 = Lv 1. */
|
||||
firewallCost: readonly number[];
|
||||
maxProgramsPerLocation: number;
|
||||
deck: { avatars: number; servers: number; main: number; maxCopies: number };
|
||||
}
|
||||
|
||||
export const DEFAULT_RULES: RulesConfig = {
|
||||
startingRam: 4,
|
||||
openingHand: 7,
|
||||
winLocations: 10,
|
||||
maxTurns: 200,
|
||||
levelRam: { 1: 4, 2: 4, 3: 6, 4: 8, 5: 10 },
|
||||
firewallCost: [2, 4, 8],
|
||||
maxProgramsPerLocation: 2,
|
||||
deck: { avatars: 4, servers: 20, main: 30, maxCopies: 2 },
|
||||
};
|
||||
163
sim/src/scripts.ts
Normal file
163
sim/src/scripts.ts
Normal file
|
|
@ -0,0 +1,163 @@
|
|||
/**
|
||||
* Card scripts: what each card does, in one place per card. The engine calls into them at fixed
|
||||
* points (hooks). Every script records the card text it was written for, so an edited card in
|
||||
* cards.csv is reported instead of silently simulated with the old wording.
|
||||
*/
|
||||
import type { CardDef, CardPool } from './cards.ts';
|
||||
import { AVATARS } from './cards/avatars.ts';
|
||||
import { EXECUTIONS } from './cards/executions.ts';
|
||||
import { HARDWARE } from './cards/hardware.ts';
|
||||
import { PROGRAMS } from './cards/programs.ts';
|
||||
import { SERVERS } from './cards/servers.ts';
|
||||
import type { LocId } from './map.ts';
|
||||
import type { Args, AvatarRef, Combat, GameState, PlayerId, Source, StackItem } from './types.ts';
|
||||
|
||||
/** An Avatar as it fights, or would fight. */
|
||||
export interface Fighter {
|
||||
ref: AvatarRef;
|
||||
role: 'attack' | 'defend' | null;
|
||||
/** Where it stands: an attacker's origin, or the location it defends. */
|
||||
at: LocId | null;
|
||||
/** The location being fought over. */
|
||||
loc: LocId | null;
|
||||
combat: Combat | null;
|
||||
}
|
||||
|
||||
/** Something a player is paying RAM for. */
|
||||
export interface Payment {
|
||||
kind: 'program' | 'hardware' | 'execution' | 'firewall' | 'ability';
|
||||
player: PlayerId;
|
||||
card?: number;
|
||||
/** Program: where it's installed. Execution: its target. */
|
||||
at?: LocId | null;
|
||||
/** Hardware: who it's installed on. */
|
||||
ref?: AvatarRef;
|
||||
line?: string;
|
||||
level?: number;
|
||||
/** Execution: enemy Avatars it targets. */
|
||||
hostile?: AvatarRef[];
|
||||
}
|
||||
|
||||
export interface Play {
|
||||
target: LocId | null;
|
||||
args: Args;
|
||||
}
|
||||
|
||||
export interface ExecutionScript {
|
||||
/** Every legal way to play the card now, ignoring RAM. */
|
||||
plays(s: GameState, p: PlayerId): Play[];
|
||||
resolve(s: GameState, item: StackItem): void;
|
||||
/** Enemy Avatars (or Avatars whose Hardware) the play targets. */
|
||||
targetsAvatars?(s: GameState, item: Pick<StackItem, 'player' | 'target' | 'args'>): AvatarRef[];
|
||||
}
|
||||
|
||||
export interface AbilityScript {
|
||||
/** RAM cost. Avatars use the Ability Cost printed on the card. */
|
||||
cost?: number;
|
||||
/** More RAM paid on activation for this particular use (Hot-Swap Bay, Push Update). */
|
||||
extraCost?(s: GameState, src: Source, args: Args): number;
|
||||
/** Every legal way to use it now, ignoring RAM; empty when it can't be used. */
|
||||
uses(s: GameState, src: Source): Args[];
|
||||
resolve(s: GameState, item: StackItem, src: Source): void;
|
||||
/** Hardware "once per turn" abilities, which Desynchronization and Cooling System refer to. */
|
||||
hardwareOncePerTurn?: boolean;
|
||||
}
|
||||
|
||||
export interface Script {
|
||||
/** The card text this script implements. */
|
||||
text: string;
|
||||
|
||||
/** Server: RAM gained once, when the card is placed. */
|
||||
ramOnPlace?: number;
|
||||
/** Server: Avatars of its controller that fit on the location. */
|
||||
capacity?: number;
|
||||
/** Server: extra Program slots on its location. */
|
||||
programSlots?: number;
|
||||
/** Hardware that doesn't use an Expansion Slot. */
|
||||
noPort?: boolean;
|
||||
/** Hardware: Expansion Slots it adds to its wearer (Network Interface Upgrade). */
|
||||
extraSlots?: number;
|
||||
/** Program: extra attacks for its controller's Avatars attacking from this location (Infinite Loop). */
|
||||
extraAttacks?: number;
|
||||
/** Program: no Hardware Core bonuses in combats here (Stock Rice). */
|
||||
blocksHardwareInCombat?: boolean;
|
||||
/** Program: enemy attackers here can't use once-per-turn Hardware abilities (Desynchronization). */
|
||||
blocksHardwareAbilities?: boolean;
|
||||
/** Program: the attacking player can't play Executions before the roll here (Latency Spike). */
|
||||
blocksAttackerExecutions?: boolean;
|
||||
/** Hardware: opponents' Bug effects can't touch the wearer (ECC Memory). */
|
||||
bugImmunity?: boolean;
|
||||
/** Hardware: Executions performed by the wearer's Server get this much more effect (Dedicated GPU). */
|
||||
executionPower?: number;
|
||||
/** Hardware: may copy Executions performed by the wearer's Server (Quantum Coprocessor). */
|
||||
copiesExecutions?: boolean;
|
||||
|
||||
/** Core change for a fighter. Called for every active source; check relevance inside. */
|
||||
cores?(s: GameState, src: Source, f: Fighter): number;
|
||||
/** Like `cores`, but counted once no matter how many copies are in play. */
|
||||
globalCores?(s: GameState, f: Fighter): number;
|
||||
|
||||
/** RAM added to (or, negative, taken off) a payment. */
|
||||
costMod?(s: GameState, src: Source, pay: Payment): number;
|
||||
/** Called after a payment that this source changed. */
|
||||
onPaid?(s: GameState, src: Source, pay: Payment): void;
|
||||
|
||||
onTurnStart?(s: GameState, src: Source): void;
|
||||
onDraw?(s: GameState, src: Source, ev: { player: PlayerId; card: number }): void;
|
||||
onAttackDeclared?(s: GameState, src: Source, ev: { ref: AvatarRef; to: LocId }): void;
|
||||
/** An enemy is capturing this source's location. Runs before the location's cards leave. */
|
||||
onBreach?(s: GameState, src: Source, ev: { ref: AvatarRef; loc: LocId }): void;
|
||||
/** Like onBreach, for effects that save cards from the capture. */
|
||||
onCaptured?(s: GameState, src: Source, ev: { ref: AvatarRef; loc: LocId }): void;
|
||||
/** A Server card was just placed. */
|
||||
onPlaced?(s: GameState, src: Source, ev: { card: number }): void;
|
||||
onInstall?(s: GameState, src: Source, ev: { card: number; at: LocId | null; ref: AvatarRef | null }): void;
|
||||
/** Reads the combat from s.combat. */
|
||||
onCombatStart?(s: GameState, src: Source): void;
|
||||
/** An Avatar was defeated at `loc`. It's already back in its slot. */
|
||||
onDefeat?(s: GameState, src: Source, ev: { ref: AvatarRef; loc: LocId; role: 'attack' | 'defend' }): void;
|
||||
onCombatEnd?(s: GameState, src: Source): void;
|
||||
/**
|
||||
* Hardware: its wearer was just defeated. Return true to take over what happens to the Hardware
|
||||
* (the script must then knock the Avatar out itself).
|
||||
*/
|
||||
onWearerDefeated?(s: GameState, hw: number, ev: { ref: AvatarRef; loc: LocId; role: 'attack' | 'defend' }): boolean;
|
||||
/** Lower goes first among onWearerDefeated Hardware. */
|
||||
savePriority?: number;
|
||||
|
||||
/** Null Pointer: stops an Execution from resolving. */
|
||||
negates?(s: GameState, src: Source, item: StackItem): boolean;
|
||||
|
||||
ability?: AbilityScript;
|
||||
execution?: ExecutionScript;
|
||||
/** Continuations after a choice or a delayed task, by name. */
|
||||
resume?: Record<string, (s: GameState, data: any, value: any) => void>;
|
||||
}
|
||||
|
||||
let registry: Record<string, Script> | null = null;
|
||||
|
||||
/** All scripts by card name. Built on first use, so card modules can import engine helpers. */
|
||||
export function scripts(): Record<string, Script> {
|
||||
return (registry ??= { ...SERVERS, ...PROGRAMS, ...HARDWARE, ...EXECUTIONS, ...AVATARS });
|
||||
}
|
||||
|
||||
export const scriptOf = (name: string): Script | undefined => scripts()[name];
|
||||
|
||||
export const isImplemented = (card: CardDef): boolean => card.name in scripts();
|
||||
|
||||
/** The text a card's script checks: the Ability for Avatars, the description for everything else. */
|
||||
export const scriptedText = (card: CardDef): string => (card.kind === 'avatar' ? card.ability?.text ?? '' : card.text).trim();
|
||||
|
||||
/** Scripts whose card is missing from, or worded differently in, the CSV; and cards with no script. */
|
||||
export function staleScripts(pool: CardPool): string[] {
|
||||
const warnings: string[] = [];
|
||||
for (const [name, script] of Object.entries(scripts())) {
|
||||
const card = pool.byName.get(name);
|
||||
if (!card) warnings.push(`${name}: has a script but isn't in cards.csv`);
|
||||
else if (scriptedText(card) !== script.text) {
|
||||
warnings.push(`${name}: card text changed; the script was written for "${script.text}"`);
|
||||
}
|
||||
}
|
||||
for (const card of pool.all) if (!isImplemented(card)) warnings.push(`${card.name}: no script yet`);
|
||||
return warnings;
|
||||
}
|
||||
293
sim/src/state.ts
Normal file
293
sim/src/state.ts
Normal file
|
|
@ -0,0 +1,293 @@
|
|||
/**
|
||||
* Small helpers for reading and changing a GameState. Nothing here knows about individual cards,
|
||||
* so both the engine and the card scripts can use it.
|
||||
*/
|
||||
import type { CardDef } from './cards.ts';
|
||||
import { GRID, LINES_AT, otherEnd, type Line, type LocId } from './map.ts';
|
||||
import { d6 } from './rng.ts';
|
||||
import {
|
||||
PLAYER_NAMES,
|
||||
type AvatarRef,
|
||||
type AvatarState,
|
||||
type CaptureStat,
|
||||
type Choice,
|
||||
type Clock,
|
||||
type Combat,
|
||||
type GameState,
|
||||
type Json,
|
||||
type Modifier,
|
||||
type PlayerId,
|
||||
type StatKey,
|
||||
type Task,
|
||||
} from './types.ts';
|
||||
|
||||
export const other = (p: PlayerId): PlayerId => (p === 0 ? 1 : 0);
|
||||
export const defOf = (s: GameState, id: number): CardDef => s.defs[s.cards[id].name];
|
||||
export const nameOf = (s: GameState, id: number): string => (id < 0 ? 'a hidden card' : s.cards[id].name);
|
||||
export const ownerOf = (s: GameState, id: number): PlayerId => s.cards[id].owner;
|
||||
export const controls = (s: GameState, p: PlayerId, loc: LocId): boolean => s.locations[loc].owner === p;
|
||||
export const isOpen = (s: GameState, line: Line): boolean => !s.firewalls[line.id];
|
||||
/** RAM to place, upgrade to, or clear a Firewall of `level`, before discounts; 0 for no Firewall. */
|
||||
export const firewallCost = (s: GameState, level: number): number => s.rules.firewallCost[level - 1] ?? 0;
|
||||
export const gridCount = (s: GameState, p: PlayerId): number => GRID.filter((loc) => controls(s, p, loc)).length;
|
||||
|
||||
/** Rolls a d6 (or takes the next rigged result). */
|
||||
export const rollDie = (s: GameState): number => (s.rigged?.length ? s.rigged.shift()! : d6(s.rng));
|
||||
|
||||
export function say(s: GameState, msg: string): void {
|
||||
s.log?.push(msg);
|
||||
}
|
||||
|
||||
export function stat(s: GameState, key: StatKey, p: PlayerId, n = 1): void {
|
||||
s.stats[key][p] += n;
|
||||
}
|
||||
|
||||
function use(s: GameState, name: string) {
|
||||
return (s.cardUse[name] ??= { played: [0, 0], fired: [0, 0] });
|
||||
}
|
||||
/** Counts a card being played, installed or activated. */
|
||||
export const played = (s: GameState, name: string, p: PlayerId): void => void use(s, name).played[p]++;
|
||||
/** Counts a card's effect happening. */
|
||||
export const fired = (s: GameState, name: string, p: PlayerId): void => void use(s, name).fired[p]++;
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Time
|
||||
|
||||
export const endOfTurn = (s: GameState): Clock => 2 * s.turn + 1;
|
||||
export const startOf = (turn: number): Clock => 2 * turn;
|
||||
export const endOf = (turn: number): Clock => 2 * turn + 1;
|
||||
/** The turn number of `p`'s next turn (not the current one). */
|
||||
export const nextTurnOf = (s: GameState, p: PlayerId): number => (s.active === p ? s.turn + 2 : s.turn + 1);
|
||||
export const running = (s: GameState, until: Clock): boolean => until > s.clock;
|
||||
|
||||
/** Once-per-turn bookkeeping. Returns how many times `key` was used this turn. */
|
||||
export const usedThisTurn = (s: GameState, key: string): number => s.used[key] ?? 0;
|
||||
export function markUsed(s: GameState, key: string): void {
|
||||
s.used[key] = (s.used[key] ?? 0) + 1;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Avatars
|
||||
|
||||
export const refKey = (r: AvatarRef): string => `${r.player}:${r.slot}`;
|
||||
export const sameRef = (a: AvatarRef | null | undefined, b: AvatarRef | null | undefined): boolean =>
|
||||
!!a && !!b && a.player === b.player && a.slot === b.slot;
|
||||
export const avatar = (s: GameState, r: AvatarRef): AvatarState => s.players[r.player].avatars[r.slot - 1];
|
||||
export const isCopy = (r: AvatarRef): boolean => r.slot > 4;
|
||||
/** The printed Avatar a ref belongs to (a copy's original). */
|
||||
export const originalOf = (r: AvatarRef): AvatarRef => (r.slot > 4 ? { player: r.player, slot: r.slot - 4 } : r);
|
||||
export const copyOf = (r: AvatarRef): AvatarRef => ({ player: r.player, slot: originalOf(r).slot + 4 });
|
||||
export const inPlay = (s: GameState, r: AvatarRef): boolean => avatar(s, r).at !== null;
|
||||
export const avatarDef = (s: GameState, r: AvatarRef): CardDef => defOf(s, avatar(s, r).card);
|
||||
|
||||
export function avatarName(s: GameState, r: AvatarRef): string {
|
||||
const n = originalOf(r).slot;
|
||||
const card = avatar(s, r).card;
|
||||
const name = card < 0 ? '?' : nameOf(s, card);
|
||||
return isCopy(r) ? `the copy of Avatar ${n} (${name})` : `Avatar ${n} (${name})`;
|
||||
}
|
||||
|
||||
/** Every Avatar of `p` in play, originals first. */
|
||||
export function refsInPlay(s: GameState, p: PlayerId): AvatarRef[] {
|
||||
const out: AvatarRef[] = [];
|
||||
s.players[p].avatars.forEach((av, i) => {
|
||||
if (av.at !== null) out.push({ player: p, slot: i + 1 });
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Avatars standing on `loc`. Only the location's owner can have Avatars there. */
|
||||
export function avatarsAt(s: GameState, loc: LocId): AvatarRef[] {
|
||||
const owner = s.locations[loc].owner;
|
||||
return owner === null ? [] : refsInPlay(s, owner).filter((r) => avatar(s, r).at === loc);
|
||||
}
|
||||
export const defendersAt = avatarsAt;
|
||||
|
||||
/** Hardware that counts for an Avatar. A copy uses its original's Hardware. */
|
||||
export const hardwareOf = (s: GameState, r: AvatarRef): number[] => avatar(s, originalOf(r)).hardware;
|
||||
|
||||
/** The Avatar wearing a Hardware card, if it's installed. */
|
||||
export function wearerOf(s: GameState, hw: number): AvatarRef | null {
|
||||
const p = ownerOf(s, hw);
|
||||
const i = s.players[p].avatars.findIndex((a) => a.hardware.includes(hw));
|
||||
return i < 0 ? null : { player: p, slot: i + 1 };
|
||||
}
|
||||
|
||||
export const isRooted = (s: GameState, r: AvatarRef): boolean => running(s, avatar(s, r).rootedUntil);
|
||||
export const isDisabledAvatar = (s: GameState, r: AvatarRef): boolean => running(s, avatar(s, r).disabledUntil);
|
||||
/** Can act: advance, attack, move, use its Ability. */
|
||||
export const canAct = (s: GameState, r: AvatarRef): boolean =>
|
||||
inPlay(s, r) && !isRooted(s, r) && !isDisabledAvatar(s, r);
|
||||
|
||||
/** Temporary modifiers that currently apply to an Avatar. */
|
||||
export function activeMods(s: GameState, av: AvatarState): Modifier[] {
|
||||
return av.mods.filter((m) =>
|
||||
m.combat !== undefined ? s.combat?.id === m.combat : running(s, m.until ?? 0));
|
||||
}
|
||||
|
||||
export function addMod(
|
||||
s: GameState,
|
||||
r: AvatarRef,
|
||||
cores: number,
|
||||
source: string,
|
||||
by: PlayerId,
|
||||
scope: { combat: number } | { until: Clock },
|
||||
): void {
|
||||
avatar(s, r).mods.push({ seq: ++s.seq, cores, source, by, ...scope });
|
||||
}
|
||||
|
||||
export const infectionOf = (av: AvatarState): number => av.infection + av.permanentInfection;
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Combat
|
||||
|
||||
export const inCombat = (s: GameState, r: AvatarRef): boolean =>
|
||||
!!s.combat && !s.combat.ended && (sameRef(s.combat.attacker, r) || s.combat.defenders.some((d) => sameRef(d, r)));
|
||||
|
||||
/** The other side of the current combat from `r`'s point of view. */
|
||||
export function opponentsInCombat(s: GameState, r: AvatarRef): AvatarRef[] {
|
||||
const c = s.combat;
|
||||
if (!c || c.ended) return [];
|
||||
if (sameRef(c.attacker, r)) return [...c.defenders];
|
||||
if (c.defenders.some((d) => sameRef(d, r))) return [c.attacker];
|
||||
return [];
|
||||
}
|
||||
|
||||
export const fightersOf = (c: Combat): AvatarRef[] => [c.attacker, ...c.defenders];
|
||||
|
||||
/**
|
||||
* Avatars "at" a location for card text: the ones standing there, plus an enemy attacking it in the
|
||||
* current combat.
|
||||
*/
|
||||
export function atServer(s: GameState, loc: LocId): AvatarRef[] {
|
||||
const out = avatarsAt(s, loc);
|
||||
const c = s.combat;
|
||||
if (c && !c.ended && c.loc === loc && !out.some((r) => sameRef(r, c.attacker))) out.push(c.attacker);
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Map
|
||||
|
||||
/** Locations joined to `loc` by a line with no Firewall. */
|
||||
export function neighbors(s: GameState, loc: LocId): LocId[] {
|
||||
return LINES_AT.get(loc)!.filter((l) => isOpen(s, l)).map((l) => otherEnd(l, loc));
|
||||
}
|
||||
export const adjacent = (s: GameState, a: LocId, b: LocId): boolean => neighbors(s, a).includes(b);
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Cards moving between zones
|
||||
|
||||
/** Clears play-time status when a card leaves play. */
|
||||
export function resetCard(s: GameState, id: number): void {
|
||||
const c = s.cards[id];
|
||||
c.disabledUntil = 0;
|
||||
c.ignoredUntil = 0;
|
||||
delete c.wormTo;
|
||||
delete c.protects;
|
||||
delete c.copies;
|
||||
delete c.spent;
|
||||
delete c.pushedUntil;
|
||||
}
|
||||
|
||||
export function toDiscard(s: GameState, id: number): void {
|
||||
resetCard(s, id);
|
||||
s.players[ownerOf(s, id)].discard.push(id);
|
||||
}
|
||||
|
||||
export function toHand(s: GameState, id: number): void {
|
||||
resetCard(s, id);
|
||||
s.players[ownerOf(s, id)].hand.push(id);
|
||||
}
|
||||
|
||||
export function removeFrom(list: number[], id: number): boolean {
|
||||
const i = list.indexOf(id);
|
||||
if (i < 0) return false;
|
||||
list.splice(i, 1);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Takes an installed Program off its location. Returns where it was. */
|
||||
export function uninstallProgram(s: GameState, id: number): LocId | null {
|
||||
for (const [loc, L] of Object.entries(s.locations)) {
|
||||
if (removeFrom(L.programs, id)) return loc;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function uninstallHardware(s: GameState, id: number): AvatarRef | null {
|
||||
const r = wearerOf(s, id);
|
||||
if (r) removeFrom(avatar(s, r).hardware, id);
|
||||
return r;
|
||||
}
|
||||
|
||||
export function programLocation(s: GameState, id: number): LocId | null {
|
||||
for (const [loc, L] of Object.entries(s.locations)) if (L.programs.includes(id)) return loc;
|
||||
return null;
|
||||
}
|
||||
|
||||
export function gainRam(s: GameState, p: PlayerId, n: number, key: StatKey = 'ramFromEffects'): void {
|
||||
if (n <= 0) return;
|
||||
s.players[p].ram += n;
|
||||
stat(s, key, p, n);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Tasks and choices
|
||||
|
||||
/** Queues tasks to run next, in the order given. */
|
||||
export function pushTasks(s: GameState, ...tasks: Task[]): void {
|
||||
s.tasks.unshift(...tasks);
|
||||
}
|
||||
|
||||
/** Asks a player to choose. The game waits until they do. */
|
||||
export function ask(s: GameState, choice: Choice): void {
|
||||
if (s.choice) throw new Error(`Two choices at once: ${s.choice.kind} and ${choice.kind}`);
|
||||
if (choice.options.length === 0) throw new Error(`Choice ${choice.kind} has no options`);
|
||||
s.choice = choice;
|
||||
}
|
||||
|
||||
/** Runs a script function after the current task, like a choice would. */
|
||||
export const later = (name: string, fn: string, data: Json = null): Task => ({ t: 'call', name, fn, data });
|
||||
|
||||
export function startCombat(
|
||||
s: GameState,
|
||||
attacker: AvatarRef,
|
||||
origin: LocId,
|
||||
loc: LocId,
|
||||
kind: Combat['kind'],
|
||||
): Combat {
|
||||
const combat: Combat = {
|
||||
id: ++s.seq,
|
||||
loc,
|
||||
attacker,
|
||||
origin,
|
||||
defenders: defendersAt(s, loc),
|
||||
kind,
|
||||
dice: {},
|
||||
rolled: false,
|
||||
ended: false,
|
||||
suppressed: [],
|
||||
race: [null, null],
|
||||
ties: 0,
|
||||
};
|
||||
s.combat = combat;
|
||||
const window = (kind: 'preRoll' | 'postRoll'): Task => ({
|
||||
t: 'window', kind, priority: attacker.player, passes: 0, base: s.stack.length, resolving: false,
|
||||
});
|
||||
pushTasks(
|
||||
s,
|
||||
{ t: 'combat', stage: 'start' },
|
||||
window('preRoll'),
|
||||
{ t: 'combat', stage: 'roll' },
|
||||
window('postRoll'),
|
||||
{ t: 'combat', stage: 'result' },
|
||||
{ t: 'combat', stage: 'end' },
|
||||
);
|
||||
return combat;
|
||||
}
|
||||
|
||||
export const pushCapture = (s: GameState, ref: AvatarRef, loc: LocId, how: CaptureStat): void =>
|
||||
pushTasks(s, { t: 'capture', ref, loc, stage: 'hooks', how });
|
||||
|
||||
export const playerName = (p: PlayerId): string => PLAYER_NAMES[p];
|
||||
185
sim/src/stats.ts
Normal file
185
sim/src/stats.ts
Normal file
|
|
@ -0,0 +1,185 @@
|
|||
import type { CardPool } from './cards.ts';
|
||||
import { gridCount } from './engine.ts';
|
||||
import { STAT_KEYS, type CardUse, type GameState, type StatKey } from './types.ts';
|
||||
|
||||
export interface GameRecord {
|
||||
seed: number;
|
||||
winner: 0 | 1 | null;
|
||||
firstPlayer: 0 | 1;
|
||||
turns: number;
|
||||
locations: [number, number];
|
||||
stats: Record<StatKey, [number, number]>;
|
||||
cardUse: Record<string, CardUse>;
|
||||
/** Card names in each player's decks (Avatars, Servers and main deck). */
|
||||
decks: [string[], string[]];
|
||||
}
|
||||
|
||||
export interface BatchSummary {
|
||||
games: number;
|
||||
wins: [number, number];
|
||||
draws: number;
|
||||
firstPlayerWins: number;
|
||||
rounds: { mean: number; median: number; p10: number; p90: number };
|
||||
/** Average per game, per player. */
|
||||
perGame: Record<StatKey, [number, number]>;
|
||||
locations: [number, number];
|
||||
}
|
||||
|
||||
export function recordOf(seed: number, s: GameState): GameRecord {
|
||||
return {
|
||||
seed,
|
||||
winner: s.winner,
|
||||
firstPlayer: s.firstPlayer,
|
||||
turns: s.turn,
|
||||
locations: [gridCount(s, 0), gridCount(s, 1)],
|
||||
stats: s.stats,
|
||||
cardUse: s.cardUse,
|
||||
decks: [0, 1].map((p) => [...new Set(s.cards.filter((c) => c.owner === p).map((c) => c.name))]) as [string[], string[]],
|
||||
};
|
||||
}
|
||||
|
||||
/** Rounds: both players taking one turn each. */
|
||||
const roundsOf = (r: GameRecord) => Math.ceil(r.turns / 2);
|
||||
|
||||
export function summarize(records: GameRecord[]): BatchSummary {
|
||||
const n = records.length;
|
||||
const avg = (f: (r: GameRecord) => number) => records.reduce((t, r) => t + f(r), 0) / n;
|
||||
const rounds = records.map(roundsOf).sort((a, b) => a - b);
|
||||
const at = (q: number) => rounds[Math.min(n - 1, Math.floor(q * n))];
|
||||
return {
|
||||
games: n,
|
||||
wins: [records.filter((r) => r.winner === 0).length, records.filter((r) => r.winner === 1).length],
|
||||
draws: records.filter((r) => r.winner === null).length,
|
||||
firstPlayerWins: records.filter((r) => r.winner !== null && r.winner === r.firstPlayer).length,
|
||||
rounds: { mean: avg(roundsOf), median: at(0.5), p10: at(0.1), p90: at(0.9) },
|
||||
perGame: Object.fromEntries(
|
||||
STAT_KEYS.map((k) => [k, [avg((r) => r.stats[k][0]), avg((r) => r.stats[k][1])]]),
|
||||
) as Record<StatKey, [number, number]>,
|
||||
locations: [avg((r) => r.locations[0]), avg((r) => r.locations[1])],
|
||||
};
|
||||
}
|
||||
|
||||
const pct = (x: number, of: number) => (of === 0 ? '—' : `${((100 * x) / of).toFixed(1)}%`);
|
||||
const fmt = (x: number) => x.toFixed(1);
|
||||
|
||||
export function formatSummary(sum: BatchSummary, labels: [string, string]): string {
|
||||
const g = sum.perGame;
|
||||
const decided = sum.wins[0] + sum.wins[1];
|
||||
const width = Math.max(9, ...labels.map((l) => l.length + 2));
|
||||
const row = (label: string, south: string, north: string) =>
|
||||
` ${label.padEnd(34)}${south.padStart(width)}${north.padStart(width)}`;
|
||||
const both = (label: string, k: StatKey) => row(label, fmt(g[k][0]), fmt(g[k][1]));
|
||||
const combats = g.attacks[0] + g.attacks[1];
|
||||
const enemyCaptures =
|
||||
g.capturesUndefended[0] + g.capturesUndefended[1] + g.capturesInCombat[0] + g.capturesInCombat[1];
|
||||
return [
|
||||
'Results',
|
||||
` ${labels[0]} wins`.padEnd(36) + pct(sum.wins[0], sum.games),
|
||||
` ${labels[1]} wins`.padEnd(36) + pct(sum.wins[1], sum.games),
|
||||
' Draws (turn limit)'.padEnd(36) + pct(sum.draws, sum.games),
|
||||
' First player wins'.padEnd(36) + `${pct(sum.firstPlayerWins, decided)} of decided games`,
|
||||
'',
|
||||
'Game length, in rounds (both players take a turn)',
|
||||
` mean ${fmt(sum.rounds.mean)} · median ${sum.rounds.median} · 10% of games ≤ ${sum.rounds.p10} · 90% ≤ ${sum.rounds.p90}`,
|
||||
'',
|
||||
row('Average per player, per game', labels[0], labels[1]),
|
||||
both('Captures: unowned', 'capturesUnowned'),
|
||||
both('Captures: undefended enemy', 'capturesUndefended'),
|
||||
both('Captures: won in combat', 'capturesInCombat'),
|
||||
both('Attacks', 'attacks'),
|
||||
row('Attack win rate', pct(g.attacksWon[0], g.attacks[0]), pct(g.attacksWon[1], g.attacks[1])),
|
||||
both('Firewalls placed', 'firewallsPlaced'),
|
||||
both('Firewalls upgraded', 'firewallsUpgraded'),
|
||||
both('Firewalls cleared', 'firewallsCleared'),
|
||||
both('RAM from captures', 'ramFromCaptures'),
|
||||
both('RAM from salvage', 'ramFromSalvage'),
|
||||
both('RAM spent on Firewalls', 'ramOnFirewalls'),
|
||||
both('RAM spent on cards', 'ramOnCards'),
|
||||
both('Cards salvaged', 'cardsSalvaged'),
|
||||
both('Hardware installed', 'hardwareInstalled'),
|
||||
both('Hardware lost in combat', 'hardwareLost'),
|
||||
both('Programs installed', 'programsInstalled'),
|
||||
both('Programs lost', 'programsLost'),
|
||||
both('Executions played', 'executionsPlayed'),
|
||||
both('Abilities used', 'abilitiesUsed'),
|
||||
both('Combats ended early', 'combatsEnded'),
|
||||
both('RAM from card effects', 'ramFromEffects'),
|
||||
both('RAM spent on Abilities', 'ramOnAbilities'),
|
||||
both('Cards drawn', 'cardsDrawn'),
|
||||
row('Locations at game end', fmt(sum.locations[0]), fmt(sum.locations[1])),
|
||||
'',
|
||||
`Fights: ${fmt(combats)} combats per game; ${pct(g.capturesInCombat[0] + g.capturesInCombat[1], enemyCaptures)} of enemy locations taken were won in combat.`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
export interface CardReport {
|
||||
name: string;
|
||||
kind: string;
|
||||
/** Player-games with the card in the deck, and that player's win rate. */
|
||||
inDeck: number;
|
||||
deckWinRate: number;
|
||||
/** Share of those player-games where it was played, used, or (Servers) placed. */
|
||||
playedShare: number;
|
||||
/** Plays and fires per player-game where it was played. */
|
||||
plays: number;
|
||||
fired: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* How each card did. Random decks make "win rate in deck" a fair measure of card strength: the
|
||||
* card's presence is the only thing that differs on average. "Played" numbers show how the bots
|
||||
* used it.
|
||||
*/
|
||||
export function cardReport(pool: CardPool, records: GameRecord[]): CardReport[] {
|
||||
return pool.all.map((card) => {
|
||||
let inDeck = 0;
|
||||
let wins = 0;
|
||||
let playedGames = 0;
|
||||
let plays = 0;
|
||||
let fired = 0;
|
||||
for (const r of records) {
|
||||
const use = r.cardUse[card.name];
|
||||
for (const p of [0, 1] as const) {
|
||||
if (!r.decks[p].includes(card.name)) continue;
|
||||
inDeck++;
|
||||
if (r.winner === p) wins++;
|
||||
if (!use || (use.played[p] === 0 && use.fired[p] === 0)) continue;
|
||||
playedGames++;
|
||||
plays += use.played[p];
|
||||
fired += use.fired[p];
|
||||
}
|
||||
}
|
||||
return {
|
||||
name: card.name,
|
||||
kind: card.kind,
|
||||
inDeck,
|
||||
deckWinRate: inDeck ? wins / inDeck : 0,
|
||||
playedShare: inDeck ? playedGames / inDeck : 0,
|
||||
plays: playedGames ? plays / playedGames : 0,
|
||||
fired: playedGames ? fired / playedGames : 0,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function formatCardReport(rows: CardReport[]): string {
|
||||
const pctOf = (x: number) => `${(100 * x).toFixed(1)}%`;
|
||||
const out = [
|
||||
'Cards. Win rate is for the player whose deck held the card (± is one standard error).',
|
||||
'Played is how often that player got it into play; plays and fired are per game where it was played.',
|
||||
'',
|
||||
` ${'Card'.padEnd(28)}${'decks'.padStart(7)}${'win rate'.padStart(10)}${'±'.padStart(6)}${'played'.padStart(9)}${'plays'.padStart(7)}${'fired'.padStart(7)}`,
|
||||
];
|
||||
let kind = '';
|
||||
for (const r of rows) {
|
||||
if (r.kind !== kind) {
|
||||
kind = r.kind;
|
||||
out.push(` ${{ avatar: 'Avatars', server: 'Servers', program: 'Programs', hardware: 'Hardware', execution: 'Executions' }[kind] ?? kind}`);
|
||||
}
|
||||
const se = r.inDeck ? Math.sqrt((r.deckWinRate * (1 - r.deckWinRate)) / r.inDeck) : 0;
|
||||
out.push(
|
||||
` ${r.name.padEnd(26)}${String(r.inDeck).padStart(7)}${(r.inDeck ? pctOf(r.deckWinRate) : '—').padStart(10)}` +
|
||||
`${(r.inDeck ? (100 * se).toFixed(1) : '').padStart(6)}${pctOf(r.playedShare).padStart(9)}${r.plays.toFixed(2).padStart(7)}${r.fired.toFixed(2).padStart(7)}`,
|
||||
);
|
||||
}
|
||||
return out.join('\n');
|
||||
}
|
||||
329
sim/src/types.ts
Normal file
329
sim/src/types.ts
Normal file
|
|
@ -0,0 +1,329 @@
|
|||
import type { CardDef } from './cards.ts';
|
||||
import type { LocId } from './map.ts';
|
||||
import type { Rng } from './rng.ts';
|
||||
import type { RulesConfig } from './rules.ts';
|
||||
|
||||
/** 0 = South (starts on S1), 1 = North (starts on S2). */
|
||||
export type PlayerId = 0 | 1;
|
||||
export const PLAYER_NAMES = ['South', 'North'] as const;
|
||||
|
||||
/**
|
||||
* Status timers count half-turns: the clock is 2T at the start of player-turn T and 2T + 1 at its
|
||||
* end. A status with `until: n` is active while the clock is below n.
|
||||
*/
|
||||
export type Clock = number;
|
||||
export const FOREVER: Clock = 1e9;
|
||||
|
||||
export interface CardInstance {
|
||||
id: number;
|
||||
name: string;
|
||||
owner: PlayerId;
|
||||
/** Hardware or Program: disabled until this clock (0 = not disabled). */
|
||||
disabledUntil: Clock;
|
||||
/** Program: text ignored until this clock (Execute: Override). */
|
||||
ignoredUntil: Clock;
|
||||
/** Turn it was last installed, for Execute: Rollback. */
|
||||
installedTurn: number;
|
||||
/** Worm Protocol: the adjacent location it spreads to. */
|
||||
wormTo?: LocId;
|
||||
/** Hardware Sandbox: the Program it protects. */
|
||||
protects?: number;
|
||||
/** Duplicate Server: the Server ability it copies. */
|
||||
copies?: string;
|
||||
/** One-time effects already used (Redundant Power Supply, Visual Artifact). */
|
||||
spent?: boolean;
|
||||
/** Hardware attached by Push Update: discarded at this clock. */
|
||||
pushedUntil?: Clock;
|
||||
}
|
||||
|
||||
/** Slots 1–4 are the printed Avatars; slot k + 4 is a copy of Avatar k. */
|
||||
export interface AvatarRef {
|
||||
player: PlayerId;
|
||||
slot: number;
|
||||
}
|
||||
|
||||
/** A temporary Core bonus or penalty on one Avatar. */
|
||||
export interface Modifier {
|
||||
/** Increases with every new modifier, so "most recent" is the highest. */
|
||||
seq: number;
|
||||
cores: number;
|
||||
source: string;
|
||||
/** Player whose card created it. */
|
||||
by: PlayerId;
|
||||
/** Ends with this combat, or at `until` on the clock. */
|
||||
combat?: number;
|
||||
until?: Clock;
|
||||
}
|
||||
|
||||
export interface AvatarState {
|
||||
/** Card id, or -1 in a player view where the Avatar is still face down. */
|
||||
card: number;
|
||||
/** Face up = unlocked. Copies are face up only while they exist. */
|
||||
faceUp: boolean;
|
||||
/** null while the Avatar is in its slot (or, for a copy, doesn't exist). */
|
||||
at: LocId | null;
|
||||
hardware: number[];
|
||||
/** Placed (entered play or repositioned) this turn. */
|
||||
placed: boolean;
|
||||
advanced: boolean;
|
||||
/** Attacks declared this turn (Infinite Loop allows 2). */
|
||||
attacks: number;
|
||||
/** Removed when the Avatar is defeated. */
|
||||
infection: number;
|
||||
/** Bug counters: like Infection, for Bug cards. Removed when the Avatar is defeated. */
|
||||
bugs: number;
|
||||
/** Persistent Infection counters survive defeat. */
|
||||
permanentInfection: number;
|
||||
mods: Modifier[];
|
||||
/** Emergency Shutdown. */
|
||||
disabledUntil: Clock;
|
||||
/** Packet Flood: can't move or retreat. */
|
||||
rootedUntil: Clock;
|
||||
/** Last turn it captured an enemy location. */
|
||||
breachedTurn: number;
|
||||
/** For copies: the original's slot. */
|
||||
copyOf: number | null;
|
||||
}
|
||||
|
||||
export interface PlayerState {
|
||||
ram: number;
|
||||
hand: number[];
|
||||
deck: number[];
|
||||
discard: number[];
|
||||
serverPile: number[];
|
||||
/** Avatar N is avatars[N - 1]; avatars[N + 3] is its copy slot. */
|
||||
avatars: AvatarState[];
|
||||
/** Highest location level captured so far; unlocks Avatars up to this number. */
|
||||
unlockedLevel: number;
|
||||
}
|
||||
|
||||
export interface LocationState {
|
||||
owner: PlayerId | null;
|
||||
server: number | null;
|
||||
programs: number[];
|
||||
/** Execute: Root Access, by player: that player ignores protection here until this clock. */
|
||||
rootAccess: [Clock, Clock];
|
||||
}
|
||||
|
||||
/** Main turn steps. Draw (1), Resolve (5) and Pass (7) happen automatically. */
|
||||
export type Step = 'deploy' | 'play' | 'attack' | 'resolve' | 'playAgain';
|
||||
|
||||
export interface Declaration {
|
||||
kind: 'advance' | 'attack';
|
||||
ref: AvatarRef;
|
||||
to: LocId;
|
||||
/** Where the attacker stood when it declared. */
|
||||
from: LocId;
|
||||
/** Infinite Loop: this Avatar's second attack this turn. */
|
||||
second: boolean;
|
||||
}
|
||||
|
||||
/** Parameters of an Execution or ability. Each card uses the fields it needs. */
|
||||
export interface Args {
|
||||
ref?: AvatarRef;
|
||||
card?: number;
|
||||
cards?: number[];
|
||||
to?: LocId;
|
||||
mode?: 'destroy' | 'disable';
|
||||
/** Bit Flip: reroll dice showing this or less. */
|
||||
k?: number;
|
||||
}
|
||||
|
||||
export interface StackItem {
|
||||
kind: 'execution' | 'ability';
|
||||
player: PlayerId;
|
||||
/** The Execution card, or the card whose ability this is. */
|
||||
card: number;
|
||||
name: string;
|
||||
target: LocId | null;
|
||||
args: Args;
|
||||
/** The Server (one of the player's locations) performing an Execution, when it matters. */
|
||||
from: LocId | null;
|
||||
/** Dedicated GPU: +1 effectiveness. */
|
||||
power: number;
|
||||
}
|
||||
|
||||
/** A copied Program effect (Fork, Process Clone, Remote Access, Undefined Behavior). */
|
||||
export interface VirtualProgram {
|
||||
id: number;
|
||||
name: string;
|
||||
controller: PlayerId;
|
||||
at: LocId;
|
||||
until: Clock;
|
||||
/** Counts as an installed Program (Process Clone, Remote Access). */
|
||||
installed: boolean;
|
||||
/** Card the effect was copied from. */
|
||||
from: number;
|
||||
}
|
||||
|
||||
export interface Combat {
|
||||
id: number;
|
||||
/** The defended location. */
|
||||
loc: LocId;
|
||||
attacker: AvatarRef;
|
||||
/** Where the attacker stands, for its Server bonus. */
|
||||
origin: LocId;
|
||||
defenders: AvatarRef[];
|
||||
kind: 'attack' | 'advance' | 'traceRoute';
|
||||
/** Dice by Avatar, keyed `player:slot`. */
|
||||
dice: Record<string, number[]>;
|
||||
rolled: boolean;
|
||||
/** Ended early (Emergency Shutdown, Disconnect). */
|
||||
ended: boolean;
|
||||
/** Hardware disabled for this combat only (Memory Parasite). */
|
||||
suppressed: number[];
|
||||
/** Race Condition picks, by player. */
|
||||
race: [('attack' | 'defend') | null, ('attack' | 'defend') | null];
|
||||
ties: number;
|
||||
}
|
||||
|
||||
/** Data stored in the state (task and choice payloads). Keep it JSON-serializable. */
|
||||
export type Json = unknown;
|
||||
|
||||
export interface ChoiceOption {
|
||||
label: string;
|
||||
value: Json;
|
||||
/** RAM needed to pick this option. */
|
||||
cost?: number;
|
||||
}
|
||||
|
||||
/** A decision a card asks a player to make before the game can continue. */
|
||||
export interface Choice {
|
||||
player: PlayerId;
|
||||
/** Stable id for bots, e.g. "RAID Array:keep". */
|
||||
kind: string;
|
||||
prompt: string;
|
||||
options: ChoiceOption[];
|
||||
/** Script function that receives the picked value. */
|
||||
resume: { name: string; fn: string; data: Json };
|
||||
}
|
||||
|
||||
export type WindowKind = 'response' | 'preRoll' | 'postRoll';
|
||||
|
||||
export type HookName =
|
||||
| 'onTurnStart'
|
||||
| 'onDraw'
|
||||
| 'onAttackDeclared'
|
||||
| 'onBreach'
|
||||
| 'onCaptured'
|
||||
| 'onPlaced'
|
||||
| 'onInstall'
|
||||
| 'onCombatStart'
|
||||
| 'onDefeat'
|
||||
| 'onCombatEnd';
|
||||
|
||||
/** Something that has an effect in play. */
|
||||
export interface Source {
|
||||
kind: 'server' | 'program' | 'hardware' | 'avatar';
|
||||
/** The card providing it (the original card for copied effects). */
|
||||
id: number;
|
||||
/** Script that runs. Differs from the card for copies (Duplicate Server, Fork...). */
|
||||
name: string;
|
||||
controller: PlayerId;
|
||||
/** Where the effect applies. */
|
||||
at: LocId | null;
|
||||
/** Hardware: its wearer. Avatar: itself. */
|
||||
ref?: AvatarRef;
|
||||
/** Virtual copy id, or -1 for a Worm Protocol spread. */
|
||||
virtual?: number;
|
||||
}
|
||||
|
||||
/** Engine work still to do. Tasks run front to back; a task may add tasks in front of the rest. */
|
||||
export type Task =
|
||||
| { t: 'window'; kind: WindowKind; priority: PlayerId; passes: number; base: number; resolving: boolean }
|
||||
| { t: 'declaration'; index: number }
|
||||
| { t: 'afterResolve' }
|
||||
| { t: 'combat'; stage: 'start' | 'roll' | 'result' | 'end' | 'cleanup' }
|
||||
| { t: 'defeat'; ref: AvatarRef; loc: LocId; role: 'attack' | 'defend' }
|
||||
| { t: 'capture'; ref: AvatarRef; loc: LocId; stage: 'hooks' | 'main'; how: CaptureStat }
|
||||
| { t: 'hook'; hook: HookName; src: Source; data: Json }
|
||||
| { t: 'call'; name: string; fn: string; data: Json }
|
||||
| { t: 'draw'; player: PlayerId }
|
||||
| { t: 'endTurn' };
|
||||
|
||||
export type Action =
|
||||
| { type: 'end' }
|
||||
| { type: 'pass' }
|
||||
| { type: 'choose'; index: number }
|
||||
| { type: 'place'; slot: number; to: LocId }
|
||||
| { type: 'advance'; slot: number; to: LocId }
|
||||
| { type: 'attack'; slot: number; to: LocId }
|
||||
| { type: 'clearFirewall'; line: string }
|
||||
| { type: 'firewall'; line: string; level: number }
|
||||
| { type: 'salvage'; card: number }
|
||||
| { type: 'installHardware'; card: number; slot: number }
|
||||
| { type: 'installProgram'; card: number; at: LocId }
|
||||
| { type: 'play'; card: number; target: LocId | null; args: Args; from: LocId | null }
|
||||
| { type: 'activate'; card: number; name: string; args: Args };
|
||||
|
||||
export const STAT_KEYS = [
|
||||
'capturesUnowned',
|
||||
'capturesUndefended',
|
||||
'capturesInCombat',
|
||||
'attacks',
|
||||
'attacksWon',
|
||||
'combatsEnded',
|
||||
'firewallsPlaced',
|
||||
'firewallsUpgraded',
|
||||
'firewallsCleared',
|
||||
'ramFromCaptures',
|
||||
'ramFromSalvage',
|
||||
'ramFromEffects',
|
||||
'ramOnFirewalls',
|
||||
'ramOnCards',
|
||||
'ramOnAbilities',
|
||||
'cardsSalvaged',
|
||||
'cardsDrawn',
|
||||
'hardwareInstalled',
|
||||
'hardwareLost',
|
||||
'programsInstalled',
|
||||
'programsLost',
|
||||
'executionsPlayed',
|
||||
'abilitiesUsed',
|
||||
] as const;
|
||||
|
||||
export type StatKey = (typeof STAT_KEYS)[number];
|
||||
export type CaptureStat = 'capturesUnowned' | 'capturesUndefended' | 'capturesInCombat';
|
||||
export type GameStats = Record<StatKey, [number, number]>;
|
||||
|
||||
/** Per card name, per player: times played or used, and times its effect fired. */
|
||||
export interface CardUse {
|
||||
played: [number, number];
|
||||
fired: [number, number];
|
||||
}
|
||||
|
||||
export interface GameState {
|
||||
rules: RulesConfig;
|
||||
rng: Rng;
|
||||
defs: Record<string, CardDef>;
|
||||
cards: CardInstance[];
|
||||
players: [PlayerState, PlayerState];
|
||||
locations: Record<LocId, LocationState>;
|
||||
/** Firewall level by line id; a missing entry means no Firewall. */
|
||||
firewalls: Record<string, number>;
|
||||
firstPlayer: PlayerId;
|
||||
active: PlayerId;
|
||||
/** Player turns so far, counting the current one. */
|
||||
turn: number;
|
||||
clock: Clock;
|
||||
step: Step;
|
||||
declarations: Declaration[];
|
||||
tasks: Task[];
|
||||
stack: StackItem[];
|
||||
choice: Choice | null;
|
||||
combat: Combat | null;
|
||||
virtuals: VirtualProgram[];
|
||||
/** Once-per-turn uses this turn, by key. */
|
||||
used: Record<string, number>;
|
||||
/** Counter for ids and modifier order. */
|
||||
seq: number;
|
||||
over: boolean;
|
||||
winner: PlayerId | null;
|
||||
endReason: 'win' | 'turnLimit' | null;
|
||||
stats: GameStats;
|
||||
cardUse: Record<string, CardUse>;
|
||||
/** Play-by-play text, when logging is on. */
|
||||
log: string[] | null;
|
||||
/** Dice results to use before the RNG. Tests set this to script a combat. */
|
||||
rigged?: number[];
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue