import { mkdirSync, writeFileSync } from 'node:fs'; import { dirname } from 'node:path'; import { parseArgs } from 'node:util'; import type { BotFactory } from './bots/bot.ts'; import { DEFAULT_GREEDY, greedyBot } from './bots/greedy.ts'; import { randomBot } from './bots/random.ts'; import { DEFAULT_CARDS_CSV, loadCards, type CardKind } from './cards.ts'; import { playGame } from './play.ts'; import { DEFAULT_RULES, withRule } from './rules.ts'; import { isImplemented, staleScripts } from './scripts.ts'; import { cardReport, formatCardReport, formatSummary, recordOf, summarize, type GameRecord } from './stats.ts'; import { PLAYER_NAMES } from './types.ts'; const BOTS: Record = { greedy: { about: 'grabs open locations, attacks at 60%+ odds, walls with Lv 1 Firewalls, plays its cards', make: () => greedyBot() }, nocards: { about: 'greedy, but only uses Core Hardware (the Phase 2 bot)', make: () => greedyBot({ ...DEFAULT_GREEDY, useCards: false }) }, bold: { about: 'greedy, but attacks at 50%+ odds', make: () => greedyBot({ ...DEFAULT_GREEDY, minWinChance: 0.5 }) }, cautious: { about: 'greedy, but attacks only at 75%+ odds', make: () => greedyBot({ ...DEFAULT_GREEDY, minWinChance: 0.75 }) }, nowall: { about: 'greedy, but never places Firewalls', make: () => greedyBot({ ...DEFAULT_GREEDY, firewallLevel: 0 }) }, wall3: { about: 'greedy, but walls with Lv 3 Firewalls', make: () => greedyBot({ ...DEFAULT_GREEDY, firewallLevel: 3 }) }, random: { about: 'picks any legal action', make: randomBot }, }; const USAGE = `Files TCG simulator node src/cli.ts [options] -n, --games N games to play (default 1000) --seed N first game's seed; game i uses seed + i (default 1) --south BOT South's bot (default greedy) --north BOT North's bot (default greedy) --max-turns N 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.draw=true, firstTurn.advance=false, firstTurn.captureRam=false, firstTurn.unlock=false, firstTurn.cards=false, 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 --card-report also print each card's win rate (decks holding it) and how often bots played it --cards FILE card CSV (default decks/files-deck-1/cards.csv) Bots: ${Object.entries(BOTS).map(([name, b]) => ` ${name.padEnd(10)} ${b.about}`).join('\n')} `; const { values: opt } = parseArgs({ options: { games: { type: 'string', short: 'n', default: '1000' }, seed: { type: 'string', default: '1' }, south: { type: 'string', default: 'greedy' }, north: { type: 'string', default: 'greedy' }, 'max-turns': { type: 'string' }, rule: { type: 'string', multiple: true, default: [] }, log: { type: 'boolean', default: false }, check: { type: 'boolean', default: false }, json: { type: 'string' }, 'card-report': { type: 'boolean', default: false }, cards: { type: 'string', default: DEFAULT_CARDS_CSV }, help: { type: 'boolean', short: 'h', default: false }, }, }); if (opt.help) { console.log(USAGE); process.exit(0); } for (const side of [opt.south, opt.north]) { if (!BOTS[side]) { console.error(`Unknown bot "${side}". Choose from: ${Object.keys(BOTS).join(', ')}`); process.exit(1); } } function count(name: string, value: string | undefined): number | undefined { if (value === undefined) return undefined; const n = Number(value); if (!Number.isInteger(n) || n < 0) { console.error(`--${name} needs a whole number, got "${value}"`); process.exit(1); } return n; } const games = count('games', opt.games)!; const seed = count('seed', opt.seed)!; const maxTurns = count('max-turns', opt['max-turns']); const pool = loadCards(opt.cards); let rules = maxTurns === undefined ? DEFAULT_RULES : { ...DEFAULT_RULES, maxTurns }; try { for (const spec of opt.rule) rules = withRule(rules, spec); } catch (e) { console.error((e as Error).message); process.exit(1); } if (opt.rule.length) console.log(`Rules changed: ${opt.rule.join(', ')}`); const bots: [BotFactory, BotFactory] = [BOTS[opt.south].make, BOTS[opt.north].make]; for (const warning of staleScripts(pool)) console.warn(`warning: ${warning}`); const KIND_LABELS: [CardKind, string][] = [ ['avatar', 'Avatars'], ['server', 'Servers'], ['hardware', 'Hardware'], ['program', 'Programs'], ['execution', 'Executions'], ]; const coverage = KIND_LABELS.map(([kind, label]) => { const cards = pool.all.filter((c) => c.kind === kind); return `${label} ${cards.filter(isImplemented).length}/${cards.length}`; }); console.log(`Card effects simulated: ${coverage.join(', ')}.\n`); if (opt.log) { const s = playGame({ pool, bots, seed, rules, log: true, check: opt.check }); console.log(s.log!.join('\n')); process.exit(0); } const labels: [string, string] = [`${PLAYER_NAMES[0]} (${opt.south})`, `${PLAYER_NAMES[1]} (${opt.north})`]; const started = performance.now(); const records: GameRecord[] = []; for (let i = 0; i < games; i++) { records.push(recordOf(seed + i, playGame({ pool, bots, seed: seed + i, rules, check: opt.check }))); } const seconds = (performance.now() - started) / 1000; const summary = summarize(records); console.log(`${games} games, ${labels[0]} vs ${labels[1]}, seeds ${seed}–${seed + games - 1} (${seconds.toFixed(1)}s)\n`); console.log(formatSummary(summary, labels)); if (opt['card-report']) console.log(`\n${formatCardReport(cardReport(pool, records))}`); if (opt.json) { mkdirSync(dirname(opt.json), { recursive: true }); writeFileSync(opt.json, JSON.stringify({ south: opt.south, north: opt.north, summary, games: records }, null, 2)); console.log(`\nWrote ${opt.json}`); }