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

@ -26,7 +26,8 @@ of how much a card helps.
## What's simulated
- **Rules:** everything in `rules.md`: setup, the turn steps, placement and advancing, attacks,
- **Rules:** everything in `rules.md`: setup, rounds of alternating commands (or whole turns, with
`--rule commands.on=false`), placement and advancing, attacks,
combat with tie rerolls, captures, levels and RAM, Avatar unlocks, Firewalls, Salvage, response
windows and chains, and the win condition.
- **Every card:** all 83 cards in `../decks/files-deck-1/cards.csv` have a script, including Avatar
@ -60,9 +61,10 @@ fixed hooks: Core totals, costs, combat start, defeat, capture, draws, installs,
## Bots
- **greedy** plans each turn: grabs open locations, attacks at 60%+ odds, guards threatened
locations, installs Hardware and Programs where they help, walls off undefended locations, and
keeps RAM for tricks. On the opponent's turn it answers after the dice are rolled with whichever
- **greedy** plans each command: takes the best single advance or attack (open locations first,
rushing the ones that unlock Avatars; attacks at 60%+ odds), guards threatened locations, installs
Hardware and Programs where they help, walls off undefended locations, and keeps RAM for tricks.
With whole turns it plans every Avatar's move at once. On the opponent's commands it answers after the dice are rolled with whichever
Execution or Ability most improves the combat, and tries to stop advances into its locations.
- **nocards** is greedy but only uses Core Hardware, like the first version of the sim.
- **bold / cautious / nowall / wall3** change one greedy setting each; **random** picks any legal

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];

View file

