This commit is contained in:
Forrest 2026-10-01 17:20:33 -04:00
parent 5368464042
commit 937f44defe
100 changed files with 10185 additions and 2042 deletions

2
app/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
node_modules
dist

115
app/README.md Normal file
View file

@ -0,0 +1,115 @@
# Files TCG App
Play a full game of Files TCG in the browser against the simulator's greedy bot. It runs on the
same engine as `../sim`, so a rule you change there shows up here, and cards come straight from
`../decks/files-deck-1/cards.csv` and its Cider templates.
## Running it
```sh
cd app
npm install
npm run dev # http://localhost:5173
npm test # headless games through the controller
npm run typecheck
npm run build # static site in dist/, openable from any static host
```
## Playing
Pick your side, a seed (blank is random), both decks, the bot's style and any rule variants, then
**Start game**. Read [QUICKSTART.md](../QUICKSTART.md) first if you haven't played.
- **To act, pick a source, then a target.** Things you can use glow: a card in your hand, one of
your Anomalies (on the board, or in its slot in your panel), a gateway, or a location with an
Ability. Its targets then light up: teal for moves, red for attacks. Click one to play it. If
several moves share a target (Sabotage's destroy or disable, say), a small menu asks which. Moves
with no target, such as Salvage, Recall, Firewall levels and most Abilities, are in the menu at
the bottom right of the board.
- **The Moves tab lists every legal move,** grouped and searchable, for anything the clicks miss.
- **Response windows** show a banner over the board ("North plays Execute: Kill Process on C2:
respond?"). Answer with a glowing card or Ability, or pass.
- **Cards:** hover any card, or a card name, to see it large. Right-click pins it until you close
it (or press Esc). Settings can switch to plain text cards.
- **Combat tab:** each side's Cores by source (the Anomaly, Hardware, Programs, Servers,
temporary effects), the dice, totals, damage and anything destroyed. Before a roll it shows the
odds and the average damage each way. While you have an Anomaly picked, pointing at an attack
target shows your odds for that attack.
- **Info tab:** details of whatever you point at: a location's Server and Programs, the Anomalies
there with their Hardware, counters and temporary Cores.
- **Log tab:** the play-by-play, filterable by Combat, Captures, Cards and Moves. Lines that name
the bot's hidden cards (Callable Server, Diagnostic Module, Race Condition picks) show only that
it made a choice.
| Key | Action |
| --- | --- |
| Space | End the step, or pass |
| Enter | End command: ends steps until your command is over, stopping if a prompt or response window comes up |
| Z | Undo (playtest mode only) |
| Esc | Cancel the selection, close a dialog or a pinned card |
| Shift (held) | Stop at the next response window, whatever the stops setting says |
### Settings
- **Stops** decide when the game waits for you to respond to the bot:
- **In combat only** (the default): the bot's Executions, Abilities, installs and declarations
outside combat pass for you.
- **Every opponent move** stops at every window where you could respond.
- **Never** passes everything.
The engine already skips windows where you have nothing you could play.
- **Skip empty steps** ends your steps for you when End and Salvage are the only moves.
- **Bot speed** runs from instant to 1 s per move. The top bar also has pause and step-one-move.
- **Dice animation**, **odds preview** and **text cards** can each be turned off.
- **Playtest tools:** the seed, copying the log, exporting the game record, and a rule-invariant
check after every move that reports any engine bug it finds.
### Saving, undo and replays
- The game saves to local storage after every move, and the start screen offers to resume it.
Resuming replays the saved moves, so if the cards or rules have changed since and a saved move
stops being legal, the game can't be resumed.
- **Undo** is on in playtest mode (a checkbox on the start screen) and off otherwise. It goes back
to your previous decision. The dice are part of the game state, so trying the same move again
rolls the same dice.
- **A game record** is the seed, both decks, the rules, the bot style and every move. The engine is
deterministic, so a record replays exactly. Export one from Settings or the game-over screen,
and open it with **Open a game record…** on the start screen. The replay viewer steps through the
game with hidden cards shown or not, and **Play on from here** takes over your side from any
move, in playtest mode. Attach a record to a bug report and the bug can be reproduced.
### Decks and rules
- Each deck is a random legal deck, a preset from `decks/*.json`, or a pasted list. A pasted list
is one card per line (`2 RAM Expansion`, lines starting with `#` are ignored) or JSON
(`{ "anomalies": [...], "servers": [...], "main": [...] }`). Picking **Paste a list…** while a
preset is selected starts from that preset's list. Every deck is checked with the sim's
`validateDeck`, and problems are listed.
- **Rule variants** take the same `K=V` lines as the CLI's `--rule`, one per line, for example
`secondPlayer.bandwidth=4` or `board=grid4` (the 4×4 boards lay out too).
- **Bot styles** are presets of the greedy bot's `GreedyParams`: Greedy (the sim's standard),
Cautious (attacks at 75%+), Bold (50%+), Wall builder (Lv 3 Firewalls) and Easy (no cards but
Core Hardware).
## How it's built
Vite, TypeScript and Preact, plus Handlebars for the card templates. The app imports the engine
from `../sim/src`; nothing is copied.
| Path | What it holds |
| --- | --- |
| `src/match.ts` | The game controller: real state, bot moves, automatic moves (skips, stops, End command), undo, records, the combat readout's data. No DOM, so tests drive it headlessly. |
| `src/moves.ts` | Legal actions as moves: label, cost, group, and a source and target for click-to-act. The UI never builds an Action. |
| `src/replay.ts` | Rebuilds any move of a game record, with checkpoints for fast seeking. |
| `src/render-card.ts` | Renders cards from the Cider templates as Cider does (`{ card, assets }`, kebab-case keys, the same helpers), inside shadow roots so each template's CSS stays scoped. Cards with no art get a placeholder. |
| `src/cards.ts`, `src/decks.ts` | The card pool (the CSV via `?raw`, so edits show on reload) and deck choices. |
| `src/layout.ts` | Board coordinates, worked out from the board's rows, so the 4×4 boards fit too. |
| `src/storage.ts` | Settings, the saved game and the last setup, in local storage. |
| `src/ui/` | Board (SVG), player panels and hand, side column (combat, info, log, moves), game screen, start screen, replay viewer. |
| `test/` | A random and a greedy "human" play hundreds of games through the controller; records replay exactly; undo restores the dice; End command stops where it should; every legal move is reachable by clicking. |
The UI only sees `viewFor(state, you)`, so it can't show the bot's hand by mistake, and the bot
only sees its own view.
Dev builds expose `globalThis.__files` (the current match, and a greedy bot to play your side) for
scripted browser tests.

View file

@ -0,0 +1,79 @@
{
"name": "Glitch Tricks",
"about": "Every kind of Anomaly and a toolbox of Executions and copies: Fork, Remote Access, Process Clone and Ghost Process.",
"anomalies": [
"Data Leaker",
"Pixelated Picture",
"Code Zero",
"Beta Version 1.0"
],
"servers": [
"Duplicate Server",
"Duplicate Server",
"Server Farm",
"Server Farm",
"High Bandwidth Server",
"High Bandwidth Server",
"Power Server",
"Power Server",
"MultiCore Server",
"MultiCore Server",
"Upgraded Hardware",
"Upgraded Hardware",
"Cloud Compute",
"Cloud Compute",
"Callable Server",
"Callable Server",
"Protected Server",
"Protected Server",
"Cluster Server",
"Cluster Server"
],
"main": [
"Ghost Process",
"Ghost Process",
"Packet Loss",
"Packet Loss",
"Fragmentation",
"Fragmentation",
"Race Condition",
"Race Condition",
"Undefined Behavior",
"Undefined Behavior",
"Garbage Collection",
"Garbage Collection",
"Compatibility Layer",
"Compatibility Layer",
"Dedicated GPU",
"Dedicated GPU",
"Quantum Coprocessor",
"Quantum Coprocessor",
"Hot-Swap Bay",
"Hot-Swap Bay",
"Additional Core",
"Additional Core",
"Diagnostic Module",
"Diagnostic Module",
"Execute: Fork",
"Execute: Fork",
"Execute: Remote Access",
"Execute: Remote Access",
"Execute: Process Clone",
"Execute: Process Clone",
"Execute: Override",
"Execute: Override",
"Execute: Memory Dump",
"Execute: Memory Dump",
"Execute: Root Access",
"Latency Spike",
"Latency Spike",
"Visual Artifact",
"Visual Artifact",
"RAM Expansion",
"RAM Expansion",
"Execute: Trace Route",
"Execute: Trace Route",
"Execute: Ping Sweep",
"Execute: Ping Sweep"
]
}

79
app/decks/patch-wall.json Normal file
View file

@ -0,0 +1,79 @@
{
"name": "Patch Wall",
"about": "Patch and Glitch Anomalies that dig in: protective Programs, Hardware that survives defeat, and Executions that break attacks.",
"anomalies": [
"Backup Machine",
"Beta Version 1.0",
"Pixelated Picture",
"Data Leaker"
],
"servers": [
"Protected Server",
"Protected Server",
"Cluster Server",
"Cluster Server",
"Backup Server",
"Backup Server",
"Callable Server",
"Callable Server",
"Duplicate Server",
"Duplicate Server",
"High Bandwidth Server",
"High Bandwidth Server",
"Power Server",
"Power Server",
"Server Farm",
"Server Farm",
"MultiCore Server",
"MultiCore Server",
"Pingable Server",
"Pingable Server"
],
"main": [
"Hotfix",
"Hotfix",
"Error Correction",
"Error Correction",
"Version Control",
"Version Control",
"Rollback Routine",
"Rollback Routine",
"Latency Spike",
"Latency Spike",
"Visual Artifact",
"Visual Artifact",
"Desynchronization",
"Desynchronization",
"False Positive",
"False Positive",
"Firewall Appliance",
"Firewall Appliance",
"Redundant Power Supply",
"Redundant Power Supply",
"RAID Array",
"RAID Array",
"ECC Memory",
"ECC Memory",
"Additional Core",
"Additional Core",
"RAM Expansion",
"RAM Expansion",
"Execute: Emergency Shutdown",
"Execute: Emergency Shutdown",
"Execute: Disconnect",
"Execute: Disconnect",
"Execute: Force Reboot",
"Execute: Force Reboot",
"Execute: Kill Process",
"Execute: Kill Process",
"Execute: Defragment",
"Garbage Collection",
"Garbage Collection",
"Compatibility Layer",
"Compatibility Layer",
"Hardware Sandbox",
"Hardware Sandbox",
"Execute: Purge",
"Execute: Purge"
]
}

View file

@ -0,0 +1,79 @@
{
"name": "Virus Swarm",
"about": "Virus and Bug Anomalies that stack Infection counters and Core-draining Programs, backed by raw Core Hardware.",
"anomalies": [
"Code Zero",
"Corrupt Driver",
"Carbon NanoBots",
"Broken Bits"
],
"servers": [
"MultiCore Server",
"MultiCore Server",
"Power Server",
"Power Server",
"Server Farm",
"Server Farm",
"High Bandwidth Server",
"High Bandwidth Server",
"Cluster Server",
"Cluster Server",
"Upgraded Hardware",
"Upgraded Hardware",
"Cloud Compute",
"Cloud Compute",
"Backup Server",
"Backup Server",
"Pingable Server",
"Pingable Server",
"Network Throttle",
"Network Throttle"
],
"main": [
"Recursive Infection",
"Recursive Infection",
"Memory Parasite",
"Memory Parasite",
"Resource Leech",
"Resource Leech",
"Worm Protocol",
"Worm Protocol",
"Persistent Infection",
"Persistent Infection",
"Payload Injector",
"Payload Injector",
"Stack Overflow",
"Stack Overflow",
"Bloatware",
"Bloatware",
"Infinite Loop",
"Infinite Loop",
"Additional Core",
"Additional Core",
"RAM Expansion",
"RAM Expansion",
"Overclocked CPU",
"Overclocked CPU",
"Packet Accelerator",
"Packet Accelerator",
"Solid-State Cache",
"Solid-State Cache",
"Execute: Trace Route",
"Execute: Trace Route",
"Execute: Packet Flood",
"Execute: Packet Flood",
"Execute: Purge",
"Execute: Purge",
"Execute: Sabotage",
"Execute: Sabotage",
"Execute: Ping Sweep",
"Replication Routine",
"Replication Routine",
"Execute: Kill Process",
"Execute: Kill Process",
"Execute: Disconnect",
"Execute: Disconnect",
"Cooling System",
"Cooling System"
]
}

12
app/index.html Normal file
View file

@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Files TCG</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="./src/main.tsx"></script>
</body>
</html>

1306
app/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

22
app/package.json Normal file
View file

@ -0,0 +1,22 @@
{
"name": "files-tcg-app",
"private": true,
"type": "module",
"description": "Play Files TCG in the browser against the simulator's greedy bot",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"test": "node --test \"test/**/*.test.ts\"",
"typecheck": "tsc"
},
"dependencies": {
"handlebars": "^4.7.9",
"preact": "^11.0.0"
},
"devDependencies": {
"@types/node": "^26.6.3",
"typescript": "^7.0.2",
"vite": "^8.3.1"
}
}

12
app/src/cards.ts Normal file
View file

@ -0,0 +1,12 @@
/**
* The card pool, read live from the Cider CSV: card edits appear on reload. Set 1 only, as the
* CLI does by default, since set 2 has no scripts yet.
*/
import csv from '../../decks/files-deck-1/cards.csv?raw';
import { parseCards } from '../../sim/src/cards.ts';
import { parseCsvObjects } from '../../sim/src/csv.ts';
export const pool = parseCards(csv);
/** Raw CSV rows by card name, for the card templates. */
export const rows: ReadonlyMap<string, Record<string, string>> = new Map(parseCsvObjects(csv).map((r) => [r['Name'], r]));

86
app/src/decks.ts Normal file
View file

