This commit is contained in:
Forrest 2026-09-28 02:54:54 -04:00
parent e590baf28d
commit 6382de19c9
15 changed files with 239 additions and 28 deletions

View file

@ -48,6 +48,7 @@ import {
wearerOf,
} from '../state.ts';
import { FOREVER, type AvatarRef, type GameState, type PlayerId, type Task } from '../types.ts';
import { shedHardware } from './hardware.ts';
import { cardOptions, ghostsOf, mine, programsOn, scopeOf, subsets } from './util.ts';
const liveCombat = (s: GameState) => (s.combat && !s.combat.ended ? s.combat : null);
@ -130,6 +131,7 @@ export const EXECUTIONS: Record<string, Script> = {
toDiscard(s, hw);
stat(s, 'hardwareLost', owner.player);
say(s, `Sabotage destroys ${nameOf(s, hw)}.`);
shedHardware(s, owner);
} else {
s.cards[hw].disabledUntil = FOREVER;
say(s, `Sabotage disables ${nameOf(s, hw)}.`);
@ -311,10 +313,12 @@ export const EXECUTIONS: Record<string, Script> = {
targetsAvatars: (s, item) => wearerList(s, item.args.card),
resolve(s, item) {
const card = item.args.card!;
const wearer = wearerOf(s, 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.`);
if (wearer) shedHardware(s, wearer);
},
},
},

View file

@ -3,7 +3,7 @@
* wearer stands on.
*/
import { knockOut } from '../flow.ts';
import { desynced, hardwareActive } from '../query.ts';
import { desynced, hardwareActive, portsFit, takesPort } from '../query.ts';
import { scriptOf, type Script } from '../scripts.ts';
import {
ask,
@ -24,6 +24,7 @@ import {
startOf,
endOf,
stat,
toDiscard,
toHand,
uninstallHardware,
usedThisTurn,
@ -53,6 +54,20 @@ function coolerFor(s: GameState, hw: number): number | null {
return null;
}
/**
* Reading: an Avatar that loses a port (Network Interface Upgrade removed) discards Hardware until it
* fits, the most recently installed first.
*/
export function shedHardware(s: GameState, r: AvatarRef): void {
while (!portsFit(s, r)) {
const hw = avatar(s, r).hardware.findLast((id) => takesPort(s, id))!;
uninstallHardware(s, hw);
toDiscard(s, hw);
stat(s, 'hardwareLost', r.player);
say(s, `${avatarName(s, r)} is out of ports and discards ${nameOf(s, hw)}.`);
}
}
export function useHardware(s: GameState, hw: number): void {
const cooler = coolerFor(s, hw);
markUsed(s, `hw:${hw}`);
@ -271,7 +286,9 @@ export const HARDWARE: Record<string, Script> = {
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] })));
return av.hardware.flatMap((out) => cardOptions(s, hand)
.filter((o) => portsFit(s, src.ref!, out, o.value as number))
.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) {
@ -279,6 +296,7 @@ export const HARDWARE: Record<string, Script> = {
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;
if (!portsFit(s, ref, out, into)) return;
uninstallHardware(s, out);
toHand(s, out);
attachHardware(s, into, ref);

View file

@ -6,7 +6,7 @@ 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 { DEFAULT_RULES, withRule } 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';
@ -30,6 +30,11 @@ const USAGE = `Files TCG simulator
--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})
--rule K=V change a rule in src/rules.ts; repeatable. Examples: winLocations=9,
levelRam=4,4,6,8,10, startingAvatars=4, firstTurn.advance=false,
firstTurn.captureRam=false, firstTurn.unlock=false, firstTurn.cards=false,
secondPlayer.ram=4, secondPlayer.avatars=1, secondPlayer.cards=2,
secondPlayer.locations=1
--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
@ -47,6 +52,7 @@ const { values: opt } = parseArgs({
south: { type: 'string', default: 'greedy' },
north: { type: 'string', default: 'greedy' },
'max-turns': { type: 'string' },
rule: { type: 'string', multiple: true, default: [] },
log: { type: 'boolean', default: false },
check: { type: 'boolean', default: false },
json: { type: 'string' },
@ -81,7 +87,14 @@ 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 };
let rules = maxTurns === undefined ? DEFAULT_RULES : { ...DEFAULT_RULES, maxTurns };
try {
for (const spec of opt.rule) rules = withRule(rules, spec);
} catch (e) {
console.error((e as Error).message);
process.exit(1);
}
if (opt.rule.length) console.log(`Rules changed: ${opt.rule.join(', ')}`);
const bots: [BotFactory, BotFactory] = [BOTS[opt.south].make, BOTS[opt.north].make];
for (const warning of staleScripts(pool)) console.warn(`warning: ${warning}`);

View file

@ -185,7 +185,7 @@ export function createGame({ pool, decks, seed, rules = DEFAULT_RULES, log = fal
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, i < rules.startingAvatars, null)),
...avatars.map((card, i) => newAvatar(card, false, i + 1)),
],
unlockedLevel: 1,
@ -202,9 +202,22 @@ export function createGame({ pool, decks, seed, rules = DEFAULT_RULES, log = fal
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;
const p2 = other(s.firstPlayer);
const second = s.players[p2];
second.ram += rules.secondPlayer.ram;
second.avatars.slice(0, rules.startingAvatars + rules.secondPlayer.avatars).forEach((av) => (av.faceUp = true));
for (let i = 0; i < rules.secondPlayer.cards; i++) drawNow(s, p2);
if (rules.secondPlayer.locations > 0) {
// The location next to the starting Server, with a Server from the pile: no RAM, no unlock.
const line = LINES_AT.get(START_LOC[p2])![0];
const L = s.locations[otherEnd(line, START_LOC[p2])];
L.owner = p2;
L.server = second.serverPile.shift()!;
played(s, s.cards[L.server].name, p2);
}
s.stats.cardsDrawn = [0, 0];
say(s, `${playerName(s.firstPlayer)} goes first.`);
beginTurn(s, true);
run(s);
@ -326,6 +339,11 @@ function pushClears(s: GameState, p: PlayerId, out: Action[]): void {
}
/** Latency Spike: the attacking player can't play Executions before the roll. */
/** Whether a first-turn rule variant stops p playing cards from hand right now. */
function cardsBlocked(s: GameState, p: PlayerId): boolean {
return s.turn === 1 && p === s.firstPlayer && !s.rules.firstTurn.cards;
}
function latencyBlocked(s: GameState, p: PlayerId): boolean {
const c = s.combat;
const w = openWindow(s);
@ -375,7 +393,7 @@ export function executionCost(s: GameState, p: PlayerId, card: number, target: L
*/
export function executionActions(s: GameState, p: PlayerId, budget: 'now' | 'reachable' | 'any', limit = Infinity): Action[] {
const out: Action[] = [];
if (latencyBlocked(s, p)) return out;
if (latencyBlocked(s, p) || cardsBlocked(s, p)) return out;
const seen = new Set<string>();
let who: (LocId | null)[] | null = null;
let all: Source[] | null = null;
@ -484,7 +502,7 @@ export function legalActions(s: GameState): Action[] {
if (s.step === 'deploy') {
const placementOpen = s.declarations.length === 0;
const targets = advanceTargets(s, p);
const targets = s.turn === 1 && !s.rules.firstTurn.advance ? [] : advanceTargets(s, p);
me.avatars.forEach((av, i) => {
const ref = { player: p, slot: i + 1 };
if (!av.faceUp || av.advanced || av.attacks > 0) return;
@ -503,7 +521,7 @@ export function legalActions(s: GameState): Action[] {
} else {
const seen = new Set<string>();
const all = sources(s);
for (const card of me.hand) {
for (const card of cardsBlocked(s, p) ? [] : me.hand) {
const def = defOf(s, card);
if (seen.has(def.name)) continue;
seen.add(def.name);

View file

@ -374,13 +374,15 @@ export function captureMain(s: GameState, ref: AvatarRef, loc: LocId, how: Captu
avatar(s, ref).at = loc;
const level = levelFor(p, loc);
const turn1 = s.turn === 1 ? s.rules.firstTurn : null;
const bonus = L.server === null ? 0 : (scriptOf(s.cards[L.server].name)?.ramOnPlace ?? 0);
gainRam(s, p, s.rules.levelRam[level] + bonus, 'ramFromCaptures');
const ram = (turn1?.captureRam === false ? 0 : s.rules.levelRam[level]) + bonus;
gainRam(s, p, ram, '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}).`);
say(s, `${playerName(p)} captures ${loc}${from} (Lv ${level}) with ${L.server === null ? 'no Server' : nameOf(s, L.server)}: +${ram} RAM (now ${me.ram}).`);
if (level > me.unlockedLevel) {
if (level > me.unlockedLevel && turn1?.unlock !== false) {
me.unlockedLevel = level;
me.avatars.slice(0, 4).forEach((av, i) => {
if (i < level && !av.faceUp) {

View file

@ -21,10 +21,8 @@ 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],
@ -47,10 +45,10 @@ export const otherEnd = (line: Line, loc: LocId): LocId => (line.a === loc ? lin
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. */
/** Level by row letter, from each player's side of the mat: your first row is Lv 1, the far row Lv 5. */
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: 1, B: 2, C: 3, D: 4, E: 5 },
{ A: 5, B: 4, C: 3, D: 2, E: 1 },
];
/** A location's level for the player capturing it. Your own start is Lv 1. */

View file

@ -95,6 +95,8 @@ export function capacity(s: GameState, loc: LocId): number {
/** 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;
// Nothing enters a location mid-combat (a copy, or an Avatar moved by Disconnect).
if (s.combat && !s.combat.ended && s.combat.loc === loc) return false;
return refsInPlay(s, p).filter((r) => avatar(s, r).at === loc).length < capacity(s, loc);
}
@ -122,6 +124,18 @@ export const portsTotal = (s: GameState, r: AvatarRef): number =>
export const portsFree = (s: GameState, r: AvatarRef): number => portsTotal(s, r) - portsUsed(s, r);
/** Whether a Hardware takes a port: Network Interface Upgrade and Hardware pushed on over the limit don't. */
export const takesPort = (s: GameState, id: number): boolean =>
!scriptOf(s.cards[id].name)?.noPort && s.cards[id].pushedUntil === undefined;
/** Whether an Avatar's Hardware fits its ports, with `out` taken off and `into` put on. */
export function portsFit(s: GameState, r: AvatarRef, out: number | null = null, into: number | null = null): boolean {
const hw = avatar(s, r).hardware.filter((id) => id !== out);
if (into !== null) hw.push(into);
const total = defOf(s, avatar(s, r).card).slots + hw.reduce((t, id) => t + (scriptOf(s.cards[id].name)?.extraSlots ?? 0), 0);
return hw.filter((id) => takesPort(s, id)).length <= total;
}
// ---------------------------------------------------------------------------------------------
// Cores

View file

@ -15,6 +15,23 @@ export interface RulesConfig {
firewallCost: readonly number[];
maxProgramsPerLocation: number;
deck: { avatars: number; servers: number; main: number; maxCopies: number };
/** Avatars face up at the start (rules: Avatar 1 only). */
startingAvatars: number;
/** What the first player may do on turn 1 (the rules allow everything). */
firstTurn: {
advance: boolean;
/** Captures pay capture RAM. A Server card's own RAM bonus is still paid. */
captureRam: boolean;
/** Captures unlock Avatars. They unlock on a later capture instead. */
unlock: boolean;
/** Playing cards from hand: Hardware, Programs, Executions. */
cards: boolean;
};
/**
* Catch-up for whoever goes second: extra starting RAM, extra Avatars face up, extra cards in the
* opening hand, and (0 or 1) owning the location next to their starting Server at the start.
*/
secondPlayer: { ram: number; avatars: number; cards: number; locations: number };
}
export const DEFAULT_RULES: RulesConfig = {
@ -22,8 +39,44 @@ export const DEFAULT_RULES: RulesConfig = {
openingHand: 7,
winLocations: 10,
maxTurns: 200,
levelRam: { 1: 4, 2: 4, 3: 6, 4: 8, 5: 10 },
levelRam: { 1: 4, 2: 4, 3: 4, 4: 4, 5: 4 },
firewallCost: [2, 4, 8],
maxProgramsPerLocation: 2,
deck: { avatars: 4, servers: 20, main: 30, maxCopies: 2 },
startingAvatars: 1,
firstTurn: { advance: true, captureRam: true, unlock: true, cards: true },
secondPlayer: { ram: 0, avatars: 0, cards: 0, locations: 0 },
};
/**
* A copy of `rules` with one setting changed, from text like "winLocations=9",
* "secondPlayer.ram=4", "firstTurn.advance=false" or "levelRam=4,4,4,4,4" (Lv 1 to 5).
*/
export function withRule(rules: RulesConfig, spec: string): RulesConfig {
const m = spec.match(/^([\w.]+)=(.+)$/);
if (!m) throw new Error(`Rule "${spec}" should look like name=value`);
const [, key, raw] = m;
const next = structuredClone(rules) as unknown as Record<string, unknown>;
const path = key.split('.');
let obj = next;
for (const part of path.slice(0, -1)) {
if (typeof obj[part] !== 'object' || obj[part] === null) throw new Error(`Unknown rule "${key}"`);
obj = obj[part] as Record<string, unknown>;
}
const last = path[path.length - 1];
const old = obj[last];
const num = (x: string) => {
const n = Number(x);
if (!Number.isFinite(n)) throw new Error(`Rule "${key}" needs numbers, got "${x}"`);
return n;
};
if (typeof old === 'number') obj[last] = num(raw);
else if (typeof old === 'boolean') {
if (raw !== 'true' && raw !== 'false') throw new Error(`Rule "${key}" needs true or false`);
obj[last] = raw === 'true';
} else if (key === 'levelRam') {
obj[last] = Object.fromEntries(raw.split(',').map((x, i) => [i + 1, num(x)]));
} else if (Array.isArray(old)) obj[last] = raw.split(',').map(num);
else throw new Error(`Unknown rule "${key}"`);
return next as unknown as RulesConfig;
}