@ -2,6 +2,7 @@ import assert from 'node:assert/strict';
import { test } from 'node:test';
import { avatarCores, openWindow } from '../src/engine.ts';
import { hasRoom } from '../src/query.ts';
import { withRule } from '../src/rules.ts';
import { card } from './card.ts';
import { Table, type Side } from './table.ts';
@ -39,6 +40,35 @@ card('Carbon NanoBots', () => {
assert.equal(t.avatar(0, 1).hardware.length, 1);
});
test('copy rule variants: a new copy defends but only advances or attacks from its next turn', () => {
const t = scene('Carbon NanoBots', 'Broken Bits');
t.s.rules = withRule(t.s.rules, 'copies.waitATurn=true');
t.own(0, 'A2');
t.ram(0, 5).use(avatarCard(t, 0, 1), { to: 'A2' }).settle();
assert.equal(t.avatar(0, 5).at, 'A2', 'the copy is in play, defending A2');
const acts = () => t.legal().filter((a) => (a.type === 'advance' || a.type === 'attack') && a.slot === 5);
assert.deepEqual(acts(), []);
assert.ok(t.legal().some((a) => a.type === 'advance' && a.slot === 1), 'the original still can');
t.to('attack');
assert.deepEqual(acts(), []);
t.to('playAgain').end().to('playAgain').end();
assert.ok(acts().length > 0, 'next turn it can advance');
});
test('copy rule variants: copies can need Avatar 2 unlocked, or be off', () => {
const t = scene('Carbon NanoBots', 'Broken Bits');
t.own(0, 'A2');
t.ram(0, 5);
const replicate = () => t.legal().some((a) => a.type === 'activate' && a.name === 'Carbon NanoBots');
assert.ok(replicate());
t.s.rules = withRule(t.s.rules, 'copies.needAvatar2=true');
assert.ok(!replicate(), 'Avatar 2 is still face down');
t.avatar(0, 2).faceUp = true;
assert.ok(replicate());
t.s.rules = withRule(t.s.rules, 'copies.allowed=false');
assert.ok(!replicate());
});
test('no copy can enter a location while a combat is going on there', () => {
const t = scene('Broken Bits', 'Carbon NanoBots', { north: { servers: ['Cluster Server'] } });
t.own(1, 'C1', 'Cluster Server');
@ -86,14 +116,14 @@ card('Beta Version 1.0', () => {
card('Code Zero', () => {
const t = scene('Broken Bits', 'Code Zero');
t.avatar(0, 1).infection = 1;
t.ram(1, 4);
fight(t);
assert.equal(t.decider, 1);
t.rig(6, 6, 6, 1, 1);
t.rig(6, 6, 6, 1, 1, 1);
t.use(avatarCard(t, 1, 1)).settle();
assert.equal(t.avatar(0, 1).infection >= 2 || t.avatar(0, 1).at === null, true);
assert.equal(dice(t, 'atk'), 3, '2 Infection counters: -1 Core while Code Zero is in play');
assert.equal(t.avatar(0, 1).infection >= 1 || t.avatar(0, 1).at === null, true);
assert.equal(dice(t, 'atk'), 3, '1 Infection counter: -1 Core while Code Zero is in play');
assert.equal(dice(t, 'def'), 3, 'Code Zero has 3 Cores');
});
card('Data Leaker', () => {

View file

@ -5,7 +5,8 @@ import { randomDeck } from '../src/deck.ts';
import { advanceTargets, avatarCores, createGame, legalActions, viewFor } from '../src/engine.ts';
import { checkInvariants } from '../src/invariants.ts';
import { makeRng } from '../src/rng.ts';
import { DEFAULT_RULES, withRule } from '../src/rules.ts';
import { DEFAULT_RULES, withRule, type RulesConfig } from '../src/rules.ts';
import { commanderOf, roundOf } from '../src/state.ts';
import { Table } from './table.ts';
const pool = loadCards();
@ -36,6 +37,31 @@ test('the first player skips the draw; the second player draws', () => {
assert.equal(t.s.players[1].hand.length, 1);
});
test('rule variants: the first player draws on turn 1', () => {
const pool = loadCards();
const hand = (rules: RulesConfig) => {
const s = createGame({ pool, decks: [randomDeck(pool, makeRng(1), rules), randomDeck(pool, makeRng(2), rules)], seed: 5, rules });
return s.players[s.firstPlayer].hand.length;
};
assert.equal(hand(withRule(DEFAULT_RULES, 'firstTurn.draw=true')), hand(DEFAULT_RULES) + 1);
});
test('rule variants: the second player draws extra in their first draw step only', () => {
const t = new Table({ north: { main: ['Additional Core', 'Additional Core', 'Additional Core', 'Additional Core'] } });
t.s.rules = withRule(t.s.rules, 'secondPlayer.firstDraw=1');
t.to('playAgain').end();
assert.equal(t.s.players[1].hand.length, 2);
t.to('playAgain').end().to('playAgain').end();
assert.equal(t.s.players[1].hand.length, 3);
});
test('rule variants: more cards per draw step', () => {
const t = new Table({ north: { main: ['Additional Core', 'Additional Core'] } });
t.s.rules = withRule(t.s.rules, 'drawPerTurn=2');
t.to('playAgain').end();
assert.equal(t.s.players[1].hand.length, 2);
});
test('advancing captures an unowned location in step 5 and pays 4 RAM; Lv 1 unlocks nothing', () => {
const t = new Table();
t.ram(0, 4);
@ -240,3 +266,200 @@ test('an opponent with a response gets a window after a declaration; without one
t.act({ type: 'pass' });
assert.equal(t.decider, 0);
});
// ---------------------------------------------------------------------------------------------
// Recruit rule (prototype): Avatars in the deck, bought with RAM
/** A table under the recruit rule: Avatar 1 stays, Avatars 2–4 move to their owner's hand, priced at 6 RAM. */
function recruitTable(o: ConstructorParameters<typeof Table>[0] = {}): Table {
const t = new Table(o);
t.s.rules = withRule(t.s.rules, 'recruit.on=true');
for (const p of [0, 1] as const) {
const avs = t.s.players[p].avatars;
for (let i = 1; i < 4; i++) {
const name = t.s.cards[avs[i].card].name;
t.s.defs[name] = { ...t.s.defs[name], ram: 6 };
t.s.players[p].hand.push(avs[i].card);
avs[i].card = avs[i + 4].card = -1;
avs[i].faceUp = false;
}
}
return t;
}
const recruits = (t: Table) => t.legal().filter((a) => a.type === 'recruit');
test('recruit rule: buy an Avatar from hand into an empty slot; it enters play on a later turn', () => {
const t = recruitTable();
const card = t.s.players[0].hand[0];
t.ram(0, 5).to('play');
assert.equal(recruits(t).length, 0, "can't afford 6 RAM");
t.ram(0, 6);
assert.deepEqual(recruits(t).map((a) => a.type === 'recruit' && a.slot), [2, 1, 2, 1, 2, 1], 'first empty slot, or over Avatar 1');
t.go({ type: 'recruit', card, slot: 2 });
assert.equal(t.s.players[0].ram, 0);
assert.equal(t.avatar(0, 2).card, card);
assert.equal(t.avatar(0, 2).faceUp, true);
assert.ok(!t.s.players[0].hand.includes(card));
t.to('playAgain').end().to('playAgain').end();
assert.ok(t.can({ type: 'place', slot: 2, to: 'S1' }));
});
test('recruit rule: captures unlock nothing, and a salvaged Avatar pays its price', () => {
const t = recruitTable();
t.own(0, 'B1');
t.place(0, 1, 'B1');
t.go({ type: 'advance', slot: 1, to: 'C2' }).to('attack').end();
assert.equal(t.s.locations.C2.owner, 0);
assert.equal(t.avatar(0, 2).card, -1);
const ram = t.s.players[0].ram;
t.go({ type: 'salvage', card: t.s.players[0].hand[0] });
assert.equal(t.s.players[0].ram, ram + 6);
});
test('recruit rule: copies count toward the 4 Avatars', () => {
const t = recruitTable({ south: { avatars: ['Carbon NanoBots', 'Broken Bits', 'Pixelated Picture', 'Corrupt Driver'] } });
t.own(0, 'A2');
t.place(0, 1, 'A2');
const [a, b] = t.s.players[0].hand;
t.ram(0, 30).to('play');
t.go({ type: 'recruit', card: a, slot: 2 }).go({ type: 'recruit', card: b, slot: 3 });
const replicate = t.legal().find((x) => x.type === 'activate' && x.name === 'Carbon NanoBots' && x.args.to === 'S1');
assert.ok(replicate, '3 Avatars, so a copy fits');
t.go(replicate).settle();
assert.equal(t.avatar(0, 5).at, 'S1');
assert.ok(!recruits(t).some((r) => r.type === 'recruit' && r.slot === 4), 'no room for a fourth with the copy out');
});
test('recruit rule: recruiting over an Avatar retires it and its Hardware', () => {
const t = recruitTable({ south: { main: ['Additional Core'] } });
t.own(0, 'A2');
const ref = t.place(0, 1, 'A2');
const old = t.avatar(0, 1).card;
const hw = t.hardware(ref.player, ref.slot, 'Additional Core');
const card = t.s.players[0].hand.find((id) => t.s.defs[t.s.cards[id].name].kind === 'avatar')!;
t.ram(0, 6).to('play').go({ type: 'recruit', card, slot: 1 });
assert.equal(t.avatar(0, 1).card, card);
assert.equal(t.avatar(0, 1).at, null);
assert.deepEqual(t.avatar(0, 1).hardware, []);
assert.ok(t.s.players[0].discard.includes(old) && t.s.players[0].discard.includes(hw));
assert.equal(t.s.locations.A2.owner, 0, 'the location stays yours');
});
test('recruit rule: decks keep one Avatar outside and shuffle the rest into the main deck', () => {
const pool = loadCards();
const rules = withRule(withRule(DEFAULT_RULES, 'recruit.on=true'), 'recruit.avatarsInDeck=5');
const deck = randomDeck(pool, makeRng(3), rules);
assert.equal(deck.avatars.length, 1);
assert.equal(deck.main.length, 45);
assert.equal(deck.main.filter((n) => pool.byName.get(n)!.kind === 'avatar').length, 5);
const s = createGame({ pool, decks: [deck, randomDeck(pool, makeRng(4), rules)], seed: 1, rules });
assert.deepEqual(s.players[0].avatars.slice(0, 4).map((a) => a.card >= 0), [true, false, false, false]);
assert.equal(checkInvariants(s).length, 0);
});
// ---------------------------------------------------------------------------------------------
// Buy-Avatars rule (prototype): pay RAM to flip the next Avatar instead of unlocking by level
test('buy rule: pay to flip the next face-down Avatar; it enters play on a later turn', () => {
const t = new Table();
t.s.rules = withRule(withRule(t.s.rules, 'buyAvatars.on=true'), 'buyAvatars.prices=8,12,16');
t.ram(0, 7).to('play');
assert.ok(!t.can({ type: 'buyAvatar', slot: 2 }), "can't afford 8 RAM");
t.ram(0, 20).go({ type: 'buyAvatar', slot: 2 });
assert.equal(t.avatar(0, 2).faceUp, true);
assert.equal(t.s.players[0].ram, 12);
assert.ok(t.can({ type: 'buyAvatar', slot: 3 }), 'Avatar 3 is next, at 12');
t.go({ type: 'buyAvatar', slot: 3 });
assert.equal(t.s.players[0].ram, 0);
t.to('playAgain').end().to('playAgain').end();
assert.ok(t.can({ type: 'place', slot: 2, to: 'S1' }));
});
test('buy rule: captures unlock nothing', () => {
const t = new Table();
t.s.rules = withRule(t.s.rules, 'buyAvatars.on=true');
t.own(0, 'B1');
t.place(0, 1, 'B1');
t.go({ type: 'advance', slot: 1, to: 'C2' }).to('attack').end();
assert.equal(t.s.locations.C2.owner, 0);
assert.deepEqual([t.avatar(0, 2).faceUp, t.avatar(0, 3).faceUp], [false, false]);
});
// ---------------------------------------------------------------------------------------------
// Command rule (prototype): alternating commands, 2 per player per round
/** Command rule with plain A B A B rounds, so tests can predict whose command it is. */
function commandTable(): Table {
const t = new Table();
t.s.rules = withRule(withRule(t.s.rules, 'commands.on=true'), 'commands.snake=false');
return t;
}
test('command rule: players alternate commands, and the lead alternates by round', () => {
const t = commandTable();
assert.deepEqual([1, 2, 3, 4, 5, 6, 7, 8, 9].map((turn) => commanderOf(t.s, turn)), [0, 1, 0, 1, 1, 0, 1, 0, 0]);
assert.deepEqual([1, 4, 5, 8, 9].map((turn) => roundOf(t.s, turn)), [1, 1, 2, 2, 3]);
t.to('playAgain').end();
assert.equal(t.s.active, 1);
t.to('playAgain').end().to('playAgain').end().to('playAgain').end();
assert.equal(t.s.turn, 5);
assert.equal(t.s.active, 1, 'North leads round 2');
});
test('command rule: the order of commands can follow a pattern of round leads, or snake', () => {
const order = (...specs: string[]) => {
const t = commandTable();
for (const sp of specs) t.s.rules = withRule(t.s.rules, sp);
return Array.from({ length: 16 }, (_, i) => 'FS'[commanderOf(t.s, i + 1)]).join('');
};
assert.equal(order(), 'FSFS' + 'SFSF' + 'FSFS' + 'SFSF');
assert.equal(order('commands.leads=F'), 'FSFS'.repeat(4));
assert.equal(order('commands.leads=FFSS'), 'FSFS' + 'FSFS' + 'SFSF' + 'SFSF');
assert.equal(order('commands.leads=thue'), 'FSFS' + 'SFSF' + 'SFSF' + 'FSFS');
assert.equal(order('commands.snake=true', 'commands.leads=F'), 'FSSF'.repeat(4));
assert.equal(order('commands.snake=true'), 'FSSF' + 'SFFS' + 'FSSF' + 'SFFS', 'the default order');
assert.equal(DEFAULT_RULES.commands.snake, true);
});
test('command rule: one advance or attack per command, each Avatar once a round', () => {
const t = commandTable();
t.own(0, 'A2');
t.own(0, 'A1');
t.place(0, 1, 'A2');
t.place(0, 2, 'A1');
t.go({ type: 'advance', slot: 1, to: 'A3' });
assert.ok(!t.legal().some((a) => a.type === 'advance'), 'the command is spent');
t.to('attack');
assert.ok(!t.legal().some((a) => a.type === 'attack'));
t.to('playAgain').end().to('playAgain').end();
assert.equal(t.s.turn, 3);
const movers = new Set(t.legal().filter((a) => a.type === 'advance').map((a) => a.type === 'advance' && a.slot));
assert.deepEqual([...movers], [2], 'Avatar 1 already acted this round');
});
test('command rule: an Avatar unlocked this round enters play next round', () => {
const t = commandTable();
t.own(0, 'A2');
t.place(0, 1, 'A2');
t.go({ type: 'advance', slot: 1, to: 'B1' }).to('attack').end();
assert.equal(t.avatar(0, 2).faceUp, true);
t.to('playAgain').end().to('playAgain').end();
assert.equal(t.s.turn, 3);
assert.ok(!t.legal().some((a) => a.type === 'place' && a.slot === 2));
t.to('playAgain').end().to('playAgain').end().to('playAgain').end();
assert.equal(t.s.turn, 6);
assert.ok(t.legal().some((a) => a.type === 'place' && a.slot === 2));
});
test('command rule: each player draws at their first command of a round only', () => {
const t = commandTable();
const hand = () => t.s.players[1].hand.length;
t.to('playAgain').end();
assert.equal(hand(), 1, "North's first command of round 1");
t.to('playAgain').end().to('playAgain').end();
assert.equal(hand(), 1, 'no draw on the second command');
t.to('playAgain').end();
assert.equal(t.s.turn, 5);
assert.equal(hand(), 2, 'round 2');
});

View file

@ -4,6 +4,7 @@ import { DEFAULT_GREEDY, greedyBot } from '../src/bots/greedy.ts';
import { randomBot } from '../src/bots/random.ts';
import { loadCards } from '../src/cards.ts';
import { playGame } from '../src/play.ts';
import { DEFAULT_RULES, withRule } from '../src/rules.ts';
const pool = loadCards();
@ -26,6 +27,42 @@ test('greedy bots play 200 games without breaking a rule', () => {
assert.ok(wins >= 196, `only ${wins}/200 games ended in a win`);
});
test('bots play the recruit rule without breaking a rule', () => {
for (const k of [3, 7]) {
const rules = withRule(withRule(DEFAULT_RULES, 'recruit.on=true'), `recruit.avatarsInDeck=${k}`);
for (let seed = 1; seed <= 25; seed++) {
assert.ok(playGame({ pool, bots: [randomBot, randomBot], seed, rules, check: true }).over);
assert.ok(playGame({ pool, bots: [() => greedyBot(), () => greedyBot()], seed, rules, check: true }).over);
}
}
});
test('bots play the buy-Avatars rule without breaking a rule', () => {
const rules = withRule(DEFAULT_RULES, 'buyAvatars.on=true');
for (let seed = 1; seed <= 25; seed++) {
assert.ok(playGame({ pool, bots: [randomBot, randomBot], seed, rules, check: true }).over);
assert.ok(playGame({ pool, bots: [() => greedyBot(), () => greedyBot()], seed, rules, check: true }).over);
}
});
test('bots play the copy-rule variants without breaking a rule', () => {
for (const spec of ['copies.waitATurn=true', 'copies.needAvatar2=true', 'copies.allowed=false']) {
const rules = withRule(DEFAULT_RULES, spec);
for (let seed = 1; seed <= 15; seed++) {
assert.ok(playGame({ pool, bots: [randomBot, randomBot], seed, rules, check: true }).over);
assert.ok(playGame({ pool, bots: [() => greedyBot(), () => greedyBot()], seed, rules, check: true }).over);
}
}
});
test('bots play the command rule without breaking a rule', () => {
const rules = withRule(DEFAULT_RULES, 'commands.on=true');
for (let seed = 1; seed <= 25; seed++) {
assert.ok(playGame({ pool, bots: [randomBot, randomBot], seed, rules, check: true }).over);
assert.ok(playGame({ pool, bots: [() => greedyBot(), () => greedyBot()], seed, rules, check: true }).over);
}
});
test('greedy beats random', () => {
let wins = 0;
for (let seed = 1; seed <= 100; seed++) {

View file

@ -36,8 +36,11 @@ export class Table {
main: [...(x.main ?? []), ...Array(12).fill(FILLER)],
});
const decks = [side(o.south), side(o.north)] as const;
// Classic turns (one turn each, every Avatar acts), which the card tests are written for. The
// command rule has its own tests in engine.test.ts.
const rules: RulesConfig = {
...DEFAULT_RULES,
commands: { ...DEFAULT_RULES.commands, on: false },
openingHand: 0,
deck: { avatars: 4, servers: decks[0].servers.length, main: decks[0].main.length, maxCopies: 99 },
};