Rules v0.8: rounds of alternating commands; sim updates

Rules (rules.md, new file):
- Rounds of 2 commands per player in snake order (A B B A, then B A A B).
  A command is one advance or one attack; each Avatar acts once per round.
- Flat 4 RAM captures, first row Lv 1, A2-C2 and C2-E2 lines cut,
  45-card decks, Code Zero at 3 Cores with Patient Zero at 1+ counters.

Simulator:
- Command rule (default on): commands.perPlayer, commands.leads,
  commands.snake; commands.on=false restores whole turns.
- Greedy bot values Avatar unlocks (unlockPoints) and picks one action
  per command.
- Prototype switches, off by default: Avatars in the deck (recruit.*),
  buying Avatars (buyAvatars.*), copy limits (copies.*), turn-1 draw and
  second-player draw options.
- cards.csv card-text revisions, with scripts and tests to match.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Forrest 2026-09-28 14:07:45 -04:00
parent 6382de19c9
commit a3eb6850ee
21 changed files with 1089 additions and 96 deletions

View file

@ -20,6 +20,14 @@ export function locationValue(v: GameState, p: PlayerId, loc: LocId): number {
return LOCATION_POINTS + taken + v.rules.levelRam[levelFor(p, loc)] * RAM_POINTS;
}
/** How many Avatars capturing `loc` would unlock for `p` (level unlocks only). */
export function unlocksAt(v: GameState, p: PlayerId, loc: LocId): number {
if (v.rules.recruit.on || v.rules.buyAvatars.on || isStart(loc)) return 0;
const level = levelFor(p, loc);
if (level <= v.players[p].unlockedLevel) return 0;
return v.players[p].avatars.slice(0, Math.min(level, 4)).filter((a) => !a.faceUp).length;
}
/** 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;

View file

@ -8,10 +8,12 @@ import {
firewallCost,
hardwareCost,
openWindow,
avatarForSale,
programCost,
recruitSlots,
} 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 { avatarRoom, coresOf, hardwareActive, hasRoom, portsFree, programSlots, sources } from '../query.ts';
import { scriptOf } from '../scripts.ts';
import {
avatar,
@ -19,6 +21,7 @@ import {
controls,
defendersAt,
defOf,
freshCopy,
hardwareOf,
isCopy,
isOpen,
@ -41,6 +44,7 @@ import {
locationValue,
printedRam,
stakes,
unlocksAt,
} from './eval.ts';
export interface GreedyParams {
@ -53,6 +57,8 @@ export interface GreedyParams {
ramReserve: number;
/** Play Programs, Executions and Abilities. Off plays like the Phase 2 bot: Core Hardware only. */
useCards: boolean;
/** Extra value of a capture per Avatar it unlocks (a location is worth about 12). 0 ignores unlocks. */
unlockPoints: number;
}
export const DEFAULT_GREEDY: GreedyParams = {
@ -61,6 +67,7 @@ export const DEFAULT_GREEDY: GreedyParams = {
maxFirewallsPerTurn: 2,
ramReserve: 6,
useCards: true,
unlockPoints: 15,
};
/**
@ -108,6 +115,7 @@ const COMBAT_TRICKS = new Set([
/** 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 === 'avatar') return recruitSlot(v, v.cards[id].owner, id) === null ? 1 : 7;
if (def.kind === 'hardware') {
if (hardwareCores(v, id) > 0) return 6;
return (UTILITY_HARDWARE[def.name] ?? 0) * 2;
@ -139,7 +147,47 @@ function salvageFor(v: GameState, me: PlayerId, cost: number, except: number | n
/** 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;
a.type === 'play' || a.type === 'installHardware' || a.type === 'installProgram' || a.type === 'recruit' ? a.card : null;
// ---------------------------------------------------------------------------------------------
// Recruiting (recruit rule)
/**
* Where the bot would recruit Avatar `id`: an empty slot while there's room, otherwise over a
* weaker Avatar (fewer Cores) that carries no Hardware, preferring one sitting in its slot.
* `taken` are slots already planned this step.
*/
function recruitSlot(v: GameState, me: PlayerId, id: number, taken: number[] = []): number | null {
if (!v.rules.recruit.on) return null;
const avs = v.players[me].avatars;
const cores = (card: number) => defOf(v, card).cores;
const empty = avs.findIndex((a, i) => i < 4 && a.card < 0 && !taken.includes(i + 1));
const planned = taken.filter((slot) => avs[slot - 1].card < 0).length;
const inUse = avs.filter((a, i) => (i < 4 ? a.card >= 0 : a.at !== null)).length;
if (empty >= 0 && avatarRoom(v, me) && inUse + planned < 4) return empty + 1;
const weaker = recruitSlots(v, me)
.filter((slot) => !taken.includes(slot) && avs[slot - 1].card >= 0 && avs[slot - 1].hardware.length === 0)
.filter((slot) => cores(avs[slot - 1].card) < cores(id))
.sort((a, b) => Number(avs[a - 1].at !== null) - Number(avs[b - 1].at !== null) || cores(avs[a - 1].card) - cores(avs[b - 1].card));
return weaker[0] ?? null;
}
/** Recruit the strongest Avatars in hand that fit, within `budget`. */
function recruitPlan(v: GameState, me: PlayerId, budget: number): Action[] {
if (!v.rules.recruit.on) return [];
const hand = v.players[me].hand
.filter((id) => id >= 0 && defOf(v, id).kind === 'avatar')
.sort((a, b) => defOf(v, b).cores - defOf(v, a).cores);
const out: Extract<Action, { type: 'recruit' }>[] = [];
for (const card of hand) {
const price = printedRam(v, card);
const slot = price <= budget ? recruitSlot(v, me, card, out.map((a) => a.slot)) : null;
if (slot === null) continue;
out.push({ type: 'recruit', card, slot });
budget -= price;
}
return out;
}
const reach = (v: GameState, me: PlayerId) =>
v.players[me].ram + v.players[me].hand.reduce((t, id) => t + printedRam(v, id), 0);
@ -210,7 +258,7 @@ function planTurn(v: GameState, me: PlayerId, params: GreedyParams): TurnPlan {
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);
const value = locationValue(v, me, to) + params.unlockPoints * unlocksAt(v, me, to);
for (const line of LINES_AT.get(to)!) {
const from = otherEnd(line, to);
if (!controls(v, me, from)) continue;
@ -220,6 +268,7 @@ function planTurn(v: GameState, me: PlayerId, params: GreedyParams): TurnPlan {
const clear = level ? line.id : undefined;
for (const { slot } of ready) {
const ref = { player: me, slot };
if (freshCopy(v, ref)) continue;
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 });
@ -244,6 +293,7 @@ function planTurn(v: GameState, me: PlayerId, params: GreedyParams): TurnPlan {
const clears = new Set<string>();
for (const o of options) {
if (o.score <= 0) break;
if (v.rules.commands.on && chosen.length > 0) break; // one advance or attack per command
if (usedTargets.has(o.to)) continue;
const n = uses.get(o.slot) ?? 0;
if (n > 0) {
@ -606,19 +656,21 @@ const totalCost = (v: GameState, list: Action[]) => list.reduce((t, a) => t + ac
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>();
const sale = avatarForSale(v, me);
const recruits = [...recruitPlan(v, me, budget), ...(sale && sale.price <= budget ? [{ type: 'buyAvatar', slot: sale.slot } as const] : [])];
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)];
return [...recruits, ...early, ...hardwarePlan(v, me, attackers, budget - totalCost(v, [...recruits, ...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 hw = hardwarePlan(v, me, attackers, budget - keep - totalCost(v, recruits), params.useCards);
let left = budget - keep - totalCost(v, [...recruits, ...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];
return [...recruits, ...hw, ...progs, ...walls, ...extra];
}
// ---------------------------------------------------------------------------------------------

View file

@ -5,7 +5,7 @@
*/
import { createCopy, drawCards } from '../flow.ts';
import { LOCATIONS } from '../map.ts';
import { costOf, hardwareActive, hasRoom, portsFree } from '../query.ts';
import { canCopy, costOf, hardwareActive, hasRoom, portsFree } from '../query.ts';
import type { Script } from '../scripts.ts';
import {
addMod,
@ -46,12 +46,12 @@ export const AVATARS: Record<string, Script> = {
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 [];
if (avatar(s, copyOf(src.ref!)).at !== null || !canCopy(s, src.controller)) 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;
if (avatar(s, copyOf(src.ref!)).at !== null || !canCopy(s, src.controller) || !hasRoom(s, src.controller, to)) return;
fired(s, 'Carbon NanoBots', src.controller);
createCopy(s, src.ref!, to);
},
@ -111,8 +111,8 @@ export const AVATARS: Record<string, Script> = {
},
'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),
text: 'Place an Infection counter on every enemy Avatar in combat at this Server. While this Avatar is in play, an Avatar with 1+ Infection counters has -1 Core.',
globalCores: (s, f) => (infectionOf(avatar(s, f.ref)) >= 1 ? -1 : 0),
ability: {
uses: (s, src) => (opponentsInCombat(s, src.ref!).length ? [{}] : []),
resolve(s, _item, src) {

View file

@ -4,7 +4,7 @@
*/
import { createCopy, drawNow } from '../flow.ts';
import { LINE_BY_ID } from '../map.ts';
import { hasRoom, sameSource, sourcesNamed } from '../query.ts';
import { canCopy, hasRoom, sameSource, sourcesNamed } from '../query.ts';
import type { Fighter, Script } from '../scripts.ts';
import {
ask,
@ -48,6 +48,7 @@ export const SERVERS: Record<string, Script> = {
ability: {
uses(s, src) {
const p = src.controller;
if (!canCopy(s, p)) return [];
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)
@ -56,7 +57,7 @@ export const SERVERS: Record<string, Script> = {
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;
if (avatar(s, r).at === null || avatar(s, copyOf(r)).at !== null || !canCopy(s, r.player) || !hasRoom(s, r.player, to)) return;
fired(s, 'Backup Server', r.player);
createCopy(s, r, to);
},

View file

@ -29,12 +29,17 @@ const USAGE = `Files TCG simulator
--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})
--max-turns N rounds × 2 before a draw (default ${DEFAULT_RULES.maxTurns}, i.e. ${DEFAULT_RULES.maxTurns / 2} rounds)
--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,
levelRam=4,4,6,8,10, startingAvatars=4, firstTurn.draw=true, firstTurn.advance=false,
firstTurn.captureRam=false, firstTurn.unlock=false, firstTurn.cards=false,
secondPlayer.ram=4, secondPlayer.avatars=1, secondPlayer.cards=2,
secondPlayer.locations=1
secondPlayer.ram=4, secondPlayer.avatars=1, secondPlayer.cards=2, secondPlayer.firstDraw=1,
secondPlayer.locations=1, drawPerTurn=2, deck.main=60,
recruit.on=true (Avatars in the deck; also recruit.avatarsInDeck=5, recruit.price=8),
buyAvatars.on=true (buy Avatars 2-4 instead of unlocking; buyAvatars.prices=8,12,16),
copies.waitATurn=true, copies.needAvatar2=true, copies.allowed=false,
commands.on=false (whole turns instead of rounds of commands),
commands.perPlayer=3, commands.leads=F|FS|FFSS|thue, commands.snake=false
--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

View file

@ -1,11 +1,11 @@
import type { CardDef, CardKind, CardPool } from './cards.ts';
import { shuffle, type Rng } from './rng.ts';
import type { RulesConfig } from './rules.ts';
import { avatarsOutside, type RulesConfig } from './rules.ts';
export interface DeckList {
avatars: string[];
servers: string[];
/** Executions, Hardware and Programs. */
/** Executions, Hardware and Programs (and Avatars, when recruiting). */
main: string[];
}
@ -22,9 +22,9 @@ export function validateDeck(pool: CardPool, deck: DeckList, rules: RulesConfig)
else if (!kinds.includes(card.kind)) errors.push(`${label}: "${name}" is a ${card.kind}`);
}
};
part('Avatars', deck.avatars, ['avatar'], rules.deck.avatars);
part('Avatars', deck.avatars, ['avatar'], avatarsOutside(rules));
part('Servers', deck.servers, ['server'], rules.deck.servers);
part('Deck', deck.main, MAIN_KINDS, rules.deck.main);
part('Deck', deck.main, rules.recruit.on ? [...MAIN_KINDS, 'avatar'] : 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);
@ -49,6 +49,12 @@ export function randomDeck(
if (names.length < size) throw new Error(`Not enough ${kinds.join('/')} cards for a deck`);
return shuffle(rng, names).slice(0, size);
};
if (rules.recruit.on) {
const k = rules.recruit.avatarsInDeck;
const avatars = sample(['avatar'], 1 + k);
const servers = sample(['server'], rules.deck.servers);
return { avatars: avatars.slice(0, 1), servers, main: shuffle(rng, [...avatars.slice(1), ...sample(MAIN_KINDS, rules.deck.main - k)]) };
}
return {
avatars: sample(['avatar'], rules.deck.avatars),
servers: sample(['server'], rules.deck.servers),

View file

@ -6,6 +6,7 @@
*/
import type { CardPool } from './cards.ts';
import { validateDeck, type DeckList } from './deck.ts';
import type { CardDef } from './cards.ts';
import {
captureHooks,
captureMain,
@ -14,9 +15,11 @@ import {
drawNow,
drawTask,
resolveDeclaration,
retireAvatar,
} from './flow.ts';
import { GRID, LINES, LINES_AT, LINE_BY_ID, LOCATIONS, START_LOC, isStart, otherEnd, type LocId } from './map.ts';
import {
avatarRoom,
costOf,
coresOf,
desynced,
@ -44,10 +47,14 @@ import {
endOf,
firewallCost,
gridCount,
commanderOf,
firstCommand,
freshCopy,
isCopy,
isOpen,
markUsed,
nameOf,
originalOf,
other,
fired,
played,
@ -55,6 +62,7 @@ import {
pushTasks,
refsInPlay,
removeFrom,
roundOf,
running,
say,
startOf,
@ -114,6 +122,32 @@ function newStats(): GameStats {
return Object.fromEntries(STAT_KEYS.map((k) => [k, [0, 0]])) as GameStats;
}
/** Recruit rule: an Avatar's printed RAM is its price, which is also what it salvages for. */
function withPrice(def: CardDef, rules: RulesConfig): CardDef {
if (!rules.recruit.on || def.kind !== 'avatar') return def;
return { ...def, ram: rules.recruit.price + rules.recruit.pricePerCore * def.cores };
}
/** Recruit rule: slots `p` can recruit into. The first empty one while there's room, or any Avatar to retire. */
export function recruitSlots(s: GameState, p: PlayerId): number[] {
const avs = s.players[p].avatars.slice(0, 4);
const out: number[] = [];
const empty = avs.findIndex((a) => a.card < 0);
if (empty >= 0 && avatarRoom(s, p)) out.push(empty + 1);
avs.forEach((a, i) => {
const declared = s.declarations.some((d) => d.ref.player === p && originalOf(d.ref).slot === i + 1);
if (a.card >= 0 && !declared) out.push(i + 1);
});
return out;
}
/** Buy-Avatars rule: the next Avatar `p` can buy (its slot) and its price, or null. */
export function avatarForSale(s: GameState, p: PlayerId): { slot: number; price: number } | null {
if (!s.rules.buyAvatars.on) return null;
const i = s.players[p].avatars.slice(0, 4).findIndex((a) => !a.faceUp);
return i < 1 ? null : { slot: i + 1, price: s.rules.buyAvatars.prices[i - 1] };
}
function newAvatar(card: number, faceUp: boolean, copyOf: number | null): AvatarState {
return {
card,
@ -131,6 +165,8 @@ function newAvatar(card: number, faceUp: boolean, copyOf: number | null): Avatar
rootedUntil: 0,
breachedTurn: 0,
copyOf,
createdTurn: 0,
unlockedTurn: 0,
};
}
@ -171,13 +207,15 @@ export function createGame({ pool, decks, seed, rules = DEFAULT_RULES, log = fal
log: log ? [] : null,
};
const add = (name: string, owner: PlayerId): number => {
s.defs[name] = pool.byName.get(name)!;
s.defs[name] = withPrice(pool.byName.get(name)!, rules);
s.cards.push({ id: s.cards.length, name, owner, disabledUntil: 0, ignoredUntil: 0, installedTurn: 0 });
return s.cards.length - 1;
};
for (const p of [0, 1] as const) {
const deck = decks[p];
// Recruit rule: slots after the starting Avatar begin empty (-1).
const avatars = shuffle(rng, deck.avatars.map((n) => add(n, p)));
const slots = [0, 1, 2, 3].map((i) => avatars[i] ?? -1);
s.players.push({
ram: 0,
hand: [],
@ -185,8 +223,8 @@ 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 < rules.startingAvatars, null)),
...avatars.map((card, i) => newAvatar(card, false, i + 1)),
...slots.map((card, i) => newAvatar(card, card >= 0 && i < rules.startingAvatars, null)),
...slots.map((card, i) => newAvatar(card, false, i + 1)),
],
unlockedLevel: 1,
});
@ -207,7 +245,7 @@ export function createGame({ pool, decks, seed, rules = DEFAULT_RULES, log = fal
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));
second.avatars.slice(0, rules.startingAvatars + rules.secondPlayer.avatars).forEach((av) => (av.faceUp = av.card >= 0));
for (let i = 0; i < rules.secondPlayer.cards; i++) drawNow(s, p2);
if (rules.secondPlayer.locations > 0) {
// The location next to the starting Server, with a Server from the pile: no RAM, no unlock.
@ -219,13 +257,14 @@ export function createGame({ pool, decks, seed, rules = DEFAULT_RULES, log = fal
}
s.stats.cardsDrawn = [0, 0];
say(s, `${playerName(s.firstPlayer)} goes first.`);
beginTurn(s, true);
beginTurn(s, !rules.firstTurn.draw);
run(s);
return s;
}
function beginTurn(s: GameState, skipDraw: boolean): void {
if (s.turn >= s.rules.maxTurns) {
const cmd = s.rules.commands.on;
if (s.turn >= s.rules.maxTurns * (cmd ? s.rules.commands.perPlayer : 1)) {
s.over = true;
s.endReason = 'turnLimit';
say(s, `Turn limit reached: draw (South ${gridCount(s, 0)}, North ${gridCount(s, 1)} locations).`);
@ -233,21 +272,34 @@ function beginTurn(s: GameState, skipDraw: boolean): void {
}
s.turn++;
s.clock = startOf(s.turn);
s.used = {};
// Command rule: a player's turn is their commands in a round, so its refreshes come at the first.
const fresh = !cmd || firstCommand(s, s.turn);
if (!cmd || roundOf(s, s.turn) !== roundOf(s, s.turn - 1)) s.used = {};
tidy(s);
const me = s.players[s.active];
for (const av of me.avatars) {
av.placed = false;
av.advanced = false;
av.attacks = 0;
if (fresh) {
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);
const title = cmd ? `Round ${roundOf(s, s.turn)}, command ${s.turn}` : `Turn ${s.turn}`;
say(s, `\n— ${title}: ${playerName(s.active)} (${me.ram} RAM, ${me.hand.length} cards, ${gridCount(s, s.active)} locations) —`);
const draws = s.rules.drawPerTurn + (s.turn === 2 ? s.rules.secondPlayer.firstDraw : 0);
if (fresh && !skipDraw) pushTasks(s, ...Array.from({ length: draws }, (): Task => ({ t: 'draw', player: s.active })));
if (fresh) emit(s, 'onTurnStart', null);
}
/** Command rule: this game turn's command is spent (an advance or attack is declared). */
const commandSpent = (s: GameState): boolean => s.rules.commands.on && s.declarations.length > 0;
/** Command rule: an Avatar unlocked this round waits in its slot until the next round. */
const waitsForRound = (s: GameState, av: AvatarState): boolean =>
s.rules.commands.on && av.at === null && av.unlockedTurn > 0 && roundOf(s, av.unlockedTurn) === roundOf(s, s.turn);
function endTurn(s: GameState): void {
s.clock = endOf(s.turn);
// Push Update: the extra Hardware leaves at the end of its controller's turn.
@ -264,7 +316,7 @@ function endTurn(s: GameState): void {
}
}
tidy(s);
s.active = other(s.active);
s.active = s.rules.commands.on ? commanderOf(s, s.turn + 1) : other(s.active);
beginTurn(s, false);
}
@ -321,7 +373,7 @@ export function maxAttacks(s: GameState, ref: AvatarRef): number {
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 [];
if (!av.faceUp || av.at === null || av.advanced || av.attacks >= maxAttacks(s, ref) || !canAct(s, ref) || freshCopy(s, ref)) return [];
const opp = other(ref.player);
return LINES_AT.get(av.at)!
.filter((line) => isOpen(s, line))
@ -507,14 +559,15 @@ export function legalActions(s: GameState): Action[] {
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) {
if (placementOpen && !av.placed && !waitsForRound(s, av)) {
for (const to of LOCATIONS) if (to !== av.at && hasRoom(s, p, to)) out.push({ type: 'place', slot: i + 1, to });
}
if (av.at !== null) for (const to of targets) out.push({ type: 'advance', slot: i + 1, to });
if (av.at !== null && !freshCopy(s, ref) && !commandSpent(s)) for (const to of targets) out.push({ type: 'advance', slot: i + 1, to });
});
pushClears(s, p, out);
} else if (s.step === 'attack') {
me.avatars.forEach((_, i) => {
if (commandSpent(s)) return;
for (const to of attackTargets(s, { player: p, slot: i + 1 })) out.push({ type: 'attack', slot: i + 1, to });
});
pushClears(s, p, out);
@ -531,6 +584,8 @@ export function legalActions(s: GameState): Action[] {
out.push({ type: 'installHardware', card, slot: ref.slot });
}
}
} else if (def.kind === 'avatar' && s.rules.recruit.on) {
if (def.ram <= me.ram) for (const slot of recruitSlots(s, p)) out.push({ type: 'recruit', card, slot });
} else if (def.kind === 'program') {
for (const at of LOCATIONS) {
if (controls(s, p, at) && s.locations[at].programs.length < programSlots(s, at) && programCost(s, p, card, at, all) <= me.ram) {
@ -539,6 +594,8 @@ export function legalActions(s: GameState): Action[] {
}
}
}
const sale = avatarForSale(s, p);
if (sale && sale.price <= me.ram) out.push({ type: 'buyAvatar', slot: sale.slot });
for (const line of LINES) {
if (!line.gateway || !(controls(s, p, line.a) || controls(s, p, line.b))) continue;
for (let level = (s.firewalls[line.id] ?? 0) + 1; level <= s.rules.firewallCost.length; level++) {
@ -560,6 +617,10 @@ export function actionCost(s: GameState, a: Action): number {
return firewallCost(s, s.firewalls[a.line] ?? 0);
case 'installHardware':
return hardwareCost(s, a.card, { player: p, slot: a.slot });
case 'recruit':
return defOf(s, a.card).ram;
case 'buyAvatar':
return avatarForSale(s, p)?.price ?? 0;
case 'installProgram':
return programCost(s, p, a.card, a.at);
case 'play':
@ -598,6 +659,10 @@ export function actionKey(a: Action): string {
return `salvage:${a.card}`;
case 'installHardware':
return `hw:${a.card}:${a.slot}`;
case 'recruit':
return `recruit:${a.card}:${a.slot}`;
case 'buyAvatar':
return `buy:${a.slot}`;
case 'installProgram':
return `prog:${a.card}:${a.at}`;
case 'play':
@ -653,6 +718,30 @@ export function applyAction(s: GameState, a: Action, legal: Action[] = legalActi
fn(s, ch.resume.data, option.value);
break;
}
case 'buyAvatar': {
const { price } = avatarForSale(s, p)!;
const av = me.avatars[a.slot - 1];
me.ram -= price;
stat(s, 'ramOnAvatars', p, price);
stat(s, 'avatarsBought', p);
av.faceUp = true;
say(s, `${who} buys Avatar ${a.slot}: ${nameOf(s, av.card)} (-${price} RAM, now ${me.ram}).`);
break;
}
case 'recruit': {
const cost = defOf(s, a.card).ram;
const av = me.avatars[a.slot - 1];
if (av.card >= 0) retireAvatar(s, ref(a.slot));
removeFrom(me.hand, a.card);
me.ram -= cost;
stat(s, 'ramOnCards', p, cost);
stat(s, 'avatarsRecruited', p);
played(s, nameOf(s, a.card), p);
Object.assign(av, newAvatar(a.card, true, null));
me.avatars[a.slot + 3].card = a.card;
say(s, `${who} recruits ${nameOf(s, a.card)} as Avatar ${a.slot} (-${cost} RAM, now ${me.ram}).`);
break;
}
case 'salvage': {
const gain = defOf(s, a.card).ram;
removeFrom(me.hand, a.card);

View file

@ -82,6 +82,18 @@ export function removeCopy(s: GameState, ref: AvatarRef): void {
dropFromCombat(s, ref);
}
/** Recruit rule: an Avatar recruited over leaves for the discard pile with its Hardware, and its copy leaves play. */
export function retireAvatar(s: GameState, ref: AvatarRef): void {
const av = avatar(s, ref);
removeCopy(s, copyOf(ref));
if (av.hardware.length) stat(s, 'hardwareLost', ref.player, av.hardware.length);
for (const hw of av.hardware) toDiscard(s, hw);
say(s, `${playerName(ref.player)} retires ${avatarName(s, ref)}${av.at ? ` from ${av.at}` : ''}.`);
dropFromCombat(s, ref);
toDiscard(s, av.card);
stat(s, 'avatarsRetired', ref.player);
}
/**
* 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).
@ -125,6 +137,7 @@ export function createCopy(s: GameState, original: AvatarRef, to: LocId): void {
disabledUntil: 0,
rootedUntil: 0,
breachedTurn: 0,
createdTurn: s.turn,
} satisfies Partial<AvatarState>);
say(s, `${playerName(ref.player)} creates ${avatarName(s, ref)} on ${to}.`);
}
@ -382,11 +395,13 @@ export function captureMain(s: GameState, ref: AvatarRef, loc: LocId, how: Captu
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)}: +${ram} RAM (now ${me.ram}).`);
if (level > me.unlockedLevel && turn1?.unlock !== false) {
const unlocks = !s.rules.recruit.on && !s.rules.buyAvatars.on;
if (unlocks && level > me.unlockedLevel && turn1?.unlock !== false) {
me.unlockedLevel = level;
me.avatars.slice(0, 4).forEach((av, i) => {
if (i < level && !av.faceUp) {
av.faceUp = true;
av.unlockedTurn = s.turn;
say(s, `${playerName(p)} unlocks Avatar ${i + 1}: ${nameOf(s, av.card)}.`);
}
});

View file

@ -31,10 +31,11 @@ export function checkInvariants(s: GameState): string[] {
const slot = i + 1;
const copy = slot > 4;
if (!copy) {
own([av.card], `avatar${slot}`);
if (av.card >= 0 || !s.rules.recruit.on) own([av.card], `avatar${slot}`);
else if (av.at !== null || av.hardware.length) errors.push(`p${p} empty slot ${slot} is in use`);
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`);
if (av.card >= 0 && 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`);
@ -46,6 +47,8 @@ export function checkInvariants(s: GameState): string[] {
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}`);
const total = pl.avatars.filter((av, i) => (i < 4 ? av.card >= 0 : av.at !== null)).length;
if (s.rules.recruit.on && total > 4) errors.push(`p${p} has ${total} Avatars, counting copies`);
});
for (const loc of LOCATIONS) {

View file

@ -24,6 +24,19 @@ 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);
/** Recruit rule: `p` has fewer than 4 Avatars, counting copies. Always true without the rule. */
export function avatarRoom(s: GameState, p: PlayerId): boolean {
if (!s.rules.recruit.on) return true;
const avs = s.players[p].avatars;
return avs.slice(0, 4).filter((a) => a.card >= 0).length + avs.slice(4).filter((a) => a.at !== null).length < 4;
}
/** Whether `p` may make a copy now: the copy-rule switches, and room under the recruit rule. */
export function canCopy(s: GameState, p: PlayerId): boolean {
const c = s.rules.copies;
return c.allowed && (!c.needAvatar2 || s.players[p].avatars[1].faceUp) && avatarRoom(s, p);
}
/** Everything with an effect in play right now. */
export function sources(s: GameState): Source[] {
const out: Source[] = [];

View file

@ -5,6 +5,8 @@
export interface RulesConfig {
startingRam: number;
openingHand: number;
/** Cards drawn in each turn's draw step. */
drawPerTurn: number;
/** Grid locations needed to win (starting Servers don't count). */
winLocations: number;
/** Player turns before the game is called a draw. */
@ -17,8 +19,9 @@ export interface RulesConfig {
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). */
/** What the first player may do on turn 1 (the rules skip the draw and allow the rest). */
firstTurn: {
draw: boolean;
advance: boolean;
/** Captures pay capture RAM. A Server card's own RAM bonus is still paid. */
captureRam: boolean;
@ -29,25 +32,65 @@ export interface RulesConfig {
};
/**
* 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.
* opening hand, extra cards in their first draw step, and (0 or 1) owning the location next to
* their starting Server at the start.
*/
secondPlayer: { ram: number; avatars: number; cards: number; locations: number };
secondPlayer: { ram: number; avatars: number; cards: number; firstDraw: number; locations: number };
/**
* Prototype: Avatars in the deck instead of level unlocks. You start with one Avatar; another
* `avatarsInDeck` are shuffled into the main deck (inside its size). On your turn (steps 3 and 6)
* pay an Avatar's price to recruit it from hand into an empty slot, or retire one of yours
* (discarding it and its Hardware) to recruit into its slot. At most 4 Avatars, copies included.
* Price = `price` + `pricePerCore` × Cores; it's also the card's salvage value.
*/
recruit: { on: boolean; avatarsInDeck: number; price: number; pricePerCore: number };
/**
* Prototype: buy Avatars instead of level unlocks. On your turn (steps 3 and 6) pay RAM to flip
* your next face-down Avatar; `prices` are for Avatars 2, 3 and 4.
*/
buyAvatars: { on: boolean; prices: number[] };
/**
* Copies (Carbon NanoBots' Replicate, Backup Server), for testing: whether they can be made at
* all; whether a new copy must wait for its owner's next turn to advance or attack (it can
* defend); whether making one needs Avatar 2 unlocked.
*/
copies: { allowed: boolean; waitATurn: boolean; needAvatar2: boolean };
/**
* Rounds of alternating commands (the rules since v0.8; off = the old one-turn-each structure).
* Each round both players get `perPlayer` commands, taken in turn. A command is one advance or one attack (or a pass),
* with placement and cards before it and cards after it. A player's "turn" is their commands in
* a round: the draw, turn-start effects and each Avatar's one action a round refresh at their
* first command; once-per-turn effects become once per round. Avatars unlocked during a round
* enter play from the next round.
* `leads` says who takes a round's first command, round after round (F = first player, S =
* second; the pattern repeats; "thue" is the Thue–Morse order F S S F S F F S…). `snake` orders
* a round's commands A B B A instead of A B A B.
*/
commands: { on: boolean; perPlayer: number; leads: string; snake: boolean };
}
export const DEFAULT_RULES: RulesConfig = {
startingRam: 4,
openingHand: 7,
drawPerTurn: 1,
winLocations: 10,
maxTurns: 200,
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 },
deck: { avatars: 4, servers: 20, main: 45, maxCopies: 2 },
startingAvatars: 1,
firstTurn: { advance: true, captureRam: true, unlock: true, cards: true },
secondPlayer: { ram: 0, avatars: 0, cards: 0, locations: 0 },
firstTurn: { draw: false, advance: true, captureRam: true, unlock: true, cards: true },
secondPlayer: { ram: 0, avatars: 0, cards: 0, firstDraw: 0, locations: 0 },
recruit: { on: false, avatarsInDeck: 3, price: 6, pricePerCore: 0 },
buyAvatars: { on: false, prices: [8, 12, 16] },
copies: { allowed: true, waitATurn: false, needAvatar2: false },
commands: { on: true, perPlayer: 2, leads: 'FS', snake: true },
};
/** Avatars kept outside the main deck: all of them, or just the starting one when recruiting. */
export const avatarsOutside = (rules: RulesConfig): number => (rules.recruit.on ? 1 : rules.deck.avatars);
/**
* 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).
@ -71,6 +114,7 @@ export function withRule(rules: RulesConfig, spec: string): RulesConfig {
return n;
};
if (typeof old === 'number') obj[last] = num(raw);
else if (typeof old === 'string') obj[last] = raw;
else if (typeof old === 'boolean') {
if (raw !== 'true' && raw !== 'false') throw new Error(`Rule "${key}" needs true or false`);
obj[last] = raw === 'true';

View file

@ -56,8 +56,39 @@ export const fired = (s: GameState, name: string, p: PlayerId): void => void use
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);
/** The turn number of `p`'s next turn (not the current one). Under the command rule, their next command. */
export function nextTurnOf(s: GameState, p: PlayerId): number {
if (!s.rules.commands.on) return s.active === p ? s.turn + 2 : s.turn + 1;
let t = s.turn + 1;
while (commanderOf(s, t) !== p) t++;
return t;
}
// Command rule: game turns are commands. A round is 2 × perPlayer of them, alternating players,
// and the lead alternates by round.
const commandsPerRound = (s: GameState): number => 2 * s.rules.commands.perPlayer;
/** Command rule: who takes game turn `turn`. */
export function commanderOf(s: GameState, turn: number): PlayerId {
const { leads, snake } = s.rules.commands;
const round = Math.floor((turn - 1) / commandsPerRound(s));
const i = (turn - 1) % commandsPerRound(s);
const ones = round.toString(2).split('1').length - 1;
const mark = leads === 'thue' ? 'FS'[ones % 2] : leads[round % leads.length];
if (mark !== 'F' && mark !== 'S') throw new Error(`commands.leads should use F and S, or be "thue": "${leads}"`);
const lead = mark === 'F' ? s.firstPlayer : other(s.firstPlayer);
const leadsThis = snake ? i % 4 === 0 || i % 4 === 3 : i % 2 === 0;
return leadsThis ? lead : other(lead);
}
/** Command rule: the round game turn `turn` belongs to, from 1. */
export const roundOf = (s: GameState, turn: number): number => Math.floor((turn - 1) / commandsPerRound(s)) + 1;
/** Command rule: whether `turn` is its commander's first command of the round. */
export const firstCommand = (s: GameState, turn: number): boolean => (turn - 1) % commandsPerRound(s) < 2;
/** Rounds played so far: both players taking a turn (or all their commands). */
export const roundsPlayed = (s: GameState): number => (s.rules.commands.on ? roundOf(s, s.turn) : Math.ceil(s.turn / 2));
export const running = (s: GameState, until: Clock): boolean => until > s.clock;
/** Once-per-turn bookkeeping. Returns how many times `key` was used this turn. */
@ -116,6 +147,10 @@ export function wearerOf(s: GameState, hw: number): AvatarRef | null {
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. */
/** Copy-rule variant: a copy made this player-turn can't advance or attack yet. It can still defend. */
export const freshCopy = (s: GameState, r: AvatarRef): boolean =>
isCopy(r) && s.rules.copies.waitATurn && avatar(s, r).createdTurn === s.turn;
export const canAct = (s: GameState, r: AvatarRef): boolean =>
inPlay(s, r) && !isRooted(s, r) && !isDisabledAvatar(s, r);

View file

@ -1,5 +1,6 @@
import type { CardPool } from './cards.ts';
import { gridCount } from './engine.ts';
import { roundsPlayed } from './state.ts';
import { STAT_KEYS, type CardUse, type GameState, type StatKey } from './types.ts';
export interface GameRecord {
@ -7,6 +8,7 @@ export interface GameRecord {
winner: 0 | 1 | null;
firstPlayer: 0 | 1;
turns: number;
rounds: number;
locations: [number, number];
stats: Record<StatKey, [number, number]>;
cardUse: Record<string, CardUse>;
@ -31,6 +33,7 @@ export function recordOf(seed: number, s: GameState): GameRecord {
winner: s.winner,
firstPlayer: s.firstPlayer,
turns: s.turn,
rounds: roundsPlayed(s),
locations: [gridCount(s, 0), gridCount(s, 1)],
stats: s.stats,
cardUse: s.cardUse,
@ -38,8 +41,7 @@ export function recordOf(seed: number, s: GameState): GameRecord {
};
}
/** Rounds: both players taking one turn each. */
const roundsOf = (r: GameRecord) => Math.ceil(r.turns / 2);
const roundsOf = (r: GameRecord) => r.rounds;
export function summarize(records: GameRecord[]): BatchSummary {
const n = records.length;
@ -79,7 +81,7 @@ export function formatSummary(sum: BatchSummary, labels: [string, string]): stri
' 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)',
'Game length, in rounds (every player takes all their commands, or 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]),

View file

@ -83,6 +83,10 @@ export interface AvatarState {
breachedTurn: number;
/** For copies: the original's slot. */
copyOf: number | null;
/** For copies: the player-turn it was made. */
createdTurn: number;
/** The game turn its level unlock happened (0 if it started face up). */
unlockedTurn: number;
}
export interface PlayerState {
@ -252,6 +256,10 @@ export type Action =
| { type: 'firewall'; line: string; level: number }
| { type: 'salvage'; card: number }
| { type: 'installHardware'; card: number; slot: number }
/** Recruit rule: an Avatar from hand into `slot`, retiring the Avatar there if there is one. */
| { type: 'recruit'; card: number; slot: number }
/** Buy-Avatars rule: flip Avatar `slot`, the next face-down one, for its price. */
| { type: 'buyAvatar'; 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 };
@ -280,6 +288,10 @@ export const STAT_KEYS = [
'programsLost',
'executionsPlayed',
'abilitiesUsed',
'avatarsRecruited',
'avatarsRetired',
'avatarsBought',
'ramOnAvatars',
] as const;
export type StatKey = (typeof STAT_KEYS)[number];