@ -0,0 +1,86 @@
/**
* Deck choices: random legal decks, the presets in app/decks, or a pasted list. A pasted list is
* JSON ({ anomalies, servers, main }) or one card per line ("2 RAM Expansion" or "2x RAM Expansion"),
* sorted into Anomalies, Servers and the main deck by card kind.
*/
import type { CardPool } from '../../sim/src/cards.ts';
import { validateDeck, type DeckList } from '../../sim/src/deck.ts';
import type { RulesConfig } from '../../sim/src/rules.ts';
export interface Preset extends DeckList {
id: string;
name: string;
about: string;
}
const files = import.meta.glob('../decks/*.json', { eager: true, import: 'default' }) as Record<string, Omit<Preset, 'id'>>;
export const PRESETS: Preset[] = Object.entries(files)
.map(([path, d]) => ({ ...d, id: path.split('/').pop()!.replace(/\.json$/, '') }))
.sort((a, b) => a.name.localeCompare(b.name));
/** A deck choice: random, a preset id, or a pasted list. */
export type DeckChoice = { kind: 'random' } | { kind: 'preset'; id: string } | { kind: 'paste'; text: string };
/** Reads a pasted deck list. Returns the deck, or the problems with it. */
export function parseDeckText(pool: CardPool, text: string): { deck: DeckList | null; errors: string[] } {
const trimmed = text.trim();
if (!trimmed) return { deck: null, errors: ['The list is empty'] };
if (trimmed.startsWith('{')) {
try {
const d = JSON.parse(trimmed) as Partial<DeckList>;
if (!Array.isArray(d.anomalies) || !Array.isArray(d.servers) || !Array.isArray(d.main)) {
return { deck: null, errors: ['JSON decks need "anomalies", "servers" and "main" lists'] };
}
return { deck: { anomalies: d.anomalies, servers: d.servers, main: d.main }, errors: [] };
} catch (e) {
return { deck: null, errors: [`Not valid JSON: ${(e as Error).message}`] };
}
}
const deck: DeckList = { anomalies: [], servers: [], main: [] };
const errors: string[] = [];
const lower = new Map(pool.all.map((c) => [c.name.toLowerCase(), c]));
for (const raw of trimmed.split(/\r?\n/)) {
const line = raw.replace(/#.*/, '').trim();
if (!line) continue;
const m = line.match(/^(\d+)\s*[x×]?\s+(.+)$/i);
const count = m ? Number(m[1]) : 1;
const name = (m ? m[2] : line).trim();
const card = lower.get(name.toLowerCase());
if (!card) {
errors.push(`Unknown card "${name}"`);
continue;
}
const part = card.kind === 'anomaly' ? deck.anomalies : card.kind === 'server' ? deck.servers : deck.main;
for (let i = 0; i < count; i++) part.push(card.name);
}
return { deck: errors.length ? null : deck, errors };
}
/** A deck as a pasteable list, one line per card name. */
export function deckText(deck: DeckList): string {
const lines: string[] = [];
for (const [title, names] of [['Anomalies', deck.anomalies], ['Servers', deck.servers], ['Deck', deck.main]] as const) {
lines.push(`# ${title}`);
const counts = new Map<string, number>();
for (const n of names) counts.set(n, (counts.get(n) ?? 0) + 1);
for (const [n, c] of counts) lines.push(`${c} ${n}`);
}
return lines.join('\n');
}
/** The deck for a choice, or its errors. `random` is used for the random choice. */
export function resolveDeck(pool: CardPool, choice: DeckChoice, rules: RulesConfig, random: DeckList): { deck: DeckList | null; errors: string[] } {
if (choice.kind === 'random') return { deck: random, errors: [] };
if (choice.kind === 'preset') {
const p = PRESETS.find((x) => x.id === choice.id);
if (!p) return { deck: null, errors: [`No preset "${choice.id}"`] };
const deck = { anomalies: p.anomalies, servers: p.servers, main: p.main };
const errors = validateDeck(pool, deck, rules);
return { deck: errors.length ? null : deck, errors };
}
const parsed = parseDeckText(pool, choice.text);
if (!parsed.deck) return parsed;
const errors = validateDeck(pool, parsed.deck, rules);
return { deck: errors.length ? null : parsed.deck, errors };
}

2
app/src/describe.ts Normal file
View file

@ -0,0 +1,2 @@
/** Action labels live in the sim, next to the engine they describe. */
export * from '../../sim/src/describe.ts';

46
app/src/layout.ts Normal file
View file

@ -0,0 +1,46 @@
/**
* Board coordinates, worked out from the current board's rows: a row is the letter of a location
* id, the starts sit beyond the first and last rows, and each row is centred. That fits the
* classic board and the 4×4 ones.
*/
import { GRID, LINES, START_LOC, type Line, type LocId } from '../../sim/src/map.ts';
import type { PlayerId } from '../../sim/src/types.ts';
export interface Point {
x: number;
y: number;
}
export interface BoardLayout {
width: number;
height: number;
at: Record<LocId, Point>;
lines: readonly Line[];
}
export const LOC_W = 140;
export const LOC_H = 70;
const COL = 180;
const ROW = 98;
const MARGIN = 16;
/** Positions with `bottom` (the viewer) nearest the bottom of the screen. */
export function boardLayout(bottom: PlayerId): BoardLayout {
const rows = [...new Set(GRID.map((l) => l[0]))].sort();
const widest = Math.max(...rows.map((r) => GRID.filter((l) => l[0] === r).length));
const width = widest * COL + MARGIN * 2;
const height = (rows.length + 2) * ROW + MARGIN * 2;
const at: Record<LocId, Point> = {};
const rowY = (i: number) => MARGIN + ROW / 2 + (rows.length + 1 - i) * ROW;
rows.forEach((r, i) => {
const locs = GRID.filter((l) => l[0] === r).sort((a, b) => Number(a.slice(1)) - Number(b.slice(1)));
locs.forEach((loc, j) => (at[loc] = { x: width / 2 + (j - (locs.length - 1) / 2) * COL, y: rowY(i + 1) }));
});
at[START_LOC[0]] = { x: width / 2, y: rowY(0) };
at[START_LOC[1]] = { x: width / 2, y: rowY(rows.length + 1) };
if (bottom === 1) {
// North at the bottom: turn the board around.
for (const loc of Object.keys(at)) at[loc] = { x: width - at[loc].x, y: height - at[loc].y };
}
return { width, height, at, lines: LINES };
}

125
app/src/main.tsx Normal file
View file

@ -0,0 +1,125 @@
/** The page shell: start screen, game, replay. */
import { render } from 'preact';
import { useEffect, useState } from 'preact/hooks';
import { pool } from './cards.ts';
import { Match, type GameRecord, type MatchOptions, type MatchSetup } from './match.ts';
import { Replay } from './replay.ts';
import { loadGame, loadSettings, loadSetup, saveGame, saveSettings, saveSetup, type SavedGame, type Settings } from './storage.ts';
import { GameScreen } from './ui/game.tsx';
import { ReplayScreen } from './ui/replay.tsx';
import { StartScreen } from './ui/start.tsx';
import './styles.css';
type Screen =
| { kind: 'start'; resumeError?: string }
| { kind: 'game'; match: Match; playtest: boolean; id: number }
| { kind: 'replay'; replay: Replay; from: Screen };
let games = 0;
const optionsFrom = (s: Settings, playtest: boolean): Partial<MatchOptions> => ({
autoSkip: s.autoSkip,
stops: s.stops,
checkInvariants: s.checkInvariants,
undo: playtest,
});
function App() {
const [settings, setSettings] = useState(loadSettings);
const [screen, setScreen] = useState<Screen>({ kind: 'start' });
const changeSettings = (s: Settings) => {
setSettings(s);
saveSettings(s);
if (screen.kind === 'game') screen.match.setOptions({ autoSkip: s.autoSkip, stops: s.stops, checkInvariants: s.checkInvariants });
};
// Save after every move; a finished game isn't offered for resuming.
useEffect(() => {
if (screen.kind !== 'game') return;
const { match, playtest } = screen;
const save = () => {
const g: SavedGame | null = match.over ? null : { record: match.record(), playtest, savedAt: Date.now() };
saveGame(g);
};
save();
return match.subscribe(save);
}, [screen]);
const play = (setup: MatchSetup, playtest: boolean) =>
setScreen({ kind: 'game', match: new Match(pool, setup, optionsFrom(settings, playtest)), playtest, id: ++games });
const playRecord = (record: GameRecord, playtest: boolean): string | null => {
try {
setScreen({ kind: 'game', match: Match.fromRecord(pool, record, optionsFrom(settings, playtest)), playtest, id: ++games });
return null;
} catch (e) {
return (e as Error).message;
}
};
current = screen.kind === 'game' ? screen.match : null;
if (screen.kind === 'game') {
const { match, playtest } = screen;
return (
<GameScreen
key={screen.id}
match={match}
settings={settings}
playtest={playtest}
onSettings={changeSettings}
onNewGame={() => setScreen({ kind: 'start' })}
onRematch={() => play(match.setup, playtest)}
onReplay={() => setScreen({ kind: 'replay', replay: new Replay(pool, match.record()), from: screen })}
/>
);
}
if (screen.kind === 'replay') {
return (
<ReplayScreen
replay={screen.replay}
settings={settings}
onBack={() => setScreen(screen.from.kind === 'game' && !screen.from.match.over ? screen.from : { kind: 'start' })}
onPlayFrom={(record) => {
const err = playRecord(record, true);
if (err) alert(err);
}}
/>
);
}
const saved = loadGame();
return (
<StartScreen
prefs={loadSetup()}
saved={saved}
resumeError={screen.resumeError ?? null}
onStart={(setup, playtest, prefs) => {
saveSetup(prefs);
play(setup, playtest);
}}
onResume={() => {
if (!saved) return;
const err = playRecord(saved.record, saved.playtest);
if (err) setScreen({ kind: 'start', resumeError: `Couldn’t resume: ${err}` });
}}
onDiscardSave={() => {
saveGame(null);
setScreen({ kind: 'start' });
}}
onOpenRecord={(record) => setScreen({ kind: 'replay', replay: new Replay(pool, record), from: { kind: 'start' } })}
/>
);
}
// Dev builds expose the current game for scripted browser tests.
let current: Match | null = null;
if (import.meta.env.DEV) {
(globalThis as Record<string, unknown>).__files = {
get match() {
return current;
},
greedyBot: () => import('../../sim/src/bots/greedy.ts').then((m) => m.greedyBot()),
};
}
render(<App />, document.getElementById('app')!);

419
app/src/match.ts Normal file
View file

@ -0,0 +1,419 @@
/**
* The game controller. It holds the real state and runs the bot; the UI only ever sees
* `viewFor(s, human)` and picks moves from `legal()`. Everything here is plain TypeScript with no
* DOM, so tests can drive it headlessly.
*/
import type { Bot } from '../../sim/src/bots/bot.ts';
import { DEFAULT_GREEDY, greedyBot, type GreedyParams } from '../../sim/src/bots/greedy.ts';
import type { CardPool } from '../../sim/src/cards.ts';
import { randomDeck, type DeckList } from '../../sim/src/deck.ts';
import { actionKey, applyAction, createGame, decider, legalActions, openWindow, viewFor } from '../../sim/src/engine.ts';
import { combatWatch, type CombatStage } from '../../sim/src/flow.ts';
import { checkInvariants } from '../../sim/src/invariants.ts';
import { fighterOf, coresOf, healthLeft, healthOf, type CorePart } from '../../sim/src/query.ts';
import { makeRng } from '../../sim/src/rng.ts';
import { DEFAULT_RULES, withRule, type RulesConfig } from '../../sim/src/rules.ts';
import { anomaly, logFor, refKey } from '../../sim/src/state.ts';
import type { Action, AnomalyRef, GameState, LogLine, PlayerId } from '../../sim/src/types.ts';
/** When the game waits for you to respond to the bot (the stops setting). */
export type Stops = 'combat' | 'all' | 'never';
export interface MatchSetup {
seed: number;
human: PlayerId;
decks: [DeckList, DeckList];
/** Rule changes as `K=V` text, like the CLI's --rule. */
rules: string[];
bot?: GreedyParams;
}
/** Everything needed to replay a game exactly: the setup and every action, as actionKeys. */
export interface GameRecord {
version: 1;
setup: MatchSetup;
actions: string[];
}
export interface MatchOptions {
/** End your steps for you when End and Salvage are the only moves. */
autoSkip: boolean;
stops: Stops;
/** Run checkInvariants after every action and collect the errors. */
checkInvariants: boolean;
/** Keep snapshots for undo (playtest mode). */
undo: boolean;
}
export const DEFAULT_OPTIONS: MatchOptions = { autoSkip: true, stops: 'combat', checkInvariants: false, undo: false };
/** One side of a combat as the readout shows it. */
export interface FighterInfo {
ref: AnomalyRef;
cores: number;
parts: CorePart[];
dice: number[];
health: number;
healthLeft: number;
}
/** The current or most recent combat. */
export interface CombatInfo {
id: number;
loc: string;
kind: 'attack' | 'advance' | 'traceRoute';
attacker: FighterInfo;
defenders: FighterInfo[];
rolled: boolean;
/** Ended early by a card. */
ended: boolean;
/** Where it has got to. 'result' has the final dice; 'end' is after the damage. */
stage: CombatStage;
/** The combat is over. */
done: boolean;
/** Index of the combat's first log line. */
logFrom: number;
}
/** Bot styles to pick from: GreedyParams presets, as the CLI offers. */
export const BOT_STYLES: Record<string, { label: string; about: string; params: GreedyParams }> = {
greedy: { label: 'Greedy', about: 'The sim’s standard bot: attacks at 60%+ odds, walls with Lv 1 Firewalls, plays its cards.', params: DEFAULT_GREEDY },
cautious: { label: 'Cautious', about: 'Greedy, but attacks only at 75%+ odds.', params: { ...DEFAULT_GREEDY, minWinChance: 0.75 } },
bold: { label: 'Bold', about: 'Greedy, but attacks at 50%+ odds.', params: { ...DEFAULT_GREEDY, minWinChance: 0.5 } },
wall3: { label: 'Wall builder', about: 'Greedy, but walls off with Lv 3 Firewalls.', params: { ...DEFAULT_GREEDY, firewallLevel: 3 } },
nocards: { label: 'Easy', about: 'Greedy, but only uses Core Hardware: no Programs, Executions or Abilities.', params: { ...DEFAULT_GREEDY, useCards: false } },
};
/** Builds the rules from `K=V` overrides. Throws on a bad one. */
export function rulesFrom(specs: string[]): RulesConfig {
let rules = DEFAULT_RULES;
for (const spec of specs) if (spec.trim()) rules = withRule(rules, spec.trim());
return rules;
}
/** Random legal decks for both players, seeded like the sim's playGame. */
export function randomDecks(pool: CardPool, seed: number, rules: RulesConfig): [DeckList, DeckList] {
const rng = makeRng(seed ^ 0x9e3779b9);
return [randomDeck(pool, rng, rules), randomDeck(pool, rng, rules)];
}
const other = (p: PlayerId): PlayerId => (p === 0 ? 1 : 0);
interface Snapshot {
state: GameState;
actions: number;
combats: number;
}
const MAX_UNDO = 200;
export class Match {
readonly pool: CardPool;
readonly setup: MatchSetup;
readonly rules: RulesConfig;
readonly human: PlayerId;
readonly botSide: PlayerId;
s: GameState;
/** Every action applied so far, as actionKeys (yours, the bot's and the automatic ones). */
actions: string[] = [];
options: MatchOptions;
/** Invariant errors found, when checking is on. */
errors: string[] = [];
/** Set while a key is held: stop at the next response window whatever the stops setting says. */
holdStop = false;
/** Every combat so far, the current or latest last. */
combats: CombatInfo[] = [];
/** Bumped on every change, so the UI knows when to redraw. */
version = 0;
private bot: Bot;
private undoStack: Snapshot[] = [];
/** End command: the game turn being ended, or null. */
private ending: number | null = null;
private listeners = new Set<() => void>();
private cachedView: { version: number; view: GameState } | null = null;
private cachedLegal: { version: number; legal: Action[] } | null = null;
constructor(pool: CardPool, setup: MatchSetup, options: Partial<MatchOptions> = {}) {
this.pool = pool;
this.setup = setup;
this.rules = rulesFrom(setup.rules);
this.human = setup.human;
this.botSide = other(setup.human);
this.options = { ...DEFAULT_OPTIONS, ...options };
this.bot = greedyBot(setup.bot ?? DEFAULT_GREEDY);
this.s = createGame({ pool, decks: setup.decks, seed: setup.seed, rules: this.rules, log: true });
this.settle();
}
/** Rebuilds a game from its record. The bot sees every one of its moves again, so it plans as before. */
static fromRecord(pool: CardPool, record: GameRecord, options: Partial<MatchOptions> = {}): Match {
const m = new Match(pool, record.setup, { ...options, autoSkip: false, stops: 'all', undo: false });
m.actions = [];
m.s = createGame({ pool, decks: record.setup.decks, seed: record.setup.seed, rules: m.rules, log: true });
m.combats = [];
for (const key of record.actions) {
const legal = legalActions(m.s);
const a = legal.find((x) => actionKey(x) === key);
if (!a) throw new Error(`The record doesn't fit this version of the game: "${key}" isn't legal at move ${m.actions.length + 1}.`);
if (decider(m.s) === m.botSide) m.bot.choose(viewFor(m.s, m.botSide), legal, m.botSide);
m.apply(a, legal);
}
m.options = { ...DEFAULT_OPTIONS, ...options };
m.settle();
return m;
}
// -------------------------------------------------------------------------------------------
// Reading
subscribe(fn: () => void): () => void {
this.listeners.add(fn);
return () => this.listeners.delete(fn);
}
private changed(): void {
this.version++;
for (const fn of this.listeners) fn();
}
get over(): boolean {
return this.s.over;
}
decider(): PlayerId | null {
return decider(this.s);
}
humanToAct(): boolean {
return decider(this.s) === this.human;
}
botToAct(): boolean {
return decider(this.s) === this.botSide;
}
/** What the human may see. Read-only. */
view(): GameState {
if (this.cachedView?.version !== this.version) this.cachedView = { version: this.version, view: viewFor(this.s, this.human) };
return this.cachedView.view;
}
/** Your legal moves, or none while the bot decides. */
legal(): Action[] {
if (!this.humanToAct()) return [];
if (this.cachedLegal?.version !== this.version) this.cachedLegal = { version: this.version, legal: legalActions(this.s) };
return this.cachedLegal.legal;
}
/** The play-by-play as you may read it. */
log(): string[] {
return logFor(this.s, this.human);
}
/** Log lines with their tags, with private text swapped for what you may read. */
logLines(): LogLine[] {
const text = this.log();
return (this.s.log ?? []).map((l, i) => ({ ...l, text: text[i], to: undefined, public: undefined }));
}
/** The current or latest combat. */
get combat(): CombatInfo | null {
return this.combats.at(-1) ?? null;
}
record(): GameRecord {
return { version: 1, setup: this.setup, actions: [...this.actions] };
}
get canUndo(): boolean {
return this.options.undo && this.undoStack.length > 0;
}
/** Whether End command is running (it stops for your prompts and response windows). */
get endingCommand(): boolean {
return this.ending !== null;
}
// -------------------------------------------------------------------------------------------
// Acting
/** Your move. It must be one of `legal()`. */
act(a: Action): void {
if (!this.humanToAct()) throw new Error("It isn't your decision");
this.ending = null;
if (this.options.undo) {
this.snapshot();
}
this.apply(a, this.legal());
this.settle();
this.changed();
}
/** Ends steps until your command is over. Stops if a prompt or response window comes up for you. */
endCommand(): void {
if (!this.humanToAct() || this.s.choice || openWindow(this.s)) return;
if (this.options.undo) this.snapshot();
this.ending = this.s.turn;
this.settle();
this.changed();
}
/** One bot move, if it's the bot's decision. Returns whether it moved. */
botStep(): boolean {
if (!this.botToAct()) return false;
const legal = legalActions(this.s);
const a = this.bot.choose(viewFor(this.s, this.botSide), legal, this.botSide);
this.apply(a, legal);
this.settle();
this.changed();
return true;
}
/** Runs the bot until you must decide or the game ends. For tests and instant bot speed. */
runBot(limit = 100_000): void {
for (let n = 0; this.botToAct(); n++) {
if (n > limit) throw new Error(`The bot made ${limit} moves in a row`);
this.botStep();
}
}
/** Goes back to your previous decision. */
undo(): boolean {
const snap = this.undoStack.pop();
if (!snap) return false;
this.s = snap.state;
this.actions.length = snap.actions;
this.combats.length = snap.combats;
if (this.combat && this.s.combat?.id === this.combat.id) this.combats[this.combats.length - 1] = this.snapCombat(this.combat.stage);
this.ending = null;
this.changed();
return true;
}
setOptions(o: Partial<MatchOptions>): void {
this.options = { ...this.options, ...o };
if (!this.options.undo) this.undoStack = [];
this.settle();
this.changed();
}
/** Re-checks automatic moves, e.g. after a held key is released. */
poke(): void {
const before = this.actions.length;
this.settle();
if (this.actions.length !== before) this.changed();
}
private snapshot(): void {
this.undoStack.push({ state: structuredClone(this.s), actions: this.actions.length, combats: this.combats.length });
if (this.undoStack.length > MAX_UNDO) this.undoStack.shift();
}
private apply(a: Action, legal: Action[]): void {
combatWatch.fn = (_s, stage) => this.watch(stage);
try {
applyAction(this.s, a, legal);
} finally {
combatWatch.fn = null;
}
this.actions.push(actionKey(a));
this.version++;
if (this.options.checkInvariants) {
for (const e of checkInvariants(this.s)) this.errors.push(`Move ${this.actions.length} (${actionKey(a)}), turn ${this.s.turn}: ${e}`);
}
const last = this.combat;
if (last && !last.done) {
// A capture in combat can win the game before the combat's end stage.
if (this.s.over) this.combats[this.combats.length - 1] = { ...last, stage: 'end', done: true };
else if (this.s.combat?.id === last.id) this.combats[this.combats.length - 1] = this.snapCombat(last.stage);
}
}
/** Makes the moves the settings make for you: skipping empty steps, passing, End command. */
private settle(): void {
for (let guard = 0; this.humanToAct(); guard++) {
if (guard > 10_000) throw new Error('The automatic moves are stuck in a loop');
const auto = this.automatic();
if (!auto) return;
this.apply(auto, this.legal());
}
if (this.ending !== null && (this.s.over || this.s.turn !== this.ending)) this.ending = null;
}
/** The move the settings make for you now, if any. */
private automatic(): Action | null {
const s = this.s;
if (s.choice) {
this.ending = null;
return null;
}
const legal = this.legal();
const w = openWindow(s);
if (w) {
if (this.passesFor(w.kind)) return legal.find((a) => a.type === 'pass') ?? null;
this.ending = null;
return null;
}
if (this.ending !== null) {
if (s.turn === this.ending) return legal.find((a) => a.type === 'end') ?? null;
this.ending = null;
}
if (this.options.autoSkip && legal.every((a) => a.type === 'end' || a.type === 'salvage')) return legal.find((a) => a.type === 'end') ?? null;
return null;
}
/** Whether the stops setting passes this response window for you. */
private passesFor(kind: 'response' | 'preRoll' | 'postRoll'): boolean {
if (this.holdStop) return false;
const stops = this.options.stops;
if (stops === 'all') return false;
if (stops === 'never') return true;
// In combat only: the bot's Executions, Abilities, installs and declarations outside combat pass.
return kind === 'response' && !(this.s.combat && !this.s.combat.ended);
}
private watch(stage: CombatStage): void {
const c = this.s.combat!;
if (stage === 'start' || this.combat?.id !== c.id) {
this.combats.push({ ...this.snapCombat(stage), logFrom: Math.max(0, (this.s.log?.length ?? 1) - 1) });
return;
}
// After the damage, keep the Cores and dice from the result: the fighters may be gone by now.
const next = stage === 'end' ? { ...this.combat, ended: c.ended, stage, done: true } : this.snapCombat(stage);
this.combats[this.combats.length - 1] = next;
}
/** The current combat as the readout shows it. Call only while there is one. */
private snapCombat(stage: CombatInfo['stage']): CombatInfo {
const c = this.s.combat!;
const prev = this.combat?.id === c.id ? this.combat : null;
const info = (ref: AnomalyRef): FighterInfo => {
const parts: CorePart[] = [];
const cores = coresOf(this.s, fighterOf(this.s, ref), undefined, parts);
const inPlay = anomaly(this.s, ref).at !== null;
return {
ref,
cores,
parts,
dice: [...(c.dice[refKey(ref)] ?? [])],
health: inPlay ? healthOf(this.s, ref) : 0,
healthLeft: inPlay ? healthLeft(this.s, ref) : 0,
};
};
// Defenders who left keep their last numbers, so the readout still shows who was there.
const gone = (prev?.defenders ?? []).filter((d) => !c.defenders.some((x) => refKey(x) === refKey(d.ref)));
return {
id: c.id,
loc: c.loc,
kind: c.kind,
attacker: info(c.attacker),
defenders: [...c.defenders.map(info), ...gone],
rolled: c.rolled,
ended: c.ended,
stage,
done: false,
logFrom: prev?.logFrom ?? Math.max(0, (this.s.log?.length ?? 1) - 1),
};
}
}

122
app/src/moves.ts Normal file
View file

@ -0,0 +1,122 @@
/**
* Turns the legal actions into moves the UI can show: a label, a cost, a group for the move list,
* and for click-to-act a source (what you pick first) and a target (what you click to play it).
* The UI never builds an Action; it only filters and labels the engine's list.
*/
import { abilitySource, actionCost, actionKey } from '../../sim/src/engine.ts';
import { defOf, nameOf, programLocation, wearerOf } from '../../sim/src/state.ts';
import type { Action, AnomalyRef, GameState, PlayerId } from '../../sim/src/types.ts';
import { describeAction } from './describe.ts';
/**
* Keys for things on screen:
* - `hand:<card name>` a card in your hand
* - `anomaly:<player>:<slot>` an Anomaly token (or its slot in the player panel when it isn't in play)
* - `loc:<id>` a location
* - `gate:<line id>` a gateway between two locations
* - `none` no target: the move is listed on its source's menu
* - `bar` the action bar (End, Pass, choices)
*/
export type Key = string;
export interface Move {
action: Action;
key: string;
label: string;
cost: number;
/** For the move list, e.g. "Place and move", "Hardware: RAM Expansion". */
group: string;
source: Key;
target: Key;
}
export const anomalyKey = (r: AnomalyRef): Key => `anomaly:${r.player}:${r.slot}`;
export const locKey = (loc: string): Key => `loc:${loc}`;
export const gateKey = (line: string): Key => `gate:${line}`;
export const handKey = (name: string): Key => `hand:${name}`;
/** Where a card on the board is: its location, or its wearer. */
function cardSpot(s: GameState, id: number): Key {
const loc = programLocation(s, id);
if (loc) return locKey(loc);
const r = wearerOf(s, id);
if (r) return anomalyKey(r);
return 'none';
}
function sourceAndTarget(s: GameState, a: Action, me: PlayerId): { source: Key; target: Key; group: string } {
const own = (slot: number) => anomalyKey({ player: me, slot });
switch (a.type) {
case 'end':
case 'pass':
case 'choose':
return { source: 'bar', target: 'none', group: 'Turn' };
case 'place':
case 'advance':
case 'attack':
return { source: own(a.slot), target: locKey(a.to), group: a.type === 'attack' ? 'Attack' : a.type === 'advance' ? 'Advance' : 'Place and move' };
case 'recall':
return { source: own(a.slot), target: 'none', group: 'Place and move' };
case 'clearFirewall':
case 'firewall':
return { source: gateKey(a.line), target: 'none', group: 'Firewalls' };
case 'salvage':
return { source: handKey(nameOf(s, a.card)), target: 'none', group: 'Salvage' };
case 'installHardware':
return { source: handKey(nameOf(s, a.card)), target: own(a.slot), group: `Hardware: ${nameOf(s, a.card)}` };
case 'recruit':
return { source: handKey(nameOf(s, a.card)), target: own(a.slot), group: `Recruit: ${nameOf(s, a.card)}` };
case 'buyAnomaly':
return { source: own(a.slot), target: 'none', group: 'Anomalies' };
case 'installProgram':
return { source: handKey(nameOf(s, a.card)), target: locKey(a.at), group: `Program: ${nameOf(s, a.card)}` };
case 'play': {
// Executions target a Server; with no target, the Anomaly or card they name.
const target = a.target ? locKey(a.target) : a.args.ref ? anomalyKey(a.args.ref) : a.args.card !== undefined ? cardSpot(s, a.args.card) : 'none';
return { source: handKey(nameOf(s, a.card)), target, group: `Execution: ${nameOf(s, a.card)}` };
}
case 'activate': {
const src = abilitySource(s, a.card, a.name);
const source = src?.ref ? anomalyKey(src.ref) : src?.at ? locKey(src.at) : 'none';
const target = a.args.to ? locKey(a.args.to) : a.args.ref ? anomalyKey(a.args.ref) : a.args.card !== undefined ? cardSpot(s, a.args.card) : 'none';
const name = src?.kind === 'anomaly' ? defOf(s, a.card).ability?.name ?? a.name : a.name;
// A target that is the source itself (a card on the same Anomaly) is listed on the source's menu.
return { source, target: target === source ? 'none' : target, group: `Ability: ${name}` };
}
}
}
/** The legal actions as moves, with duplicate labels (interchangeable copies of a card) dropped. */
export function movesOf(s: GameState, legal: Action[], me: PlayerId): Move[] {
const seen = new Set<string>();
const out: Move[] = [];
for (const a of legal) {
const label = describeAction(s, a);
if (seen.has(label)) continue;
seen.add(label);
out.push({ action: a, key: actionKey(a), label, cost: actionCost(s, a), ...sourceAndTarget(s, a, me) });
}
return out;
}
const GROUP_ORDER = ['Turn', 'Place and move', 'Advance', 'Attack', 'Hardware', 'Program', 'Execution', 'Ability', 'Recruit', 'Anomalies', 'Firewalls', 'Salvage'];
/** Moves grouped for the move list, in a steady order. */
export function groupMoves(moves: Move[]): [string, Move[]][] {
const groups = new Map<string, Move[]>();
for (const m of moves) {
if (!groups.has(m.group)) groups.set(m.group, []);
groups.get(m.group)!.push(m);
}
const rank = (g: string) => {
const i = GROUP_ORDER.indexOf(g.split(':')[0]);
return i < 0 ? GROUP_ORDER.length : i;
};
return [...groups.entries()].sort((a, b) => rank(a[0]) - rank(b[0]) || a[0].localeCompare(b[0]));
}
/** An Anomaly ref from an `anomaly:` key. */
export function refOfKey(key: Key): AnomalyRef | null {
const m = key.match(/^anomaly:(\d):(\d)$/);
return m ? { player: Number(m[1]) as PlayerId, slot: Number(m[2]) } : null;
}

94
app/src/render-card.ts Normal file
View file

@ -0,0 +1,94 @@
/**
* Renders cards from the Cider templates in decks/files-deck-1, the way Cider does: each template's
* HTML and CSS go through Handlebars with `{ card, assets }`, where `card` is the CSV row with
* kebab-case keys and `assets` maps image names to URLs. Cards are drawn inside a shadow root, so
* every template's CSS stays scoped to its own cards.
*/
import Handlebars from 'handlebars';
import { rows } from './cards.ts';
const templateFiles = import.meta.glob('../../decks/files-deck-1/*.{html,css}', { query: '?raw', import: 'default', eager: true }) as Record<string, string>;
const assetFiles = import.meta.glob('../../assets/*.{jpeg,jpg,png,svg,webp,gif}', { query: '?url', import: 'default', eager: true }) as Record<string, string>;
/** Cider's kebab case: "Expansion Slots" → "expansion-slots". */
export const kebab = (s: string): string =>
String(s)
.replace(/([a-z0-9])([A-Z])/g, '$1-$2')
.replace(/[\s_]+/g, '-')
.toLowerCase();
const baseName = (path: string) => path.split('/').pop()!.replace(/\.[^.]+$/, '');
/** A stand-in for cards with no art yet. Parentheses and quotes are escaped, so it fits in an unquoted url(). */
const PLACEHOLDER =
'data:image/svg+xml,' +
encodeURIComponent(
"<svg xmlns='http://www.w3.org/2000/svg' width='600' height='400' viewBox='0 0 600 400'>" +
"<rect width='600' height='400' fill='#0b1017'/>" +
"<g stroke='#1f2a36' stroke-width='2'><path d='M0 0L600 400M600 0L0 400'/></g>" +
"<text x='300' y='215' fill='#3d4c5c' font-family='monospace' font-size='44' text-anchor='middle'>NO ART YET</text></svg>",
).replace(/[()']/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
const assets: Record<string, string> = { placeholder: PLACEHOLDER };
for (const [path, url] of Object.entries(assetFiles)) assets[kebab(baseName(path))] = url;
const hb = Handlebars.create();
hb.registerHelper('index', (obj: Record<string, unknown> | undefined, key: string | undefined) => {
if (!obj || !key) return '';
const value = String(key).split('.').reduce<unknown>((o, part) => (o as Record<string, unknown> | undefined)?.[kebab(part)], obj);
// A SafeString, or Handlebars escapes "=" and data URLs break.
return new hb.SafeString(typeof value === 'string' ? value : '');
});
hb.registerHelper('eq', (a: unknown, b: unknown) => a == b);
hb.registerHelper('and', (a: unknown, b: unknown) => a && b);
hb.registerHelper('or', (a: unknown, b: unknown) => a || b);
hb.registerHelper('gt', (a: number, b: number) => a > b);
hb.registerHelper('gte', (a: number, b: number) => a >= b);
hb.registerHelper('lt', (a: number, b: number) => a < b);
hb.registerHelper('lte', (a: number, b: number) => a <= b);
hb.registerHelper('concat', (a: unknown, b: unknown) => `${a}${b}`);
hb.registerHelper('lowercase', (a: unknown) => String(a).toLowerCase());
hb.registerHelper('uppercase', (a: unknown) => String(a).toUpperCase());
hb.registerHelper('kebabcase', (a: unknown) => kebab(String(a)));
type Template = ReturnType<typeof hb.compile>;
const compiled = new Map<string, Template>();
function template(file: string): Template | null {
if (!compiled.has(file)) {
const src = Object.entries(templateFiles).find(([path]) => path.endsWith(`/${file}`))?.[1];
if (src === undefined) return null;
compiled.set(file, hb.compile(src));
}
return compiled.get(file)!;
}
export const CARD_W = 750;
export const CARD_H = 1050;
const cache = new Map<string, string | null>();
/** The card's markup (a style block and the card), or null if it has no row or template. */
export function cardMarkup(name: string): string | null {
if (cache.has(name)) return cache.get(name)!;
const row = rows.get(name);
let out: string | null = null;
if (row) {
const file = kebab(row['Front Template'] ?? '');
const html = template(`${file}.html`);
const css = template(`${file}.css`);
if (html) {
const card: Record<string, string> = {};
for (const [k, v] of Object.entries(row)) card[kebab(k)] = v;
if (!card.image || !assets[kebab(card.image)]) card.image = 'placeholder';
const ctx = { card, assets };
try {
const style = css ? css(ctx).replace(/!important/g, '') : '';
out = `<style>${style}</style>${html(ctx)}`;
} catch (e) {
console.warn(`Couldn't render ${name}:`, e);
}
}
}
cache.set(name, out);
return out;
}

55
app/src/replay.ts Normal file
View file

@ -0,0 +1,55 @@
/**
* Replays a game record move by move. The engine is deterministic, so the seed, decks, rules and
* action list rebuild every state exactly. Checkpoints keep seeking fast.
*/
import type { CardPool } from '../../sim/src/cards.ts';
import { actionKey, applyAction, createGame, legalActions } from '../../sim/src/engine.ts';
import type { GameState } from '../../sim/src/types.ts';
import { rulesFrom, type GameRecord } from './match.ts';
const EVERY = 25;
export class Replay {
readonly record: GameRecord;
/** Moves that replayed; less than the record's length if it stopped fitting the engine. */
readonly length: number;
/** Why the replay stopped early, if it did. */
readonly error: string | null = null;
private checkpoints: GameState[] = [];
constructor(pool: CardPool, record: GameRecord) {
this.record = record;
const rules = rulesFrom(record.setup.rules);
const s = createGame({ pool, decks: record.setup.decks, seed: record.setup.seed, rules, log: true });
this.checkpoints.push(structuredClone(s));
let n = 0;
for (const key of record.actions) {
const a = legalActions(s).find((x) => actionKey(x) === key);
if (!a) {
this.error = `Move ${n + 1} (${key}) isn't legal here. The cards or rules may have changed since the game was played.`;
break;
}
applyAction(s, a);
n++;
if (n % EVERY === 0) this.checkpoints.push(structuredClone(s));
}
this.length = n;
}
/** The state after the first `n` moves. A fresh object each time. */
stateAt(n: number): GameState {
n = Math.max(0, Math.min(this.length, n));
const base = Math.floor(n / EVERY);
const s = structuredClone(this.checkpoints[base]);
for (let i = base * EVERY; i < n; i++) {
const key = this.record.actions[i];
applyAction(s, legalActions(s).find((x) => actionKey(x) === key)!);
}
return s;
}
/** The record cut after `n` moves, for playing on from there. */
cut(n: number): GameRecord {
return { ...this.record, actions: this.record.actions.slice(0, n) };
}
}

96
app/src/storage.ts Normal file
View file

@ -0,0 +1,96 @@
/** Settings and the saved game, in local storage. */
import type { DeckChoice } from './decks.ts';
import type { GameRecord, Stops } from './match.ts';
export interface Settings {
/** End your steps for you when End and Salvage are the only moves. */
autoSkip: boolean;
stops: Stops;
/** Milliseconds between bot moves. */
botDelay: number;
/** Roll the dice on screen before showing them. */
diceAnimation: boolean;
/** Show your chance to win a roll before you attack. */
odds: boolean;
/** Draw cards from the Cider templates; off shows plain text cards. */
realCards: boolean;
/** Run the rule invariants after every move and show any errors. */
checkInvariants: boolean;
}
export const DEFAULT_SETTINGS: Settings = {
autoSkip: true,
stops: 'combat',
botDelay: 400,
diceAnimation: true,
odds: true,
realCards: true,
checkInvariants: false,
};
/** What the start screen last used. */
export interface SetupPrefs {
side: 'south' | 'north' | 'random';
seed: string;
decks: [DeckChoice, DeckChoice];
rules: string;
/** Bot style, a key of BOT_STYLES. */
bot: string;
playtest: boolean;
}
export const DEFAULT_SETUP: SetupPrefs = {
side: 'south',
seed: '',
decks: [{ kind: 'random' }, { kind: 'random' }],
rules: '',
bot: 'greedy',
playtest: false,
};
export interface SavedGame {
record: GameRecord;
playtest: boolean;
savedAt: number;
}
const KEYS = { settings: 'files-tcg.settings', setup: 'files-tcg.setup', save: 'files-tcg.save' };
function read<T>(key: string, fallback: T): T {
try {
const raw = localStorage.getItem(key);
return raw ? { ...fallback, ...JSON.parse(raw) } : fallback;
} catch {
return fallback;
}
}
function write(key: string, value: unknown): void {
try {
if (value === null) localStorage.removeItem(key);
else localStorage.setItem(key, JSON.stringify(value));
} catch (e) {
console.warn(`Couldn't save ${key}:`, e);
}
}
export const loadSettings = (): Settings => read(KEYS.settings, DEFAULT_SETTINGS);
export const saveSettings = (s: Settings): void => write(KEYS.settings, s);
export const loadSetup = (): SetupPrefs => read(KEYS.setup, DEFAULT_SETUP);
export const saveSetup = (s: SetupPrefs): void => write(KEYS.setup, s);
export function loadGame(): SavedGame | null {
const g = read<SavedGame | null>(KEYS.save, null);
return g && g.record?.version === 1 ? g : null;
}
export const saveGame = (g: SavedGame | null): void => write(KEYS.save, g);
/** Downloads text as a file. */
export function download(filename: string, text: string): void {
const url = URL.createObjectURL(new Blob([text], { type: 'application/json' }));
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}

1321
app/src/styles.css Normal file

File diff suppressed because it is too large Load diff

257
app/src/ui/board.tsx Normal file
View file

@ -0,0 +1,257 @@
/** The board: locations, lines and gateways, and the Anomalies standing on them. */
import { anomalyCores } from '../../../sim/src/engine.ts';
import { isStart, levelFor, START_LOC, type LocId } from '../../../sim/src/map.ts';
import { capacity, healthLeft, healthOf, programActive } from '../../../sim/src/query.ts';
import { activeMods, anomaly, infectionOf, isDisabledAnomaly, isRooted, refsInPlay } from '../../../sim/src/state.ts';
import type { AnomalyRef, GameState, PlayerId } from '../../../sim/src/types.ts';
import { LOC_H, LOC_W, type BoardLayout, type Point } from '../layout.ts';
import { anomalyKey, gateKey, locKey, type Key } from '../moves.ts';
import { zoomable } from './cards.tsx';
/** How something on the board is highlighted. */
export type Mark = 'source' | 'selected' | 'target' | 'attack' | 'respond' | 'fight';
/** A short animation: a capture, damage, a Firewall going up. */
export interface Effect {
id: number;
kind: 'capture' | 'damage' | 'firewall' | 'destroyed';
loc?: LocId;
line?: string;
ref?: AnomalyRef;
player?: PlayerId;
amount?: number;
}
interface Props {
view: GameState;
me: PlayerId;
layout: BoardLayout;
marks: Map<Key, Mark>;
effects: Effect[];
onPick(key: Key, e: MouseEvent): void;
onHover(key: Key | null): void;
}
const TOKEN_R = 19;
/** Hover handlers that report the hover and also show `card` in the zoom. */
function hoverProps(onHover: (on: boolean) => void, card: string | null) {
const z = zoomable(card, 700);
return {
onMouseEnter: (e: MouseEvent) => {
onHover(true);
z.onMouseEnter?.(e);
},
onMouseMove: z.onMouseMove,
onMouseLeave: (e: MouseEvent) => {
onHover(false);
z.onMouseLeave?.(e);
},
onContextMenu: z.onContextMenu,
};
}
/** Where each Anomaly token sits: on the bottom edge of its location, side by side. */
function tokenSpots(view: GameState, layout: BoardLayout): Map<string, Point> {
const out = new Map<string, Point>();
for (const p of [0, 1] as const) {
const byLoc = new Map<LocId, AnomalyRef[]>();
for (const r of refsInPlay(view, p)) {
const at = anomaly(view, r).at!;
if (!byLoc.has(at)) byLoc.set(at, []);
byLoc.get(at)!.push(r);
}
for (const [loc, refs] of byLoc) {
const c = layout.at[loc];
refs.forEach((r, i) => out.set(anomalyKey(r), { x: c.x + (i - (refs.length - 1) / 2) * (TOKEN_R * 2 + 6), y: c.y + LOC_H / 2 }));
}
}
return out;
}
export function Board({ view, me, layout, marks, effects, onPick, onHover }: Props) {
const spots = tokenSpots(view, layout);
const hover = (key: Key) => (on: boolean) => onHover(on ? key : null);
const pick = (key: Key) => (e: MouseEvent) => {
e.stopPropagation();
onPick(key, e);
};
return (
<svg class="board" viewBox={`0 0 ${layout.width} ${layout.height}`} preserveAspectRatio="xMidYMid meet" onClick={(e) => onPick('none', e)}>
<defs>
<pattern id="pat-0" width="10" height="10" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
<rect width="4" height="10" fill="rgba(255,255,255,0.10)" />
</pattern>
<pattern id="pat-1" width="10" height="10" patternUnits="userSpaceOnUse">
<circle cx="5" cy="5" r="1.8" fill="rgba(255,255,255,0.14)" />
</pattern>
<filter id="glow" x="-50%" y="-50%" width="200%" height="200%">
<feGaussianBlur stdDeviation="4" result="b" />
<feMerge>
<feMergeNode in="b" />
<feMergeNode in="SourceGraphic" />
</feMerge>
</filter>
</defs>
{layout.lines.map((line) => {
const a = layout.at[line.a];
const b = layout.at[line.b];
const level = view.firewalls[line.id] ?? 0;
return <line key={line.id} class={`link ${level ? 'walled' : ''}`} x1={a.x} y1={a.y} x2={b.x} y2={b.y} />;
})}
{Object.keys(layout.at).map((loc) => (
<Location key={loc} view={view} me={me} loc={loc} at={layout.at[loc]} mark={marks.get(locKey(loc))} onClick={pick(locKey(loc))} onHover={hover(locKey(loc))} />
))}
{layout.lines.filter((l) => l.gateway).map((line) => {
const a = layout.at[line.a];
const b = layout.at[line.b];
const level = view.firewalls[line.id] ?? 0;
const mark = marks.get(gateKey(line.id));
if (!level && !mark) return null;
const x = (a.x + b.x) / 2;
const y = (a.y + b.y) / 2;
return (
<g key={line.id} class={`gate ${level ? `fw fw-${level}` : 'open'} ${mark ? `mark-${mark}` : ''}`} transform={`translate(${x},${y})`} onClick={pick(gateKey(line.id))} {...hoverProps(hover(gateKey(line.id)), null)}>
<title>{level ? `Lv ${level} Firewall on ${line.a}–${line.b}` : `Gateway ${line.a}–${line.b}: no Firewall`}</title>
<rect x="-11" y="-11" width="22" height="22" transform="rotate(45)" />
{level > 0 && <text y="5">{level}</text>}
</g>
);
})}
{[0, 1].flatMap((p) =>
refsInPlay(view, p as PlayerId).map((r) => {
const key = anomalyKey(r);
return <Token key={key} view={view} r={r} at={spots.get(key)!} mark={marks.get(key)} onClick={pick(key)} onHover={hover(key)} />;
}),
)}
{effects.map((e) => <EffectView key={e.id} e={e} layout={layout} spots={spots} />)}
</svg>
);
}
function Location({ view, me, loc, at, mark, onClick, onHover }: {
view: GameState;
me: PlayerId;
loc: LocId;
at: Point;
mark?: Mark;
onClick(e: MouseEvent): void;
onHover(on: boolean): void;
}) {
const L = view.locations[loc];
const server = L.server !== null ? view.cards[L.server].name : null;
const start = isStart(loc);
const level = start ? null : levelFor(me, loc);
const x = at.x - LOC_W / 2;
const y = at.y - LOC_H / 2;
const owner = L.owner === null ? 'none' : String(L.owner);
const room = L.owner === null ? 0 : capacity(view, loc);
return (
<g class={`loc owner-${owner} ${start ? 'start' : ''} ${mark ? `mark-${mark}` : ''}`} onClick={onClick} {...hoverProps(onHover, server)}>
<rect class="loc-bg" x={x} y={y} width={LOC_W} height={LOC_H} rx="9" />
{L.owner !== null && <rect class="loc-pat" x={x} y={y} width={LOC_W} height={LOC_H} rx="9" fill={`url(#pat-${L.owner})`} />}
<rect class="loc-edge" x={x} y={y} width={LOC_W} height={LOC_H} rx="9" />
<text class="loc-id" x={x + 8} y={y + 17}>
{loc}
{room > 1 && (
<tspan class="loc-room" dx="5">
×{room}
<title>Holds {room} of its owner’s Anomalies</title>
</tspan>
)}
</text>
<text class="loc-lv" x={x + LOC_W - 8} y={y + 17}>
{start ? (loc === START_LOC[me] ? 'YOUR START' : 'START') : `Lv ${level}`}
</text>
<text class="loc-server" x={at.x} y={y + 38}>{server ? shorten(server, 19) : L.owner === null ? 'open' : 'no Server'}</text>
{L.programs.length > 0 && (
<g class="progs">
{L.programs.map((id, i) => (
<rect key={id} class={`prog ${programActive(view, id) ? '' : 'off'}`} x={x + 8 + i * 13} y={y + LOC_H - 16} width="10" height="10" rx="2" {...zoomable(view.cards[id].name, 250)}>
<title>{view.cards[id].name}{programActive(view, id) ? '' : ' (disabled)'}</title>
</rect>
))}
</g>
)}
</g>
);
}
const shorten = (s: string, n: number) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
function Token({ view, r, at, mark, onClick, onHover }: {
view: GameState;
r: AnomalyRef;
at: Point;
mark?: Mark;
onClick(e: MouseEvent): void;
onHover(on: boolean): void;
}) {
const av = anomaly(view, r);
const name = av.card >= 0 ? view.cards[av.card].name : null;
const copy = r.slot > 4;
const cores = anomalyCores(view, r.player, r.slot, 'defend');
const hp = healthOf(view, r);
const left = healthLeft(view, r);
const frac = Math.max(0, Math.min(1, left / hp));
const circ = 2 * Math.PI * (TOKEN_R + 3);
const mods = activeMods(view, av).reduce((t, m) => t + m.cores, 0);
const icons: [string, string][] = [];
const infection = infectionOf(av);
if (infection) icons.push(['☣', `${infection} Infection counter${infection === 1 ? '' : 's'}${av.permanentInfection ? ` (${av.permanentInfection} permanent)` : ''}`]);
if (av.bugs) icons.push(['✱', `${av.bugs} Bug counter${av.bugs === 1 ? '' : 's'}`]);
if (isDisabledAnomaly(view, r)) icons.push(['⏻', 'Disabled: defends, but can’t move, attack or use its Ability']);
if (isRooted(view, r)) icons.push(['⚓', 'Rooted: can’t move or retreat']);
if (mods) icons.push([mods > 0 ? `+${mods}` : `${mods}`, `Temporary Cores: ${activeMods(view, av).map((m) => `${m.cores > 0 ? '+' : ''}${m.cores} ${m.source}`).join(', ')}`]);
if (av.hardware.length) icons.push([`⚙${av.hardware.length}`, `Hardware: ${av.hardware.map((h) => view.cards[h].name).join(', ')}`]);
const title = `${copy ? 'Copy of ' : ''}Anomaly ${copy ? r.slot - 4 : r.slot}: ${name ?? '?'} — ${cores} Cores, ${left}/${hp} Health`;
return (
<g class={`token owner-${r.player} ${copy ? 'copy' : ''} ${mark ? `mark-${mark}` : ''}`} transform={`translate(${at.x},${at.y})`} onClick={onClick} {...hoverProps(onHover, name)}>
<title>{title}</title>
<circle class="hp-track" r={TOKEN_R + 3} />
<circle class="hp-ring" r={TOKEN_R + 3} stroke-dasharray={`${circ * frac} ${circ}`} transform="rotate(-90)" />
<circle class="token-body" r={TOKEN_R} />
<text class="token-slot" y="6">{copy ? `${r.slot - 4}′` : r.slot}</text>
<g transform={`translate(${TOKEN_R - 2},${-TOKEN_R + 2})`}>
<circle class="core-badge" r="9" />
<text class="core-text" y="4">{cores}</text>
</g>
{icons.length > 0 && (
<text class="token-icons" y={TOKEN_R + 17}>
{icons.map(([glyph, tip], i) => (
<tspan key={i} dx={i ? 3 : 0}>
{glyph}
<title>{tip}</title>
</tspan>
))}
</text>
)}
</g>
);
}
function EffectView({ e, layout, spots }: { e: Effect; layout: BoardLayout; spots: Map<string, Point> }) {
if (e.kind === 'firewall' && e.line) {
const [a, b] = e.line.split('-');
const pa = layout.at[a];
const pb = layout.at[b];
if (!pa || !pb) return null;
return <circle class="fx fx-firewall" cx={(pa.x + pb.x) / 2} cy={(pa.y + pb.y) / 2} r="14" />;
}
const at = (e.ref && spots.get(anomalyKey(e.ref))) || (e.loc ? layout.at[e.loc] : null);
if (!at) return null;
if (e.kind === 'capture') return <rect class={`fx fx-capture owner-${e.player}`} x={at.x - LOC_W / 2} y={at.y - LOC_H / 2} width={LOC_W} height={LOC_H} rx="9" />;
if (e.kind === 'damage' || e.kind === 'destroyed') {
return (
<text class={`fx fx-damage ${e.kind === 'destroyed' ? 'dead' : ''}`} x={at.x} y={at.y - TOKEN_R - 8}>
{e.kind === 'destroyed' ? `−${e.amount} ✖` : `−${e.amount}`}
</text>
);
}
return null;
}

132
app/src/ui/cards.tsx Normal file
View file

@ -0,0 +1,132 @@
/** Cards: the Cider template render, a plain text card, and the hover zoom. */
import { useEffect, useLayoutEffect, useRef, useState } from 'preact/hooks';
import { pool } from '../cards.ts';
import { CARD_H, CARD_W, cardMarkup } from '../render-card.ts';
// ---------------------------------------------------------------------------------------------
// Zoom: one card shown large near the pointer while you hover a card or its name. Right-click
// pins it until you close it.
interface ZoomState {
name: string | null;
x: number;
y: number;
pinned: boolean;
}
let zoom: ZoomState = { name: null, x: 0, y: 0, pinned: false };
const zoomListeners = new Set<() => void>();
const setZoom = (z: Partial<ZoomState>) => {
zoom = { ...zoom, ...z };
for (const fn of zoomListeners) fn();
};
export interface ZoomHandlers {
onMouseEnter?: (e: MouseEvent) => void;
onMouseMove?: (e: MouseEvent) => void;
onMouseLeave?: (e: MouseEvent) => void;
onContextMenu?: (e: MouseEvent) => void;
}
let pending: ReturnType<typeof setTimeout> | undefined;
/**
* Handlers that make any element (HTML or SVG) show `name` in the zoom on hover and pin it on
* right-click. `delay` waits before showing it, for things you mostly point at to click.
*/
export function zoomable(name: string | null | undefined, delay = 0): ZoomHandlers {
if (!name) return {};
return {
onMouseEnter: (e) => {
if (zoom.pinned) return;
clearTimeout(pending);
const at = { x: e.clientX, y: e.clientY };
if (delay) pending = setTimeout(() => setZoom({ name, ...at }), delay);
else setZoom({ name, ...at });
},
onMouseMove: (e) => !zoom.pinned && zoom.name === name && setZoom({ x: e.clientX, y: e.clientY }),
onMouseLeave: () => {
clearTimeout(pending);
if (!zoom.pinned) setZoom({ name: null });
},
onContextMenu: (e) => {
e.preventDefault();
setZoom({ name, x: e.clientX, y: e.clientY, pinned: true });
},
};
}
export const unpinZoom = () => setZoom({ name: null, pinned: false });
const ZOOM_W = 360;
export function CardZoom({ real }: { real: boolean }) {
const [, setTick] = useState(0);
useEffect(() => {
const fn = () => setTick((t) => t + 1);
zoomListeners.add(fn);
return () => void zoomListeners.delete(fn);
}, []);
if (!zoom.name) return null;
const h = (ZOOM_W * CARD_H) / CARD_W;
// Beside the pointer, kept on screen.
const left = zoom.x + 24 + ZOOM_W < innerWidth ? zoom.x + 24 : Math.max(8, zoom.x - 24 - ZOOM_W);
const top = Math.min(Math.max(8, zoom.y - h / 2), innerHeight - h - 8);
return (
<div class={`zoom ${zoom.pinned ? 'pinned' : ''}`} style={{ left: `${left}px`, top: `${top}px`, width: `${ZOOM_W}px` }}>
{real ? <CardView name={zoom.name} width={ZOOM_W} /> : <TextCard name={zoom.name} large />}
{zoom.pinned && (
<button class="zoom-close" onClick={unpinZoom} title="Close (Esc)">
×
</button>
)}
</div>
);
}
// ---------------------------------------------------------------------------------------------
/** A card drawn from its Cider template, scaled to `width` pixels. */
export function CardView({ name, width }: { name: string; width: number }) {
const host = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
const el = host.current;
if (!el) return;
const root = el.shadowRoot ?? el.attachShadow({ mode: 'open' });
const markup = cardMarkup(name);
root.innerHTML = markup
? `<div style="width:${CARD_W}px;height:${CARD_H}px;transform:scale(${width / CARD_W});transform-origin:0 0">${markup}</div>`
: `<div style="font:12px monospace;color:#8b949e;padding:8px">${name}</div>`;
}, [name, width]);
return <div class="card-view" ref={host} style={{ width: `${width}px`, height: `${(width * CARD_H) / CARD_W}px` }} />;
}
const KIND_LABEL = { anomaly: 'Anomaly', server: 'Server', program: 'Program', hardware: 'Hardware', execution: 'Execution' } as const;
const TYPE_LABEL: Record<string, string> = { V: 'Virus', B: 'Bug', G: 'Glitch', P: 'Patch' };
/** A plain text card: name, kind, type, Gb and text. */
export function TextCard({ name, large = false }: { name: string; large?: boolean }) {
const def = pool.byName.get(name);
if (!def) return <div class="text-card">{name}</div>;
const type = TYPE_LABEL[def.type];
return (
<div class={`text-card kind-${def.kind} ${def.type ? `type-${def.type.toLowerCase()}` : ''} ${large ? 'large' : ''}`}>
<div class="tc-head">
<span class="tc-name">{def.name}</span>
{def.bandwidth > 0 && <span class="tc-gb">{def.bandwidth} Gb</span>}
</div>
<div class="tc-kind">
{KIND_LABEL[def.kind]}
{type ? ` · ${type}` : ''}
{def.kind === 'anomaly' ? ` · ${def.cores} Cores · ${def.health} Health · ${def.slots} Slots` : ''}
</div>
{def.ability && (
<div class="tc-ability">
<b>{def.ability.name}</b>
{def.ability.cost ? ` (${def.ability.cost} Gb)` : ''}: {def.ability.text}
</div>
)}
{def.kind !== 'anomaly' && <div class="tc-text">{def.text}</div>}
</div>
);
}

629
app/src/ui/game.tsx Normal file
View file

@ -0,0 +1,629 @@
/**
* The game screen. You act by picking a source (a card in hand, an Anomaly, a gateway, one of your
* locations) and then one of its highlighted targets; the move list has everything else.
*/
import { useCallback, useEffect, useMemo, useRef, useState } from 'preact/hooks';
import { openWindow } from '../../../sim/src/engine.ts';
import { roundOf } from '../../../sim/src/state.ts';
import { PLAYER_NAMES, STAT_KEYS, type GameState, type LogLine, type PlayerId } from '../../../sim/src/types.ts';
import { lineName, refName } from '../describe.ts';
import { boardLayout } from '../layout.ts';
import type { Match } from '../match.ts';
import { movesOf, refOfKey, type Key, type Move } from '../moves.ts';
import { download, type Settings } from '../storage.ts';
import { Board, type Effect, type Mark } from './board.tsx';
import { CardZoom, TextCard, unpinZoom, zoomable } from './cards.tsx';
import { Hand, PlayerPanel } from './panels.tsx';
import { attackPreview, CombatPanel, InfoPanel, LogPanel, MovesList } from './side.tsx';
interface Props {
match: Match;
settings: Settings;
playtest: boolean;
onSettings(s: Settings): void;
onNewGame(): void;
onRematch(): void;
onReplay(): void;
}
/** Re-renders when the match changes. */
function useMatch(match: Match): number {
const [version, setVersion] = useState(match.version);
useEffect(() => match.subscribe(() => setVersion(match.version)), [match]);
return version;
}
const STEPS = [
['deploy', 'Deploy'],
['play', 'Play'],
['attack', 'Attack'],
['playAgain', 'Play again'],
] as const;
type Tab = 'combat' | 'info' | 'log' | 'moves';
let effectSeq = 0;
export function GameScreen({ match, settings, playtest, onSettings, onNewGame, onRematch, onReplay }: Props) {
const version = useMatch(match);
const view = match.view();
const me = match.human;
const bot = match.botSide;
const layout = useMemo(() => boardLayout(me), [me]);
const legal = match.legal();
const moves = useMemo(() => movesOf(view, legal, me), [version]);
const lines = useMemo(() => match.logLines(), [version]);
const [selected, setSelected] = useState<Key | null>(null);
const [hover, setHover] = useState<Key | null>(null);
const [focus, setFocus] = useState<Key | null>(null);
const [popover, setPopover] = useState<{ x: number; y: number; moves: Move[] } | null>(null);
const [tab, setTab] = useState<Tab>('log');
const [paused, setPaused] = useState(false);
const [dialog, setDialog] = useState<'settings' | { pile: PlayerId } | null>(null);
const [effects, setEffects] = useState<Effect[]>([]);
const [overClosed, setOverClosed] = useState(false);
const window_ = openWindow(view);
const myTurn = match.humanToAct();
const inWindow = myTurn && window_ !== null && !view.choice;
const myChoice = myTurn && view.choice?.player === me;
// Drop a selection that no longer has moves.
useEffect(() => {
if (selected && !moves.some((m) => m.source === selected)) setSelected(null);
setPopover(null);
}, [version]);
// The combat tab comes up when a combat starts.
const combatId = match.combat?.id ?? 0;
useEffect(() => {
if (combatId) setTab('combat');
}, [combatId]);
// Animations from new log lines.
const seen = useRef(lines.length);
useEffect(() => {
if (lines.length < seen.current) seen.current = lines.length; // undo
const fresh = lines.slice(seen.current);
seen.current = lines.length;
const out: Effect[] = [];
for (const l of fresh) {
if (l.tag === 'capture' && l.loc && l.text.includes(' captures ')) out.push({ id: ++effectSeq, kind: 'capture', loc: l.loc, player: l.player });
else if (l.ref && l.amount) out.push({ id: ++effectSeq, kind: l.text.includes('destroyed') ? 'destroyed' : 'damage', ref: l.ref, loc: l.loc, amount: l.amount });
else if (l.tag === 'firewall') {
const m = l.text.match(/on ([A-Z0-9]+-[A-Z0-9]+)/);
if (m) out.push({ id: ++effectSeq, kind: 'firewall', line: m[1] });
}
}
if (!out.length) return;
setEffects((e) => [...e, ...out]);
const ids = new Set(out.map((e) => e.id));
setTimeout(() => setEffects((e) => e.filter((x) => !ids.has(x.id))), 1600);
}, [lines]);
// The bot moves one step at a time.
useEffect(() => {
if (paused || match.over || !match.botToAct()) return;
const t = setTimeout(() => match.botStep(), settings.botDelay);
return () => clearTimeout(t);
}, [version, paused, settings.botDelay]);
const play = useCallback(
(m: Move) => {
setSelected(null);
setPopover(null);
if (match.humanToAct() && match.legal().some((a) => a === m.action)) match.act(m.action);
},
[match],
);
const primary = moves.find((m) => m.action.type === 'pass') ?? moves.find((m) => m.action.type === 'end');
// Keyboard: Space ends the step or passes, Enter ends the command, Z undoes, Esc cancels.
// Holding Shift stops at the next response window whatever the stops setting says.
useEffect(() => {
const down = (e: KeyboardEvent) => {
if ((e.target as HTMLElement).closest('input, textarea, select')) return;
if (e.key === 'Shift') {
match.holdStop = true;
return;
}
// A focused button would also take Space or Enter as a click.
if ((e.key === ' ' || e.key === 'Enter') && e.target instanceof HTMLButtonElement) e.target.blur();
if (e.key === 'Escape') {
setSelected(null);
setPopover(null);
setDialog(null);
unpinZoom();
} else if (e.key === ' ') {
e.preventDefault();
if (primary && !view.choice) play(primary);
} else if (e.key === 'Enter') {
e.preventDefault();
match.endCommand();
} else if (e.key === 'z' || e.key === 'Z') {
if (match.canUndo) match.undo();
}
};
const up = (e: KeyboardEvent) => {
if (e.key !== 'Shift') return;
match.holdStop = false;
match.poke();
};
addEventListener('keydown', down);
addEventListener('keyup', up);
return () => {
removeEventListener('keydown', down);
removeEventListener('keyup', up);
};
}, [match, primary, play, view]);
// Highlights.
const marks = new Map<Key, Mark>();
if (match.combat && !match.combat.done) marks.set(`loc:${match.combat.loc}`, 'fight');
if (!myChoice) {
// Salvage is always there, so only other moves make a card glow.
for (const m of moves) if (m.source !== 'bar' && m.source !== 'none' && m.action.type !== 'salvage') marks.set(m.source, inWindow ? 'respond' : 'source');
if (selected) {
marks.set(selected, 'selected');
for (const m of moves) if (m.source === selected && m.target !== 'none') marks.set(m.target, m.action.type === 'attack' ? 'attack' : 'target');
}
}
const pick = (key: Key, e: MouseEvent) => {
if (popover) {
setPopover(null);
return;
}
if (key !== 'none') setFocus(key);
if (myChoice) return;
if (selected) {
const hits = moves.filter((m) => m.source === selected && m.target === key);
if (hits.length === 1) return play(hits[0]);
if (hits.length > 1) return setPopover({ x: e.clientX, y: e.clientY, moves: hits });
if (key === selected) return setSelected(null);
}
setSelected(moves.some((m) => m.source === key) ? key : null);
};
const onHover = (key: Key | null) => {
setHover(key);
if (key) setFocus(key);
};
const responseSources = [...Map.groupBy(inWindow ? moves.filter((m) => m.action.type !== 'pass' && m.action.type !== 'salvage') : [], (m) => m.source)];
const sourceMoves = selected ? moves.filter((m) => m.source === selected) : [];
const untargeted = sourceMoves.filter((m) => m.target === 'none');
const targeted = sourceMoves.filter((m) => m.target !== 'none');
const preview =
settings.odds && selected && hover
? (() => {
const attack = targeted.find((m) => m.target === hover && m.action.type === 'attack');
if (!attack || attack.action.type !== 'attack') return null;
return attackPreview(view, me, attack.action.slot, attack.action.to);
})()
: null;
const status = statusLine(view, match, me);
const stackItems = view.stack;
return (
<div class="game">
<header class="topbar">
<span class="brand">FILES TCG</span>
<span class="status">{status}</span>
{stackItems.length > 0 && (
<span class="stack" title="Waiting to resolve, last in first out">
Waiting: {stackItems.map((it) => `${it.name.replace(/^Execute: /, '')} (${PLAYER_NAMES[it.player]}${it.target ? ` → ${it.target}` : ''})`).join(' ← ')}
</span>
)}
<span class="spacer" />
<span class="bot-controls" title="Bot speed">
<label>
Bot
<input type="range" min="0" max="1000" step="50" value={settings.botDelay} onInput={(e) => onSettings({ ...settings, botDelay: Number(e.currentTarget.value) })} />
<span class="muted">{(settings.botDelay / 1000).toFixed(2)}s</span>
</label>
<button onClick={() => setPaused(!paused)} title="Pause or resume the bot">
{paused ? '▶' : '❚❚'}
</button>
<button disabled={!paused || !match.botToAct()} onClick={() => match.botStep()} title="One bot move">
⏭
</button>
</span>
<button onClick={() => setDialog('settings')}>⚙ Settings</button>
<button onClick={onNewGame}>New game</button>
</header>
<aside class="left">
<PlayerPanel view={view} p={bot} me={me} marks={marks} onPick={pick} onPiles={(p) => setDialog({ pile: p })} active={match.decider() === bot} />
<PlayerPanel view={view} p={me} me={me} marks={marks} onPick={pick} onPiles={(p) => setDialog({ pile: p })} active={myTurn} />
</aside>
<main class="center">
<Banner view={view} match={match} lines={lines} inWindow={inWindow} myTurn={myTurn} paused={paused} />
<Board view={view} me={me} layout={layout} marks={marks} effects={effects} onPick={pick} onHover={onHover} />
{selected && !myChoice && (
<div class="source-menu">
<div class="sm-title">{sourceTitle(view, selected, me)}</div>
{targeted.length > 0 && <div class="sm-hint">Click a highlighted {targetWords(targeted)}.</div>}
{preview && <div class="sm-odds">Attack odds: {preview.text}</div>}
<div class="sm-moves">
{untargeted.map((m) => (
<button key={m.key} onClick={() => play(m)}>
{m.label}
</button>
))}
<button class="ghost" onClick={() => setSelected(null)}>
Cancel (Esc)
</button>
</div>
</div>
)}
{inWindow && !selected && (
<div class="source-menu responses">
<div class="sm-title">Your responses</div>
<div class="sm-moves">
{responseSources.map(([source, list]) =>
list.length === 1 ? (
<button key={source} onClick={() => play(list[0])}>
{list[0].label}
</button>
) : (
<button key={source} onClick={() => setSelected(source)}>
{sourceTitle(view, source, me)} <span class="muted">· {list.length} ways</span>
</button>
),
)}
{primary && (
<button class="ghost" onClick={() => play(primary)}>
Pass <kbd>Space</kbd>
</button>
)}
</div>
</div>
)}
{popover && (
<div class="popover" style={{ left: `${Math.min(popover.x, innerWidth - 380)}px`, top: `${Math.max(8, Math.min(popover.y, innerHeight - 40 - popover.moves.length * 34))}px` }}>
{popover.moves.map((m) => (
<button key={m.key} onClick={() => play(m)}>
{m.label}
</button>
))}
<button class="ghost" onClick={() => setPopover(null)}>
Cancel
</button>
</div>
)}
{match.errors.length > 0 && (
<div class="errors">
<b>Rule invariants broke ({match.errors.length}).</b> Export the game record from Settings and attach it to a bug report.
<div class="muted">{match.errors.at(-1)}</div>
</div>
)}
</main>
<aside class="right">
<nav class="tabs">
{(['combat', 'info', 'log', 'moves'] as Tab[]).map((t) => (
<button key={t} class={tab === t ? 'on' : ''} onClick={() => setTab(t)}>
{{ combat: 'Combat', info: 'Info', log: 'Log', moves: `Moves${legal.length ? ` (${moves.length})` : ''}` }[t]}
</button>
))}
</nav>
<div class="tab-body">
{tab === 'combat' && <CombatPanel view={view} combat={match.combat} lines={lines} me={me} odds={settings.odds} diceAnimation={settings.diceAnimation} />}
{tab === 'info' && <InfoPanel view={view} me={me} focus={focus} />}
{tab === 'log' && <LogPanel lines={lines} />}
{tab === 'moves' && <MovesList moves={moves} over={match.over} onPlay={play} />}
</div>
{tab !== 'info' && focus && (
<div class="mini-info">
<InfoPanel view={view} me={me} focus={focus} />
</div>
)}
</aside>
<footer class="bottom">
<Hand view={view} me={me} marks={marks} real={settings.realCards} onPick={pick} />
<div class="actions">
<div class="steps">
{view.active === me ? (
STEPS.map(([id, label]) => (
<span key={id} class={`step ${view.step === id || (view.step === 'resolve' && id === 'attack') ? 'on' : ''}`}>
{label}
</span>
))
) : (
<span class="step other">{PLAYER_NAMES[bot]}’s command</span>
)}
</div>
<button class="primary" disabled={!primary || !!view.choice} onClick={() => primary && play(primary)}>
{primary ? primary.label : match.over ? 'Game over' : `${PLAYER_NAMES[bot]} is deciding…`} <kbd>Space</kbd>
</button>
<button disabled={!myTurn || !!view.choice || !!window_ || view.active !== me} onClick={() => match.endCommand()}>
End command <kbd>Enter</kbd>
</button>
{playtest && (
<button disabled={!match.canUndo} onClick={() => match.undo()}>
Undo <kbd>Z</kbd>
</button>
)}
</div>
</footer>
{myChoice && view.choice && <ChoiceDialog view={view} moves={moves} onPlay={play} />}
{match.over && !overClosed && <GameOver match={match} onClose={() => setOverClosed(true)} onNewGame={onNewGame} onRematch={onRematch} onReplay={onReplay} />}
{dialog === 'settings' && <SettingsDialog match={match} settings={settings} playtest={playtest} onSettings={onSettings} onClose={() => setDialog(null)} />}
{dialog && typeof dialog === 'object' && <PileDialog view={view} p={dialog.pile} me={me} onClose={() => setDialog(null)} />}
<CardZoom real={settings.realCards} />
</div>
);
}
function statusLine(view: GameState, match: Match, me: PlayerId): string {
if (view.over) return view.winner === null ? 'Game over: a draw' : `Game over: ${view.winner === me ? 'you win' : `${PLAYER_NAMES[view.winner]} wins`}`;
const round = view.rules.commands.on ? `Round ${roundOf(view, view.turn)} · command ${view.turn}` : `Turn ${view.turn}`;
const whose = view.active === me ? 'your command' : `${PLAYER_NAMES[view.active]}’s command`;
const step = { deploy: 'Deploy', play: 'Play', attack: 'Attack', resolve: 'Resolve', playAgain: 'Play again' }[view.step];
const deciding = match.humanToAct() ? 'your decision' : `${PLAYER_NAMES[match.botSide]} deciding`;
return `${round} · ${whose} · ${step} step · ${deciding}`;
}
function sourceTitle(view: GameState, key: Key, me: PlayerId): string {
const r = refOfKey(key);
if (r) return refName(view, r, me);
if (key.startsWith('hand:')) return key.slice(5);
if (key.startsWith('loc:')) return `${key.slice(4)}${view.locations[key.slice(4)].server !== null ? `: ${view.cards[view.locations[key.slice(4)].server!].name}` : ''}`;
if (key.startsWith('gate:')) return `Gateway ${lineName(key.slice(5))}`;
return key;
}
function targetWords(moves: Move[]): string {
const kinds = new Set(moves.map((m) => m.target.split(':')[0]));
const words = [...kinds].map((k) => ({ loc: 'location', anomaly: 'Anomaly', gate: 'gateway', hand: 'card' })[k] ?? k);
return words.join(' or ');
}
/** What's going on, over the board: whose command, and what you're being asked to respond to. */
function Banner({ view, match, lines, inWindow, myTurn, paused }: { view: GameState; match: Match; lines: LogLine[]; inWindow: boolean; myTurn: boolean; paused: boolean }) {
const me = match.human;
if (view.over) return null;
if (inWindow) {
const w = openWindow(view)!;
const c = view.combat && !view.combat.ended ? view.combat : null;
const top = view.stack.at(-1);
let what: string;
if (w.kind === 'preRoll' && c) what = `Combat at ${c.loc}, before the roll`;
else if (w.kind === 'postRoll' && c) what = `Combat at ${c.loc}, after the roll`;
else if (top && top.player !== me) what = `${PLAYER_NAMES[top.player]} ${top.kind === 'execution' ? 'plays' : 'uses'} ${top.name}${top.target ? ` on ${top.target}` : ''}`;
else what = (lastBy(lines, match.botSide) ?? 'A response window is open').replace(/\.$/, '');
return (
<div class="banner respond">
<b>{what}: respond?</b> Pick a glowing card or Ability, or <kbd>Space</kbd> to pass.
</div>
);
}
if (myTurn && !view.choice) {
const hint = {
deploy: 'Place, move or recall Anomalies, then advance one. A command is one advance or one attack.',
play: 'Play Hardware, Programs and Executions, and build Firewalls.',
attack: 'Attack from a location next to an enemy one.',
resolve: '',
playAgain: 'Play more cards, then end your command.',
}[view.step];
return (
<div class="banner mine">
<b>Your command.</b> {hint}
</div>
);
}
if (!myTurn) {
return (
<div class="banner theirs">
{PLAYER_NAMES[match.botSide]} {paused ? 'is paused.' : 'is deciding…'} <span class="muted">{lastBy(lines, match.botSide) ?? ''}</span>
</div>
);
}
return null;
}
const lastBy = (lines: LogLine[], p: PlayerId): string | null => {
for (let i = lines.length - 1; i >= Math.max(0, lines.length - 12); i--) if (lines[i].player === p && lines[i].tag !== 'turn') return lines[i].text;
return null;
};
function ChoiceDialog({ view, moves, onPlay }: { view: GameState; moves: Move[]; onPlay(m: Move): void }) {
const choice = view.choice!;
const options = moves.filter((m) => m.action.type === 'choose');
const salvage = moves.filter((m) => m.action.type === 'salvage');
const blocked = choice.options.filter((o, i) => !options.some((m) => m.action.type === 'choose' && m.action.index === i));
return (
<div class="modal-back see-through">
<div class="modal choice">
<h2>{choice.prompt}</h2>
<div class="choice-options">
{options.map((m) => (
<button key={m.key} onClick={() => onPlay(m)} {...zoomable(view.defs[m.label] ? m.label : null)}>
{m.label}
</button>
))}
</div>
{blocked.length > 0 && <p class="muted">Not enough Gb for: {blocked.map((o) => `${o.label} (${o.cost} Gb)`).join(', ')}. Salvage a card first.</p>}
{salvage.length > 0 && blocked.length > 0 && (
<div class="choice-salvage">
{salvage.map((m) => (
<button key={m.key} class="ghost" onClick={() => onPlay(m)}>
{m.label}
</button>
))}
</div>
)}
</div>
</div>
);
}
const STAT_LABELS: Record<string, string> = {
capturesUnowned: 'Open locations captured',
capturesUndefended: 'Undefended enemy locations captured',
capturesInCombat: 'Locations won in combat',
attacks: 'Attacks',
attacksWon: 'Rolls won attacking',
combatsTied: 'Stalemates',
damageDealt: 'Damage dealt',
anomaliesDestroyed: 'Anomalies lost',
recalls: 'Recalls',
firewallsPlaced: 'Firewalls placed',
bandwidthFromCaptures: 'Gb from captures',
bandwidthFromSalvage: 'Gb from Salvage',
bandwidthOnCards: 'Gb spent on cards',
cardsSalvaged: 'Cards salvaged',
hardwareInstalled: 'Hardware installed',
hardwareLost: 'Hardware lost',
programsInstalled: 'Programs installed',
programsLost: 'Programs lost',
executionsPlayed: 'Executions played',
abilitiesUsed: 'Abilities used',
};
function GameOver({ match, onClose, onNewGame, onRematch, onReplay }: { match: Match; onClose(): void; onNewGame(): void; onRematch(): void; onReplay(): void }) {
const s = match.s;
const me = match.human;
const title = s.winner === null ? 'A draw' : s.winner === me ? 'You win' : `${PLAYER_NAMES[s.winner]} (the bot) wins`;
const reason = s.endReason === 'win' ? `${PLAYER_NAMES[s.winner!]} holds ${s.rules.winLocations} locations.` : `The turn limit was reached.`;
return (
<div class="modal-back">
<div class="modal over">
<h2>{title}</h2>
<p>
{reason} Round {roundOf(s, s.turn)}, seed {match.setup.seed}.
</p>
<table class="stats">
<thead>
<tr>
<th />
<th class={`owner-${me}`}>{PLAYER_NAMES[me]} (you)</th>
<th class={`owner-${match.botSide}`}>{PLAYER_NAMES[match.botSide]} (bot)</th>
</tr>
</thead>
<tbody>
{STAT_KEYS.filter((k) => STAT_LABELS[k] && (s.stats[k][0] || s.stats[k][1])).map((k) => (
<tr key={k}>
<td>{STAT_LABELS[k]}</td>
<td>{s.stats[k][me]}</td>
<td>{s.stats[k][match.botSide]}</td>
</tr>
))}
</tbody>
</table>
<div class="buttons">
<button class="primary" onClick={onNewGame}>New game</button>
<button onClick={onRematch}>Rematch (same seed and decks)</button>
<button onClick={onReplay}>Watch the replay</button>
<button onClick={() => download(`files-tcg-seed-${match.setup.seed}.json`, JSON.stringify(match.record()))}>Export record</button>
<button class="ghost" onClick={onClose}>Look at the board</button>
</div>
</div>
</div>
);
}
function SettingsDialog({ match, settings, playtest, onSettings, onClose }: { match: Match; settings: Settings; playtest: boolean; onSettings(s: Settings): void; onClose(): void }) {
const set = (patch: Partial<Settings>) => onSettings({ ...settings, ...patch });
const [copied, setCopied] = useState('');
return (
<div class="modal-back" onClick={(e) => e.target === e.currentTarget && onClose()}>
<div class="modal settings">
<h2>Settings</h2>
<fieldset>
<legend>When the game stops for you to respond</legend>
{(
[
['combat', 'In combat only', 'The bot’s Executions, Abilities, installs and declarations outside combat pass for you.'],
['all', 'Every opponent move', 'Stops at every response window you have an answer for.'],
['never', 'Never', 'Passes every response for you.'],
] as const
).map(([id, label, about]) => (
<label key={id} class="radio">
<input type="radio" checked={settings.stops === id} onChange={() => set({ stops: id })} />
<b>{label}</b> <span class="muted">{about}</span>
</label>
))}
<p class="muted">Hold Shift to stop at the next window anyway.</p>
</fieldset>
<label class="check">
<input type="checkbox" checked={settings.autoSkip} onChange={(e) => set({ autoSkip: e.currentTarget.checked })} /> Skip steps where End and Salvage are the only moves
</label>
<label class="check">
<input type="checkbox" checked={settings.odds} onChange={(e) => set({ odds: e.currentTarget.checked })} /> Show the odds before a roll
</label>
<label class="check">
<input type="checkbox" checked={settings.diceAnimation} onChange={(e) => set({ diceAnimation: e.currentTarget.checked })} /> Roll the dice on screen
</label>
<label class="check">
<input type="checkbox" checked={settings.realCards} onChange={(e) => set({ realCards: e.currentTarget.checked })} /> Draw cards from the Cider templates (off: text cards)
</label>
<label class="range">
Bot speed: {(settings.botDelay / 1000).toFixed(2)}s per move
<input type="range" min="0" max="1000" step="50" value={settings.botDelay} onInput={(e) => set({ botDelay: Number(e.currentTarget.value) })} />
</label>
<fieldset>
<legend>Playtest tools</legend>
<p>
Seed <b>{match.setup.seed}</b> · {match.actions.length} moves so far · undo {playtest ? 'on (playtest mode)' : 'off'}
{match.setup.rules.length > 0 && ` · rules: ${match.setup.rules.join(', ')}`}
</p>
<label class="check">
<input type="checkbox" checked={settings.checkInvariants} onChange={(e) => set({ checkInvariants: e.currentTarget.checked })} /> Check the rule invariants after every move
</label>
{match.errors.length > 0 && (
<ul class="error-list">
{match.errors.slice(-20).map((e, i) => <li key={i}>{e}</li>)}
</ul>
)}
<div class="buttons">
<button
onClick={() => {
navigator.clipboard.writeText(match.log().join('\n')).then(() => setCopied('Log copied.'));
}}
>
Copy the log
</button>
<button onClick={() => download(`files-tcg-seed-${match.setup.seed}.json`, JSON.stringify(match.record()))}>Export game record</button>
<span class="muted">{copied}</span>
</div>
</fieldset>
<div class="buttons">
<button class="primary" onClick={onClose}>Done</button>
</div>
</div>
</div>
);
}
function PileDialog({ view, p, me, onClose }: { view: GameState; p: PlayerId; me: PlayerId; onClose(): void }) {
const pile = view.players[p].discard;
return (
<div class="modal-back" onClick={(e) => e.target === e.currentTarget && onClose()}>
<div class="modal pile">
<h2>
{p === me ? 'Your' : `${PLAYER_NAMES[p]}’s`} discard pile <span class="muted">({pile.length})</span>
</h2>
<div class="pile-cards">
{pile.length === 0 && <p class="muted">Empty.</p>}
{[...pile].reverse().map((id) => (
<div key={id} class="pile-card">
<TextCard name={view.cards[id].name} />
</div>
))}
</div>
<p class="muted">Newest first. {p !== me && `${PLAYER_NAMES[p]} has ${view.players[p].hand.length} cards in hand and ${view.players[p].serverPile.length} Servers in the pile.`}</p>
<div class="buttons">
<button class="primary" onClick={onClose}>Close</button>
</div>
</div>
</div>
);
}

139
app/src/ui/panels.tsx Normal file
View file

@ -0,0 +1,139 @@
/** The player panels (Bandwidth, piles, Anomaly slots) and your hand. */
import { useEffect, useState } from 'preact/hooks';
import { anomalyCores } from '../../../sim/src/engine.ts';
import { healthLeft, healthOf, slotsTotal } from '../../../sim/src/query.ts';
import { gridCount, infectionOf, isDisabledAnomaly, isRooted } from '../../../sim/src/state.ts';
import { PLAYER_NAMES, type GameState, type PlayerId } from '../../../sim/src/types.ts';
import { anomalyKey, handKey, type Key } from '../moves.ts';
import type { Mark } from './board.tsx';
import { CardView, TextCard, zoomable } from './cards.tsx';
interface PanelProps {
view: GameState;
p: PlayerId;
me: PlayerId;
marks: Map<Key, Mark>;
onPick(key: Key, e: MouseEvent): void;
onPiles(p: PlayerId, pile: 'discard'): void;
active: boolean;
}
export function PlayerPanel({ view, p, me, marks, onPick, onPiles, active }: PanelProps) {
const pl = view.players[p];
const mine = p === me;
const held = gridCount(view, p);
const need = view.rules.winLocations;
return (
<section class={`panel player owner-${p} ${active ? 'active' : ''}`}>
<header>
<span class="seat">{PLAYER_NAMES[p]}</span>
<span class="who">{mine ? 'you' : 'bot'}</span>
<span class="gb" title="Bandwidth">{pl.bandwidth} Gb</span>
</header>
<div class="held" title={`Grid locations held; ${need} wins`}>
<div class="held-bar">
<div class="held-fill" style={{ width: `${(100 * held) / need}%` }} />
</div>
<span>
{held}/{need} locations
</span>
</div>
<div class="piles">
<span title="Cards in hand">✋ {pl.hand.length}</span>
<span title="Cards in deck">▤ {pl.deck.length}</span>
<button class="linkish" title="Discard pile: click to look" onClick={() => onPiles(p, 'discard')}>
🗑 {pl.discard.length}
</button>
<span title="Servers left in the Server pile">⛁ {pl.serverPile.length}</span>
</div>
<ul class="slots">
{pl.anomalies.map((av, i) => {
const slot = i + 1;
const copy = slot > 4;
if (copy && av.at === null) return null;
const r = { player: p, slot };
const key = anomalyKey(r);
const name = av.card >= 0 && av.faceUp ? view.cards[av.card].name : null;
const mark = marks.get(key);
const inPlay = av.at !== null;
const status: string[] = [];
if (inPlay) {
if (infectionOf(av)) status.push(`☣${infectionOf(av)}`);
if (av.bugs) status.push(`✱${av.bugs}`);
if (isDisabledAnomaly(view, r)) status.push('⏻');
if (isRooted(view, r)) status.push('⚓');
}
return (
<li key={slot} class={`slot ${inPlay ? 'in-play' : ''} ${name ? '' : 'face-down'} ${mark ? `mark-${mark}` : ''}`} onClick={(e) => onPick(key, e)} {...zoomable(name)}>
<span class="slot-n">{copy ? `${slot - 4}′` : slot}</span>
<span class="slot-name">{name ?? (view.rules.recruit.on && av.card < 0 && !copy ? 'empty' : 'face down')}</span>
<span class="slot-where">{inPlay ? av.at : name ? 'in slot' : ''}</span>
{name && (
<span class="slot-stats">
{anomalyCores(view, p, slot, 'defend')}⚙ {inPlay ? `${healthLeft(view, r)}/${healthOf(view, r)}♥` : `${healthOf(view, r)}♥`}
{!copy && ` ${av.hardware.length}/${slotsTotal(view, r)}▭`}
{status.length > 0 && ` ${status.join(' ')}`}
</span>
)}
{av.hardware.length > 0 && (
<span class="slot-hw">
{av.hardware.map((h) => (
<span key={h} class="hw" {...zoomable(view.cards[h].name)}>
{view.cards[h].name}
</span>
))}
</span>
)}
</li>
);
})}
</ul>
</section>
);
}
interface HandProps {
view: GameState;
me: PlayerId;
marks: Map<Key, Mark>;
real: boolean;
onPick(key: Key, e: MouseEvent): void;
}
/** Hand card width: the footer grows with the window (see .game in styles.css), and the cards with it. */
function useHandWidth(): number {
const [h, setH] = useState(innerHeight);
useEffect(() => {
const fn = () => setH(innerHeight);
addEventListener('resize', fn);
return () => removeEventListener('resize', fn);
}, []);
const footer = Math.min(260, Math.max(184, 0.22 * h));
return Math.round((footer - 40) / 1.4);
}
/** Your hand. A card you can do something with glows; click it to pick it up. */
export function Hand({ view, me, marks, real, onPick }: HandProps) {
const hand = view.players[me].hand;
const width = useHandWidth();
return (
<div class="hand">
{hand.map((id) => {
const name = view.cards[id].name;
const key = handKey(name);
const mark = marks.get(key);
const def = view.defs[name];
return (
<div key={id} class={`hand-card ${mark ? `mark-${mark}` : ''}`} style={{ width: `${width}px` }} onClick={(e) => onPick(key, e as unknown as MouseEvent)} {...zoomable(name)}>
{real ? <CardView name={name} width={width} /> : <TextCard name={name} />}
<div class="hand-label">
<span>{name.replace(/^Execute: /, '')}</span>
<b>{def.bandwidth} Gb</b>
</div>
</div>
);
})}
{hand.length === 0 && <div class="hand-empty">Your hand is empty.</div>}
</div>
);
}

143
app/src/ui/replay.tsx Normal file
View file

@ -0,0 +1,143 @@
/** Watch a game record move by move, and play on from any point. */
import { useEffect, useMemo, useState } from 'preact/hooks';
import { viewFor } from '../../../sim/src/engine.ts';
import { logFor, roundOf } from '../../../sim/src/state.ts';
import { PLAYER_NAMES, type LogLine, type PlayerId } from '../../../sim/src/types.ts';
import { boardLayout } from '../layout.ts';
import type { GameRecord } from '../match.ts';
import type { Replay } from '../replay.ts';
import { download, type Settings } from '../storage.ts';
import { Board } from './board.tsx';
import { CardZoom, zoomable } from './cards.tsx';
import { PlayerPanel } from './panels.tsx';
import { LogPanel } from './side.tsx';
interface Props {
replay: Replay;
settings: Settings;
onBack(): void;
/** Play on from move `n` as the record's human. */
onPlayFrom(record: GameRecord): void;
}
const NO_MARKS = new Map();
export function ReplayScreen({ replay, settings, onBack, onPlayFrom }: Props) {
const [n, setN] = useState(replay.length);
const [playing, setPlaying] = useState(false);
const [all, setAll] = useState(true);
const [speed, setSpeed] = useState(150);
const human = replay.record.setup.human;
const layout = useMemo(() => boardLayout(human), [human]);
const s = useMemo(() => replay.stateAt(n), [n]);
const view = all ? s : viewFor(s, human);
const lines = useMemo((): LogLine[] => {
const text = logFor(s, all ? null : human);
return (s.log ?? []).map((l, i) => ({ ...l, text: text[i] }));
}, [s, all]);
useEffect(() => {
if (!playing) return;
if (n >= replay.length) return setPlaying(false);
const t = setTimeout(() => setN(n + 1), speed);
return () => clearTimeout(t);
}, [playing, n, speed]);
useEffect(() => {
const key = (e: KeyboardEvent) => {
if ((e.target as HTMLElement).closest('input, textarea, select')) return;
if (e.key === 'ArrowRight') setN((x) => Math.min(replay.length, x + (e.shiftKey ? 10 : 1)));
else if (e.key === 'ArrowLeft') setN((x) => Math.max(0, x - (e.shiftKey ? 10 : 1)));
else if (e.key === ' ') {
e.preventDefault();
setPlaying((p) => !p);
}
};
addEventListener('keydown', key);
return () => removeEventListener('keydown', key);
}, []);
/** Jumps to the next or previous start of a command. */
const jump = (dir: 1 | -1) => {
let i = n + dir;
const turnAt = (k: number) => replay.stateAt(k).turn;
const here = turnAt(n);
while (i > 0 && i < replay.length && turnAt(i) === here) i += dir;
setN(Math.max(0, Math.min(replay.length, i)));
};
const setup = replay.record.setup;
const header = `${s.rules.commands.on ? `Round ${roundOf(s, s.turn)} · command ${s.turn}` : `Turn ${s.turn}`} · ${PLAYER_NAMES[s.active]}’s command`;
return (
<div class="game replay">
<header class="topbar">
<span class="brand">FILES TCG · REPLAY</span>
<span class="status">
Seed {setup.seed} · you were {PLAYER_NAMES[human]} · {header}
</span>
<span class="spacer" />
<label class="check">
<input type="checkbox" checked={all} onChange={(e) => setAll(e.currentTarget.checked)} /> Show hidden cards
</label>
<button onClick={() => download(`files-tcg-seed-${setup.seed}.json`, JSON.stringify(replay.record))}>Export record</button>
<button onClick={onBack}>Back</button>
</header>
<aside class="left">
{[1 - human, human].map((p) => (
<PlayerPanel key={p} view={view} p={p as PlayerId} me={human} marks={NO_MARKS} onPick={() => {}} onPiles={() => {}} active={s.active === p} />
))}
</aside>
<main class="center">
{replay.error && <div class="banner respond">{replay.error}</div>}
<Board view={view} me={human} layout={layout} marks={NO_MARKS} effects={[]} onPick={() => {}} onHover={() => {}} />
</main>
<aside class="right">
<div class="tab-body">
<LogPanel lines={lines} />
</div>
</aside>
<footer class="bottom replay-controls">
<div class="hands">
{([0, 1] as const).map((p) => (
<div key={p} class={`replay-hand owner-${p}`}>
<b>{PLAYER_NAMES[p]}’s hand</b>{' '}
{view.players[p].hand.map((id, i) =>
id < 0 ? (
<span key={i} class="hidden-card">▮</span>
) : (
<span key={i} class="hand-name" {...zoomable(view.cards[id].name)}>
{view.cards[id].name}
</span>
),
)}
</div>
))}
</div>
<div class="scrub">
<button onClick={() => setN(0)} title="Start">⏮</button>
<button onClick={() => jump(-1)} title="Previous command">⏪</button>
<button onClick={() => setN(Math.max(0, n - 1))} title="Back one move (←)">◀</button>
<button class="primary" onClick={() => setPlaying(!playing)} title="Play or pause (Space)">
{playing ? '❚❚' : '▶'}
</button>
<button onClick={() => setN(Math.min(replay.length, n + 1))} title="Forward one move (→)">▶</button>
<button onClick={() => jump(1)} title="Next command">⏩</button>
<button onClick={() => setN(replay.length)} title="End">⏭</button>
<input type="range" min="0" max={replay.length} value={n} onInput={(e) => setN(Number(e.currentTarget.value))} />
<span class="muted">
move {n}/{replay.length}
</span>
<select value={speed} onChange={(e) => setSpeed(Number(e.currentTarget.value))} title="Playback speed">
<option value={600}>slow</option>
<option value={150}>normal</option>
<option value={30}>fast</option>
</select>
<button disabled={s.over} onClick={() => onPlayFrom(replay.cut(n))} title="Take over as the record's human from this move">
Play on from here
</button>
</div>
</footer>
<CardZoom real={settings.realCards} />
</div>
);
}

340
app/src/ui/side.tsx Normal file
View file

@ -0,0 +1,340 @@
/** The side column: combat readout, details of what you're pointing at, the log, all moves. */
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'preact/hooks';
import { anomalyCores } from '../../../sim/src/engine.ts';
import { isStart, levelFor, LINES_AT, otherEnd } from '../../../sim/src/map.ts';
import { rollOdds } from '../../../sim/src/odds.ts';
import { healthLeft, healthOf, programActive, slotsTotal, type CorePart } from '../../../sim/src/query.ts';
import { activeMods, anomaly, anomaliesAt, infectionOf, isDisabledAnomaly, isRooted } from '../../../sim/src/state.ts';
import { PLAYER_NAMES, type AnomalyRef, type GameState, type LogLine, type PlayerId } from '../../../sim/src/types.ts';
import { refName } from '../describe.ts';
import type { CombatInfo, FighterInfo } from '../match.ts';
import { groupMoves, refOfKey, type Key, type Move } from '../moves.ts';
import { zoomable } from './cards.tsx';
// ---------------------------------------------------------------------------------------------
// Combat
const KIND_NAMES = { anomaly: 'Anomaly', hardware: 'Hardware', program: 'Program', server: 'Server', modifier: 'Effect' } as const;
const pct = (x: number) => `${Math.round(100 * x)}%`;
/** True for a moment after `key` changes, for the dice animation. */
function useRolling(key: string, on: boolean, ms = 650): boolean {
const [rolling, setRolling] = useState(false);
const last = useRef(key);
useEffect(() => {
if (key === last.current) return;
last.current = key;
if (!on || !key.endsWith(':rolled')) return;
setRolling(true);
const t = setTimeout(() => setRolling(false), ms);
return () => clearTimeout(t);
}, [key, on, ms]);
return rolling;
}
function Dice({ dice, rolling }: { dice: number[]; rolling: boolean }) {
const [, setTick] = useState(0);
useEffect(() => {
if (!rolling) return;
const t = setInterval(() => setTick((n) => n + 1), 70);
return () => clearInterval(t);
}, [rolling]);
return (
<span class={`dice ${rolling ? 'rolling' : ''}`}>
{dice.map((d, i) => (
<span key={i} class="die">
{rolling ? 1 + Math.floor(Math.random() * 6) : d}
</span>
))}
</span>
);
}
function Parts({ parts }: { parts: CorePart[] }) {
return (
<ul class="parts">
{parts.map((p, i) => (
<li key={i} {...zoomable(p.kind === 'modifier' ? null : p.source)}>
<span class="part-kind">{KIND_NAMES[p.kind]}</span>
<span class="part-src">{p.source}</span>
<b class={p.cores < 0 ? 'neg' : ''}>{i === 0 ? p.cores : `${p.cores > 0 ? '+' : ''}${p.cores}`}</b>
</li>
))}
</ul>
);
}
function Fighter({ view, f, role, me, rolling, damage }: { view: GameState; f: FighterInfo; role: string; me: PlayerId; rolling: boolean; damage: { amount: number; dead: boolean } }) {
const total = f.dice.reduce((t, d) => t + d, 0);
return (
<div class={`fighter owner-${f.ref.player}`}>
<div class="fighter-head">
<span class="role">{role}</span>
<span class="fname" {...zoomable(anomaly(view, f.ref).card >= 0 ? view.cards[anomaly(view, f.ref).card].name : null)}>
{refName(view, f.ref, me)}
</span>
<span class="fcores" title="Cores = dice rolled">{f.cores} Cores</span>
</div>
<Parts parts={f.parts} />
{f.dice.length > 0 && (
<div class="roll">
<Dice dice={f.dice} rolling={rolling} />
{!rolling && <b class="total">= {total}</b>}
</div>
)}
<div class="fhealth">
{f.health > 0 && `${f.healthLeft}/${f.health} Health before the result`}
{damage.amount > 0 && !rolling && <b class="took"> · took {damage.amount}{damage.dead ? ', destroyed' : ''}</b>}
</div>
</div>
);
}
export function CombatPanel({ view, combat, lines, me, odds, diceAnimation }: {
view: GameState;
combat: CombatInfo | null;
lines: LogLine[];
me: PlayerId;
odds: boolean;
diceAnimation: boolean;
}) {
const rolling = useRolling(combat ? `${combat.id}:${combat.rolled ? 'rolled' : 'waiting'}` : '', diceAnimation);
if (!combat) return <div class="empty-note">No combat yet. Combats show here with each side’s Cores, dice and damage.</div>;
const own = lines.slice(combat.logFrom);
const end = own.findIndex((l, i) => i > 0 && l.tag === 'combat' && l.text.startsWith('Combat at'));
const mine = end < 0 ? own : own.slice(0, end);
const damage = (r: AnomalyRef) => {
const hits = mine.filter((l) => l.ref && l.ref.player === r.player && l.ref.slot === r.slot && l.amount);
return { amount: hits.reduce((t, l) => t + (l.amount ?? 0), 0), dead: hits.some((l) => l.text.includes('destroyed')) };
};
const defCores = combat.defenders.reduce((t, d) => t + d.cores, 0);
const o = rollOdds(combat.attacker.cores, defCores);
const attackerMine = combat.attacker.ref.player === me;
const stage = combat.done ? (combat.ended ? 'ended early' : 'over') : combat.rolled ? 'after the roll' : 'before the roll';
const result = mine.filter((l) => l.tag === 'combat' || l.tag === 'capture').slice(1).filter((l) => !l.text.startsWith('Roll:'));
return (
<div class="combat">
<div class="combat-head">
Combat at <b>{combat.loc}</b> <span class="muted">· {combat.kind === 'traceRoute' ? 'Trace Route' : combat.kind} · {stage}</span>
</div>
<Fighter view={view} f={combat.attacker} role="Attacker" me={me} rolling={rolling} damage={damage(combat.attacker.ref)} />
<div class="vs">vs</div>
{combat.defenders.map((d) => <Fighter key={`${d.ref.player}:${d.ref.slot}`} view={view} f={d} role="Defender" me={me} rolling={rolling} damage={damage(d.ref)} />)}
{odds && !combat.rolled && !combat.done && (
<div class="odds">
{attackerMine ? 'Your' : `${PLAYER_NAMES[combat.attacker.ref.player]}’s`} roll, {combat.attacker.cores} vs {defCores} Cores: win {pct(o.win)} · tie {pct(o.tie)} · lose {pct(o.lose)}
<div class="muted">
Average damage: {o.damageDealt.toFixed(1)} to the defender, {o.damageTaken.toFixed(1)} to the attacker
</div>
</div>
)}
{!rolling && result.length > 0 && (
<ul class="result">
{result.map((l, i) => <li key={i} class={l.player !== undefined ? `owner-${l.player}` : ''}>{l.text}</li>)}
</ul>
)}
</div>
);
}
/** Odds for an attack you're about to declare. */
export function attackPreview(view: GameState, me: PlayerId, slot: number, to: string): { atk: number; def: number; text: string } | null {
const from = anomaly(view, { player: me, slot }).at;
const owner = view.locations[to].owner;
if (!from || owner === null || owner === me) return null;
const atk = anomalyCores(view, me, slot, 'attack', from, to);
const def = anomaliesAt(view, to).reduce((t, r) => t + anomalyCores(view, r.player, r.slot, 'defend', to, to), 0);
if (!def) return null;
const o = rollOdds(atk, def);
return {
atk,
def,
text: `${atk} vs ${def} Cores: win ${pct(o.win)}, tie ${pct(o.tie)}, lose ${pct(o.lose)}. Average damage ${o.damageDealt.toFixed(1)} dealt, ${o.damageTaken.toFixed(1)} taken.`,
};
}
// ---------------------------------------------------------------------------------------------
// Details
export function InfoPanel({ view, me, focus }: { view: GameState; me: PlayerId; focus: Key | null }) {
if (!focus) return <div class="empty-note">Point at a location or an Anomaly for its details. Right-click a card to pin it.</div>;
const ref = refOfKey(focus);
if (ref) return <AnomalyInfo view={view} me={me} r={ref} />;
const m = focus.match(/^loc:(.+)$/);
if (m) return <LocationInfo view={view} me={me} loc={m[1]} />;
const g = focus.match(/^gate:(.+)$/);
if (g) {
const level = view.firewalls[g[1]] ?? 0;
return (
<div class="info">
<h3>Gateway {g[1].replace('-', '–')}</h3>
<p>{level ? `A Lv ${level} Firewall blocks this line. Clearing it costs ${view.rules.firewallCost[level - 1]} Gb.` : 'Open: no Firewall.'}</p>
</div>
);
}
return null;
}
function LocationInfo({ view, me, loc }: { view: GameState; me: PlayerId; loc: string }) {
const L = view.locations[loc];
const server = L.server !== null ? view.cards[L.server].name : null;
const def = server ? view.defs[server] : null;
const owner = L.owner === null ? 'Open' : L.owner === me ? 'Yours' : PLAYER_NAMES[L.owner];
const walls = LINES_AT.get(loc)!.filter((l) => view.firewalls[l.id]);
return (
<div class="info">
<h3>
{loc} <span class="muted">· {isStart(loc) ? 'start' : `Lv ${levelFor(me, loc)} for you`} · {owner}</span>
</h3>
{server && def && (
<div class="info-card" {...zoomable(server)}>
<b>{server}</b>
<p>{def.text}</p>
</div>
)}
{L.programs.map((id) => {
const name = view.cards[id].name;
return (
<div key={id} class={`info-card program ${programActive(view, id) ? '' : 'off'}`} {...zoomable(name)}>
<b>
{name}
{programActive(view, id) ? '' : ' (disabled)'}
</b>
<p>{view.defs[name].text}</p>
</div>
);
})}
{anomaliesAt(view, loc).map((r) => <AnomalyInfo key={`${r.player}:${r.slot}`} view={view} me={me} r={r} compact />)}
{walls.length > 0 && (
<p class="muted">
Firewalls: {walls.map((l) => `${otherEnd(l, loc)} (Lv ${view.firewalls[l.id]})`).join(', ')}
</p>
)}
</div>
);
}
function AnomalyInfo({ view, me, r, compact = false }: { view: GameState; me: PlayerId; r: AnomalyRef; compact?: boolean }) {
const av = anomaly(view, r);
if (av.card < 0) return <div class="info"><h3>Anomaly {r.slot}: face down</h3></div>;
const name = view.cards[av.card].name;
const def = view.defs[name];
const inPlay = av.at !== null;
const mods = activeMods(view, av);
return (
<div class={`info ${compact ? 'compact' : ''}`}>
<h3 {...zoomable(name)}>
{refName(view, r, me)}
{inPlay && <span class="muted"> · on {av.at}</span>}
</h3>
<p>
{inPlay ? anomalyCores(view, r.player, r.slot, 'defend') : def.cores} Cores · {inPlay ? `${healthLeft(view, r)}/${healthOf(view, r)}` : healthOf(view, r)} Health
{r.slot <= 4 && ` · Hardware ${av.hardware.length}/${slotsTotal(view, r)}`}
</p>
{!compact && def.ability && (
<p>
<b>{def.ability.name}</b>
{def.ability.cost ? ` (${def.ability.cost} Gb)` : ''}: {def.ability.text}
</p>
)}
{av.hardware.map((h) => (
<div key={h} class="info-card hardware" {...zoomable(view.cards[h].name)}>
<b>{view.cards[h].name}</b>
{!compact && <p>{view.defs[view.cards[h].name].text}</p>}
</div>
))}
{inPlay && (
<ul class="statuses">
{infectionOf(av) > 0 && <li>☣ {infectionOf(av)} Infection{av.permanentInfection ? ` (${av.permanentInfection} permanent)` : ''}</li>}
{av.bugs > 0 && <li>✱ {av.bugs} Bug counters</li>}
{isDisabledAnomaly(view, r) && <li>⏻ Disabled</li>}
{isRooted(view, r) && <li>⚓ Can’t move or retreat</li>}
{mods.map((m) => (
<li key={m.seq}>
{m.cores > 0 ? '+' : ''}
{m.cores} Cores from {m.source}
{m.combat !== undefined ? ' this combat' : ''}
</li>
))}
</ul>
)}
</div>
);
}
// ---------------------------------------------------------------------------------------------
// Log
const FILTERS = [
{ id: 'all', label: 'All', test: () => true },
{ id: 'combat', label: 'Combat', test: (l: LogLine) => l.tag === 'combat' || l.tag === 'turn' },
{ id: 'capture', label: 'Captures', test: (l: LogLine) => l.tag === 'capture' || l.tag === 'turn' || l.tag === 'game' },
{ id: 'card', label: 'Cards', test: (l: LogLine) => l.tag === 'card' || l.tag === 'choice' || l.tag === undefined || l.tag === 'turn' },
{ id: 'move', label: 'Moves', test: (l: LogLine) => l.tag === 'move' || l.tag === 'firewall' || l.tag === 'turn' },
] as const;
export function LogPanel({ lines }: { lines: LogLine[] }) {
const [filter, setFilter] = useState<(typeof FILTERS)[number]['id']>('all');
const box = useRef<HTMLDivElement>(null);
const stick = useRef(true);
const shown = useMemo(() => {
const f = FILTERS.find((x) => x.id === filter)!;
return lines.map((l, i) => [l, i] as const).filter(([l]) => l.text && f.test(l));
}, [lines, filter]);
useLayoutEffect(() => {
if (stick.current && box.current) box.current.scrollTop = box.current.scrollHeight;
}, [shown.length]);
return (
<div class="log-panel">
<div class="chips">
{FILTERS.map((f) => (
<button key={f.id} class={filter === f.id ? 'on' : ''} onClick={() => setFilter(f.id)}>
{f.label}
</button>
))}
</div>
<div
class="log"
ref={box}
onScroll={(e) => {
const el = e.currentTarget;
stick.current = el.scrollTop + el.clientHeight >= el.scrollHeight - 8;
}}
>
{shown.map(([l, i]) => (
<div key={i} class={`line tag-${l.tag ?? 'effect'} ${l.player !== undefined ? `owner-${l.player}` : ''}`}>
{l.text.trim()}
</div>
))}
</div>
</div>
);
}
// ---------------------------------------------------------------------------------------------
// All moves
export function MovesList({ moves, over, onPlay }: { moves: Move[]; over: boolean; onPlay(m: Move): void }) {
const [q, setQ] = useState('');
const shown = q ? moves.filter((m) => m.label.toLowerCase().includes(q.toLowerCase())) : moves;
const groups = groupMoves(shown);
return (
<div class="moves">
<input class="search" placeholder={`Filter ${moves.length} moves…`} value={q} onInput={(e) => setQ(e.currentTarget.value)} />
{moves.length === 0 && <div class="empty-note">{over ? 'The game is over.' : 'No moves: it’s the bot’s decision.'}</div>}
{groups.map(([group, list]) => (
<details key={group} open={list.length <= 12 || !!q}>
<summary>
{group} <span class="muted">({list.length})</span>
</summary>
{list.map((m) => (
<button key={m.key} class="move" onClick={() => onPlay(m)}>
{m.label}
</button>
))}
</details>
))}
</div>
);
}

209
app/src/ui/start.tsx Normal file
View file

@ -0,0 +1,209 @@
/** The start screen: side, seed, decks, bot style, rule variants; resume a saved game or open a record. */
import { useMemo, useState } from 'preact/hooks';
import type { DeckList } from '../../../sim/src/deck.ts';
import { PLAYER_NAMES, type PlayerId } from '../../../sim/src/types.ts';
import { pool } from '../cards.ts';
import { deckText, PRESETS, resolveDeck, type DeckChoice } from '../decks.ts';
import { BOT_STYLES, randomDecks, rulesFrom, type GameRecord, type MatchSetup } from '../match.ts';
import type { SavedGame, SetupPrefs } from '../storage.ts';
interface Props {
prefs: SetupPrefs;
saved: SavedGame | null;
resumeError: string | null;
onStart(setup: MatchSetup, playtest: boolean, prefs: SetupPrefs): void;
onResume(): void;
onDiscardSave(): void;
onOpenRecord(record: GameRecord): void;
}
const randomSeed = () => 1 + Math.floor(Math.random() * 999_999);
export function StartScreen({ prefs: initial, saved, resumeError, onStart, onResume, onDiscardSave, onOpenRecord }: Props) {
const [prefs, setPrefs] = useState<SetupPrefs>(initial);
const [importError, setImportError] = useState<string | null>(null);
const set = (patch: Partial<SetupPrefs>) => setPrefs({ ...prefs, ...patch });
const ruleLines = prefs.rules.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
const rulesResult = useMemo(() => {
try {
return { rules: rulesFrom(ruleLines), error: null };
} catch (e) {
return { rules: null, error: (e as Error).message };
}
}, [prefs.rules]);
const seedText = prefs.seed.trim();
const seedOk = seedText === '' || /^\d+$/.test(seedText);
const deckChecks = useMemo(() => {
if (!rulesResult.rules) return [null, null];
const dummy: DeckList = { anomalies: [], servers: [], main: [] };
return prefs.decks.map((d) => (d.kind === 'random' ? null : resolveDeck(pool, d, rulesResult.rules!, dummy)));
}, [prefs.decks, rulesResult.rules]);
const deckErrors = deckChecks.some((c) => c && c.errors.length);
const ready = rulesResult.rules && seedOk && !deckErrors;
const start = () => {
const rules = rulesResult.rules!;
const seed = seedText ? Number(seedText) : randomSeed();
const human: PlayerId = prefs.side === 'south' ? 0 : prefs.side === 'north' ? 1 : ((seed % 2) as PlayerId);
const random = randomDecks(pool, seed, rules);
// prefs.decks is [yours, the bot's]; the setup's decks are [South's, North's].
const mine = resolveDeck(pool, prefs.decks[0], rules, random[human]).deck!;
const theirs = resolveDeck(pool, prefs.decks[1], rules, random[1 - human]).deck!;
const decks = (human === 0 ? [mine, theirs] : [theirs, mine]) as [DeckList, DeckList];
onStart({ seed, human, decks, rules: ruleLines, bot: BOT_STYLES[prefs.bot]?.params }, prefs.playtest, prefs);
};
const openFile = async (file: File | undefined) => {
if (!file) return;
try {
const record = JSON.parse(await file.text()) as GameRecord;
if (record.version !== 1 || !record.setup || !Array.isArray(record.actions)) throw new Error('This file isn’t a Files TCG game record.');
onOpenRecord(record);
} catch (e) {
setImportError((e as Error).message);
}
};
return (
<div class="start">
<div class="start-box">
<h1>
FILES TCG <span class="muted">· play the bot</span>
</h1>
{saved && (
<div class="saved">
<div>
<b>Game in progress</b>: seed {saved.record.setup.seed}, you’re {PLAYER_NAMES[saved.record.setup.human]}, {saved.record.actions.length} moves in
{saved.playtest ? ' (playtest mode)' : ''}. Saved {new Date(saved.savedAt).toLocaleString()}.
</div>
{resumeError && <div class="error">{resumeError}</div>}
<div class="buttons">
<button class="primary" onClick={onResume}>Resume</button>
<button class="ghost" onClick={onDiscardSave}>Discard it</button>
</div>
</div>
)}
<div class="form">
<label>Your side</label>
<div class="seg">
{(['south', 'north', 'random'] as const).map((s) => (
<button key={s} class={prefs.side === s ? 'on' : ''} onClick={() => set({ side: s })}>
{s === 'random' ? 'Random' : PLAYER_NAMES[s === 'south' ? 0 : 1]}
</button>
))}
<span class="muted">Who goes first is random either way.</span>
</div>
<label for="seed">Seed</label>
<div>
<input id="seed" class={seedOk ? '' : 'bad'} placeholder="random" value={prefs.seed} onInput={(e) => set({ seed: e.currentTarget.value })} />
<span class="muted"> The same seed and decks always deal the same game.</span>
</div>
{(['Your deck', 'The bot’s deck'] as const).map((label, i) => (
<DeckPicker
key={label}
label={label}
choice={prefs.decks[i]}
errors={deckChecks[i]?.errors ?? []}
onChange={(d) => set({ decks: (i === 0 ? [d, prefs.decks[1]] : [prefs.decks[0], d]) as [DeckChoice, DeckChoice] })}
/>
))}
<label for="bot">Bot</label>
<div>
<select id="bot" value={prefs.bot} onChange={(e) => set({ bot: e.currentTarget.value })}>
{Object.entries(BOT_STYLES).map(([id, b]) => (
<option key={id} value={id}>
{b.label}
</option>
))}
</select>
<span class="muted"> {BOT_STYLES[prefs.bot]?.about}</span>
</div>
<label>Playtest mode</label>
<label class="check">
<input type="checkbox" checked={prefs.playtest} onChange={(e) => set({ playtest: e.currentTarget.checked })} /> Allow undo (Z). Off for a normal game.
</label>
<label for="rules">Rule variants</label>
<div>
<textarea
id="rules"
rows={3}
class={rulesResult.error ? 'bad' : ''}
placeholder={'One K=V per line, as the CLI’s --rule. For example:\nsecondPlayer.bandwidth=4\nhealth.override=8'}
value={prefs.rules}
onInput={(e) => set({ rules: e.currentTarget.value })}
/>
{rulesResult.error && <div class="error">{rulesResult.error}</div>}
</div>
</div>
<div class="buttons">
<button class="primary big" disabled={!ready} onClick={start}>
Start game
</button>
<label class="file-button">
Open a game record…
<input type="file" accept=".json,application/json" onChange={(e) => openFile(e.currentTarget.files?.[0])} />
</label>
</div>
{importError && <div class="error">{importError}</div>}
<p class="muted small">
New to the game? Read QUICKSTART.md first. In play: pick a glowing card or Anomaly, then a highlighted target. Space ends a step or passes, Enter
ends your command, right-click a card to pin it.
</p>
</div>
</div>
);
}
function DeckPicker({ label, choice, errors, onChange }: { label: string; choice: DeckChoice; errors: string[]; onChange(d: DeckChoice): void }) {
const value = choice.kind === 'preset' ? `preset:${choice.id}` : choice.kind;
const preset = choice.kind === 'preset' ? PRESETS.find((p) => p.id === choice.id) : null;
return (
<>
<label>{label}</label>
<div>
<select
value={value}
onChange={(e) => {
const v = e.currentTarget.value;
if (v === 'random') onChange({ kind: 'random' });
else if (v === 'paste') onChange({ kind: 'paste', text: choice.kind === 'preset' && preset ? deckText(preset) : '' });
else onChange({ kind: 'preset', id: v.slice(7) });
}}
>
<option value="random">Random legal deck</option>
{PRESETS.map((p) => (
<option key={p.id} value={`preset:${p.id}`}>
{p.name}
</option>
))}
<option value="paste">Paste a list…</option>
</select>
{preset && <span class="muted"> {preset.about}</span>}
{choice.kind === 'paste' && (
<textarea
rows={5}
class={errors.length ? 'bad' : ''}
placeholder={'One card per line, with a count: "2 RAM Expansion". Or JSON: { "anomalies": […], "servers": […], "main": […] }.\n4 Anomalies, 20 Servers and 45 other cards, at most 2 of each.'}
value={choice.text}
onInput={(e) => onChange({ kind: 'paste', text: e.currentTarget.value })}
/>
)}
{errors.length > 0 && (
<ul class="error">
{errors.slice(0, 6).map((e, i) => <li key={i}>{e}</li>)}
{errors.length > 6 && <li>…and {errors.length - 6} more</li>}
</ul>
)}
</div>
</>
);
}

148
app/test/match.test.ts Normal file
View file

@ -0,0 +1,148 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { greedyBot } from '../../sim/src/bots/greedy.ts';
import { openWindow } from '../../sim/src/engine.ts';
import { loadCards } from '../../sim/src/load.ts';
import { makeRng, nextFloat, pick } from '../../sim/src/rng.ts';
import type { Action, PlayerId } from '../../sim/src/types.ts';
import { Match, randomDecks, rulesFrom, type MatchOptions, type Stops } from '../src/match.ts';
const pool = loadCards();
function newMatch(seed: number, options: Partial<MatchOptions> = {}, rules: string[] = []): Match {
const human = (seed % 2) as PlayerId;
return new Match(pool, { seed, human, decks: randomDecks(pool, seed, rulesFrom(rules)), rules }, options);
}
/** A "human" that clicks at random: ends or passes a third of the time, otherwise any move. */
function clicker(seed: number) {
const rng = makeRng(seed);
return (legal: Action[]): Action => {
const stop = legal.find((a) => a.type === 'end' || a.type === 'pass');
const moves = legal.filter((a) => a.type !== 'end' && a.type !== 'pass');
if (moves.length === 0 || (stop && nextFloat(rng) < 0.35)) return stop ?? legal[0];
return pick(rng, moves);
};
}
/**
* Plays a game to the end. After every call into the controller, control must come back: the game
* is over, or it's the bot's move, or you have at least one legal move.
*/
function playOut(m: Match, seed: number, onHuman?: (m: Match) => boolean | void, choose: (legal: Action[]) => Action = clicker(seed)): number {
let decisions = 0;
for (let n = 0; !m.over; n++) {
assert.ok(n < 20_000, `seed ${seed}: the game didn't finish`);
if (m.botToAct()) {
m.runBot();
continue;
}
assert.ok(m.humanToAct(), `seed ${seed}: nobody is deciding at turn ${m.s.turn}`);
const legal = m.legal();
assert.ok(legal.length > 0, `seed ${seed}: no legal moves at turn ${m.s.turn}`);
if (onHuman?.(m)) continue;
decisions++;
m.act(choose(legal));
}
return decisions;
}
test('a random human plays 200 games against the bot to the end, and control always comes back', () => {
const stops: Stops[] = ['combat', 'all', 'never'];
for (let seed = 1; seed <= 200; seed++) {
const m = newMatch(seed, { checkInvariants: true, stops: stops[seed % 3], autoSkip: seed % 4 !== 0 });
playOut(m, seed);
assert.deepEqual(m.errors, [], `seed ${seed}: invariants broke`);
assert.ok(m.s.winner !== null || m.s.endReason === 'turnLimit');
}
});
test('a greedy human plays 40 full-length games through the controller', () => {
const stops: Stops[] = ['combat', 'all', 'never'];
for (let seed = 1; seed <= 40; seed++) {
const m = newMatch(seed, { checkInvariants: true, stops: stops[seed % 3] });
const me = greedyBot();
playOut(m, seed, undefined, (legal) => me.choose(m.view(), legal, m.human));
assert.deepEqual(m.errors, [], `seed ${seed}: invariants broke`);
}
});
test('End command ends your command, stopping only for your prompts and response windows', () => {
let used = 0;
for (let seed = 1; seed <= 40; seed++) {
const m = newMatch(seed, { stops: 'all' });
playOut(m, seed, (g) => {
if (g.s.active !== g.human || g.s.choice || openWindow(g.s) || g.s.turn % 3 !== 0) return false;
const turn = g.s.turn;
g.endCommand();
used++;
if (g.over) return true;
const stopped = g.humanToAct() && (g.s.choice !== null || openWindow(g.s) !== null);
assert.ok(g.s.turn !== turn || stopped || g.botToAct(), `seed ${seed}: End command stopped at step ${g.s.step}`);
// While the bot answers, End command keeps going, and finishes once the bot is done.
while (g.botToAct()) g.runBot();
if (!g.over && g.s.turn === turn && g.humanToAct()) {
assert.ok(g.s.choice !== null || openWindow(g.s) !== null, `seed ${seed}: End command left you in your own step`);
}
return true;
});
}
assert.ok(used > 100);
});
test('a game record replays to the same state', () => {
for (let seed = 1; seed <= 20; seed++) {
const m = newMatch(seed);
let n = 0;
playOut(m, seed, (g) => {
if (++n % 97 !== 0) return false;
const copy = Match.fromRecord(pool, g.record());
assert.equal(JSON.stringify(copy.s), JSON.stringify(g.s), `seed ${seed}: replay differs at move ${g.actions.length}`);
return false;
});
const copy = Match.fromRecord(pool, JSON.parse(JSON.stringify(m.record())));
assert.equal(JSON.stringify(copy.s), JSON.stringify(m.s));
}
});
test('undo goes back to your previous decision, dice included', () => {
for (let seed = 1; seed <= 10; seed++) {
const m = newMatch(seed, { undo: true });
let checked = 0;
playOut(m, seed, (g) => {
if (checked > 30 || g.s.turn % 5 !== 1) return false;
const before = JSON.stringify(g.s);
const actions = g.actions.length;
const legal = g.legal();
const a = legal[legal.length - 1];
g.act(a);
if (g.botToAct()) g.runBot();
const after = JSON.stringify(g.s);
assert.ok(g.undo());
assert.equal(JSON.stringify(g.s), before);
assert.equal(g.actions.length, actions);
// The same move again plays out the same way: the dice are part of the state.
g.act(a);
if (g.botToAct()) g.runBot();
assert.equal(JSON.stringify(g.s), after);
assert.ok(g.undo());
checked++;
return false;
});
assert.ok(checked > 0);
}
});
test('the combat readout sees every combat, even ones that resolve inside one move', () => {
for (let seed = 1; seed <= 20; seed++) {
const m = newMatch(seed, { stops: 'never' });
playOut(m, seed);
const started = m.s.log!.filter((l) => l.tag === 'combat' && l.text.startsWith('Combat at')).length;
assert.equal(m.combats.length, started, `seed ${seed}`);
for (const c of m.combats) {
assert.ok(c.done, `seed ${seed}: combat ${c.id} isn't finished`);
assert.ok(m.s.log![c.logFrom].text.startsWith(`Combat at ${c.loc}`), `seed ${seed}: combat ${c.id} starts at the wrong log line`);
if (c.rolled) assert.equal(c.attacker.dice.length, c.attacker.cores, `seed ${seed}: combat ${c.id} lost its dice`);
}
}
});

59
app/test/moves.test.ts Normal file
View file

@ -0,0 +1,59 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { greedyBot } from '../../sim/src/bots/greedy.ts';
import { describeAction } from '../../sim/src/describe.ts';
import { actionKey } from '../../sim/src/engine.ts';
import { loadCards } from '../../sim/src/load.ts';
import { LINE_BY_ID, LOCATIONS } from '../../sim/src/map.ts';
import { makeRng, nextFloat, pick } from '../../sim/src/rng.ts';
import type { GameState, PlayerId } from '../../sim/src/types.ts';
import { Match, randomDecks, rulesFrom } from '../src/match.ts';
import { movesOf, refOfKey, type Key } from '../src/moves.ts';
const pool = loadCards();
/** Whether the screen has something to click for `key`: a hand card, a token or slot, a location, a gateway. */
function onScreen(view: GameState, me: PlayerId, key: Key, asSource: boolean): boolean {
if (key.startsWith('hand:')) return view.players[me].hand.some((id) => view.cards[id].name === key.slice(5));
if (key.startsWith('loc:')) return LOCATIONS.includes(key.slice(4));
// A gateway is drawn when it has a Firewall or is marked as a source.
if (key.startsWith('gate:')) return LINE_BY_ID.get(key.slice(5))?.gateway === true && (asSource || !!view.firewalls[key.slice(5)]);
const r = refOfKey(key);
if (r) {
const av = view.players[r.player].anomalies[r.slot - 1];
// Tokens for Anomalies in play; panel rows for slots 1–4 (and copies in play).
return av.at !== null || r.slot <= 4;
}
return false;
}
function check(m: Match): void {
const view = m.view();
const legal = m.legal();
const moves = movesOf(view, legal, m.human);
const labels = new Set(moves.map((x) => x.label));
for (const a of legal) assert.ok(labels.has(describeAction(view, a)), `no move for ${actionKey(a)}`);
for (const x of moves) {
if (x.source === 'bar') continue;
assert.ok(onScreen(view, m.human, x.source, true), `nothing to click for the source of "${x.label}" (${x.source})`);
if (x.target !== 'none') assert.ok(onScreen(view, m.human, x.target, false), `nothing to click for the target of "${x.label}" (${x.target})`);
}
}
test('every legal move can be reached by clicking: a source on screen, then a target on screen or its menu', () => {
for (let seed = 1; seed <= 60; seed++) {
const rules = seed % 10 === 0 ? ['board=grid4'] : [];
const m = new Match(pool, { seed, human: (seed % 2) as PlayerId, decks: randomDecks(pool, seed, rulesFrom(rules)), rules }, { stops: 'all', autoSkip: false });
const me = greedyBot();
const rng = makeRng(seed);
for (let n = 0; !m.over && n < 5000; n++) {
if (m.botToAct()) {
m.runBot();
continue;
}
check(m);
const legal = m.legal();
m.act(seed % 3 === 0 && nextFloat(rng) < 0.5 ? pick(rng, legal) : me.choose(m.view(), legal, m.human));
}
}
});

19
app/tsconfig.json Normal file
View file

@ -0,0 +1,19 @@
{
"compilerOptions": {
"target": "es2024",
"lib": ["es2024", "dom", "dom.iterable"],
"module": "esnext",
"moduleResolution": "bundler",
"jsx": "react-jsx",
"jsxImportSource": "preact",
"strict": true,
"noUnusedLocals": true,
"noEmit": true,
"allowImportingTsExtensions": true,
"erasableSyntaxOnly": true,
"verbatimModuleSyntax": true,
"skipLibCheck": true,
"types": ["node", "vite/client"]
},
"include": ["src", "test", "vite.config.ts"]
}

9
app/vite.config.ts Normal file
View file

@ -0,0 +1,9 @@
import { defineConfig } from 'vite';
// The app imports the engine straight from ../sim/src and the cards from ../decks and ../assets,
// so the dev server may read the whole files-tcg folder.
export default defineConfig({
base: './',
server: { fs: { allow: ['..'] } },
oxc: { jsx: { runtime: 'automatic', importSource: 'preact' } },
});