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 = { '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 = { '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; } /** 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(); 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(); const usedTargets = new Set(); const origins = new Map(); const clears = new Set(); 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(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) => boolean): Action | null { if (inHand(v, me, name) === undefined) return null; let best: Extract | 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) => 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, 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(); 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(); 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(); 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(); 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): 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' }; }, }; }