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

View file

@ -5,9 +5,9 @@ ruling, are in [rules.md](rules.md).
## The Idea
You and your opponent are hackers fighting over a network. Your **Avatars** move out from your
starting Server and capture **Server locations** on a shared grid. Every capture earns **RAM**, which
you spend on cards that upgrade your Avatars, trap your locations and disrupt your opponent.
You and your opponent are hackers fighting over a network. Your **Anomalies** move out from your
starting Server and capture **Server locations** on a shared grid. Every capture earns **Bandwidth**, which
you spend on cards that upgrade your Anomalies, trap your locations and disrupt your opponent.
**Win by controlling 10 Server locations.** Your starting Server doesn't count.
@ -15,10 +15,10 @@ you spend on cards that upgrade your Avatars, trap your locations and disrupt yo
Each player needs:
- **4 Avatars**
- **4 Anomalies**
- **20 Servers**, kept as a separate pile
- A **45-card deck** of Executions, Hardware and Programs, with at most 2 copies of any card
- A few **d6**, and something to track RAM
- A few **d6**, and something to track Bandwidth (counted in **Gb**)
You'll also need the **playmat**, which has 13 locations plus the two starting Servers.
@ -26,22 +26,22 @@ You'll also need the **playmat**, which has 13 locations plus the two starting S
| Card | What it is | Where it goes | When you play it |
|---|---|---|---|
| **Avatar** | Your units. **Cores** = dice in combat. **Health** = damage it takes to destroy it. **Expansion Slots** = how much Hardware it can hold. Its **Ability** can be used once per round by paying its RAM cost. | Your Avatar slots, then onto locations you control | Free, at the start of your command |
| **Anomaly** | Your units. **Cores** = dice in combat. **Health** = damage it takes to destroy it. **Expansion Slots** = how much Hardware it can hold. Its **Ability** can be used once per round by paying its Bandwidth cost. | Your Anomaly slots, then onto locations you control | Free, at the start of your command |
| **Server** | The locations you capture. Each has an ability that helps whoever holds it. | Onto a location when you capture it | Automatically |
| **Program** | Buffs and traps for a location | A location you control, 2 at most | During your command |
| **Hardware** | Upgrades for an Avatar | An Avatar in play, up to its Expansion Slots | During your command |
| **Hardware** | Upgrades for an Anomaly | An Anomaly in play, up to its Expansion Slots | During your command |
| **Execution** | One-shot tricks, then discarded | Wherever the card says | **Any time**, even in your opponent's command |
Every card except Avatars and Servers costs the **RAM** printed on it.
Every card except Anomalies and Servers costs the **Bandwidth** printed on it.
## Setup
1. Shuffle your 4 Avatars and put them **face down** in your Avatar slots 1–4. Flip **Avatar 1**
1. Shuffle your 4 Anomalies and put them **face down** in your Anomaly slots 1–4. Flip **Anomaly 1**
face up.
2. Shuffle your Servers into a face-down pile. Put the top one face down on your starting Server, and
reveal it when the game starts.
3. Shuffle your deck and draw **7 cards**.
4. Start with **4 RAM**.
4. Start with **4 Gb**.
5. Pick a first player at random. They lead every round.
## The Board
@ -73,11 +73,11 @@ A1 -----o------ A2 -----o----- A3
- Lines connect the locations. Each `o` is a **gateway**, where Firewalls go.
- Each row is a **level**, counted from your side: your first row is Lv 1, the middle row (C) is
Lv 3, and the enemy's first row is Lv 5.
- **Unlocking Avatars:** the first time you capture a location of level N, flip Avatar N face up.
Take your second row for Avatar 2, the middle row for Avatar 3, and the enemy's second row for
Avatar 4. A new Avatar can enter play from the next round.
- **Unlocking Anomalies:** the first time you capture a location of level N, flip Anomaly N face up.
Take your second row for Anomaly 2, the middle row for Anomaly 3, and the enemy's second row for
Anomaly 4. A new Anomaly can enter play from the next round.
More Avatars means more actions each round, so pushing forward early matters.
More Anomalies means more actions each round, so pushing forward early matters.
## How a Round Works
@ -87,44 +87,44 @@ Each round, each player gets **2 commands**, and the order snakes the same way e
|---|---|
| every round | P1, P2, P2, P1 |
**At your first command of each round:** draw a card, then **refresh** your Avatars so they can
**At your first command of each round:** draw a card, then **refresh** your Anomalies so they can
act again.
**Each command has five steps:**
1. **Place and advance.** Put any of your face-up Avatars on any locations you control, for free.
A damaged Avatar can instead be **recalled** to its slot to heal (it keeps its Hardware, but
that's its placement for the round). Then you may **advance** one Avatar into an **empty or
1. **Place and advance.** Put any of your face-up Anomalies on any locations you control, for free.
A damaged Anomaly can instead be **recalled** to its slot to heal (it keeps its Hardware, but
that's its placement for the round). Then you may **advance** one Anomaly into an **empty or
undefended** location next to your territory.
2. **Play cards** from your hand.
3. **Attack.** If you didn't advance, one Avatar may attack a **defended** enemy location next to
3. **Attack.** If you didn't advance, one Anomaly may attack a **defended** enemy location next to
the location it's standing on.
4. **Resolve** the capture or combat right away.
5. **Play more cards**, including with the RAM you just earned.
5. **Play more cards**, including with the Bandwidth you just earned.
**The key limits:**
- Each command gets **one advance or one attack**, not both.
- Each Avatar can advance or attack **once per round**.
- Each location holds 1 of your Avatars.
- Each Anomaly can advance or attack **once per round**.
- Each location holds 1 of your Anomalies.
Your Avatars don't have to walk. Each round you can place them on any location you hold, then
Your Anomalies don't have to walk. Each round you can place them on any location you hold, then
step out from your territory.
## Capturing and Combat
**Taking an empty or undefended location** needs no fight. Move in, flip the top Server from your
pile onto it, and **gain 4 RAM**, plus any RAM bonus the Server card gives. If the location was the
pile onto it, and **gain 4 Gb**, plus any Bandwidth bonus the Server card gives. If the location was the
enemy's, their Server goes to the bottom of their pile and their Programs there are discarded.
**Attacking a defended location** means a fight:
1. Each side rolls **1d6 per Core**. Count the Avatar, its Hardware, Programs, effects, and the
1. Each side rolls **1d6 per Core**. Count the Anomaly, its Hardware, Programs, effects, and the
Server it's on.
2. **The higher total wins the roll.** The loser takes **damage equal to the difference**. On a tie,
nothing happens.
3. Damage stays on an Avatar. When it reaches its **Health**, the Avatar is **destroyed**: it goes
back to its Avatar slot at full Health and discards its Hardware.
3. Damage stays on an Anomaly. When it reaches its **Health**, the Anomaly is **destroyed**: it goes
back to its Anomaly slot at full Health and discards its Hardware.
4. **The location falls** only when its last defender is destroyed. Then the attacker moves in and
captures it. Otherwise everyone stays where they are, so a defended location usually takes two
or three attacks to take.
@ -137,24 +137,24 @@ Starting Servers can never be attacked.
| +1 Core | 75–90% | 5–8 |
| +2 Cores | 90–99% | 7–11 |
## RAM
## Bandwidth
- **Earn it** by capturing, which pays 4 RAM every time, including recaptures.
- **Salvage:** discard any card from your hand to gain its printed RAM. You can do this whenever you
- **Earn it** by capturing, which pays 4 Gb every time, including recaptures.
- **Salvage:** discard any card from your hand to gain its printed Bandwidth. You can do this whenever you
need to pay for something.
- **Spend it** on cards, Avatar Abilities and Firewalls.
- **Spend it** on cards, Anomaly Abilities and Firewalls.
- It carries over between rounds, and there's no cap.
## Firewalls
Firewalls aren't cards. You buy them with RAM and put them on a gateway (`o`) on a line touching one
Firewalls aren't cards. You buy them with Bandwidth and put them on a gateway (`o`) on a line touching one
of your locations. A Firewall **blocks all movement and attacks** along its line, for both players.
| Level | Cost to place or clear |
|---|---|
| Lv 1 | 2 RAM |
| Lv 2 | 4 RAM |
| Lv 3 | 8 RAM |
| Lv 1 | 2 Gb |
| Lv 2 | 4 Gb |
| Lv 3 | 8 Gb |
- **Place** Firewalls in steps 2 and 5. Upgrading one costs the full price of the new level.
- **Clear** a Firewall before you advance or attack, by paying its current level. The player who
@ -165,27 +165,27 @@ of your locations. A Firewall **blocks all movement and attacks** along its line
Say you're the first player, starting at S1:
1. **Your first command.** You don't draw, because you're first in round 1. Place Avatar 1 on S1 and
advance it to **A2**, the only way out. Flip a Server onto A2 and gain 4 RAM, which gives you 8.
1. **Your first command.** You don't draw, because you're first in round 1. Place Anomaly 1 on S1 and
advance it to **A2**, the only way out. Flip a Server onto A2 and gain 4 Gb, which gives you 8.
Play a card if you like.
2. **Their two commands.** They draw, place their Avatar on S2, and advance it to E2. Their second
command can play cards, but their only Avatar has already acted this round.
3. **Your second command.** Your Avatar has also acted, so you can only play cards or Firewalls.
Or pass, and save your RAM.
2. **Their two commands.** They draw, place their Anomaly on S2, and advance it to E2. Their second
command can play cards, but their only Anomaly has already acted this round.
3. **Your second command.** Your Anomaly has also acted, so you can only play cards or Firewalls.
Or pass, and save your Bandwidth.
4. **Round 2.** Your opponent leads. When your turn comes, you draw, refresh, and advance into A1,
A3, B1 or B2. **B1 and B2 unlock Avatar 2.**
A3, B1 or B2. **B1 and B2 unlock Anomaly 2.**
## Tips for New Players
- **Grab empty locations early.** They cost nothing to take and pay 4 RAM each.
- **Head for your second row.** Avatar 2 doubles what you can do each round, and it's the biggest
- **Grab empty locations early.** They cost nothing to take and pay 4 Gb each.
- **Head for your second row.** Anomaly 2 doubles what you can do each round, and it's the biggest
early swing.
- **Plan both commands.** With one Avatar, your second command can only play cards. Use it to buy
- **Plan both commands.** With one Anomaly, your second command can only play cards. Use it to buy
Hardware or set Programs and Firewalls.
- **Don't leave fronts empty.** An undefended enemy location can be taken without a fight. Stand
your Avatars where the opponent can reach.
your Anomalies where the opponent can reach.
- **Attack with an edge.** One extra Core wins most fights, and Hardware is the easiest way to get it.
- **Salvage freely.** A card you won't use soon is RAM in your hand.
- **Salvage freely.** A card you won't use soon is Bandwidth in your hand.
- **Keep an Execution back.** They work in your opponent's command too, often during a fight.
## Reading "Turn" on Cards

318
app-plan.md Normal file
View file

@ -0,0 +1,318 @@
# App Plan: Play Files TCG Against the Bot
_Prepared 2026-09-30 against rules v0.9 and the simulator in `sim/`._
> **Status, 2026-09-30: built.** Levels 1 and 2 are in `app/`; see [app/README.md](app/README.md).
> The open decisions in section 7 were given defaults for now: the app runs locally (the build is a
> static site, so it can be hosted later), undo is on only in playtest mode, and the odds preview is
> on, with a setting to turn it off.
This plan covers a browser app where one person plays a full game of Files TCG against the
simulator's greedy bot. It comes in two levels:
- **Level 1, the playtest prototype.** Every rule and card works, and the screen is plain. It
replaces paper playtests.
- **Level 2, properly playable.** You act by clicking the board and your cards, which look like the
printed cards. Combat is easy to read, and games can be saved, undone and replayed. Someone who has
read [QUICKSTART.md](QUICKSTART.md) can play without help.
Online play between two people, sound, mobile layouts and a tutorial are out of scope. Those are
level 3.
## 1. What the Simulator Already Provides
The engine in `sim/src/engine.ts` is already built the way a game app needs:
| Function | What the app uses it for |
| --- | --- |
| `createGame({ pool, decks, seed, rules })` | Starts a game. The same seed always gives the same game. |
| `decider(s)` | Whose decision it is: the human or the bot. |
| `legalActions(s)` | Every legal move right now. The UI only ever picks from this list. |
| `applyAction(s, a)` | Makes the move, then runs the game until the next decision. |
| `viewFor(s, p)` | Player `p`'s view: the opponent's hand, deck, Server pile and face-down Anomalies are hidden. |
| `actionCost(s, a)` | The Gb cost to show on a move. |
| `greedyBot(DEFAULT_GREEDY)` | The opponent. It already only sees its own `viewFor`, so it can't cheat. |
| `winChance(atk, def)` in `odds.ts` | The odds of winning one combat roll, for the attack preview. |
| `checkInvariants(s)` | Catches engine bugs during play. |
Response windows only stop for a player who actually has an Execution or Ability they could use.
The engine already passes automatically for everyone else.
**Measured numbers.** These come from 50 greedy-vs-greedy games, counting South as the human:
| Measure | Value |
| --- | --- |
| Decisions per game for one player | 367, about 10 per command |
| Decisions where the only options are End, Pass or Salvage | 55 |
| Legal moves per decision | 23 on average, 112 at most |
| Response windows reaching you in the bot's command | 43 per game |
| Combat windows (before and after the roll) | 28 when you attack, 26 when the bot attacks |
| Card prompts ("pick one") | 16 per game |
| Bot's slowest move | 1.3 ms |
What this means for the design:
- **Speed is not a concern.** The bot can run in the browser, and no server is needed.
- **Click count is the main design problem.** The large number of decisions is why both levels
include step skipping. Level 2 adds settings for when the game stops to let you respond.
## 2. Architecture
```
files-tcg/
sim/ engine, card scripts, bots (unchanged, apart from section 3)
app/
index.html
src/
main.tsx start screen and page shell
match.ts game controller: real state, bot loop, undo stack
describe.ts re-export of sim/src/describe.ts
ui/ board, hand, panels, prompts
vite.config.ts
package.json
```
- **Stack: Vite, TypeScript and Preact.** Preact is the only runtime dependency. It's a small React
equivalent, and it's worth having because level 2 has a lot of selection and highlighting state.
Vite serves the sim's `.ts` imports as they are.
- **The app imports the engine from `../sim/src`, and nothing is copied.** Rule changes you test in
the sim appear in the app automatically. The app only breaks if the `Action` or `GameState` shapes
change.
- **Card data is imported live.** The app loads `cards.csv` with Vite's `?raw` import, so card edits
appear on reload.
- **The controller in `match.ts` holds the real state.** Components only receive `viewFor(s, human)`,
so the UI can't show the bot's hand by mistake.
- **Every move is one of the actions from `legalActions`.** The UI filters and labels that list and
never builds an `Action` itself. Illegal moves are therefore impossible, and the rules stay in one
place.
## 3. Sim Changes Needed First
These are small, and each keeps `npm test` passing.
1. **Browser-safe card loading.** `loadCards` reads the file with `node:fs`. Split it into
`parseCards(csvText, sets)` in `cards.ts`, and move the file-reading wrapper into a Node-only
module used by the CLI and tests.
2. **`describeAction(s, a)` in a new `sim/src/describe.ts`.** It gives a readable label for every
action type, for example `Play Execute: Force Reboot on D2 (5 Gb)` or
`Place Firewall Lv 2 on B1–C2 (4 Gb)`. Execution and Ability arguments (target Anomaly, cards,
mode) need labels too. `describeArgs` in `cards/hardware.ts` is a starting point and can be
generalized. Add a test: across fuzz games, every legal action gets a label, and no two actions in
the same decision share one.
3. **Private log lines.** `say()` writes a single public log, and some lines name hidden cards. For
example, "North chooses: Bottom Undefined Behavior and draw again" names a card in North's hand.
Give `say` an optional audience and a public version of the message. Then audit the 92 `say`
calls.
## 4. Level 1: Playtest Prototype
**Goal:** a full game against the bot in a browser, on the classic board. Every card works, and the
look is plain.
```
+--------------------------------------------------------------------------+
| NORTH (bot) 12 Gb 6 cards 4/10 locations Anomalies [1][2][■][■] |
+-----------------------------------------------+--------------------------+
| | Log |
| board (SVG) | - Round 4, command 13 - |
| locations, Servers, Anomalies, gateways | South captures B2 with |
| | Server Farm: +8 Gb |
| hover a location for details | North places a Firewall |
| | ... |
+-----------------------------------------------+--------------------------+
| SOUTH (you) 16 Gb 5/10 locations Anomalies [1][2][3][■] |
| Hand: [Overclocked CPU 6][Execute: Packet Flood 5][Resource Leech 5] ... |
| Step: Deploy > Play > Attack > Play again [End step] |
| Moves: Place > | Advance > | Play > | Install > | Firewall > | Salvage > |
+--------------------------------------------------------------------------+
```
### Features
1. **Start screen.** Pick your side (South, North or random) and a seed, which is random by default.
Both decks are random legal decks from `randomDeck`.
2. **Board.** An SVG of the 13 locations and 2 starts, with fixed coordinates for the classic board.
- Each location shows its owner color, level, Server name and Program count.
- Anomalies appear as tokens showing slot, Cores and damage/Health.
- Gateways show their Firewall level.
- Hovering a location shows a details panel: Server text, Programs, and the Anomalies there with
their Hardware.
3. **Player panels** for both sides:
- Gb, cards in hand, deck, discard and Server pile.
- Locations held out of 10.
- The four Anomaly slots: face down or up, in the slot or on a location, damage, Hardware.
- The bot's hand shows only as a count. Its discard pile can be opened.
4. **Hand.** Text cards showing name, kind, type, Gb and text.
5. **Moves panel.** The legal actions are grouped by kind and then by card, and labelled with
`describeAction` and their cost. Clicking one plays it.
- A step bar shows Deploy, Play, Attack, Play again, with an **End step** button.
- An **End command** button repeats End step. It stops early if a prompt or response window comes
up for you.
6. **Prompts.**
- A card prompt (`s.choice` for you) opens a dialog with the prompt and its options.
- A response window shows a banner such as "North attacks D1 — respond?". It lists your possible
responses and a Pass button.
7. **Bot turns.** The bot's moves play one at a time with an adjustable delay from 0 to 1 s, and the
log scrolls with them.
8. **Auto-skip.** Steps where you can only end or salvage are ended for you. This is a setting and
on by default. It saves about 55 clicks a game.
9. **Combat readout.** While a combat is live, it shows attacker and defenders, each side's Cores,
the dice once rolled, the totals and the damage.
10. **Game over.** Shows the winner, the reason and the game stats from `stats.ts`, with **New game**
and **Rematch** (same seed) buttons.
11. **Dev tools.**
- Show the seed.
- Copy the log.
- A toggle that runs `checkInvariants` after every move and shows any errors.
### Tests
- A headless test drives `match.ts` with a random "human" for a few hundred games. It checks that no
game gets stuck and the loop always hands control back.
- The `describeAction` label test from section 3.
### Done when
You can play a full game on the classic board, start to finish, without opening the browser
console, and both tests pass.
### Not in level 1
Art and card templates, acting by clicking the board, animations, undo, save, other boards, rule
variants and deck choice.
### Effort
| Work | Days |
| --- | --- |
| Sim changes (section 3) | 0.5–1 |
| App scaffold, controller, bot loop | 0.5 |
| Board, panels, hand | 1 |
| Moves panel, prompts, windows, combat readout, game over | 0.5–1 |
| Controller test and fixes from the first playtests | 0.5 |
| **Total** | **3–4** |
## 5. Level 2: Properly Playable
**Goal:** it feels like a digital card game. Each workstream below can ship on its own, in the order
listed.
### A. Click to act (2–3 days)
- **Select, then target.** Select a source: a card in hand, an Anomaly, a gateway or an Anomaly
Ability. Its legal targets then light up on the board, and clicking a target plays the move.
- This works by filtering `legalActions` by source, then by target.
- When several moves share a source and target, a small popover picks between them. Examples are
Firewall levels, Sabotage's destroy or disable, and Bit Flip's number.
- **Keep the full move list.** The level 1 moves panel becomes an "All moves" drawer, so anything
the click UI misses is still reachable.
- **Keyboard:**
| Key | Action |
| --- | --- |
| Space | End step, or Pass |
| Enter | End command |
| Z | Undo |
| Esc | Cancel the selection |
### B. Real cards (2 days)
- Render cards in the browser from the Cider templates in `decks/files-deck-1`.
- Use Handlebars with each template's CSS, scoped per template.
- Include the art from the Image column.
- Provide the helpers the templates use (`lowercase`, `eq`, `index`). `index` must return a
SafeString.
- Templates are 750×1050, so show them scaled down, with a hover zoom and right-click to pin.
- On the board, Servers, Programs and Anomalies use compact tokens, and the full card appears on hover.
- Cards without art show a placeholder in the art window.
### C. Combat and dice (1–2 days)
- A combat panel breaks down each Anomaly's Cores by source: Anomaly, Hardware, Programs, Server and
temporary modifiers. This needs a breakdown version of `anomalyCores`.
- **Before you attack,** it shows your chance to win the roll from `winChance` and the expected
damage.
- **After the roll,** it shows the dice, totals, damage and any Anomaly destroyed.
- A short dice animation, which can be turned off.
### D. Stops and pacing (1 day)
- **Stops setting.** This decides when the game waits for your response:
| Setting | Behavior |
| --- | --- |
| In combat only | The default. The bot's Executions and Ability uses outside combat pass automatically, which skips about 43 windows a game. |
| Every opponent move | Stops for every response window. |
| Never | Passes every response automatically. |
A held key overrides the setting for one window.
- Bot speed slider, pause, and step-one-move.
- A status banner shows whose command it is, the step, and any Executions waiting to resolve.
### E. Information (2 days)
- **Structured events.** Add events next to the text log, such as capture, damage, card played and
Firewall placed. They drive animations and a filterable log (Combat, Captures, Cards).
- The hooks already fired through `emit()` are a starting point.
- **Status icons** on Anomalies and cards, with tooltips:
- Infection and Bug counters
- disabled, rooted, copies, temporary Core modifiers
- Viewable discard piles and Server pile counts for both sides.
### F. Setup, saving and replays (2–3 days)
- **Decks.**
- Choose a random deck, a preset from `app/decks/*.json`, or paste a list.
- Every list is checked with `validateDeck` and errors are shown.
- **Rule variants.** An advanced panel takes the same `K=V` overrides as the CLI's `--rule`, for
playtesting variants in the app.
- **Save and resume.**
- The game saves to local storage after every move and resumes on reload.
- The state is plain data, apart from the card definitions, which are rebuilt from the CSV.
- **Undo.**
- The app snapshots the state with `structuredClone` before each of your moves. Undo goes back to
your previous decision.
- The dice RNG is part of the snapshot, so undoing and trying again doesn't reroll the dice.
- A playtest mode turns undo on. It's off for a normal game.
- **Replays.**
- A game record is the seed, both decks, the rules and the list of `actionKey`s.
- The engine is deterministic, so a record replays exactly. You can export and import records.
- Attach a record to any bug report, so the bug can be reproduced.
### G. Layout and finish (2 days)
- Targets 1280×720 and up, not phones.
- Owner colors that stay distinct for color-blind players, with a pattern as a second cue.
- Fixes from playtests.
### Effort
| Workstream | Days |
| --- | --- |
| A. Click to act | 2–3 |
| B. Real cards | 2 |
| C. Combat and dice | 1–2 |
| D. Stops and pacing | 1 |
| E. Information | 2 |
| F. Setup, saving and replays | 2–3 |
| G. Layout and finish | 2 |
| **Total** | **12–15, about 3 weeks** |
## 6. Risks
- **Human play reaches paths the bots never take.** The invariant toggle and replay records turn
these into bugs that can be reproduced. Expect the first playtests to find a few engine bugs.
- **The greedy bot is tuned for balance testing, not for fun.** Players may spot patterns it falls
for. Changing `GreedyParams` could give difficulty levels without writing a new bot.
- **The 4×4 boards need their own coordinates.** The app starts with the classic board only.
- **Set 2 cards have no scripts yet.** The app loads set 1 only, as the CLI does by default.
- **Hidden information.** The log audit in section 3 is the main risk. The engine's view and the
bot's view are already correct.
## 7. Open Decisions for the Owner
1. **Local or public.** Is the app local-only for now, or should the level 2 build go on a static
host such as itch.io or GitHub Pages for outside playtesters?
2. **Undo in normal games.** Is undo allowed outside playtest mode?
3. **Odds preview.** Should the win odds for a roll show before attacking? It helps playtesting, but
takes some tension out of the choice.

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' } },
});

View file

@ -1,14 +1,14 @@
<!--
Cider front-card template — "tech" theme
Card size: 2.5in x 3.5in poker (750 x 1050 px @ 300 DPI)
Attributes used: {{name}} {{image}} {{ram}} {{cores}} {{description}}
Attributes used: {{name}} {{image}} {{bandwidth}} {{cores}} {{description}}
-->
<div class="card">
<!-- Top stat badges -->
<div class="stat ram" title="RAM / Energy">
<span class="stat-value">{{ram}}</span>
<span class="stat-label">RAM</span>
<div class="stat bandwidth" title="Bandwidth (Gb)">
<span class="stat-value">{{bandwidth}}</span>
<span class="stat-label">Gb</span>
</div>
<div class="stat cores" title="Cores / Power">
@ -90,7 +90,7 @@
margin-top: 4px;
opacity: 0.9;
}
.ram {
.bandwidth {
left: 30px;
background: radial-gradient(circle at 35% 30%, #4aa3ff, #0b57c9 70%);
color: #eaf4ff;

210
cards.md
View file

@ -10,24 +10,24 @@ deck. Every card has a Count of 1 and uses the `Card Back` template, so neither
- Glitch (G)
- Patch (P)
### RAM
### Bandwidth
A card's printed RAM value serves two purposes:
A card's printed Bandwidth value serves two purposes:
- **Play/Install Cost:** Spend that amount of RAM to play or install the card.
- **Sacrifice Value:** Sacrifice the card to add its printed RAM value to your available RAM pool.
- **Play/Install Cost:** Spend that amount of Bandwidth to play or install the card.
- **Sacrifice Value:** Sacrifice the card to add its printed Bandwidth value to your available Bandwidth pool.
Spent RAM remains used. Any unused RAM carries over between turns. Additional RAM must be generated by Servers, abilities, or sacrificing cards.
Spent Bandwidth remains used. Any unused Bandwidth carries over between turns. Additional Bandwidth must be generated by Servers, abilities, or sacrificing cards.
### Locality (Programs & Executions)
The battlefield is a network of **Servers**. Programs and Executions do not bolt onto Avatars — they act on a **Server** and resolve **locally**, affecting the Avatars, Programs, Hardware, and combats *at that Server*.
The battlefield is a network of **Servers**. Programs and Executions do not bolt onto Anomalies — they act on a **Server** and resolve **locally**, affecting the Anomalies, Programs, Hardware, and combats *at that Server*.
- **Programs** are installed on a **Server you control** and remain there, exerting a continuous localized effect. A Server holds up to **2 Programs** (raise this with *Compatibility Layer*).
- **Enemy Avatars never occupy a Server you control.** An enemy Avatar can only reach your Server by **attacking** it — placing or moving an enemy Avatar onto your Server triggers an **immediate battle**. So a Program's "enemy" effects trigger on Avatars **attacking or breaching** this Server, and during the resulting **combat** — never on an enemy sitting idle at it. Only *your own* Avatars can be based at / defend / move away from a Server you control.
- **Program scope follows its type:** **Virus (V)** effects hit the **attacker** (Avatars attacking/breaching the Server); **Bug (B)** effects warp the **combat** at the Server; **Glitch (G)** effects manipulate **information & adjacency**; **Patch (P)** effects protect/support **your own** Avatars and economy at the Server.
- **Executions** are one-shot actions **played targeting a Server** (usually one where you have an Avatar or that you are attacking); they resolve within that Server's locality and are then discarded.
- "This Server" means the Server the Program is installed on. "At this Server" means Avatars **based/defending there** (yours) or **attacking/breaching it** (the enemy's) — plus the Programs, Hardware, and combats there.
- **Enemy Anomalies never occupy a Server you control.** An enemy Anomaly can only reach your Server by **attacking** it — placing or moving an enemy Anomaly onto your Server triggers an **immediate battle**. So a Program's "enemy" effects trigger on Anomalies **attacking or breaching** this Server, and during the resulting **combat** — never on an enemy sitting idle at it. Only *your own* Anomalies can be based at / defend / move away from a Server you control.
- **Program scope follows its type:** **Virus (V)** effects hit the **attacker** (Anomalies attacking/breaching the Server); **Bug (B)** effects warp the **combat** at the Server; **Glitch (G)** effects manipulate **information & adjacency**; **Patch (P)** effects protect/support **your own** Anomalies and economy at the Server.
- **Executions** are one-shot actions **played targeting a Server** (usually one where you have an Anomaly or that you are attacking); they resolve within that Server's locality and are then discarded.
- "This Server" means the Server the Program is installed on. "At this Server" means Anomalies **based/defending there** (yours) or **attacking/breaching it** (the enemy's) — plus the Programs, Hardware, and combats there.
### Cores
@ -36,142 +36,142 @@ A card's printed Core value is the attacking and defending amount:
- **Core:** A single core resolves to a 1d6 dice.
- **Printed Cores:** The number of cores corresponds to the number of dice rolled during action.
### Abilities (Avatars)
### Abilities (Anomalies)
Every Avatar has one printed **Ability**: an activated power with its own RAM cost, paid from your
available RAM pool and resolved during the **Resolve Abilities** step of the turn (see `notes.md`).
An Ability's cost is separate from the cost of playing the Avatar itself.
Every Anomaly has one printed **Ability**: an activated power with its own Bandwidth cost, paid from your
available Bandwidth pool and resolved during the **Resolve Abilities** step of the turn (see `notes.md`).
An Ability's cost is separate from the cost of playing the Anomaly itself.
Ability scope follows the Avatar's type, the same way Program scope does: **Virus (V)** hits the
opposing Avatar and its Hardware; **Bug (B)** warps the combat itself; **Glitch (G)** manipulates
Ability scope follows the Anomaly's type, the same way Program scope does: **Virus (V)** hits the
opposing Anomaly and its Hardware; **Bug (B)** warps the combat itself; **Glitch (G)** manipulates
information and adjacency; **Patch (P)** protects and repairs your own side.
### Expansion Slots (Avatars)
### Expansion Slots (Anomalies)
An Avatar's **Expansion Slots** are its Hardware ports — the number of Hardware cards that can be
installed on it at once. They print as the `PORTS` badge on the card face.
An Anomaly's **Expansion Slots** are the number of Hardware cards that can be
installed on it at once. They print as the `SLOTS` badge on the card face.
---
## Avatars (8)
## Anomalies (8)
*Placed on Servers you control. Cores are its combat dice; Expansion Slots are its Hardware ports.*
*Avatar play cost is not currently recorded in `cards.csv` — the RAM column is empty for all Avatars.*
*Placed on Servers you control. Cores are its combat dice; Expansion Slots are how much Hardware it holds.*
*Anomaly play cost is not currently recorded in `cards.csv` — the Bandwidth column is empty for all Anomalies.*
1. Carbon NanoBots (B) | 2 Cores | 4 Expansion Slots
- **Replicate** (5 RAM) | Avatar may create a copy of itself. Only one copy is allowed at a time. If the copy is defeated the original does not lose any hardware upgrades. If the original is defeated the replicate is as well.
- **Replicate** (5 Gb) | Anomaly may create a copy of itself. Only one copy is allowed at a time. If the copy is defeated the original does not lose any hardware upgrades. If the original is defeated the replicate is as well.
- *“Nasty little bugs...”*
2. Corrupt Driver (V) | 3 Cores | 3 Expansion Slots
- **Driver Fault** (4 RAM) | Choose one Hardware on an enemy Avatar in combat with this Avatar. It is disabled until the end of your next turn.
- **Driver Fault** (4 Gb) | Choose one Hardware on an enemy Anomaly in combat with this Anomaly. It is disabled until the end of your next turn.
3. Pixelated Picture (G) | 3 Cores | 3 Expansion Slots
- **Low Resolution** (3 RAM) | Attacking Avatars have -1 cores against this Avatar.
- **Low Resolution** (3 Gb) | Attacking Anomalies have -1 cores against this Anomaly.
4. Beta Version 1.0 (P) | 4 Cores | 2 Expansion Slots
- **Push Update** (4 RAM) | While in combat an additional piece of hardware can be placed on this avatar until the end of your turn. If there no ports available this can still be attached.
- **Push Update** (4 Gb) | While in combat an additional piece of hardware can be placed on this anomaly until the end of your turn. If there are no Expansion Slots available this can still be attached.
5. Code Zero (V) | 2 Cores | 4 Expansion Slots
- **Patient Zero** (4 RAM) | Place an Infection counter on every enemy Avatar in combat at this Server. While this Avatar is in play, an Avatar with 2+ Infection counters has -1 Core.
- **Patient Zero** (4 Gb) | Place an Infection counter on every enemy Anomaly in combat at this Server. While this Anomaly is in play, an Anomaly with 2+ Infection counters has -1 Core.
6. Data Leaker (G) | 3 Cores | 3 Expansion Slots
- **Exfiltrate** (3 RAM) | Look at your opponent's hand and choose one card in it. They must discard that card without gaining RAM. If this Avatar breached a Server this turn, draw a card.
- **Exfiltrate** (3 Gb) | Look at your opponent's hand and choose one card in it. They must discard that card without gaining Bandwidth. If this Anomaly breached a Server this turn, draw a card.
7. Backup Machine (P) | 3 Cores | 3 Expansion Slots
- **Restore Point** (5 RAM) | Return one Hardware or Program from your discard pile to your hand. If it is a Hardware and this Avatar has an open port, you may install it immediately for 2 less RAM.
- **Restore Point** (5 Gb) | Return one Hardware or Program from your discard pile to your hand. If it is a Hardware and this Anomaly has an open Expansion Slot, you may install it immediately for 2 less Gb.
8. Broken Bits (B) | 4 Cores | 2 Expansion Slots
- **Bit Flip** (4 RAM) | During a combat at this Server, reroll any number of this Avatar's Core dice.
- **Bit Flip** (4 Gb) | During a combat at this Server, reroll any number of this Anomaly's Core dice.
## Programs (28)
*Installed on a Server you control (max 2 per Server). Effects are localized to that Server.*
1. Recursive Infection (V) | Whenever an enemy Avatar attacks or breaches this Server, place an Infection counter on it. An Avatar with 3+ Infection counters has -1 Core. | 6 RAM
2. Memory Parasite (V) | Enemy Avatars attacking this Server have -1 RAM available for Executions. | 5 RAM
3. Replication Routine (V) | When you install a Virus Program on this Server, you may install a second Virus Program from your hand here for 1 less RAM. | 6 RAM
4. Resource Leech (V) | Whenever an enemy Avatar is destroyed while attacking this Server, gain 2 RAM. | 5 RAM
5. Worm Protocol (V) | The localized effects of your other Programs on this Server also apply at one adjacent Server you choose when this is installed. | 4 RAM
6. Payload Injector (V) | The first Execution you play targeting this Server each turn costs 1 less RAM. | 6 RAM
7. Persistent Infection (V) | If this Server stops being under your control, keep this Program installed here; its effect now applies to every Avatar at that Server regardless of controller. | 6 RAM
1. Recursive Infection (V) | Whenever an enemy Anomaly attacks or breaches this Server, place an Infection counter on it. An Anomaly with 3+ Infection counters has -1 Core. | 6 Gb
2. Memory Parasite (V) | Enemy Anomalies attacking this Server have -1 Gb available for Executions. | 5 Gb
3. Replication Routine (V) | When you install a Virus Program on this Server, you may install a second Virus Program from your hand here for 1 less Gb. | 6 Gb
4. Resource Leech (V) | Whenever an enemy Anomaly is destroyed while attacking this Server, gain 2 Gb. | 5 Gb
5. Worm Protocol (V) | The localized effects of your other Programs on this Server also apply at one adjacent Server you choose when this is installed. | 4 Gb
6. Payload Injector (V) | The first Execution you play targeting this Server each turn costs 1 less Gb. | 6 Gb
7. Persistent Infection (V) | If this Server stops being under your control, keep this Program installed here; its effect now applies to every Anomaly at that Server regardless of controller. | 6 Gb
8. Infinite Loop (B) | The first enemy Avatar to attack this Server each turn is caught in a loop: if it survives the battle, it must immediately repeat its attack once. Gain 1 RAM. | 5 RAM
9. Stack Overflow (B) | Avatars you control defending this Server gain +1 Core for each Program installed on this Server (including this one). | 7 RAM
10. Race Condition (B) | During any combat at this Server, both players secretly choose Attack or Defend. If the choices differ, the defender gains a combat bonus. | 4 RAM
11. Memory Leak (B) | At the start of any combat at this Server, the attacking Avatar loses 1 RAM for each Hardware installed on it. | 6 RAM
12. Null Pointer (B) | Once per turn, when an enemy Execution would resolve at this Server, resolve the game's uncertainty mechanic. On success, it does nothing. | 5 RAM
13. Deadlock (B) | Neither Avatar in a combat that takes place at this Server may retreat until that combat resolves. | 4 RAM
14. Overflow Error (B) | When an enemy Avatar is destroyed while attacking this Server, destroy or disable one Hardware or Program that Avatar's controller has in play. | 5 RAM
15. Undefined Behavior (B) | Once per turn, copy the localized effect of another Program on this Server. Then disable this Program until your next turn. | 8 RAM
8. Infinite Loop (B) | The first enemy Anomaly to attack this Server each turn is caught in a loop: if it survives the battle, it must immediately repeat its attack once. Gain 1 Gb. | 5 Gb
9. Stack Overflow (B) | Anomalies you control defending this Server gain +1 Core for each Program installed on this Server (including this one). | 7 Gb
10. Race Condition (B) | During any combat at this Server, both players secretly choose Attack or Defend. If the choices differ, the defender gains a combat bonus. | 4 Gb
11. Bloatware (B) | At the start of any combat at this Server, the attacking Anomaly loses 1 Gb for each Hardware installed on it. | 6 Gb
12. Null Pointer (B) | Once per turn, when an enemy Execution would resolve at this Server, resolve the game's uncertainty mechanic. On success, it does nothing. | 5 Gb
13. Deadlock (B) | Neither Anomaly in a combat that takes place at this Server may retreat until that combat resolves. | 4 Gb
14. Overflow Error (B) | When an enemy Anomaly is destroyed while attacking this Server, destroy or disable one Hardware or Program that Anomaly's controller has in play. | 5 Gb
15. Undefined Behavior (B) | Once per turn, copy the localized effect of another Program on this Server. Then disable this Program until your next turn. | 8 Gb
16. Packet Loss (G) | When an enemy successfully breaches this Server, its controller discards a card at random. | 6 RAM
17. Desynchronization (G) | Enemy Avatars attacking this Server cannot use their Hardware's "once per turn" abilities during that combat. | 5 RAM
18. Visual Artifact (G) | The first attack made against an Avatar you control at this Server each turn suffers -1 Core. | 5 RAM
19. Ghost Process (G) | Your Executions played targeting this Server may also affect Avatars, Programs, and Hardware at one adjacent Server. | 6 RAM
20. False Positive (G) | When an enemy Execution targets an Avatar you control at this Server, you may redirect it to another legal Avatar at this Server. | 7 RAM
21. Fragmentation (G) | Executions your opponents play targeting this Server cost +1 RAM. | 6 RAM
22. Latency Spike (G) | The attacking player cannot play Executions during the first step of any combat at this Server. | 5 RAM
16. Packet Loss (G) | When an enemy successfully breaches this Server, its controller discards a card at random. | 6 Gb
17. Desynchronization (G) | Enemy Anomalies attacking this Server cannot use their Hardware's "once per turn" abilities during that combat. | 5 Gb
18. Visual Artifact (G) | The first attack made against an Anomaly you control at this Server each turn suffers -1 Core. | 5 Gb
19. Ghost Process (G) | Your Executions played targeting this Server may also affect Anomalies, Programs, and Hardware at one adjacent Server. | 6 Gb
20. False Positive (G) | When an enemy Execution targets an Anomaly you control at this Server, you may redirect it to another legal Anomaly at this Server. | 7 Gb
21. Fragmentation (G) | Executions your opponents play targeting this Server cost +1 Gb. | 6 Gb
22. Latency Spike (G) | The attacking player cannot play Executions during the first step of any combat at this Server. | 5 Gb
23. Hotfix (P) | The first Program on this Server that would be destroyed each turn is instead disabled until your next turn. | 7 RAM
24. Error Correction (P) | At the beginning of your turn, remove one negative counter or status from each Avatar you control at this Server. | 5 RAM
25. Garbage Collection (P) | Once per turn, sacrifice one Program installed on this Server to recover its printed RAM value. | 6 RAM
26. Version Control (P) | When a Program on this Server would be destroyed, or when this Server is captured, return one Program from this Server to your hand instead of discarding it. | 5 RAM
27. Rollback Routine (P) | Once per turn, undo the most recent temporary stat reduction applied to an Avatar you control at this Server. | 4 RAM
28. Compatibility Layer (P) | This Server may hold one additional Program beyond the normal limit, and Patch Programs installed here cost 1 less RAM. | 6 RAM
23. Hotfix (P) | The first Program on this Server that would be destroyed each turn is instead disabled until your next turn. | 7 Gb
24. Error Correction (P) | At the beginning of your turn, remove one negative counter or status from each Anomaly you control at this Server. | 5 Gb
25. Garbage Collection (P) | Once per turn, sacrifice one Program installed on this Server to recover its printed Bandwidth value. | 6 Gb
26. Version Control (P) | When a Program on this Server would be destroyed, or when this Server is captured, return one Program from this Server to your hand instead of discarding it. | 5 Gb
27. Rollback Routine (P) | Once per turn, undo the most recent temporary stat reduction applied to an Anomaly you control at this Server. | 4 Gb
28. Compatibility Layer (P) | This Server may hold one additional Program beyond the normal limit, and Patch Programs installed here cost 1 less Gb. | 6 Gb
## Hardware (16)
*Installed on an Avatar, occupying one of its Expansion Slots.*
*Installed on an Anomaly, occupying one of its Expansion Slots.*
1. RAM Expansion | Avatar gains +2 RAM capacity. | 5 RAM
2. Additional Core | Avatar gains +1 Core. | 5 RAM
3. Overclocked CPU | Avatar gains +2 Cores during combat, but one installed Program becomes disabled afterward. | 6 RAM
4. Solid-State Cache | The first Program installed on this Avatar each turn costs 1 less RAM. | 6 RAM
5. Redundant Power Supply | The first time this Avatar would be destroyed, destroy this Hardware instead and leave the Avatar active. | 8 RAM
6. Network Interface Upgrade | Moving between adjacent Servers costs 1 less resource or may occur once per turn for free. | 4 RAM
7. Dedicated GPU | Executions performed by this Avatar receive +1 effectiveness or combat strength. | 6 RAM
8. ECC Memory | Opponents cannot place Bug counters or Bug status effects on this Avatar. | 5 RAM
9. Cooling System | Prevent penalties caused by Overclocking Hardware or allow one Hardware to activate twice per turn. | 6 RAM
10. RAID Array | When a Program on this Avatar is destroyed, resolve the game's uncertainty mechanic. On success, return it to your hand. | 5 RAM
11. Packet Accelerator | This Avatar acts first when it initiates combat. | 4 RAM
12. Firewall Appliance | The first hostile Program or Execution targeting this Avatar each turn costs the opponent +1 RAM. | 6 RAM
13. Hardware Sandbox | Choose one Program installed on this Avatar. It cannot be targeted by opponents. | 7 RAM
14. Diagnostic Module | Look at one facedown or hidden card associated with an opposing Avatar or Server once per turn. | 4 RAM
15. Hot-Swap Bay | Once per turn, return one Hardware to your hand and install another Hardware from your hand, paying the difference in cost. | 6 RAM
16. Quantum Coprocessor | Once per turn when this Avatar uses an Execution, you may copy that Execution's effect with a different legal target, then disable this Hardware until your next turn. | 9 RAM
1. RAM Expansion | Anomaly gains +2 Gb capacity. | 5 Gb
2. Additional Core | Anomaly gains +1 Core. | 5 Gb
3. Overclocked CPU | Anomaly gains +2 Cores during combat, but one installed Program becomes disabled afterward. | 6 Gb
4. Solid-State Cache | The first Program installed on this Anomaly each turn costs 1 less Gb. | 6 Gb
5. Redundant Power Supply | The first time this Anomaly would be destroyed, destroy this Hardware instead and leave the Anomaly active. | 8 Gb
6. Network Interface Upgrade | Moving between adjacent Servers costs 1 less resource or may occur once per turn for free. | 4 Gb
7. Dedicated GPU | Executions performed by this Anomaly receive +1 effectiveness or combat strength. | 6 Gb
8. ECC Memory | Opponents cannot place Bug counters or Bug status effects on this Anomaly. | 5 Gb
9. Cooling System | Prevent penalties caused by Overclocking Hardware or allow one Hardware to activate twice per turn. | 6 Gb
10. RAID Array | When a Program on this Anomaly is destroyed, resolve the game's uncertainty mechanic. On success, return it to your hand. | 5 Gb
11. Packet Accelerator | This Anomaly acts first when it initiates combat. | 4 Gb
12. Firewall Appliance | The first hostile Program or Execution targeting this Anomaly each turn costs the opponent +1 Gb. | 6 Gb
13. Hardware Sandbox | Choose one Program installed on this Anomaly. It cannot be targeted by opponents. | 7 Gb
14. Diagnostic Module | Look at one facedown or hidden card associated with an opposing Anomaly or Server once per turn. | 4 Gb
15. Hot-Swap Bay | Once per turn, return one Hardware to your hand and install another Hardware from your hand, paying the difference in cost. | 6 Gb
16. Quantum Coprocessor | Once per turn when this Anomaly uses an Execution, you may copy that Execution's effect with a different legal target, then disable this Hardware until your next turn. | 9 Gb
## Executions (18)
*Played targeting a Server; resolve within that Server's locality, then discard.*
1. Execute: Disconnect | Move one Avatar you control at the target Server to an adjacent Server, removing it from any combat there. | 4 RAM
2. Execute: Sabotage | Destroy or disable one Hardware on an enemy Avatar in combat at the target Server. | 7 RAM
3. Execute: Kill Process | Disable one Program installed on the target Server until its controller's next turn. | 5 RAM
4. Execute: Force Reboot | Remove all temporary bonuses and penalties from one Avatar you control at the target Server, or one Avatar attacking it. That Avatar cannot play another Execution this turn. | 5 RAM
5. Execute: Fork | Copy the localized effect of one Program installed on the target Server until end of turn. | 7 RAM
6. Execute: Ping Sweep | Look at all Programs and Hardware attached to the target Server and to every Avatar based at or attacking it, then draw a card. | 4 RAM
7. Execute: Trace Route | Move one Avatar you control from an adjacent Server to the target Server. If the target Server is enemy-controlled, your Avatar attacks it with +1 Core for the resulting combat. | 5 RAM
8. Execute: Override | Choose one enemy Program installed on the target Server. Ignore its text until the end of turn. | 5 RAM
9. Execute: Memory Dump | Draw 2 cards, then discard 1. If you control the target Server, draw 1 extra card instead of discarding. | 4 RAM
10. Execute: Rollback | Return one Program or Hardware installed at the target Server this turn to its owner's hand. | 4 RAM
11. Execute: Root Access | Until end of turn, your Programs and Executions at the target Server may target protected Programs and Hardware as though they were unprotected. | 4 RAM
12. Execute: Packet Flood | Avatars based at the target Server cannot move or retreat until the start of their controller's next turn. | 5 RAM
13. Execute: Emergency Shutdown | End any combat at the target Server immediately. All Avatars there remain and become Disabled until end of turn. | 6 RAM
14. Execute: Process Clone | Choose one Program installed on the target Server you control. Treat it as though a second copy were installed there until end of turn. | 7 RAM
15. Execute: Defragment | Re-enable one Disabled Program on the target Server, or one Disabled Hardware on an Avatar there. | 4 RAM
16. Execute: Remote Access | Activate one Program installed on a Server adjacent to the target Server as though it were installed on the target Server, until end of turn. | 6 RAM
17. Execute: Purge | Remove all Virus/Infection counters and hostile persistent effects from every Avatar you control at the target Server. | 4 RAM
18. Execute: Hard Reset | Uninstall any number of Programs from the target Server you control. For each card returned to your hand this way, recover 1 RAM. | 6 RAM
1. Execute: Disconnect | Move one Anomaly you control at the target Server to an adjacent Server, removing it from any combat there. | 4 Gb
2. Execute: Sabotage | Destroy or disable one Hardware on an enemy Anomaly in combat at the target Server. | 7 Gb
3. Execute: Kill Process | Disable one Program installed on the target Server until its controller's next turn. | 5 Gb
4. Execute: Force Reboot | Remove all temporary bonuses and penalties from one Anomaly you control at the target Server, or one Anomaly attacking it. That Anomaly cannot play another Execution this turn. | 5 Gb
5. Execute: Fork | Copy the localized effect of one Program installed on the target Server until end of turn. | 7 Gb
6. Execute: Ping Sweep | Look at all Programs and Hardware attached to the target Server and to every Anomaly based at or attacking it, then draw a card. | 4 Gb
7. Execute: Trace Route | Move one Anomaly you control from an adjacent Server to the target Server. If the target Server is enemy-controlled, your Anomaly attacks it with +1 Core for the resulting combat. | 5 Gb
8. Execute: Override | Choose one enemy Program installed on the target Server. Ignore its text until the end of turn. | 5 Gb
9. Execute: Memory Dump | Draw 2 cards, then discard 1. If you control the target Server, draw 1 extra card instead of discarding. | 4 Gb
10. Execute: Rollback | Return one Program or Hardware installed at the target Server this turn to its owner's hand. | 4 Gb
11. Execute: Root Access | Until end of turn, your Programs and Executions at the target Server may target protected Programs and Hardware as though they were unprotected. | 4 Gb
12. Execute: Packet Flood | Anomalies based at the target Server cannot move or retreat until the start of their controller's next turn. | 5 Gb
13. Execute: Emergency Shutdown | End any combat at the target Server immediately. All Anomalies there remain and become Disabled until end of turn. | 6 Gb
14. Execute: Process Clone | Choose one Program installed on the target Server you control. Treat it as though a second copy were installed there until end of turn. | 7 Gb
15. Execute: Defragment | Re-enable one Disabled Program on the target Server, or one Disabled Hardware on an Anomaly there. | 4 Gb
16. Execute: Remote Access | Activate one Program installed on a Server adjacent to the target Server as though it were installed on the target Server, until end of turn. | 6 Gb
17. Execute: Purge | Remove all Virus/Infection counters and hostile persistent effects from every Anomaly you control at the target Server. | 4 Gb
18. Execute: Hard Reset | Uninstall any number of Programs from the target Server you control. For each card returned to your hand this way, recover 1 Gb. | 6 Gb
## Servers (13)
*The nodes of the battlefield. Servers have no RAM cost.*
*The nodes of the battlefield. Servers have no Bandwidth cost.*
1. High Efficiency RAM Server | Add additional 4 RAM to resource total
2. MultiCore Server | Add 2 Cores to any Avatars
3. Cluster Server | Up to 2 Avatars can defend this Server
4. Power Server | Add additional 4 RAM to resource total
5. Backup Server | Duplicate Avatar based at this Server
6. Server Farm | Add 4 RAM to resource total and 2 Cores to any Avatar
7. Upgraded Hardware | Hardware upgrades cost 2 less RAM to install
8. Network Throttle | Firewalls cost 1 less RAM to install
9. Cloud Compute | Add 4 Cores to any Avatars
1. High Bandwidth Server | Add additional 4 Gb to resource total
2. MultiCore Server | Add 2 Cores to any Anomalies
3. Cluster Server | Up to 2 Anomalies can defend this Server
4. Power Server | Add additional 4 Gb to resource total
5. Backup Server | Duplicate Anomaly based at this Server
6. Server Farm | Add 4 Gb to resource total and 2 Cores to any Anomaly
7. Upgraded Hardware | Hardware upgrades cost 2 less Gb to install
8. Network Throttle | Firewalls cost 1 less Gb to install
9. Cloud Compute | Add 4 Cores to any Anomalies
10. Duplicate Server | Copy one adjacent Server ability
11. Pingable Server | Up to 2 Avatars can defend this Server
12. Protected Server | Add 2 RAM if defending this Server
11. Pingable Server | Up to 2 Anomalies can defend this Server
12. Protected Server | Add 2 Gb if defending this Server
13. Callable Server | When drawing a card, you may choose to place it on the bottom of the deck and draw another
## Turn Order (1)

View file

@ -1,8 +1,8 @@
/* ======================================================
Avatar card — full-bleed cyber HUD unit
Anomaly card — full-bleed cyber HUD unit
Inspired by the CD PROJEKT cyberpunk TCG frame, fused with
our deck: type accents, CPU-core power chip, gold hardware
expansion bus. RAM = cost, Cores = power.
expansion bus. Bandwidth = cost, Cores = power.
====================================================== */
.card {
@ -245,7 +245,7 @@
color: var(--accent);
text-shadow: 0 0 12px rgba(0,0,0,0.9), 0 2px 4px #000;
}
/* RAM cost chip — mirrors the .ram-chip on Program/Hardware cards */
/* Bandwidth cost chip — mirrors the .bandwidth-chip on Program/Hardware cards */
.ability-cost {
flex: none;
min-width: 92px;
@ -290,8 +290,8 @@
box-shadow: inset 0 0 26px rgba(0,0,0,0.5);
}
/* ----- Ports badge (hardware capacity) ----- */
.ports {
/* ----- Slots badge (hardware capacity: Expansion Slots) ----- */
.slots {
position: absolute;
z-index: 5;
top: 96px;
@ -306,14 +306,14 @@
background: linear-gradient(160deg, var(--accent) 0%, var(--accent-dk) 100%);
box-shadow: 0 0 16px var(--accent);
}
.ports::before {
.slots::before {
content: "";
position: absolute;
inset: 3px;
clip-path: polygon(14% 0, 100% 0, 100% 86%, 86% 100%, 0 100%, 0 14%);
background: linear-gradient(160deg, #12181f 0%, #0a0e13 100%);
}
.ports b {
.slots b {
position: relative;
z-index: 1;
font-size: 42px;
@ -322,7 +322,7 @@
color: #fff;
text-shadow: 0 0 10px var(--accent), 0 2px 3px #000;
}
.ports i {
.slots i {
position: relative;
z-index: 1;
font-style: normal;
@ -333,7 +333,7 @@
color: var(--accent);
}
/* ----- Health badge (damage to destroy) — same chassis as PORTS, with a pulse line ----- */
/* ----- Health badge (damage to destroy) — same chassis as SLOTS, with a pulse line ----- */
.health {
position: absolute;
z-index: 5;

View file

@ -1,12 +1,12 @@
<!--
Avatar-Front template — full-bleed cyber HUD unit card
Anomaly-Front template — full-bleed cyber HUD unit card
Card size: 750 x 1050 px (2.5in x 3.5in @ 300 DPI)
Attributes: {{card.name}} {{card.image}} {{card.cores}} {{card.health}} {{card.type}} {{card.description}} {{card.[expansion-slots]}}
{{card.[ability-name]}} {{card.[ability-cost]}} {{card.[ability-description]}}
Cores = CPU-core chip (top-left), accent driven by Type (V/B/G/P).
Expansion Slots = number of hardware ports (shown on the PORTS badge, top-right).
Health = damage that destroys the Avatar (HEALTH badge with a pulse line, under PORTS).
Ability = the Avatar's activated power: name + RAM cost chip, then its rules text.
Expansion Slots = how much Hardware it holds (shown on the SLOTS badge, top-right).
Health = damage that destroys the Anomaly (HEALTH badge with a pulse line, under SLOTS).
Ability = the Anomaly's activated power: name + Bandwidth cost chip, then its rules text.
Text section order (top to bottom): name, ability, description.
The gold expansion bus (bottom) mirrors the Hardware card edge connector — hardware plugs in here.
-->
@ -27,16 +27,16 @@
<div class="typechip">{{card.type}}</div>
<!-- Top-right: unit tab -->
<div class="unit-tab">AVATAR</div>
<div class="unit-tab">ANOMALY</div>
<!-- Ports badge: hardware capacity (Expansion Slots) -->
<div class="ports">
<!-- Slots badge: hardware capacity (Expansion Slots) -->
<div class="slots">
<span class="plug"></span>
<b>{{card.[expansion-slots]}}</b>
<i>PORTS</i>
<i>SLOTS</i>
</div>
<!-- Health badge: damage it takes to destroy this Avatar -->
<!-- Health badge: damage it takes to destroy this Anomaly -->
<div class="health">
<span class="pulse"></span>
<b>{{card.health}}</b>
@ -57,9 +57,9 @@
<div class="ability-head">
<span class="ability-name">{{card.[ability-name]}}</span>
{{#if card.[ability-cost]}}
<span class="ability-cost" title="Ability RAM cost">
<span class="ability-cost" title="Ability Bandwidth cost">
<b>{{card.[ability-cost]}}</b>
<i>RAM</i>
<i>Gb</i>
</span>
{{/if}}
</div>

View file

@ -3,14 +3,14 @@
"Count","How many of this card appear in the deck","numeric","[]","60","1"
"Front Template","The card's front template","dropdown","[]","263","2"
"Back Template","The card's back template","dropdown","[]","135","3"
"RAM",,"numeric",,"60","4"
"Bandwidth",,"numeric",,"60","4"
"Cores",,"numeric",,"60","5"
"Description",,"text",,"152","6"
"Type","Virus / Bug / Glitch / Patch","dropdown","[{""value"":""V,B,G,P"",""color"":""#214ACE""}]","60","7"
"Image",,"text",,"135","8"
"Expansion Slots","Expansion Slots for Upgrades","numeric",,"60","9"
"Ability Cost","Ability Ram cost","numeric",,"60","10"
"Ability Cost","Ability Bandwidth cost","numeric",,"60","10"
"Ability Name","Name of Ability","text",,"72","11"
"Ability Description","Description for ABility","text",,"202","12"
"Health","Avatar Health: the damage that destroys it","numeric",,"60","13"
"Health","Anomaly Health: the damage that destroys it","numeric",,"60","13"
"Set","Card set: 1 = base, 2 = expansion","numeric",,"60","14"
1 Name Description Type Options Width Order
3 Count How many of this card appear in the deck numeric [] 60 1
4 Front Template The card's front template dropdown [] 263 2
5 Back Template The card's back template dropdown [] 135 3
6 RAM Bandwidth numeric 60 4
7 Cores numeric 60 5
8 Description text 152 6
9 Type Virus / Bug / Glitch / Patch dropdown [{"value":"V,B,G,P","color":"#214ACE"}] 60 7
10 Image text 135 8
11 Expansion Slots Expansion Slots for Upgrades numeric 60 9
12 Ability Cost Ability Ram cost Ability Bandwidth cost numeric 60 10
13 Ability Name Name of Ability text 72 11
14 Ability Description Description for ABility text 202 12
15 Health Avatar Health: the damage that destroys it Anomaly Health: the damage that destroys it numeric 60 13
16 Set Card set: 1 = base, 2 = expansion numeric 60 14

View file

@ -1,137 +1,137 @@
"Name","Count","Front Template","Back Template","RAM","Cores","Description","Type","Image","Expansion Slots","Ability Cost","Ability Name","Ability Description","Health","Set"
"Carbon NanoBots","1","Avatar Front","Card Back",,"2","Nasty little bugs...","B","nano-bots","4","6","Replicate","Avatar may create a copy of itself. Only one copy is allowed at a time. If the copy is defeated the original does not lose any hardware upgrades. If the original is defeated the replicate is as well.","10","1"
"Corrupt Driver","1","Avatar Front","Card Back",,"3",,"V","driver-ascii-art","3","4","Driver Fault","Choose one Hardware on an enemy Avatar in combat with this Avatar. It is disabled until the end of your next command.","10","1"
"Pixelated Picture","1","Avatar Front","Card Back",,"3",,"G","pix","3","3","Low Resolution","Attacking Avatars have -1 cores against this Avatar.","10","1"
"Beta Version 1.0","1","Avatar Front","Card Back",,"4",,"P","broken-bits","2","4","Push Update","While in combat an additional piece of hardware can be placed on this avatar until the end of your command. If there no ports available this can still be attached.","9","1"
"Code Zero","1","Avatar Front","Card Back",,"3",,"V","code-zero","4","4","Patient Zero","Place an Infection counter on every enemy Avatar in combat at this Server. While this Avatar is in play, an Avatar with 1+ Infection counters has -1 Core.","10","1"
"Data Leaker","1","Avatar Front","Card Back",,"3",,"G","data-leaker","3","3","Exfiltrate","Look at your opponent's hand and choose one card in it. They must discard that card without gaining RAM. If this Avatar breached a Server this command, draw a card.","10","1"
"Backup Machine","1","Avatar Front","Card Back",,"3",,"P","backup","3","5","Restore Point","Remove 3 damage from this Avatar, or return one Hardware or Program from your discard pile to your hand. If it is a Hardware and this Avatar has an open port, you may install it immediately for 2 less RAM.","10","1"
"Broken Bits","1","Avatar Front","Card Back",,"4",,"B","broken-bits-2","2","4","Bit Flip","During a combat at this Server, reroll any number of this Avatar's Core dice.","9","1"
"Recursive Infection","1","Program Front","Card Back","6",,"Whenever an enemy Avatar attacks or breaches this Server, place an Infection counter on it. An Avatar with 3+ Infection counters has -2 Core.","V",,,,,,,"1"
"Memory Parasite","1","Program Front","Card Back","5",,"Enemy Avatars attacking this Server have 1 hardware component disabled of the owners choosing.","V",,,,,,,"1"
"Replication Routine","1","Program Front","Card Back","6",,"When you install a Virus Program on this Server, you may install a second Virus Program from your hand here for no RAM cost.","V",,,,,,,"1"
"Resource Leech","1","Program Front","Card Back","5",,"Whenever an enemy Avatar takes damage while attacking this Server, gain 3 RAM.","V",,,,,,,"1"
"Worm Protocol","1","Program Front","Card Back","4",,"The localized effects of your other Programs on this Server also apply at one adjacent Server you choose when this is installed.","V",,,,,,,"1"
"Payload Injector","1","Program Front","Card Back","6",,"The first Execution you play targeting this Server each round costs 2 less RAM.","V",,,,,,,"1"
"Persistent Infection","1","Program Front","Card Back","6",,"Whenever an enemy Avatar takes damage at this Server, place an Infection counter on it permanently.","V",,,,,,,"1"
"Infinite Loop","1","Program Front","Card Back","5",,"If the attacking Avatar is controlled by the owner of this Program, it may attack a second adjacent Server in the same command.","B",,,,,,,"1"
"Stack Overflow","1","Program Front","Card Back","7",,"Avatars you control defending this Server gain +1 Core for each Program installed on this Server (including this one).","B",,,,,,,"1"
"Race Condition","1","Program Front","Card Back","4",,"During any combat at this Server, both players secretly choose Attack or Defend. If the choices differ, the defender gains a combat bonus of +2 Cores.","B",,,,,,,"1"
"Memory Leak","1","Program Front","Card Back","6",,"At the start of any combat at this Server, the attacking Avatar loses 1 Core for each Hardware installed on it.","B",,,,,,,"1"
"Null Pointer","1","Program Front","Card Back","5",,"Once per round, when an enemy Execution would resolve at this Server, it's effect does not occur.","B",,,,,,,"1"
"Stock Rice","1","Program Front","Card Back","4",,"Neither Avatar in a combat that takes place at this Server may use any Hardware bonuses.","B",,,,,,,"1"
"Overflow Error","1","Program Front","Card Back","5",,"When an enemy Avatar takes damage while attacking this Server, disable one Program its controller has in play until their next command. If the Avatar was destroyed, you may destroy that Program instead.","B",,,,,,,"1"
"Undefined Behavior","1","Program Front","Card Back","8",,"Once per round, copy the localized effect of another Program on another Server. Then disable this Program until your next command.","B",,,,,,,"1"
"Packet Loss","1","Program Front","Card Back","6",,"When an enemy successfully breaches this Server, its controller discards a card at random.","G",,,,,,,"1"
"Desynchronization","1","Program Front","Card Back","5",,"Enemy Avatars attacking this Server cannot use their Hardware's ""once per round"" abilities during that combat.","G",,,,,,,"1"
"Visual Artifact","1","Program Front","Card Back","5",,"The first attack made against an Avatar you control at this Server suffers -1 Core.","G",,,,,,,"1"
"Ghost Process","1","Program Front","Card Back","6",,"Your Executions played targeting this Server may also affect Avatars, Programs, and Hardware at one adjacent Server.","G",,,,,,,"1"
"False Positive","1","Program Front","Card Back","7",,"When an enemy Execution targets an Avatar you control at this Server, you may redirect it to another legal Avatar at another Server.","G",,,,,,,"1"
"Fragmentation","1","Program Front","Card Back","6",,"Executions your opponents play targeting this Server cost +2 RAM.","G",,,,,,,"1"
"Latency Spike","1","Program Front","Card Back","5",,"The attacking player cannot play Executions during the first step of any combat at this Server.","G",,,,,,,"1"
"Hotfix","1","Program Front","Card Back","7",,"The first Program on this Server that would be destroyed each round is instead disabled until your next command.","P",,,,,,,"1"
"Error Correction","1","Program Front","Card Back","5",,"At the beginning of your first command each round, remove one negative counter or status from each Avatar you control at this Server.","P",,,,,,,"1"
"Garbage Collection","1","Program Front","Card Back","6",,"Once per round, sacrifice one Program installed on this Server to recover its printed RAM value.","P",,,,,,,"1"
"Version Control","1","Program Front","Card Back","5",,"When a Program on this Server would be destroyed, or when this Server is captured, return one Program from this Server to your hand instead of discarding it.","P",,,,,,,"1"
"Rollback Routine","1","Program Front","Card Back","4",,"Once per round, undo the most recent temporary stat reduction applied to an Avatar you control at this Server.","P",,,,,,,"1"
"Compatibility Layer","1","Program Front","Card Back","6",,"This Server may hold one additional Program beyond the normal limit, and Patch Programs installed here cost 2 less RAM.","P",,,,,,,"1"
"RAM Expansion","1","Hardware Front","Card Back","5",,"Avatar gains +2 Health.",,,,,,,,"1"
"Additional Core","1","Hardware Front","Card Back","5",,"Avatar gains +1 Core.",,,,,,,,"1"
"Overclocked CPU","1","Hardware Front","Card Back","6",,"Avatar gains +2 Cores during combat, but one installed Program at the current server becomes disabled afterward for 2 commands.",,,,,,,,"1"
"Solid-State Cache","1","Hardware Front","Card Back","6",,"The first Program installed on the occupied Server each round costs 3 less RAM.",,,,,,,,"1"
"Redundant Power Supply","1","Hardware Front","Card Back","8",,"The first time this Avatar would be destroyed, do not destroy the Hardware.",,,,,,,,"1"
"Network Interface Upgrade","1","Hardware Front","Card Back","4",,"This Hardware can be played without taking an upgrade port on the Avatar.",,,,,,,,"1"
"Dedicated GPU","1","Hardware Front","Card Back","6",,"Executions performed by this Avatar receive +1 effectiveness or combat strength.",,,,,,,,"1"
"ECC Memory","1","Hardware Front","Card Back","5",,"Opponents cannot place Bug counters or Bug status effects on this Avatar.",,,,,,,,"1"
"Cooling System","1","Hardware Front","Card Back","6",,"Allow one Hardware to activate twice per round.",,,,,,,,"1"
"RAID Array","1","Hardware Front","Card Back","5",,"When this Avatar is destroyed, all hardware can be kept by paying half the RAM cost.",,,,,,,,"1"
"Packet Accelerator","1","Hardware Front","Card Back","4",,"This Avatar gains +1 Core hen attacking.",,,,,,,,"1"
"Firewall Appliance","1","Hardware Front","Card Back","6",,"The first hostile Program or Execution targeting this Avatar each round costs the opponent +3 RAM.",,,,,,,,"1"
"Hardware Sandbox","1","Hardware Front","Card Back","7",,"Choose one Program installed on the occupied Server. It cannot be targeted by opponents.",,,,,,,,"1"
"Diagnostic Module","1","Hardware Front","Card Back","4",,"Look at one face down card in your draw pile. You may place it at the bottom and draw another to start your first command each round.",,,,,,,,"1"
"Hot-Swap Bay","1","Hardware Front","Card Back","6",,"Once per round, return one Hardware to your hand and install another Hardware from your hand, paying the difference in cost.",,,,,,,,"1"
"Quantum Coprocessor","1","Hardware Front","Card Back","9",,"Once per round when this Avatar uses an Execution, you may copy that Execution's effect with a different legal target, then disable this Hardware.",,,,,,,,"1"
"High Efficiency RAM Server","1","Server Front","Card Back",,,"Add additional 4 RAM to resource total",,,,,,,,"1"
"MultiCore Server","1","Server Front","Card Back",,,"Add 2 Cores to any Avatars",,,,,,,,"1"
"Cluster Server","1","Server Front","Card Back",,,"Up to 2 Avatars can defend this Server",,,,,,,,"1"
"Power Server","1","Server Front","Card Back",,,"Add additional 4 RAM to resource total",,,,,,,,"1"
"Backup Server","1","Server Front","Card Back",,,"Duplicate Avatar based at this Server",,,,,,,,"1"
"Server Farm","1","Server Front","Card Back",,,"Add 4 RAM to resource total and 2 Cores to any Avatar",,,,,,,,"1"
"Upgraded Hardware","1","Server Front","Card Back",,,"Hardware upgrades cost 2 less RAM to install",,,,,,,,"1"
"Network Throttle","1","Server Front","Card Back",,,"Firewalls cost 1 less RAM to install",,,,,,,,"1"
"Cloud Compute","1","Server Front","Card Back",,,"Add 4 Cores to any Avatars",,,,,,,,"1"
"Name","Count","Front Template","Back Template","Bandwidth","Cores","Description","Type","Image","Expansion Slots","Ability Cost","Ability Name","Ability Description","Health","Set"
"Carbon NanoBots","1","Anomaly Front","Card Back",,"2","Nasty little bugs...","B","nano-bots","4","6","Replicate","Anomaly may create a copy of itself. Only one copy is allowed at a time. If the copy is defeated the original does not lose any hardware upgrades. If the original is defeated the replicate is as well.","10","1"
"Corrupt Driver","1","Anomaly Front","Card Back",,"3",,"V","driver-ascii-art","3","4","Driver Fault","Choose one Hardware on an enemy Anomaly in combat with this Anomaly. It is disabled until the end of your next command.","10","1"
"Pixelated Picture","1","Anomaly Front","Card Back",,"3",,"G","pix","3","3","Low Resolution","Attacking Anomalies have -1 cores against this Anomaly.","10","1"
"Beta Version 1.0","1","Anomaly Front","Card Back",,"4",,"P","broken-bits","2","4","Push Update","While in combat an additional piece of hardware can be placed on this anomaly until the end of your command. If there are no Expansion Slots available this can still be attached.","9","1"
"Code Zero","1","Anomaly Front","Card Back",,"3",,"V","code-zero","4","4","Patient Zero","Place an Infection counter on every enemy Anomaly in combat at this Server. While this Anomaly is in play, an Anomaly with 1+ Infection counters has -1 Core.","10","1"
"Data Leaker","1","Anomaly Front","Card Back",,"3",,"G","data-leaker","3","3","Exfiltrate","Look at your opponent's hand and choose one card in it. They must discard that card without gaining Bandwidth. If this Anomaly breached a Server this command, draw a card.","10","1"
"Backup Machine","1","Anomaly Front","Card Back",,"3",,"P","backup","3","5","Restore Point","Remove 3 damage from this Anomaly, or return one Hardware or Program from your discard pile to your hand. If it is a Hardware and this Anomaly has an open Expansion Slot, you may install it immediately for 2 less Gb.","10","1"
"Broken Bits","1","Anomaly Front","Card Back",,"4",,"B","broken-bits-2","2","4","Bit Flip","During a combat at this Server, reroll any number of this Anomaly's Core dice.","9","1"
"Recursive Infection","1","Program Front - Alt","Card Back","6",,"Whenever an enemy Anomaly attacks or breaches this Server, place an Infection counter on it. An Anomaly with 3+ Infection counters has -2 Core.","V",,,,,,,"1"
"Memory Parasite","1","Program Front - Alt","Card Back","5",,"Enemy Anomalies attacking this Server have 1 hardware component disabled of the owners choosing.","V",,,,,,,"1"
"Replication Routine","1","Program Front - Alt","Card Back","6",,"When you install a Virus Program on this Server, you may install a second Virus Program from your hand here for no Bandwidth cost.","V",,,,,,,"1"
"Resource Leech","1","Program Front - Alt","Card Back","5",,"Whenever an enemy Anomaly takes damage while attacking this Server, gain 3 Gb.","V",,,,,,,"1"
"Worm Protocol","1","Program Front - Alt","Card Back","4",,"The localized effects of your other Programs on this Server also apply at one adjacent Server you choose when this is installed.","V",,,,,,,"1"
"Payload Injector","1","Program Front - Alt","Card Back","6",,"The first Execution you play targeting this Server each round costs 2 less Gb.","V",,,,,,,"1"
"Persistent Infection","1","Program Front - Alt","Card Back","6",,"Whenever an enemy Anomaly takes damage at this Server, place an Infection counter on it permanently.","V",,,,,,,"1"
"Infinite Loop","1","Program Front - Alt","Card Back","5",,"If the attacking Anomaly is controlled by the owner of this Program, it may attack a second adjacent Server in the same command.","B",,,,,,,"1"
"Stack Overflow","1","Program Front - Alt","Card Back","7",,"Anomalies you control defending this Server gain +1 Core for each Program installed on this Server (including this one).","B",,,,,,,"1"
"Race Condition","1","Program Front - Alt","Card Back","4",,"During any combat at this Server, both players secretly choose Attack or Defend. If the choices differ, the defender gains a combat bonus of +2 Cores.","B",,,,,,,"1"
"Bloatware","1","Program Front - Alt","Card Back","6",,"At the start of any combat at this Server, the attacking Anomaly loses 1 Core for each Hardware installed on it.","B",,,,,,,"1"
"Null Pointer","1","Program Front - Alt","Card Back","5",,"Once per round, when an enemy Execution would resolve at this Server, it's effect does not occur.","B",,,,,,,"1"
"Stock Rice","1","Program Front - Alt","Card Back","4",,"Neither Anomaly in a combat that takes place at this Server may use any Hardware bonuses.","B",,,,,,,"1"
"Overflow Error","1","Program Front - Alt","Card Back","5",,"When an enemy Anomaly takes damage while attacking this Server, disable one Program its controller has in play until their next command. If the Anomaly was destroyed, you may destroy that Program instead.","B",,,,,,,"1"
"Undefined Behavior","1","Program Front - Alt","Card Back","8",,"Once per round, copy the localized effect of another Program on another Server. Then disable this Program until your next command.","B",,,,,,,"1"
"Packet Loss","1","Program Front - Alt","Card Back","6",,"When an enemy successfully breaches this Server, its controller discards a card at random.","G",,,,,,,"1"
"Desynchronization","1","Program Front - Alt","Card Back","5",,"Enemy Anomalies attacking this Server cannot use their Hardware's ""once per round"" abilities during that combat.","G",,,,,,,"1"
"Visual Artifact","1","Program Front - Alt","Card Back","5",,"The first attack made against an Anomaly you control at this Server suffers -1 Core.","G",,,,,,,"1"
"Ghost Process","1","Program Front - Alt","Card Back","6",,"Your Executions played targeting this Server may also affect Anomalies, Programs, and Hardware at one adjacent Server.","G",,,,,,,"1"
"False Positive","1","Program Front - Alt","Card Back","7",,"When an enemy Execution targets an Anomaly you control at this Server, you may redirect it to another legal Anomaly at another Server.","G",,,,,,,"1"
"Fragmentation","1","Program Front - Alt","Card Back","6",,"Executions your opponents play targeting this Server cost +2 Gb.","G",,,,,,,"1"
"Latency Spike","1","Program Front - Alt","Card Back","5",,"The attacking player cannot play Executions during the first step of any combat at this Server.","G",,,,,,,"1"
"Hotfix","1","Program Front - Alt","Card Back","7",,"The first Program on this Server that would be destroyed each round is instead disabled until your next command.","P",,,,,,,"1"
"Error Correction","1","Program Front - Alt","Card Back","5",,"At the beginning of your first command each round, remove one negative counter or status from each Anomaly you control at this Server.","P",,,,,,,"1"
"Garbage Collection","1","Program Front - Alt","Card Back","6",,"Once per round, sacrifice one Program installed on this Server to recover its printed Bandwidth value.","P",,,,,,,"1"
"Version Control","1","Program Front - Alt","Card Back","5",,"When a Program on this Server would be destroyed, or when this Server is captured, return one Program from this Server to your hand instead of discarding it.","P",,,,,,,"1"
"Rollback Routine","1","Program Front - Alt","Card Back","4",,"Once per round, undo the most recent temporary stat reduction applied to an Anomaly you control at this Server.","P",,,,,,,"1"
"Compatibility Layer","1","Program Front - Alt","Card Back","6",,"This Server may hold one additional Program beyond the normal limit, and Patch Programs installed here cost 2 less Gb.","P",,,,,,,"1"
"RAM Expansion","1","Hardware Front - Alt","Card Back","5",,"Anomaly gains +2 Health.",,,,,,,,"1"
"Additional Core","1","Hardware Front - Alt","Card Back","5",,"Anomaly gains +1 Core.",,,,,,,,"1"
"Overclocked CPU","1","Hardware Front - Alt","Card Back","6",,"Anomaly gains +2 Cores during combat, but one installed Program at the current server becomes disabled afterward for 2 commands.",,,,,,,,"1"
"Solid-State Cache","1","Hardware Front - Alt","Card Back","6",,"The first Program installed on the occupied Server each round costs 3 less Gb.",,,,,,,,"1"
"Redundant Power Supply","1","Hardware Front - Alt","Card Back","8",,"The first time this Anomaly would be destroyed, do not destroy the Hardware.",,,,,,,,"1"
"Network Interface Upgrade","1","Hardware Front - Alt","Card Back","4",,"This Hardware can be played without taking an Expansion Slot on the Anomaly.",,,,,,,,"1"
"Dedicated GPU","1","Hardware Front - Alt","Card Back","6",,"Executions performed by this Anomaly receive +1 effectiveness or combat strength.",,,,,,,,"1"
"ECC Memory","1","Hardware Front - Alt","Card Back","5",,"Opponents cannot place Bug counters or Bug status effects on this Anomaly.",,,,,,,,"1"
"Cooling System","1","Hardware Front - Alt","Card Back","6",,"Allow one Hardware to activate twice per round.",,,,,,,,"1"
"RAID Array","1","Hardware Front - Alt","Card Back","5",,"When this Anomaly is destroyed, all hardware can be kept by paying half the Bandwidth cost.",,,,,,,,"1"
"Packet Accelerator","1","Hardware Front - Alt","Card Back","4",,"This Anomaly gains +1 Core hen attacking.",,,,,,,,"1"
"Firewall Appliance","1","Hardware Front - Alt","Card Back","6",,"The first hostile Program or Execution targeting this Anomaly each round costs the opponent +3 Gb.",,,,,,,,"1"
"Hardware Sandbox","1","Hardware Front - Alt","Card Back","7",,"Choose one Program installed on the occupied Server. It cannot be targeted by opponents.",,,,,,,,"1"
"Diagnostic Module","1","Hardware Front - Alt","Card Back","4",,"Look at one face down card in your draw pile. You may place it at the bottom and draw another to start your first command each round.",,,,,,,,"1"
"Hot-Swap Bay","1","Hardware Front - Alt","Card Back","6",,"Once per round, return one Hardware to your hand and install another Hardware from your hand, paying the difference in cost.",,,,,,,,"1"
"Quantum Coprocessor","1","Hardware Front - Alt","Card Back","9",,"Once per round when this Anomaly uses an Execution, you may copy that Execution's effect with a different legal target, then disable this Hardware.",,,,,,,,"1"
"High Bandwidth Server","1","Server Front","Card Back",,,"Add additional 4 Gb to resource total",,,,,,,,"1"
"MultiCore Server","1","Server Front","Card Back",,,"Add 2 Cores to any Anomalies",,,,,,,,"1"
"Cluster Server","1","Server Front","Card Back",,,"Up to 2 Anomalies can defend this Server",,,,,,,,"1"
"Power Server","1","Server Front","Card Back",,,"Add additional 4 Gb to resource total",,,,,,,,"1"
"Backup Server","1","Server Front","Card Back",,,"Duplicate Anomaly based at this Server",,,,,,,,"1"
"Server Farm","1","Server Front","Card Back",,,"Add 4 Gb to resource total and 2 Cores to any Anomaly",,,,,,,,"1"
"Upgraded Hardware","1","Server Front","Card Back",,,"Hardware upgrades cost 2 less Gb to install",,,,,,,,"1"
"Network Throttle","1","Server Front","Card Back",,,"Firewalls cost 1 less Gb to install",,,,,,,,"1"
"Cloud Compute","1","Server Front","Card Back",,,"Add 4 Cores to any Anomalies",,,,,,,,"1"
"Duplicate Server","1","Server Front","Card Back",,,"Copy one adjacent Server ability",,,,,,,,"1"
"Pingable Server","1","Server Front","Card Back",,,"Up to 2 Avatars can defend this Server",,,,,,,,"1"
"Protected Server","1","Server Front","Card Back",,,"Add 2 RAM if defending this Server",,,,,,,,"1"
"Pingable Server","1","Server Front","Card Back",,,"Up to 2 Anomalies can defend this Server",,,,,,,,"1"
"Protected Server","1","Server Front","Card Back",,,"Add 2 Gb if defending this Server",,,,,,,,"1"
"Callable Server","1","Server Front","Card Back",,,"When drawing a card, you may choose to place it on the bottom of the deck and draw another",,,,,,,,"1"
"Execute: Disconnect","1","Execution Front","Card Back","4",,"Move one Avatar you control at the target Server to an adjacent Server, removing it from any combat there.",,,,,,,,"1"
"Execute: Sabotage","1","Execution Front","Card Back","7",,"Destroy or disable one Hardware on an enemy Avatar in combat at the target Server.",,,,,,,,"1"
"Execute: Kill Process","1","Execution Front","Card Back","5",,"Disable one Program installed on the target Server until its controller's next command.",,,,,,,,"1"
"Execute: Force Reboot","1","Execution Front","Card Back","5",,"Remove all temporary bonuses and penalties from one Avatar you control at the target Server, or one Avatar attacking it. That Avatar cannot play another Execution until end of current command.",,,,,,,,"1"
"Execute: Fork","1","Execution Front","Card Back","7",,"Copy the localized effect of one Program installed on the target Server until end of current command.",,,,,,,,"1"
"Execute: Ping Sweep","1","Execution Front","Card Back","4",,"You may draw 2 cards from the top of your deck.",,,,,,,,"1"
"Execute: Trace Route","1","Execution Front","Card Back","5",,"Move one Avatar you control from an adjacent Server to the target Server. If the target Server is enemy-controlled, your Avatar attacks it with +1 Core for the resulting combat.",,,,,,,,"1"
"Execute: Override","1","Execution Front","Card Back","5",,"Choose one enemy Program installed on the target Server. Ignore its text until end of current command.",,,,,,,,"1"
"Execute: Memory Dump","1","Execution Front","Card Back","4",,"Draw 2 cards, then discard 1. If you control the target Server, draw 1 extra card instead of discarding.",,,,,,,,"1"
"Execute: Rollback","1","Execution Front","Card Back","4",,"Return one Program or Hardware installed at the target Server this command to its owner's hand.",,,,,,,,"1"
"Execute: Root Access","1","Execution Front","Card Back","4",,"Until end of current command, your Programs and Executions at the target Server may target protected Programs and Hardware as though they were unprotected.",,,,,,,,"1"
"Execute: Packet Flood","1","Execution Front","Card Back","5",,"Avatars based at the target Server cannot move or retreat until the start of their controller's next command.",,,,,,,,"1"
"Execute: Emergency Shutdown","1","Execution Front","Card Back","6",,"End any combat at the target Server immediately. All Avatars there remain and become Disabled until end of current command.",,,,,,,,"1"
"Execute: Process Clone","1","Execution Front","Card Back","7",,"Choose one Program installed on the target Server you control. Treat it as though a second copy were installed there until end of current command.",,,,,,,,"1"
"Execute: Defragment","1","Execution Front","Card Back","4",,"Re-enable one Disabled Program on the target Server, or one Disabled Hardware on an Avatar there.",,,,,,,,"1"
"Execute: Remote Access","1","Execution Front","Card Back","6",,"Activate one Program installed on a Server adjacent to the target Server as though it were installed on the target Server, until end of current command.",,,,,,,,"1"
"Execute: Purge","1","Execution Front","Card Back","4",,"Remove all Virus/Infection counters and hostile persistent effects from every Avatar you control at the target Server.",,,,,,,,"1"
"Execute: Hard Reset","1","Execution Front","Card Back","6",,"Uninstall any number of Programs from the target Server you control. For each card returned to your hand this way, recover 1 RAM.",,,,,,,,"1"
"Execute: Disconnect","1","Execution Front - Alt","Card Back","4",,"Move one Anomaly you control at the target Server to an adjacent Server, removing it from any combat there.",,,,,,,,"1"
"Execute: Sabotage","1","Execution Front - Alt","Card Back","7",,"Destroy or disable one Hardware on an enemy Anomaly in combat at the target Server.",,,,,,,,"1"
"Execute: Kill Process","1","Execution Front - Alt","Card Back","5",,"Disable one Program installed on the target Server until its controller's next command.",,,,,,,,"1"
"Execute: Force Reboot","1","Execution Front - Alt","Card Back","5",,"Remove all temporary bonuses and penalties from one Anomaly you control at the target Server, or one Anomaly attacking it. That Anomaly cannot play another Execution until end of current command.",,,,,,,,"1"
"Execute: Fork","1","Execution Front - Alt","Card Back","7",,"Copy the localized effect of one Program installed on the target Server until end of current command.",,,,,,,,"1"
"Execute: Ping Sweep","1","Execution Front - Alt","Card Back","4",,"You may draw 2 cards from the top of your deck.",,,,,,,,"1"
"Execute: Trace Route","1","Execution Front - Alt","Card Back","5",,"Move one Anomaly you control from an adjacent Server to the target Server. If the target Server is enemy-controlled, your Anomaly attacks it with +1 Core for the resulting combat.",,,,,,,,"1"
"Execute: Override","1","Execution Front - Alt","Card Back","5",,"Choose one enemy Program installed on the target Server. Ignore its text until end of current command.",,,,,,,,"1"
"Execute: Memory Dump","1","Execution Front - Alt","Card Back","4",,"Draw 2 cards, then discard 1. If you control the target Server, draw 1 extra card instead of discarding.",,,,,,,,"1"
"Execute: Rollback","1","Execution Front - Alt","Card Back","4",,"Return one Program or Hardware installed at the target Server this command to its owner's hand.",,,,,,,,"1"
"Execute: Root Access","1","Execution Front - Alt","Card Back","4",,"Until end of current command, your Programs and Executions at the target Server may target protected Programs and Hardware as though they were unprotected.",,,,,,,,"1"
"Execute: Packet Flood","1","Execution Front - Alt","Card Back","5",,"Anomalies based at the target Server cannot move or retreat until the start of their controller's next command.",,,,,,,,"1"
"Execute: Emergency Shutdown","1","Execution Front - Alt","Card Back","6",,"End any combat at the target Server immediately. All Anomalies there remain and become Disabled until end of current command.",,,,,,,,"1"
"Execute: Process Clone","1","Execution Front - Alt","Card Back","7",,"Choose one Program installed on the target Server you control. Treat it as though a second copy were installed there until end of current command.",,,,,,,,"1"
"Execute: Defragment","1","Execution Front - Alt","Card Back","4",,"Re-enable one Disabled Program on the target Server, or one Disabled Hardware on an Anomaly there.",,,,,,,,"1"
"Execute: Remote Access","1","Execution Front - Alt","Card Back","6",,"Activate one Program installed on a Server adjacent to the target Server as though it were installed on the target Server, until end of current command.",,,,,,,,"1"
"Execute: Purge","1","Execution Front - Alt","Card Back","4",,"Remove all Virus/Infection counters and hostile persistent effects from every Anomaly you control at the target Server.",,,,,,,,"1"
"Execute: Hard Reset","1","Execution Front - Alt","Card Back","6",,"Uninstall any number of Programs from the target Server you control. For each card returned to your hand this way, recover 1 Gb.",,,,,,,,"1"
"Turn Sequence","1","Turn Order Front","Card Back",,,"The order of a round and the steps of one command. The first player leads every round.",,,,,,,,"1"
"Ransomware","1","Avatar Front","Card Back",,"4",,"V","ransomware","2","4","Extortion","Choose one enemy Avatar in combat with this Avatar. Its controller either pays you 2 RAM for each Hardware on it, or discards one of its Hardware.","9","2"
"Botnet","1","Avatar Front","Card Back",,"2",,"V","botnet","4","3","Command and Control","Place an Infection counter on one enemy Avatar adjacent to this Avatar. While this Avatar is in play, whenever an enemy Avatar with an Infection counter takes damage, gain 1 RAM.","12","2"
"Trojan Horse","1","Avatar Front","Card Back",,"3",,"V","trojan-horse","3","4","Payload","Choose one enemy Avatar in combat with this Avatar. Place an Infection counter on it, then it takes 1 damage for each Infection counter on it.","10","2"
"Fuzzer","1","Avatar Front","Card Back",,"3",,"B","fuzzer","3","3","Fuzz Input","Place a Bug counter on each enemy Avatar in combat with this Avatar.","10","2"
"Off By One","1","Avatar Front","Card Back",,"4",,"B","off-by-one","2","4","Boundary Error","After the roll in a combat at this Server, set one of this Avatar's dice to 6, or one enemy die to 1.","9","2"
"Heisenbug","1","Avatar Front","Card Back",,"2",,"B","heisenbug","4","3","Observer Effect","Once per round, when this Avatar takes damage, prevent 2 of that damage and place a Bug counter on the enemy Avatar that dealt it.","12","2"
"Screen Tear","1","Avatar Front","Card Back",,"3",,"G","screen-tear","3","4","Tear","This command, this Avatar may attack a location two lines away as though it were adjacent, crossing at most one Firewall.","10","2"
"Phantom Cursor","1","Avatar Front","Card Back",,"2",,"G","phantom-cursor","4","3","Haunt","Look at the top 2 cards of your opponent's Server pile and put one of them on the bottom. If this Avatar breached a Server this command, draw a card.","12","2"
"Dead Pixel","1","Avatar Front","Card Back",,"4",,"G","dead-pixel","2","3","Blackout","Until your next command, the Server this Avatar stands on counts as adjacent to nothing for enemy Executions and Programs.","9","2"
"Service Pack","1","Avatar Front","Card Back",,"3",,"P","service-pack","3","4","Roll Out","Re-enable all of your disabled Hardware and Programs at this Server, and remove 2 damage from this Avatar.","10","2"
"Long Term Support","1","Avatar Front","Card Back",,"4",,"P","long-term-support","2","3","Stable Branch","Until your next command, each time this Avatar would take damage, it takes 2 less.","9","2"
"Checksum","1","Avatar Front","Card Back",,"2",,"P","checksum","4","4","Rebuild","Move one Hardware from an Avatar you control at an adjacent Server onto this Avatar. It must fit its ports.","12","2"
"Zero-Day","1","Program Front","Card Back","5",,"When your Avatar attacks from this Server, place an Infection counter on each defender before the roll.","V",,,,,,,"2"
"Keylogger","1","Program Front","Card Back","5",,"Whenever an enemy Avatar with an Infection counter attacks this Server, look at its controller's hand and choose a card. They discard it unless they pay 2 RAM.","V",,,,,,,"2"
"Rootkit","1","Program Front","Card Back","6",,"At the start of your first command each round, each enemy Avatar with an Infection counter that is adjacent to this Server takes 1 damage.","V",,,,,,,"2"
"Drive-By Download","1","Program Front","Card Back","4",,"When an enemy Avatar breaches this Server, place 2 Infection counters on it.","V",,,,,,,"2"
"Segmentation Fault","1","Program Front","Card Back","5",,"Enemy Avatars with 2 or more Bug counters attacking this Server roll one die fewer.","B",,,,,,,"2"
"Unhandled Exception","1","Program Front","Card Back","4",,"When a combat at this Server ends in a stalemate, place a Bug counter on the attacker and gain 2 RAM. When an Avatar attacking this Server loses the roll by exactly 1, it takes 1 more damage.","B",,,,,,,"2"
"Heap Corruption","1","Program Front","Card Back","5",,"When your Avatar attacks from this Server, place a Bug counter on each defender before the roll.","B",,,,,,,"2"
"Bit Rot","1","Program Front","Card Back","5",,"At the start of your first command each round, place a Bug counter on each enemy Avatar adjacent to this Server that already has one.","B",,,,,,,"2"
"Tunnel","1","Program Front","Card Back","5",,"Your Avatars may advance and attack along Firewalled lines touching this Server as though the Firewalls were not there.","G",,,,,,,"2"
"Mirror Site","1","Program Front","Card Back","6",,"When you install this, choose a location that is not adjacent to this Server. For your Avatars, this Server counts as adjacent to it.","G",,,,,,,"2"
"Session Hijack","1","Program Front","Card Back","4",,"Whenever an enemy Avatar adjacent to this Server is recalled, draw a card.","G",,,,,,,"2"
"Packet Sniffer","1","Program Front","Card Back","4",,"When an enemy Avatar breaches this Server, look at its controller's hand and draw a card.","G",,,,,,,"2"
"Uptime Monitor","1","Program Front","Card Back","5",,"At the start of your first command each round, gain 1 RAM for each Patch Program you control, up to 3.","P",,,,,,,"2"
"Warm Standby","1","Program Front","Card Back","5",,"When your Avatar defending this Server is destroyed, it may be placed again this round.","P",,,,,,,"2"
"Hot Patch","1","Program Front","Card Back","5",,"At the start of your first command each round, remove 1 damage from each Avatar you control at this Server, or 2 from each Patch Avatar.","P",,,,,,,"2"
"Failover","1","Program Front","Card Back","4",,"When your Avatar defending this Server is destroyed, return one of its Hardware to your hand instead of discarding it.","P",,,,,,,"2"
"Sandbox Mode","1","Program Front","Card Back","5",,"Avatars you control at this Server cannot receive Infection or Bug counters.","P",,,,,,,"2"
"Payload Module","1","Hardware Front","Card Back","5",,"When this Avatar wins a roll, place an Infection counter on each enemy Avatar adjacent to it.",,,,,,,,"2"
"Exploit Kit","1","Hardware Front","Card Back","5",,"This Avatar has +1 Core in combat against an Avatar with an Infection counter.",,,,,,,,"2"
"Watchdog Timer","1","Hardware Front","Card Back","5",,"Once per round, in a combat this Avatar is in, one of its dice showing 1 counts as 6.",,,,,,,,"2"
"Bug Injector","1","Hardware Front","Card Back","4",,"When this Avatar attacks, place a Bug counter on one defender before the roll.",,,,,,,,"2"
"Spoofed MAC","1","Hardware Front","Card Back","5",,"Enemy Programs do not treat this Avatar as attacking their Server.",,,,,,,,"2"
"Proxy Relay","1","Hardware Front","Card Back","4",,"Level 1 Firewalls do not block this Avatar.",,,,,,,,"2"
"Surge Protector","1","Hardware Front","Card Back","5",,"The first Core penalty on this Avatar each round is ignored. If a Patch Avatar wears this, the second is too.",,,,,,,,"2"
"Heat Sink","1","Hardware Front","Card Back","6",,"This Avatar has +2 Health, or +4 if it is a Patch Avatar.",,,,,,,,"2"
"Execute: Quarantine","1","Execution Front","Card Back","4",,"Choose one enemy Avatar with an Infection counter at the target Server. It cannot advance or attack until its controller's next command. If a Virus Avatar you control is at the target Server, it also has -1 Core this combat.",,,,,,,,"2"
"Execute: Data Siphon","1","Execution Front","Card Back","4",,"Gain 1 RAM for each Infection counter on enemy Avatars at the target Server, up to 5.",,,,,,,,"2"
"Execute: Fuzz","1","Execution Front","Card Back","4",,"After the roll in a combat at the target Server, reroll every die showing 1 on one side. If a Bug Avatar you control is in the combat you choose the side; otherwise your opponent does.",,,,,,,,"2"
"Execute: Segfault","1","Execution Front","Card Back","4",,"Deal 2 damage to one Avatar at the target Server, or 3 if a Bug Avatar you control is in combat there.",,,,,,,,"2"
"Execute: Port Scan","1","Execution Front","Card Back","3",,"Look at one of your opponent's face-down Avatars. If a Glitch Avatar you control is at the target Server, draw a card.",,,,,,,,"2"
"Execute: Lag Spike","1","Execution Front","Card Back","4",,"One enemy Avatar at the target Server cannot be recalled or placed until its controller's next command. If a Glitch Avatar you control is at the target Server, it also takes 1 damage.",,,,,,,,"2"
"Execute: Snapshot","1","Execution Front","Card Back","4",,"Until the end of the current command, one Hardware on an Avatar you control at the target Server is protected.",,,,,,,,"2"
"Execute: Snapshot Restore","1","Execution Front","Card Back","4",,"Remove 4 damage from one Avatar you control at the target Server. If it is a Patch Avatar, also re-enable its disabled Hardware.",,,,,,,,"2"
"Quarantine Host","1","Server Front","Card Back",,,"Virus Programs installed here cost 2 less RAM",,,,,,,,"2"
"Ransomware","1","Anomaly Front","Card Back",,"4",,"V","ransomware","2","4","Extortion","Choose one enemy Anomaly in combat with this Anomaly. Its controller either pays you 2 Gb for each Hardware on it, or discards one of its Hardware.","9","2"
"Botnet","1","Anomaly Front","Card Back",,"2",,"V","botnet","4","3","Command and Control","Place an Infection counter on one enemy Anomaly adjacent to this Anomaly. While this Anomaly is in play, whenever an enemy Anomaly with an Infection counter takes damage, gain 1 Gb.","12","2"
"Trojan Horse","1","Anomaly Front","Card Back",,"3",,"V","trojan-horse","3","4","Payload","Choose one enemy Anomaly in combat with this Anomaly. Place an Infection counter on it, then it takes 1 damage for each Infection counter on it.","10","2"
"Fuzzer","1","Anomaly Front","Card Back",,"3",,"B","fuzzer","3","3","Fuzz Input","Place a Bug counter on each enemy Anomaly in combat with this Anomaly.","10","2"
"Off By One","1","Anomaly Front","Card Back",,"4",,"B","off-by-one","2","4","Boundary Error","After the roll in a combat at this Server, set one of this Anomaly's dice to 6, or one enemy die to 1.","9","2"
"Heisenbug","1","Anomaly Front","Card Back",,"2",,"B","heisenbug","4","3","Observer Effect","Once per round, when this Anomaly takes damage, prevent 2 of that damage and place a Bug counter on the enemy Anomaly that dealt it.","12","2"
"Screen Tear","1","Anomaly Front","Card Back",,"3",,"G","screen-tear","3","4","Tear","This command, this Anomaly may attack a location two lines away as though it were adjacent, crossing at most one Firewall.","10","2"
"Phantom Cursor","1","Anomaly Front","Card Back",,"2",,"G","phantom-cursor","4","3","Haunt","Look at the top 2 cards of your opponent's Server pile and put one of them on the bottom. If this Anomaly breached a Server this command, draw a card.","12","2"
"Dead Pixel","1","Anomaly Front","Card Back",,"4",,"G","dead-pixel","2","3","Blackout","Until your next command, the Server this Anomaly stands on counts as adjacent to nothing for enemy Executions and Programs.","9","2"
"Service Pack","1","Anomaly Front","Card Back",,"3",,"P","service-pack","3","4","Roll Out","Re-enable all of your disabled Hardware and Programs at this Server, and remove 2 damage from this Anomaly.","10","2"
"Long Term Support","1","Anomaly Front","Card Back",,"4",,"P","long-term-support","2","3","Stable Branch","Until your next command, each time this Anomaly would take damage, it takes 2 less.","9","2"
"Checksum","1","Anomaly Front","Card Back",,"2",,"P","checksum","4","4","Rebuild","Move one Hardware from an Anomaly you control at an adjacent Server onto this Anomaly. It must fit its Expansion Slots.","12","2"
"Zero-Day","1","Program Front - Alt","Card Back","5",,"When your Anomaly attacks from this Server, place an Infection counter on each defender before the roll.","V",,,,,,,"2"
"Keylogger","1","Program Front - Alt","Card Back","5",,"Whenever an enemy Anomaly with an Infection counter attacks this Server, look at its controller's hand and choose a card. They discard it unless they pay 2 Gb.","V",,,,,,,"2"
"Rootkit","1","Program Front - Alt","Card Back","6",,"At the start of your first command each round, each enemy Anomaly with an Infection counter that is adjacent to this Server takes 1 damage.","V",,,,,,,"2"
"Drive-By Download","1","Program Front - Alt","Card Back","4",,"When an enemy Anomaly breaches this Server, place 2 Infection counters on it.","V",,,,,,,"2"
"Segmentation Fault","1","Program Front - Alt","Card Back","5",,"Enemy Anomalies with 2 or more Bug counters attacking this Server roll one die fewer.","B",,,,,,,"2"
"Unhandled Exception","1","Program Front - Alt","Card Back","4",,"When a combat at this Server ends in a stalemate, place a Bug counter on the attacker and gain 2 Gb. When an Anomaly attacking this Server loses the roll by exactly 1, it takes 1 more damage.","B",,,,,,,"2"
"Heap Corruption","1","Program Front - Alt","Card Back","5",,"When your Anomaly attacks from this Server, place a Bug counter on each defender before the roll.","B",,,,,,,"2"
"Bit Rot","1","Program Front - Alt","Card Back","5",,"At the start of your first command each round, place a Bug counter on each enemy Anomaly adjacent to this Server that already has one.","B",,,,,,,"2"
"Tunnel","1","Program Front - Alt","Card Back","5",,"Your Anomalies may advance and attack along Firewalled lines touching this Server as though the Firewalls were not there.","G",,,,,,,"2"
"Mirror Site","1","Program Front - Alt","Card Back","6",,"When you install this, choose a location that is not adjacent to this Server. For your Anomalies, this Server counts as adjacent to it.","G",,,,,,,"2"
"Session Hijack","1","Program Front - Alt","Card Back","4",,"Whenever an enemy Anomaly adjacent to this Server is recalled, draw a card.","G",,,,,,,"2"
"Packet Sniffer","1","Program Front - Alt","Card Back","4",,"When an enemy Anomaly breaches this Server, look at its controller's hand and draw a card.","G",,,,,,,"2"
"Uptime Monitor","1","Program Front - Alt","Card Back","5",,"At the start of your first command each round, gain 1 Gb for each Patch Program you control, up to 3.","P",,,,,,,"2"
"Warm Standby","1","Program Front - Alt","Card Back","5",,"When your Anomaly defending this Server is destroyed, it may be placed again this round.","P",,,,,,,"2"
"Hot Patch","1","Program Front - Alt","Card Back","5",,"At the start of your first command each round, remove 1 damage from each Anomaly you control at this Server, or 2 from each Patch Anomaly.","P",,,,,,,"2"
"Failover","1","Program Front - Alt","Card Back","4",,"When your Anomaly defending this Server is destroyed, return one of its Hardware to your hand instead of discarding it.","P",,,,,,,"2"
"Sandbox Mode","1","Program Front - Alt","Card Back","5",,"Anomalies you control at this Server cannot receive Infection or Bug counters.","P",,,,,,,"2"
"Payload Module","1","Hardware Front - Alt","Card Back","5",,"When this Anomaly wins a roll, place an Infection counter on each enemy Anomaly adjacent to it.",,,,,,,,"2"
"Exploit Kit","1","Hardware Front - Alt","Card Back","5",,"This Anomaly has +1 Core in combat against an Anomaly with an Infection counter.",,,,,,,,"2"
"Watchdog Timer","1","Hardware Front - Alt","Card Back","5",,"Once per round, in a combat this Anomaly is in, one of its dice showing 1 counts as 6.",,,,,,,,"2"
"Bug Injector","1","Hardware Front - Alt","Card Back","4",,"When this Anomaly attacks, place a Bug counter on one defender before the roll.",,,,,,,,"2"
"Spoofed MAC","1","Hardware Front - Alt","Card Back","5",,"Enemy Programs do not treat this Anomaly as attacking their Server.",,,,,,,,"2"
"Proxy Relay","1","Hardware Front - Alt","Card Back","4",,"Level 1 Firewalls do not block this Anomaly.",,,,,,,,"2"
"Surge Protector","1","Hardware Front - Alt","Card Back","5",,"The first Core penalty on this Anomaly each round is ignored. If a Patch Anomaly wears this, the second is too.",,,,,,,,"2"
"Heat Sink","1","Hardware Front - Alt","Card Back","6",,"This Anomaly has +2 Health, or +4 if it is a Patch Anomaly.",,,,,,,,"2"
"Execute: Quarantine","1","Execution Front - Alt","Card Back","4",,"Choose one enemy Anomaly with an Infection counter at the target Server. It cannot advance or attack until its controller's next command. If a Virus Anomaly you control is at the target Server, it also has -1 Core this combat.",,,,,,,,"2"
"Execute: Data Siphon","1","Execution Front - Alt","Card Back","4",,"Gain 1 Gb for each Infection counter on enemy Anomalies at the target Server, up to 5.",,,,,,,,"2"
"Execute: Fuzz","1","Execution Front - Alt","Card Back","4",,"After the roll in a combat at the target Server, reroll every die showing 1 on one side. If a Bug Anomaly you control is in the combat you choose the side; otherwise your opponent does.",,,,,,,,"2"
"Execute: Segfault","1","Execution Front - Alt","Card Back","4",,"Deal 2 damage to one Anomaly at the target Server, or 3 if a Bug Anomaly you control is in combat there.",,,,,,,,"2"
"Execute: Port Scan","1","Execution Front - Alt","Card Back","3",,"Look at one of your opponent's face-down Anomalies. If a Glitch Anomaly you control is at the target Server, draw a card.",,,,,,,,"2"
"Execute: Lag Spike","1","Execution Front - Alt","Card Back","4",,"One enemy Anomaly at the target Server cannot be recalled or placed until its controller's next command. If a Glitch Anomaly you control is at the target Server, it also takes 1 damage.",,,,,,,,"2"
"Execute: Snapshot","1","Execution Front - Alt","Card Back","4",,"Until the end of the current command, one Hardware on an Anomaly you control at the target Server is protected.",,,,,,,,"2"
"Execute: Snapshot Restore","1","Execution Front - Alt","Card Back","4",,"Remove 4 damage from one Anomaly you control at the target Server. If it is a Patch Anomaly, also re-enable its disabled Hardware.",,,,,,,,"2"
"Quarantine Host","1","Server Front","Card Back",,,"Virus Programs installed here cost 2 less Gb",,,,,,,,"2"
"Test Bench","1","Server Front","Card Back",,,"When a combat starts here, place a Bug counter on the attacker if a Bug Program is installed here",,,,,,,,"2"
"Proxy Node","1","Server Front","Card Back",,,"Executions you play targeting this Server may target an adjacent Server instead",,,,,,,,"2"
"Stable Release","1","Server Front","Card Back",,,"Patch Programs installed here cannot be disabled",,,,,,,,"2"
"Cache Server","1","Server Front","Card Back",,,"Gain 2 RAM when you capture this Server back from an enemy",,,,,,,,"2"
"Honeypot","1","Server Front","Card Back",,,"The first Avatar to attack this Server each round has -1 Core",,,,,,,,"2"
"Load Balancer","1","Server Front","Card Back",,,"Once per round, your Avatar here may swap places with another Avatar you control at an adjacent Server",,,,,,,,"2"
"Cache Server","1","Server Front","Card Back",,,"Gain 2 Gb when you capture this Server back from an enemy",,,,,,,,"2"
"Honeypot","1","Server Front","Card Back",,,"The first Anomaly to attack this Server each round has -1 Core",,,,,,,,"2"
"Load Balancer","1","Server Front","Card Back",,,"Once per round, your Anomaly here may swap places with another Anomaly you control at an adjacent Server",,,,,,,,"2"
1 Name Count Front Template Back Template RAM Bandwidth Cores Description Type Image Expansion Slots Ability Cost Ability Name Ability Description Health Set
2 Carbon NanoBots 1 Avatar Front Anomaly Front Card Back 2 Nasty little bugs... B nano-bots 4 6 Replicate Avatar may create a copy of itself. Only one copy is allowed at a time. If the copy is defeated the original does not lose any hardware upgrades. If the original is defeated the replicate is as well. Anomaly may create a copy of itself. Only one copy is allowed at a time. If the copy is defeated the original does not lose any hardware upgrades. If the original is defeated the replicate is as well. 10 1
3 Corrupt Driver 1 Avatar Front Anomaly Front Card Back 3 V driver-ascii-art 3 4 Driver Fault Choose one Hardware on an enemy Avatar in combat with this Avatar. It is disabled until the end of your next command. Choose one Hardware on an enemy Anomaly in combat with this Anomaly. It is disabled until the end of your next command. 10 1
4 Pixelated Picture 1 Avatar Front Anomaly Front Card Back 3 G pix 3 3 Low Resolution Attacking Avatars have -1 cores against this Avatar. Attacking Anomalies have -1 cores against this Anomaly. 10 1
5 Beta Version 1.0 1 Avatar Front Anomaly Front Card Back 4 P broken-bits 2 4 Push Update While in combat an additional piece of hardware can be placed on this avatar until the end of your command. If there no ports available this can still be attached. While in combat an additional piece of hardware can be placed on this anomaly until the end of your command. If there are no Expansion Slots available this can still be attached. 9 1
6 Code Zero 1 Avatar Front Anomaly Front Card Back 3 V code-zero 4 4 Patient Zero Place an Infection counter on every enemy Avatar in combat at this Server. While this Avatar is in play, an Avatar with 1+ Infection counters has -1 Core. Place an Infection counter on every enemy Anomaly in combat at this Server. While this Anomaly is in play, an Anomaly with 1+ Infection counters has -1 Core. 10 1
7 Data Leaker 1 Avatar Front Anomaly Front Card Back 3 G data-leaker 3 3 Exfiltrate Look at your opponent's hand and choose one card in it. They must discard that card without gaining RAM. If this Avatar breached a Server this command, draw a card. Look at your opponent's hand and choose one card in it. They must discard that card without gaining Bandwidth. If this Anomaly breached a Server this command, draw a card. 10 1
8 Backup Machine 1 Avatar Front Anomaly Front Card Back 3 P backup 3 5 Restore Point Remove 3 damage from this Avatar, or return one Hardware or Program from your discard pile to your hand. If it is a Hardware and this Avatar has an open port, you may install it immediately for 2 less RAM. Remove 3 damage from this Anomaly, or return one Hardware or Program from your discard pile to your hand. If it is a Hardware and this Anomaly has an open Expansion Slot, you may install it immediately for 2 less Gb. 10 1
9 Broken Bits 1 Avatar Front Anomaly Front Card Back 4 B broken-bits-2 2 4 Bit Flip During a combat at this Server, reroll any number of this Avatar's Core dice. During a combat at this Server, reroll any number of this Anomaly's Core dice. 9 1
10 Recursive Infection 1 Program Front Program Front - Alt Card Back 6 Whenever an enemy Avatar attacks or breaches this Server, place an Infection counter on it. An Avatar with 3+ Infection counters has -2 Core. Whenever an enemy Anomaly attacks or breaches this Server, place an Infection counter on it. An Anomaly with 3+ Infection counters has -2 Core. V 1
11 Memory Parasite 1 Program Front Program Front - Alt Card Back 5 Enemy Avatars attacking this Server have 1 hardware component disabled of the owners choosing. Enemy Anomalies attacking this Server have 1 hardware component disabled of the owners choosing. V 1
12 Replication Routine 1 Program Front Program Front - Alt Card Back 6 When you install a Virus Program on this Server, you may install a second Virus Program from your hand here for no RAM cost. When you install a Virus Program on this Server, you may install a second Virus Program from your hand here for no Bandwidth cost. V 1
13 Resource Leech 1 Program Front Program Front - Alt Card Back 5 Whenever an enemy Avatar takes damage while attacking this Server, gain 3 RAM. Whenever an enemy Anomaly takes damage while attacking this Server, gain 3 Gb. V 1
14 Worm Protocol 1 Program Front Program Front - Alt Card Back 4 The localized effects of your other Programs on this Server also apply at one adjacent Server you choose when this is installed. V 1
15 Payload Injector 1 Program Front Program Front - Alt Card Back 6 The first Execution you play targeting this Server each round costs 2 less RAM. The first Execution you play targeting this Server each round costs 2 less Gb. V 1
16 Persistent Infection 1 Program Front Program Front - Alt Card Back 6 Whenever an enemy Avatar takes damage at this Server, place an Infection counter on it permanently. Whenever an enemy Anomaly takes damage at this Server, place an Infection counter on it permanently. V 1
17 Infinite Loop 1 Program Front Program Front - Alt Card Back 5 If the attacking Avatar is controlled by the owner of this Program, it may attack a second adjacent Server in the same command. If the attacking Anomaly is controlled by the owner of this Program, it may attack a second adjacent Server in the same command. B 1
18 Stack Overflow 1 Program Front Program Front - Alt Card Back 7 Avatars you control defending this Server gain +1 Core for each Program installed on this Server (including this one). Anomalies you control defending this Server gain +1 Core for each Program installed on this Server (including this one). B 1
19 Race Condition 1 Program Front Program Front - Alt Card Back 4 During any combat at this Server, both players secretly choose Attack or Defend. If the choices differ, the defender gains a combat bonus of +2 Cores. B 1
20 Memory Leak Bloatware 1 Program Front Program Front - Alt Card Back 6 At the start of any combat at this Server, the attacking Avatar loses 1 Core for each Hardware installed on it. At the start of any combat at this Server, the attacking Anomaly loses 1 Core for each Hardware installed on it. B 1
21 Null Pointer 1 Program Front Program Front - Alt Card Back 5 Once per round, when an enemy Execution would resolve at this Server, it's effect does not occur. B 1
22 Stock Rice 1 Program Front Program Front - Alt Card Back 4 Neither Avatar in a combat that takes place at this Server may use any Hardware bonuses. Neither Anomaly in a combat that takes place at this Server may use any Hardware bonuses. B 1
23 Overflow Error 1 Program Front Program Front - Alt Card Back 5 When an enemy Avatar takes damage while attacking this Server, disable one Program its controller has in play until their next command. If the Avatar was destroyed, you may destroy that Program instead. When an enemy Anomaly takes damage while attacking this Server, disable one Program its controller has in play until their next command. If the Anomaly was destroyed, you may destroy that Program instead. B 1
24 Undefined Behavior 1 Program Front Program Front - Alt Card Back 8 Once per round, copy the localized effect of another Program on another Server. Then disable this Program until your next command. B 1
25 Packet Loss 1 Program Front Program Front - Alt Card Back 6 When an enemy successfully breaches this Server, its controller discards a card at random. G 1
26 Desynchronization 1 Program Front Program Front - Alt Card Back 5 Enemy Avatars attacking this Server cannot use their Hardware's "once per round" abilities during that combat. Enemy Anomalies attacking this Server cannot use their Hardware's "once per round" abilities during that combat. G 1
27 Visual Artifact 1 Program Front Program Front - Alt Card Back 5 The first attack made against an Avatar you control at this Server suffers -1 Core. The first attack made against an Anomaly you control at this Server suffers -1 Core. G 1
28 Ghost Process 1 Program Front Program Front - Alt Card Back 6 Your Executions played targeting this Server may also affect Avatars, Programs, and Hardware at one adjacent Server. Your Executions played targeting this Server may also affect Anomalies, Programs, and Hardware at one adjacent Server. G 1
29 False Positive 1 Program Front Program Front - Alt Card Back 7 When an enemy Execution targets an Avatar you control at this Server, you may redirect it to another legal Avatar at another Server. When an enemy Execution targets an Anomaly you control at this Server, you may redirect it to another legal Anomaly at another Server. G 1
30 Fragmentation 1 Program Front Program Front - Alt Card Back 6 Executions your opponents play targeting this Server cost +2 RAM. Executions your opponents play targeting this Server cost +2 Gb. G 1
31 Latency Spike 1 Program Front Program Front - Alt Card Back 5 The attacking player cannot play Executions during the first step of any combat at this Server. G 1
32 Hotfix 1 Program Front Program Front - Alt Card Back 7 The first Program on this Server that would be destroyed each round is instead disabled until your next command. P 1
33 Error Correction 1 Program Front Program Front - Alt Card Back 5 At the beginning of your first command each round, remove one negative counter or status from each Avatar you control at this Server. At the beginning of your first command each round, remove one negative counter or status from each Anomaly you control at this Server. P 1
34 Garbage Collection 1 Program Front Program Front - Alt Card Back 6 Once per round, sacrifice one Program installed on this Server to recover its printed RAM value. Once per round, sacrifice one Program installed on this Server to recover its printed Bandwidth value. P 1
35 Version Control 1 Program Front Program Front - Alt Card Back 5 When a Program on this Server would be destroyed, or when this Server is captured, return one Program from this Server to your hand instead of discarding it. P 1
36 Rollback Routine 1 Program Front Program Front - Alt Card Back 4 Once per round, undo the most recent temporary stat reduction applied to an Avatar you control at this Server. Once per round, undo the most recent temporary stat reduction applied to an Anomaly you control at this Server. P 1
37 Compatibility Layer 1 Program Front Program Front - Alt Card Back 6 This Server may hold one additional Program beyond the normal limit, and Patch Programs installed here cost 2 less RAM. This Server may hold one additional Program beyond the normal limit, and Patch Programs installed here cost 2 less Gb. P 1
38 RAM Expansion 1 Hardware Front Hardware Front - Alt Card Back 5 Avatar gains +2 Health. Anomaly gains +2 Health. 1
39 Additional Core 1 Hardware Front Hardware Front - Alt Card Back 5 Avatar gains +1 Core. Anomaly gains +1 Core. 1
40 Overclocked CPU 1 Hardware Front Hardware Front - Alt Card Back 6 Avatar gains +2 Cores during combat, but one installed Program at the current server becomes disabled afterward for 2 commands. Anomaly gains +2 Cores during combat, but one installed Program at the current server becomes disabled afterward for 2 commands. 1
41 Solid-State Cache 1 Hardware Front Hardware Front - Alt Card Back 6 The first Program installed on the occupied Server each round costs 3 less RAM. The first Program installed on the occupied Server each round costs 3 less Gb. 1
42 Redundant Power Supply 1 Hardware Front Hardware Front - Alt Card Back 8 The first time this Avatar would be destroyed, do not destroy the Hardware. The first time this Anomaly would be destroyed, do not destroy the Hardware. 1
43 Network Interface Upgrade 1 Hardware Front Hardware Front - Alt Card Back 4 This Hardware can be played without taking an upgrade port on the Avatar. This Hardware can be played without taking an Expansion Slot on the Anomaly. 1
44 Dedicated GPU 1 Hardware Front Hardware Front - Alt Card Back 6 Executions performed by this Avatar receive +1 effectiveness or combat strength. Executions performed by this Anomaly receive +1 effectiveness or combat strength. 1
45 ECC Memory 1 Hardware Front Hardware Front - Alt Card Back 5 Opponents cannot place Bug counters or Bug status effects on this Avatar. Opponents cannot place Bug counters or Bug status effects on this Anomaly. 1
46 Cooling System 1 Hardware Front Hardware Front - Alt Card Back 6 Allow one Hardware to activate twice per round. 1
47 RAID Array 1 Hardware Front Hardware Front - Alt Card Back 5 When this Avatar is destroyed, all hardware can be kept by paying half the RAM cost. When this Anomaly is destroyed, all hardware can be kept by paying half the Bandwidth cost. 1
48 Packet Accelerator 1 Hardware Front Hardware Front - Alt Card Back 4 This Avatar gains +1 Core hen attacking. This Anomaly gains +1 Core hen attacking. 1
49 Firewall Appliance 1 Hardware Front Hardware Front - Alt Card Back 6 The first hostile Program or Execution targeting this Avatar each round costs the opponent +3 RAM. The first hostile Program or Execution targeting this Anomaly each round costs the opponent +3 Gb. 1
50 Hardware Sandbox 1 Hardware Front Hardware Front - Alt Card Back 7 Choose one Program installed on the occupied Server. It cannot be targeted by opponents. 1
51 Diagnostic Module 1 Hardware Front Hardware Front - Alt Card Back 4 Look at one face down card in your draw pile. You may place it at the bottom and draw another to start your first command each round. 1
52 Hot-Swap Bay 1 Hardware Front Hardware Front - Alt Card Back 6 Once per round, return one Hardware to your hand and install another Hardware from your hand, paying the difference in cost. 1
53 Quantum Coprocessor 1 Hardware Front Hardware Front - Alt Card Back 9 Once per round when this Avatar uses an Execution, you may copy that Execution's effect with a different legal target, then disable this Hardware. Once per round when this Anomaly uses an Execution, you may copy that Execution's effect with a different legal target, then disable this Hardware. 1
54 High Efficiency RAM Server High Bandwidth Server 1 Server Front Card Back Add additional 4 RAM to resource total Add additional 4 Gb to resource total 1
55 MultiCore Server 1 Server Front Card Back Add 2 Cores to any Avatars Add 2 Cores to any Anomalies 1
56 Cluster Server 1 Server Front Card Back Up to 2 Avatars can defend this Server Up to 2 Anomalies can defend this Server 1
57 Power Server 1 Server Front Card Back Add additional 4 RAM to resource total Add additional 4 Gb to resource total 1
58 Backup Server 1 Server Front Card Back Duplicate Avatar based at this Server Duplicate Anomaly based at this Server 1
59 Server Farm 1 Server Front Card Back Add 4 RAM to resource total and 2 Cores to any Avatar Add 4 Gb to resource total and 2 Cores to any Anomaly 1
60 Upgraded Hardware 1 Server Front Card Back Hardware upgrades cost 2 less RAM to install Hardware upgrades cost 2 less Gb to install 1
61 Network Throttle 1 Server Front Card Back Firewalls cost 1 less RAM to install Firewalls cost 1 less Gb to install 1
62 Cloud Compute 1 Server Front Card Back Add 4 Cores to any Avatars Add 4 Cores to any Anomalies 1
63 Duplicate Server 1 Server Front Card Back Copy one adjacent Server ability 1
64 Pingable Server 1 Server Front Card Back Up to 2 Avatars can defend this Server Up to 2 Anomalies can defend this Server 1
65 Protected Server 1 Server Front Card Back Add 2 RAM if defending this Server Add 2 Gb if defending this Server 1
66 Callable Server 1 Server Front Card Back When drawing a card, you may choose to place it on the bottom of the deck and draw another 1
67 Execute: Disconnect 1 Execution Front Execution Front - Alt Card Back 4 Move one Avatar you control at the target Server to an adjacent Server, removing it from any combat there. Move one Anomaly you control at the target Server to an adjacent Server, removing it from any combat there. 1
68 Execute: Sabotage 1 Execution Front Execution Front - Alt Card Back 7 Destroy or disable one Hardware on an enemy Avatar in combat at the target Server. Destroy or disable one Hardware on an enemy Anomaly in combat at the target Server. 1
69 Execute: Kill Process 1 Execution Front Execution Front - Alt Card Back 5 Disable one Program installed on the target Server until its controller's next command. 1
70 Execute: Force Reboot 1 Execution Front Execution Front - Alt Card Back 5 Remove all temporary bonuses and penalties from one Avatar you control at the target Server, or one Avatar attacking it. That Avatar cannot play another Execution until end of current command. Remove all temporary bonuses and penalties from one Anomaly you control at the target Server, or one Anomaly attacking it. That Anomaly cannot play another Execution until end of current command. 1
71 Execute: Fork 1 Execution Front Execution Front - Alt Card Back 7 Copy the localized effect of one Program installed on the target Server until end of current command. 1
72 Execute: Ping Sweep 1 Execution Front Execution Front - Alt Card Back 4 You may draw 2 cards from the top of your deck. 1
73 Execute: Trace Route 1 Execution Front Execution Front - Alt Card Back 5 Move one Avatar you control from an adjacent Server to the target Server. If the target Server is enemy-controlled, your Avatar attacks it with +1 Core for the resulting combat. Move one Anomaly you control from an adjacent Server to the target Server. If the target Server is enemy-controlled, your Anomaly attacks it with +1 Core for the resulting combat. 1
74 Execute: Override 1 Execution Front Execution Front - Alt Card Back 5 Choose one enemy Program installed on the target Server. Ignore its text until end of current command. 1
75 Execute: Memory Dump 1 Execution Front Execution Front - Alt Card Back 4 Draw 2 cards, then discard 1. If you control the target Server, draw 1 extra card instead of discarding. 1
76 Execute: Rollback 1 Execution Front Execution Front - Alt Card Back 4 Return one Program or Hardware installed at the target Server this command to its owner's hand. 1
77 Execute: Root Access 1 Execution Front Execution Front - Alt Card Back 4 Until end of current command, your Programs and Executions at the target Server may target protected Programs and Hardware as though they were unprotected. 1
78 Execute: Packet Flood 1 Execution Front Execution Front - Alt Card Back 5 Avatars based at the target Server cannot move or retreat until the start of their controller's next command. Anomalies based at the target Server cannot move or retreat until the start of their controller's next command. 1
79 Execute: Emergency Shutdown 1 Execution Front Execution Front - Alt Card Back 6 End any combat at the target Server immediately. All Avatars there remain and become Disabled until end of current command. End any combat at the target Server immediately. All Anomalies there remain and become Disabled until end of current command. 1
80 Execute: Process Clone 1 Execution Front Execution Front - Alt Card Back 7 Choose one Program installed on the target Server you control. Treat it as though a second copy were installed there until end of current command. 1
81 Execute: Defragment 1 Execution Front Execution Front - Alt Card Back 4 Re-enable one Disabled Program on the target Server, or one Disabled Hardware on an Avatar there. Re-enable one Disabled Program on the target Server, or one Disabled Hardware on an Anomaly there. 1
82 Execute: Remote Access 1 Execution Front Execution Front - Alt Card Back 6 Activate one Program installed on a Server adjacent to the target Server as though it were installed on the target Server, until end of current command. 1
83 Execute: Purge 1 Execution Front Execution Front - Alt Card Back 4 Remove all Virus/Infection counters and hostile persistent effects from every Avatar you control at the target Server. Remove all Virus/Infection counters and hostile persistent effects from every Anomaly you control at the target Server. 1
84 Execute: Hard Reset 1 Execution Front Execution Front - Alt Card Back 6 Uninstall any number of Programs from the target Server you control. For each card returned to your hand this way, recover 1 RAM. Uninstall any number of Programs from the target Server you control. For each card returned to your hand this way, recover 1 Gb. 1
85 Turn Sequence 1 Turn Order Front Card Back The order of a round and the steps of one command. The first player leads every round. 1
86 Ransomware 1 Avatar Front Anomaly Front Card Back 4 V ransomware 2 4 Extortion Choose one enemy Avatar in combat with this Avatar. Its controller either pays you 2 RAM for each Hardware on it, or discards one of its Hardware. Choose one enemy Anomaly in combat with this Anomaly. Its controller either pays you 2 Gb for each Hardware on it, or discards one of its Hardware. 9 2
87 Botnet 1 Avatar Front Anomaly Front Card Back 2 V botnet 4 3 Command and Control Place an Infection counter on one enemy Avatar adjacent to this Avatar. While this Avatar is in play, whenever an enemy Avatar with an Infection counter takes damage, gain 1 RAM. Place an Infection counter on one enemy Anomaly adjacent to this Anomaly. While this Anomaly is in play, whenever an enemy Anomaly with an Infection counter takes damage, gain 1 Gb. 12 2
88 Trojan Horse 1 Avatar Front Anomaly Front Card Back 3 V trojan-horse 3 4 Payload Choose one enemy Avatar in combat with this Avatar. Place an Infection counter on it, then it takes 1 damage for each Infection counter on it. Choose one enemy Anomaly in combat with this Anomaly. Place an Infection counter on it, then it takes 1 damage for each Infection counter on it. 10 2
89 Fuzzer 1 Avatar Front Anomaly Front Card Back 3 B fuzzer 3 3 Fuzz Input Place a Bug counter on each enemy Avatar in combat with this Avatar. Place a Bug counter on each enemy Anomaly in combat with this Anomaly. 10 2
90 Off By One 1 Avatar Front Anomaly Front Card Back 4 B off-by-one 2 4 Boundary Error After the roll in a combat at this Server, set one of this Avatar's dice to 6, or one enemy die to 1. After the roll in a combat at this Server, set one of this Anomaly's dice to 6, or one enemy die to 1. 9 2
91 Heisenbug 1 Avatar Front Anomaly Front Card Back 2 B heisenbug 4 3 Observer Effect Once per round, when this Avatar takes damage, prevent 2 of that damage and place a Bug counter on the enemy Avatar that dealt it. Once per round, when this Anomaly takes damage, prevent 2 of that damage and place a Bug counter on the enemy Anomaly that dealt it. 12 2
92 Screen Tear 1 Avatar Front Anomaly Front Card Back 3 G screen-tear 3 4 Tear This command, this Avatar may attack a location two lines away as though it were adjacent, crossing at most one Firewall. This command, this Anomaly may attack a location two lines away as though it were adjacent, crossing at most one Firewall. 10 2
93 Phantom Cursor 1 Avatar Front Anomaly Front Card Back 2 G phantom-cursor 4 3 Haunt Look at the top 2 cards of your opponent's Server pile and put one of them on the bottom. If this Avatar breached a Server this command, draw a card. Look at the top 2 cards of your opponent's Server pile and put one of them on the bottom. If this Anomaly breached a Server this command, draw a card. 12 2
94 Dead Pixel 1 Avatar Front Anomaly Front Card Back 4 G dead-pixel 2 3 Blackout Until your next command, the Server this Avatar stands on counts as adjacent to nothing for enemy Executions and Programs. Until your next command, the Server this Anomaly stands on counts as adjacent to nothing for enemy Executions and Programs. 9 2
95 Service Pack 1 Avatar Front Anomaly Front Card Back 3 P service-pack 3 4 Roll Out Re-enable all of your disabled Hardware and Programs at this Server, and remove 2 damage from this Avatar. Re-enable all of your disabled Hardware and Programs at this Server, and remove 2 damage from this Anomaly. 10 2
96 Long Term Support 1 Avatar Front Anomaly Front Card Back 4 P long-term-support 2 3 Stable Branch Until your next command, each time this Avatar would take damage, it takes 2 less. Until your next command, each time this Anomaly would take damage, it takes 2 less. 9 2
97 Checksum 1 Avatar Front Anomaly Front Card Back 2 P checksum 4 4 Rebuild Move one Hardware from an Avatar you control at an adjacent Server onto this Avatar. It must fit its ports. Move one Hardware from an Anomaly you control at an adjacent Server onto this Anomaly. It must fit its Expansion Slots. 12 2
98 Zero-Day 1 Program Front Program Front - Alt Card Back 5 When your Avatar attacks from this Server, place an Infection counter on each defender before the roll. When your Anomaly attacks from this Server, place an Infection counter on each defender before the roll. V 2
99 Keylogger 1 Program Front Program Front - Alt Card Back 5 Whenever an enemy Avatar with an Infection counter attacks this Server, look at its controller's hand and choose a card. They discard it unless they pay 2 RAM. Whenever an enemy Anomaly with an Infection counter attacks this Server, look at its controller's hand and choose a card. They discard it unless they pay 2 Gb. V 2
100 Rootkit 1 Program Front Program Front - Alt Card Back 6 At the start of your first command each round, each enemy Avatar with an Infection counter that is adjacent to this Server takes 1 damage. At the start of your first command each round, each enemy Anomaly with an Infection counter that is adjacent to this Server takes 1 damage. V 2
101 Drive-By Download 1 Program Front Program Front - Alt Card Back 4 When an enemy Avatar breaches this Server, place 2 Infection counters on it. When an enemy Anomaly breaches this Server, place 2 Infection counters on it. V 2
102 Segmentation Fault 1 Program Front Program Front - Alt Card Back 5 Enemy Avatars with 2 or more Bug counters attacking this Server roll one die fewer. Enemy Anomalies with 2 or more Bug counters attacking this Server roll one die fewer. B 2
103 Unhandled Exception 1 Program Front Program Front - Alt Card Back 4 When a combat at this Server ends in a stalemate, place a Bug counter on the attacker and gain 2 RAM. When an Avatar attacking this Server loses the roll by exactly 1, it takes 1 more damage. When a combat at this Server ends in a stalemate, place a Bug counter on the attacker and gain 2 Gb. When an Anomaly attacking this Server loses the roll by exactly 1, it takes 1 more damage. B 2
104 Heap Corruption 1 Program Front Program Front - Alt Card Back 5 When your Avatar attacks from this Server, place a Bug counter on each defender before the roll. When your Anomaly attacks from this Server, place a Bug counter on each defender before the roll. B 2
105 Bit Rot 1 Program Front Program Front - Alt Card Back 5 At the start of your first command each round, place a Bug counter on each enemy Avatar adjacent to this Server that already has one. At the start of your first command each round, place a Bug counter on each enemy Anomaly adjacent to this Server that already has one. B 2
106 Tunnel 1 Program Front Program Front - Alt Card Back 5 Your Avatars may advance and attack along Firewalled lines touching this Server as though the Firewalls were not there. Your Anomalies may advance and attack along Firewalled lines touching this Server as though the Firewalls were not there. G 2
107 Mirror Site 1 Program Front Program Front - Alt Card Back 6 When you install this, choose a location that is not adjacent to this Server. For your Avatars, this Server counts as adjacent to it. When you install this, choose a location that is not adjacent to this Server. For your Anomalies, this Server counts as adjacent to it. G 2
108 Session Hijack 1 Program Front Program Front - Alt Card Back 4 Whenever an enemy Avatar adjacent to this Server is recalled, draw a card. Whenever an enemy Anomaly adjacent to this Server is recalled, draw a card. G 2
109 Packet Sniffer 1 Program Front Program Front - Alt Card Back 4 When an enemy Avatar breaches this Server, look at its controller's hand and draw a card. When an enemy Anomaly breaches this Server, look at its controller's hand and draw a card. G 2
110 Uptime Monitor 1 Program Front Program Front - Alt Card Back 5 At the start of your first command each round, gain 1 RAM for each Patch Program you control, up to 3. At the start of your first command each round, gain 1 Gb for each Patch Program you control, up to 3. P 2
111 Warm Standby 1 Program Front Program Front - Alt Card Back 5 When your Avatar defending this Server is destroyed, it may be placed again this round. When your Anomaly defending this Server is destroyed, it may be placed again this round. P 2
112 Hot Patch 1 Program Front Program Front - Alt Card Back 5 At the start of your first command each round, remove 1 damage from each Avatar you control at this Server, or 2 from each Patch Avatar. At the start of your first command each round, remove 1 damage from each Anomaly you control at this Server, or 2 from each Patch Anomaly. P 2
113 Failover 1 Program Front Program Front - Alt Card Back 4 When your Avatar defending this Server is destroyed, return one of its Hardware to your hand instead of discarding it. When your Anomaly defending this Server is destroyed, return one of its Hardware to your hand instead of discarding it. P 2
114 Sandbox Mode 1 Program Front Program Front - Alt Card Back 5 Avatars you control at this Server cannot receive Infection or Bug counters. Anomalies you control at this Server cannot receive Infection or Bug counters. P 2
115 Payload Module 1 Hardware Front Hardware Front - Alt Card Back 5 When this Avatar wins a roll, place an Infection counter on each enemy Avatar adjacent to it. When this Anomaly wins a roll, place an Infection counter on each enemy Anomaly adjacent to it. 2
116 Exploit Kit 1 Hardware Front Hardware Front - Alt Card Back 5 This Avatar has +1 Core in combat against an Avatar with an Infection counter. This Anomaly has +1 Core in combat against an Anomaly with an Infection counter. 2
117 Watchdog Timer 1 Hardware Front Hardware Front - Alt Card Back 5 Once per round, in a combat this Avatar is in, one of its dice showing 1 counts as 6. Once per round, in a combat this Anomaly is in, one of its dice showing 1 counts as 6. 2
118 Bug Injector 1 Hardware Front Hardware Front - Alt Card Back 4 When this Avatar attacks, place a Bug counter on one defender before the roll. When this Anomaly attacks, place a Bug counter on one defender before the roll. 2
119 Spoofed MAC 1 Hardware Front Hardware Front - Alt Card Back 5 Enemy Programs do not treat this Avatar as attacking their Server. Enemy Programs do not treat this Anomaly as attacking their Server. 2
120 Proxy Relay 1 Hardware Front Hardware Front - Alt Card Back 4 Level 1 Firewalls do not block this Avatar. Level 1 Firewalls do not block this Anomaly. 2
121 Surge Protector 1 Hardware Front Hardware Front - Alt Card Back 5 The first Core penalty on this Avatar each round is ignored. If a Patch Avatar wears this, the second is too. The first Core penalty on this Anomaly each round is ignored. If a Patch Anomaly wears this, the second is too. 2
122 Heat Sink 1 Hardware Front Hardware Front - Alt Card Back 6 This Avatar has +2 Health, or +4 if it is a Patch Avatar. This Anomaly has +2 Health, or +4 if it is a Patch Anomaly. 2
123 Execute: Quarantine 1 Execution Front Execution Front - Alt Card Back 4 Choose one enemy Avatar with an Infection counter at the target Server. It cannot advance or attack until its controller's next command. If a Virus Avatar you control is at the target Server, it also has -1 Core this combat. Choose one enemy Anomaly with an Infection counter at the target Server. It cannot advance or attack until its controller's next command. If a Virus Anomaly you control is at the target Server, it also has -1 Core this combat. 2
124 Execute: Data Siphon 1 Execution Front Execution Front - Alt Card Back 4 Gain 1 RAM for each Infection counter on enemy Avatars at the target Server, up to 5. Gain 1 Gb for each Infection counter on enemy Anomalies at the target Server, up to 5. 2
125 Execute: Fuzz 1 Execution Front Execution Front - Alt Card Back 4 After the roll in a combat at the target Server, reroll every die showing 1 on one side. If a Bug Avatar you control is in the combat you choose the side; otherwise your opponent does. After the roll in a combat at the target Server, reroll every die showing 1 on one side. If a Bug Anomaly you control is in the combat you choose the side; otherwise your opponent does. 2
126 Execute: Segfault 1 Execution Front Execution Front - Alt Card Back 4 Deal 2 damage to one Avatar at the target Server, or 3 if a Bug Avatar you control is in combat there. Deal 2 damage to one Anomaly at the target Server, or 3 if a Bug Anomaly you control is in combat there. 2
127 Execute: Port Scan 1 Execution Front Execution Front - Alt Card Back 3 Look at one of your opponent's face-down Avatars. If a Glitch Avatar you control is at the target Server, draw a card. Look at one of your opponent's face-down Anomalies. If a Glitch Anomaly you control is at the target Server, draw a card. 2
128 Execute: Lag Spike 1 Execution Front Execution Front - Alt Card Back 4 One enemy Avatar at the target Server cannot be recalled or placed until its controller's next command. If a Glitch Avatar you control is at the target Server, it also takes 1 damage. One enemy Anomaly at the target Server cannot be recalled or placed until its controller's next command. If a Glitch Anomaly you control is at the target Server, it also takes 1 damage. 2
129 Execute: Snapshot 1 Execution Front Execution Front - Alt Card Back 4 Until the end of the current command, one Hardware on an Avatar you control at the target Server is protected. Until the end of the current command, one Hardware on an Anomaly you control at the target Server is protected. 2
130 Execute: Snapshot Restore 1 Execution Front Execution Front - Alt Card Back 4 Remove 4 damage from one Avatar you control at the target Server. If it is a Patch Avatar, also re-enable its disabled Hardware. Remove 4 damage from one Anomaly you control at the target Server. If it is a Patch Anomaly, also re-enable its disabled Hardware. 2
131 Quarantine Host 1 Server Front Card Back Virus Programs installed here cost 2 less RAM Virus Programs installed here cost 2 less Gb 2
132 Test Bench 1 Server Front Card Back When a combat starts here, place a Bug counter on the attacker if a Bug Program is installed here 2
133 Proxy Node 1 Server Front Card Back Executions you play targeting this Server may target an adjacent Server instead 2
134 Stable Release 1 Server Front Card Back Patch Programs installed here cannot be disabled 2
135 Cache Server 1 Server Front Card Back Gain 2 RAM when you capture this Server back from an enemy Gain 2 Gb when you capture this Server back from an enemy 2
136 Honeypot 1 Server Front Card Back The first Avatar to attack this Server each round has -1 Core The first Anomaly to attack this Server each round has -1 Core 2
137 Load Balancer 1 Server Front Card Back Once per round, your Avatar here may swap places with another Avatar you control at an adjacent Server Once per round, your Anomaly here may swap places with another Anomaly you control at an adjacent Server 2

View file

@ -1,6 +1,6 @@
/* ======================================================
Server card — full-bleed cyber HUD node
Matches the Avatar frame: full-bleed art, neon HUD, corner
Matches the Anomaly frame: full-bleed art, neon HUD, corner
badges. Server identity = green accent + rack-glyph badge.
====================================================== */
@ -108,7 +108,7 @@
box-shadow: 0 0 6px var(--accent);
}
/* SRV glyph under the rack badge (mirrors avatar type glyph) */
/* SRV glyph under the rack badge (mirrors anomaly type glyph) */
.srvchip {
position: absolute;
z-index: 5;
@ -144,7 +144,7 @@
box-shadow: 0 0 14px var(--accent);
}
/* status badge (mirrors avatar ports slot) */
/* status badge (mirrors anomaly slots badge) */
.status {
position: absolute;
z-index: 5;

View file

@ -1,7 +1,7 @@
<!--
Server-Front template — full-bleed cyber HUD node (matches the Avatar family)
Server-Front template — full-bleed cyber HUD node (matches the Anomaly family)
Card size: 750 x 1050 px (2.5in x 3.5in @ 300 DPI)
Attributes: {{card.name}} {{card.image}} {{card.description}} (Servers have no RAM/Cores)
Attributes: {{card.name}} {{card.image}} {{card.description}} (Servers have no Bandwidth/Cores)
Green signature accent. Server identity: rack-glyph badge + status LEDs.
-->
<div class="card">

View file

@ -0,0 +1,225 @@
/* ======================================================
Execution card — command-line terminal
Signature accent: amber (distinct from the other cards).
====================================================== */
.card {
position: relative;
width: 750px;
height: 1050px;
box-sizing: border-box;
padding: 0;
overflow: hidden;
font-family: "Consolas", "Courier New", monospace;
background: #05060a;
--accent: #ffb02e;
--accent-dk: #7a4d00;
--screen: #f6ecd8;
--chamfer: 22px;
}
/* cinematic tint: accent top-corner light, cool counter-light, dark bottom for text */
.tint {
position: absolute;
inset: 0;
z-index: 1;
pointer-events: none;
background:
radial-gradient(70% 45% at 100% 0%, var(--accent) 0%, transparent 55%),
radial-gradient(60% 40% at 0% 8%, rgba(40,150,255,0.22) 0%, transparent 60%),
linear-gradient(180deg, rgba(3,6,9,0.55) 0%, rgba(3,6,9,0) 22%, rgba(3,6,9,0) 40%, rgba(3,6,9,0.78) 72%, rgba(3,6,9,0.96) 100%);
opacity: 0.9;
}
/* ----- Neon HUD outline (shared across card types) ----- */
.neon {
position: absolute;
inset: 13px;
z-index: 40;
pointer-events: none;
border: 3px solid var(--accent);
clip-path: polygon(
var(--chamfer) 0, calc(100% - var(--chamfer)) 0, 100% var(--chamfer),
100% calc(100% - var(--chamfer)), calc(100% - var(--chamfer)) 100%,
var(--chamfer) 100%, 0 calc(100% - var(--chamfer)), 0 var(--chamfer)
);
box-shadow: 0 0 16px var(--accent), 0 0 6px var(--accent), inset 0 0 16px rgba(0,0,0,0.4);
}
/* ----- Terminal screen shell ----- */
.terminal {
position: absolute;
inset: 20px;
box-sizing: border-box;
border-radius: 16px;
padding: 0 0 24px;
color: var(--screen);
background: radial-gradient(120% 90% at 50% 0%, #14120a 0%, #0a0905 60%, #050403 100%);
box-shadow:
inset 0 0 70px rgba(0,0,0,0.7),
inset 0 0 0 2px rgba(255,176,46,0.08),
0 0 0 2px rgba(0,0,0,0.6),
0 10px 24px rgba(0,0,0,0.6);
overflow: hidden;
}
/* ----- Terminal top bar ----- */
.term-bar {
position: relative;
z-index: 2;
display: flex;
align-items: center;
gap: 14px;
height: 82px;
padding: 0 20px;
background: linear-gradient(180deg, rgba(255,176,46,0.10) 0%, rgba(0,0,0,0) 100%);
border-bottom: 2px solid var(--accent-dk);
}
.title {
flex: 1;
font-size: 30px;
font-weight: 800;
letter-spacing: 0.5px;
text-transform: uppercase;
color: #fff6e6;
text-shadow: 0 0 12px rgba(255,176,46,0.5), 0 2px 4px #000;
line-height: 1.02;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.bandwidth-chip {
flex: none;
min-width: 92px;
height: 58px;
padding: 0 14px;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
border-radius: 8px;
color: #fff;
background: #0a0805;
border: 3px solid var(--accent);
box-shadow: inset 0 0 10px rgba(0,0,0,0.6);
}
.bandwidth-value {
font-size: 38px;
font-weight: 800;
line-height: 1;
text-shadow: 0 2px 3px rgba(0,0,0,0.7);
}
.bandwidth-label {
font-size: 19px;
font-weight: 700;
letter-spacing: 2px;
color: var(--accent);
}
/* ----- Command line ----- */
.cmdline {
position: relative;
z-index: 2;
margin: 20px 24px 0 24px;
font-size: 24px;
font-weight: 700;
letter-spacing: 1px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.cmdline .user { color: var(--accent); }
.cmdline .punc { color: #8a8072; margin: 0 2px; }
.cmdline .cwd { color: #cbb98f; }
.cmdline .cmd { color: #fff6e6; margin-left: 10px; }
/* ----- Output viewport (art) ----- */
.viewport {
position: absolute;
top: 0;
left: 0;
z-index: 0;
height: 100%;
width: 100%;
border-radius: 10px;
overflow: hidden;
background: #020202;
border: 4px solid var(--accent-dk);
box-shadow: inset 0 0 0 3px rgba(0,0,0,0.6), inset 0 0 0 4px rgba(255,176,46,0.15), 0 0 18px rgba(0,0,0,0.6);
}
.art {
width: 100%;
height: 100%;
display: block;
image-rendering: pixelated;
background-color: #676767;
background-image: url({{index assets card.image}});
background-position: center;
background-size: cover;
background-repeat: no-repeat;
}
/* ----- stdout / description ----- */
.stdout {
position: relative;
z-index: 2;
margin: 550px 24px 0;
min-height: 210px;
padding: 16px 18px;
border-radius: 10px;
background: rgba(0,0,0,0.45);
border: 2px dashed var(--accent-dk);
}
.stdout-label {
font-size: 20px;
font-weight: 800;
letter-spacing: 2px;
color: var(--accent);
}
.description {
margin: 8px 0 0;
font-size: 23px;
line-height: 1.4;
color: #fbf3e3;
}
.cursor {
display: inline-block;
width: 16px;
height: 26px;
margin-top: 6px;
vertical-align: text-bottom;
background: var(--accent);
box-shadow: 0 0 10px var(--accent);
}
/* ----- Status bar footer ----- */
.statusbar {
position: absolute;
left: 24px;
right: 24px;
bottom: 18px;
z-index: 2;
display: flex;
justify-content: space-between;
align-items: center;
font-size: 20px;
font-weight: 700;
letter-spacing: 2px;
color: #8a8072;
}
.statusbar .target {
display: inline-flex;
align-items: center;
gap: 8px;
color: var(--accent);
}
.statusbar .target::before {
content: "";
width: 14px;
height: 14px;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 8px var(--accent);
}

View file

@ -0,0 +1,48 @@
<!--
Execution-Front template — command-line terminal theme
Card size: 750 x 1050 px (2.5in x 3.5in @ 300 DPI)
Attributes: {{card.name}} {{card.bandwidth}} {{card.image}} {{card.description}}
(Executions have no Type/Cores.) Signature accent: amber terminal.
Executions are one-shot commands played targeting a Server.
-->
<div class="card">
<div class="neon"></div>
<div class="tint"></div>
<div class="terminal">
<div class="scanlines"></div>
<!-- Terminal top bar -->
<div class="term-bar">
<span class="title">{{card.name}}</span>
<span class="bandwidth-chip" title="Bandwidth cost">
<span class="bandwidth-value">{{card.bandwidth}}</span>
<span class="bandwidth-label">Gb</span>
</span>
</div>
<!-- Command line -->
<div class="cmdline">
<span class="user">root@files</span><span class="punc">:</span><span class="cwd">~</span><span class="punc">$</span>
<span class="cmd">sudo execute --now</span>
</div>
<!-- Output viewport (art) -->
<div class="viewport">
<div class="art"></div>
</div>
<!-- stdout: description -->
<div class="stdout">
<span class="stdout-label">[stdout]</span>
<p class="description">{{card.description}}</p>
<span class="cursor"></span>
</div>
<!-- Status bar footer -->
<div class="statusbar">
<span class="target">TARGET: SERVER</span>
<span class="model">FILES-TCG · EXECUTION</span>
</div>
</div>
</div>

View file

@ -77,7 +77,7 @@
overflow: hidden;
text-overflow: ellipsis;
}
.ram-chip {
.bandwidth-chip {
flex: none;
min-width: 92px;
height: 58px;
@ -92,13 +92,13 @@
border: 3px solid var(--accent);
box-shadow: inset 0 0 10px rgba(0,0,0,0.6);
}
.ram-value {
.bandwidth-value {
font-size: 38px;
font-weight: 800;
line-height: 1;
text-shadow: 0 2px 3px rgba(0,0,0,0.7);
}
.ram-label {
.bandwidth-label {
font-size: 19px;
font-weight: 700;
letter-spacing: 2px;

View file

@ -1,7 +1,7 @@
<!--
Execution-Front template — command-line terminal theme
Card size: 750 x 1050 px (2.5in x 3.5in @ 300 DPI)
Attributes: {{card.name}} {{card.ram}} {{card.image}} {{card.description}}
Attributes: {{card.name}} {{card.bandwidth}} {{card.image}} {{card.description}}
(Executions have no Type/Cores.) Signature accent: amber terminal.
Executions are one-shot commands played targeting a Server.
-->
@ -13,9 +13,9 @@
<!-- Terminal top bar -->
<div class="term-bar">
<span class="title">{{card.name}}</span>
<span class="ram-chip" title="RAM cost">
<span class="ram-value">{{card.ram}}</span>
<span class="ram-label">RAM</span>
<span class="bandwidth-chip" title="Bandwidth cost">
<span class="bandwidth-value">{{card.bandwidth}}</span>
<span class="bandwidth-label">Gb</span>
</span>
</div>

View file

@ -0,0 +1,338 @@
/* ======================================================
Hardware card — expansion module
Same chassis as Program/Execution (neon outline, header,
viewport, console, status bar). Hardware identity = gold
contacts: DIP-chip Bandwidth cost, PCB traces, edge connector.
====================================================== */
.card {
position: relative;
width: 750px;
height: 1050px;
box-sizing: border-box;
padding: 0;
overflow: hidden;
font-family: "Consolas", "Courier New", monospace;
background: #05070a;
--accent: #ffd24a;
--accent-dk: #8a6a1a;
--chamfer: 22px;
}
/* cinematic tint: accent top-corner light, cool counter-light, dark bottom for text */
.tint {
position: absolute;
inset: 0;
z-index: 1;
pointer-events: none;
background:
radial-gradient(70% 45% at 100% 0%, var(--accent) 0%, transparent 55%),
radial-gradient(60% 40% at 0% 8%, rgba(40,150,255,0.22) 0%, transparent 60%),
linear-gradient(180deg, rgba(3,6,9,0.55) 0%, rgba(3,6,9,0) 22%, rgba(3,6,9,0) 40%, rgba(3,6,9,0.78) 72%, rgba(3,6,9,0.96) 100%);
opacity: 0.9;
}
/* ----- Neon HUD outline (shared across card types) ----- */
.neon {
position: absolute;
inset: 13px;
z-index: 40;
pointer-events: none;
border: 3px solid var(--accent);
clip-path: polygon(
var(--chamfer) 0, calc(100% - var(--chamfer)) 0, 100% var(--chamfer),
100% calc(100% - var(--chamfer)), calc(100% - var(--chamfer)) 100%,
var(--chamfer) 100%, 0 calc(100% - var(--chamfer)), 0 var(--chamfer)
);
box-shadow: 0 0 16px var(--accent), 0 0 6px var(--accent), inset 0 0 16px rgba(0,0,0,0.4);
}
/* ----- Module shell (gunmetal board) ----- */
.module {
position: absolute;
inset: 20px;
box-sizing: border-box;
border-radius: 16px;
color: #f3efe4;
background: linear-gradient(180deg, #2b2f36 0%, #1c1f25 100%);
box-shadow:
inset 0 0 60px rgba(0,0,0,0.55),
0 0 0 2px rgba(0,0,0,0.6),
0 10px 24px rgba(0,0,0,0.6);
overflow: hidden;
}
/* Faint PCB traces (hardware's texture, like the CRT scanlines on Executions) */
.traces {
position: absolute;
inset: 0;
pointer-events: none;
opacity: 0.6;
background-image:
linear-gradient(rgba(255,210,74,0.05) 1px, transparent 1px),
linear-gradient(90deg, rgba(255,210,74,0.05) 1px, transparent 1px),
repeating-linear-gradient(45deg, rgba(255,210,74,0.035) 0 2px, transparent 2px 38px);
background-size: 44px 44px, 44px 44px, auto;
}
/* ----- Heat-spreader header ----- */
.spreader {
position: relative;
z-index: 2;
display: flex;
align-items: center;
gap: 16px;
height: 82px;
padding: 0 20px;
}
/* HW glyph (mirrors the Anomaly type chip) */
.hw-chip {
flex: none;
width: 64px;
height: 56px;
display: flex;
align-items: center;
justify-content: center;
font-size: 26px;
font-weight: 800;
letter-spacing: 1px;
color: #05070a;
clip-path: polygon(14% 0, 100% 0, 100% 86%, 86% 100%, 0 100%, 0 14%);
background: linear-gradient(160deg, var(--accent) 0%, var(--accent-dk) 100%);
}
.name {
flex: 1;
font-size: 32px;
font-weight: 800;
letter-spacing: 1px;
text-transform: uppercase;
line-height: 1.02;
color: #fff8e6;
text-shadow: 0 0 12px rgba(255,210,74,0.35), 0 2px 4px #000;
/* long names wrap to a second line instead of truncating */
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
/* ----- Bandwidth cost as a DIP chip (mirrors the Anomaly core chip) ----- */
.bandwidth-ic {
position: relative;
flex: none;
min-width: 108px;
height: 56px;
box-sizing: border-box;
padding: 0 14px;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
border-radius: 6px;
color: #fff;
background:
radial-gradient(circle at 11px 11px, #5a5e66 0 3px, transparent 4px), /* pin-1 dot */
linear-gradient(160deg, #2a2f36 0%, #0e1115 100%);
border: 2px solid var(--accent-dk);
box-shadow: 0 3px 6px rgba(0,0,0,0.6), inset 0 0 10px rgba(0,0,0,0.75);
}
/* gold pins along the top and bottom edges */
.bandwidth-ic::before,
.bandwidth-ic::after {
content: "";
position: absolute;
left: 10px;
right: 10px;
height: 9px;
background-image: linear-gradient(90deg,
var(--accent-dk) 0 1px, var(--accent) 1px 5px, var(--accent-dk) 5px 6px, transparent 6px);
background-size: 14px 100%;
background-repeat: space;
}
.bandwidth-ic::before { top: -11px; }
.bandwidth-ic::after { bottom: -11px; }
.bandwidth-value {
font-size: 38px;
font-weight: 800;
line-height: 1;
text-shadow: 0 2px 3px rgba(0,0,0,0.7);
}
.bandwidth-label {
font-size: 19px;
font-weight: 700;
letter-spacing: 2px;
color: var(--accent);
}
/* ----- Spec strip: silkscreen label + status LEDs ----- */
.spec-strip {
position: relative;
z-index: 2;
display: flex;
align-items: center;
justify-content: space-between;
margin: 20px 24px 0;
padding: 12px 18px;
border-radius: 10px;
background: rgba(0,0,0,0.35);
border: 2px solid var(--accent-dk);
}
.silk {
font-size: 22px;
font-weight: 700;
letter-spacing: 4px;
color: var(--accent);
}
.leds { display: flex; gap: 20px; }
.led {
display: inline-flex;
align-items: center;
gap: 8px;
font-size: 18px;
font-weight: 800;
letter-spacing: 2px;
color: #9a9384;
}
.led i {
width: 14px;
height: 14px;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 8px var(--accent), inset 0 0 3px rgba(0,0,0,0.4);
}
.led.dim i {
background: var(--accent-dk);
box-shadow: inset 0 0 3px rgba(0,0,0,0.6);
}
/* ----- Component bay (art) ----- */
.bay {
position: absolute;
z-index: 0;
top: 0;
left: 0;
height: 100%;
width: 100%;
border-radius: 10px;
overflow: hidden;
border: 4px solid var(--accent-dk);
background-color: #07090c;
/* empty-bay fallback: faint traces + vias, hidden once art is set */
background-image:
radial-gradient(circle, rgba(255,210,74,0.16) 0 3px, transparent 4px),
linear-gradient(rgba(255,210,74,0.05) 2px, transparent 2px),
linear-gradient(90deg, rgba(255,210,74,0.05) 2px, transparent 2px);
background-size: 66px 66px;
background-position: -32px -32px, 0 0, 0 0;
box-shadow: inset 0 0 0 3px rgba(0,0,0,0.6), 0 0 18px rgba(0,0,0,0.6);
}
.art {
position: absolute;
inset: 0;
image-rendering: pixelated;
background-color: #696969;
background-image: url({{index assets card.image}});
background-position: center;
background-size: cover;
background-repeat: no-repeat;
}
/* gold corner brackets framing the component */
.brackets {
position: absolute;
inset: 14px;
pointer-events: none;
--b: linear-gradient(var(--accent), var(--accent));
background:
var(--b) top left / 36px 3px no-repeat,
var(--b) top left / 3px 36px no-repeat,
var(--b) top right / 36px 3px no-repeat,
var(--b) top right / 3px 36px no-repeat,
var(--b) bottom left / 36px 3px no-repeat,
var(--b) bottom left / 3px 36px no-repeat,
var(--b) bottom right / 36px 3px no-repeat,
var(--b) bottom right / 3px 36px no-repeat;
filter: drop-shadow(0 0 6px var(--accent));
}
/* ----- Datasheet / description ----- */
.spec {
position: relative;
z-index: 2;
margin: 600px 24px 0;
min-height: 200px;
box-sizing: border-box;
padding: 16px 18px;
border-radius: 10px;
background: rgba(0,0,0,0.4);
border: 2px dashed var(--accent-dk);
}
.spec-label {
color: var(--accent);
font-weight: 800;
font-size: 24px;
}
.description {
margin: 6px 0 0;
font-size: 23px;
line-height: 1.4;
color: #f6f1e4;
}
/* ----- Status bar footer ----- */
.statusbar {
position: absolute;
left: 24px;
right: 24px;
bottom: 50px;
z-index: 2;
display: flex;
justify-content: space-between;
align-items: center;
font-size: 20px;
font-weight: 700;
letter-spacing: 2px;
color: #8f8a7e;
}
.statusbar .slot {
display: inline-flex;
align-items: center;
gap: 8px;
color: var(--accent);
}
.statusbar .slot::before {
/* square solder pad instead of the round status dot */
content: "";
width: 14px;
height: 14px;
border-radius: 2px;
background: var(--accent);
box-shadow: 0 0 8px var(--accent);
}
/* ----- Gold edge connector (plugs into an Anomaly's Expansion Slot) ----- */
.edge-connector {
position: absolute;
left: 56px;
right: 56px;
bottom: 0;
height: 24px;
z-index: 2;
border-top: 2px solid var(--accent-dk);
background:
repeating-linear-gradient(90deg, transparent 0 16px, #15181c 16px 24px),
linear-gradient(180deg, #fbe7a1 0%, var(--accent) 35%, var(--accent-dk) 100%);
box-shadow: 0 0 12px rgba(255,210,74,0.25);
}
/* key notch */
.edge-connector::after {
content: "";
position: absolute;
left: 30%;
top: -2px;
bottom: 0;
width: 22px;
background: #05070a;
}

View file

@ -0,0 +1,55 @@
<!--
Hardware-Front template — expansion-module theme
Card size: 750 x 1050 px (2.5in x 3.5in @ 300 DPI)
Attributes: {{card.name}} {{card.bandwidth}} {{card.image}} {{card.description}}
(Hardware has no Type/Cores.) Signature accent: gold contacts.
Hardware plugs into an Anomaly's Expansion Slots — the gold edge connector (bottom) is the plug.
-->
<div class="card">
<div class="neon"></div>
<div class="tint"></div>
<div class="module">
<div class="traces"></div>
<!-- Heat-spreader header: HW glyph, name, Bandwidth cost as a DIP chip -->
<div class="spreader">
<span class="hw-chip">HW</span>
<span class="name">{{card.name}}</span>
<span class="bandwidth-ic" title="Bandwidth cost">
<span class="bandwidth-value">{{card.bandwidth}}</span>
<span class="bandwidth-label">Gb</span>
</span>
</div>
<!-- Spec strip: silkscreen label + status LEDs
<div class="spec-strip">
<span class="silk">EXPANSION MODULE</span>
<span class="leds">
<span class="led"><i></i>PWR</span>
<span class="led dim"><i></i>ACT</span>
</span>
</div> -->
<!-- Component bay (art) -->
<div class="bay">
<div class="art"></div>
<div class="brackets"></div>
</div>
<!-- Datasheet / description -->
<div class="spec">
<span class="spec-label">spec&gt;</span>
<p class="description">{{card.description}}</p>
</div>
<!-- Status bar footer -->
<div class="statusbar">
<span class="slot">INSTALLS ON ANOMALY</span>
<span class="model">FILES-TCG · HARDWARE</span>
</div>
<!-- Gold edge connector: plugs into an Anomaly's Expansion Slot -->
<div class="edge-connector"></div>
</div>
</div>

View file

@ -2,7 +2,7 @@
Hardware card — expansion module
Same chassis as Program/Execution (neon outline, header,
viewport, console, status bar). Hardware identity = gold
contacts: DIP-chip RAM cost, PCB traces, edge connector.
contacts: DIP-chip Bandwidth cost, PCB traces, edge connector.
====================================================== */
.card {
@ -78,7 +78,7 @@
box-shadow: inset 0 1px 0 rgba(255,255,255,0.06), inset 0 -10px 18px rgba(0,0,0,0.35);
}
/* HW glyph (mirrors the Avatar type chip) */
/* HW glyph (mirrors the Anomaly type chip) */
.hw-chip {
flex: none;
width: 64px;
@ -110,8 +110,8 @@
overflow: hidden;
}
/* ----- RAM cost as a DIP chip (mirrors the Avatar core chip) ----- */
.ram-ic {
/* ----- Bandwidth cost as a DIP chip (mirrors the Anomaly core chip) ----- */
.bandwidth-ic {
position: relative;
flex: none;
min-width: 108px;
@ -131,8 +131,8 @@
box-shadow: 0 3px 6px rgba(0,0,0,0.6), inset 0 0 10px rgba(0,0,0,0.75);
}
/* gold pins along the top and bottom edges */
.ram-ic::before,
.ram-ic::after {
.bandwidth-ic::before,
.bandwidth-ic::after {
content: "";
position: absolute;
left: 10px;
@ -143,15 +143,15 @@
background-size: 14px 100%;
background-repeat: space;
}
.ram-ic::before { top: -11px; }
.ram-ic::after { bottom: -11px; }
.ram-value {
.bandwidth-ic::before { top: -11px; }
.bandwidth-ic::after { bottom: -11px; }
.bandwidth-value {
font-size: 38px;
font-weight: 800;
line-height: 1;
text-shadow: 0 2px 3px rgba(0,0,0,0.7);
}
.ram-label {
.bandwidth-label {
font-size: 19px;
font-weight: 700;
letter-spacing: 2px;
@ -301,7 +301,7 @@
box-shadow: 0 0 8px var(--accent);
}
/* ----- Gold edge connector (plugs into an Avatar port) ----- */
/* ----- Gold edge connector (plugs into an Anomaly's Expansion Slot) ----- */
.edge-connector {
position: absolute;
left: 56px;

View file

@ -1,22 +1,22 @@
<!--
Hardware-Front template — expansion-module theme
Card size: 750 x 1050 px (2.5in x 3.5in @ 300 DPI)
Attributes: {{card.name}} {{card.ram}} {{card.image}} {{card.description}}
Attributes: {{card.name}} {{card.bandwidth}} {{card.image}} {{card.description}}
(Hardware has no Type/Cores.) Signature accent: gold contacts.
Hardware plugs into an Avatar's PORTS — the gold edge connector (bottom) is the plug.
Hardware plugs into an Anomaly's Expansion Slots — the gold edge connector (bottom) is the plug.
-->
<div class="card">
<div class="neon"></div>
<div class="module">
<div class="traces"></div>
<!-- Heat-spreader header: HW glyph, name, RAM cost as a DIP chip -->
<!-- Heat-spreader header: HW glyph, name, Bandwidth cost as a DIP chip -->
<div class="spreader">
<span class="hw-chip">HW</span>
<span class="name">{{card.name}}</span>
<span class="ram-ic" title="RAM cost">
<span class="ram-value">{{card.ram}}</span>
<span class="ram-label">RAM</span>
<span class="bandwidth-ic" title="Bandwidth cost">
<span class="bandwidth-value">{{card.bandwidth}}</span>
<span class="bandwidth-label">Gb</span>
</span>
</div>
@ -43,11 +43,11 @@
<!-- Status bar footer -->
<div class="statusbar">
<span class="slot">INSTALLS ON AVATAR</span>
<span class="slot">INSTALLS ON ANOMALY</span>
<span class="model">FILES-TCG · HARDWARE</span>
</div>
<!-- Gold edge connector: plugs into an Avatar port -->
<!-- Gold edge connector: plugs into an Anomaly's Expansion Slot -->
<div class="edge-connector"></div>
</div>

View file

@ -0,0 +1,251 @@
/* ======================================================
Program card — software / terminal-window
Accent color driven by Type (V/B/G/P), matching Anomalies.
====================================================== */
.card {
position: relative;
width: 750px;
height: 1050px;
box-sizing: border-box;
padding: 0;
overflow: hidden;
font-family: "Consolas", "Courier New", monospace;
background: #05070a;
--accent: #8b949e;
--accent-dk: #3a3f47;
--chamfer: 22px;
}
/* cinematic tint: accent top-corner light, cool counter-light, dark bottom for text */
.tint {
position: absolute;
inset: 0;
z-index: 1;
pointer-events: none;
background:
radial-gradient(70% 45% at 100% 0%, var(--accent) 0%, transparent 55%),
radial-gradient(60% 40% at 0% 8%, rgba(40,150,255,0.22) 0%, transparent 60%),
linear-gradient(180deg, rgba(3,6,9,0.55) 0%, rgba(3,6,9,0) 22%, rgba(3,6,9,0) 40%, rgba(3,6,9,0.48) 82%, rgba(3,6,9,0.76) 100%);
opacity: 0.9;
}
/* ----- Neon HUD outline (shared across card types) ----- */
.neon {
position: absolute;
inset: 13px;
z-index: 40;
pointer-events: none;
border: 3px solid var(--accent);
clip-path: polygon(
var(--chamfer) 0, calc(100% - var(--chamfer)) 0, 100% var(--chamfer),
100% calc(100% - var(--chamfer)), calc(100% - var(--chamfer)) 100%,
var(--chamfer) 100%, 0 calc(100% - var(--chamfer)), 0 var(--chamfer)
);
box-shadow: 0 0 16px var(--accent), 0 0 6px var(--accent), inset 0 0 16px rgba(0,0,0,0.4);
}
/* Type-driven accent palette (shared with Anomaly cards) */
.type-v { --accent: #3fb950; --accent-dk: #176b2c; } /* Virus */
.type-b { --accent: #ff5c5c; --accent-dk: #a11a1a; } /* Bug */
.type-g { --accent: #d264ff; --accent-dk: #7a1fb0; } /* Glitch */
.type-p { --accent: #4aa3ff; --accent-dk: #0b57c9; } /* Patch */
/* ----- Application window shell ----- */
.app {
position: absolute;
inset: 20px;
box-sizing: border-box;
border-radius: 16px;
padding: 0 0 24px;
color: #e6edf3;
background: linear-gradient(180deg, #2b2f36 0%, #1c1f25 100%);
box-shadow:
inset 0 0 60px rgba(0,0,0,0.55),
0 0 0 2px rgba(0,0,0,0.6),
0 10px 24px rgba(0,0,0,0.6);
overflow: hidden;
}
/* ----- Window title bar ----- */
.titlebar {
position: relative;
display: flex;
align-items: center;
gap: 16px;
height: 82px;
padding: 0 20px;
z-index: 2;
}
.win-dots { display: flex; gap: 12px; flex: none; }
.win-dots i {
width: 20px;
height: 20px;
border-radius: 50%;
background: #2a2f36;
box-shadow: inset 0 0 3px rgba(0,0,0,0.7);
}
.win-dots i:first-child {
background: var(--accent);
box-shadow: 0 0 10px var(--accent), inset 0 0 3px rgba(0,0,0,0.4);
}
.app-name {
flex: 1;
font-size: 36px;
font-weight: 800;
letter-spacing: 1px;
text-transform: uppercase;
color: #f2f7fb;
text-shadow: 0 2px 4px #000;
line-height: 1.02;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.type-badge {
flex: none;
width: 60px;
height: 60px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 12px;
font-size: 34px;
font-weight: 800;
color: #05070a;
background: var(--accent);
border: 3px solid #05070a;
box-shadow: 0 0 16px var(--accent);
}
/* ----- Toolbar: exec path + Bandwidth chip ----- */
.toolbar {
position: relative;
display: flex;
align-items: center;
gap: 16px;
margin: 22px 24px 0;
padding: 14px 18px;
border-radius: 10px;
background: rgba(0,0,0,0.35);
border: 2px solid var(--accent-dk);
z-index: 2;
}
.path {
flex: 1;
font-size: 24px;
font-weight: 700;
letter-spacing: 1px;
color: var(--accent);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.bandwidth-chip {
flex: none;
min-width: 96px;
height: 60px;
padding: 0 16px;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 10px;
border-radius: 8px;
color: #fff;
background: #0a0f14;
border: 3px solid var(--accent);
box-shadow: inset 0 0 10px rgba(0,0,0,0.6);
}
.bandwidth-value {
font-size: 40px;
font-weight: 800;
line-height: 1;
text-shadow: 0 2px 3px rgba(0,0,0,0.7);
}
.bandwidth-label {
font-size: 20px;
font-weight: 700;
letter-spacing: 2px;
color: var(--accent);
}
/* ----- Art viewport ----- */
.viewport {
position: absolute;
height: 100%;
width: 100%;
top: 0;
left: 0;
z-index: 0;
border-radius: 10px;
overflow: hidden;
background: #020405;
}
.art {
width: 100%;
height: 100%;
display: block;
image-rendering: pixelated;
background-color: #898989;
background-image: url({{index assets card.image}});
background-position: center;
background-size: cover;
background-repeat: no-repeat;
}
/* ----- Console output / description ----- */
.console {
position: relative;
margin: 550px 24px 0;
min-height: 200px;
padding: 16px 18px;
border-radius: 10px;
background: rgba(0,0,0,0.4);
border: 2px dashed var(--accent-dk);
z-index: 2;
}
.console .prompt {
color: var(--accent);
font-weight: 800;
font-size: 24px;
margin-right: 8px;
}
.description {
margin: 6px 0 0;
font-size: 23px;
line-height: 1.4;
color: #eef5fb;
}
/* ----- Status bar footer ----- */
.statusbar {
position: absolute;
left: 24px;
right: 24px;
bottom: 18px;
display: flex;
justify-content: space-between;
align-items: center;
font-size: 20px;
font-weight: 700;
letter-spacing: 2px;
color: #8a9099;
z-index: 2;
}
.statusbar .run {
display: inline-flex;
align-items: center;
gap: 8px;
color: var(--accent);
}
.statusbar .run::before {
content: "";
width: 14px;
height: 14px;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 8px var(--accent);
}

View file

@ -0,0 +1,48 @@
<!--
Program-Front template — software / terminal-window theme
Card size: 750 x 1050 px (2.5in x 3.5in @ 300 DPI)
Attributes: {{card.name}} {{card.bandwidth}} {{card.type}} {{card.image}} {{card.description}}
Accent color is driven by Type (V/B/G/P), matching the Anomaly cards.
Programs are installed on Servers — reinforced by the "RUNS ON SERVER" status line.
-->
<div class="card type-{{lowercase card.type}}">
<div class="tint"></div>
<div class="neon"></div>
<div class="app">
<!-- Window title bar -->
<div class="titlebar">
<span class="win-dots"><i></i><i></i><i></i></span>
<span class="app-name">{{card.name}}</span>
<span class="type-badge">{{card.type}}</span>
</div>
<!-- Toolbar: exec path + Bandwidth cost chip -->
<div class="toolbar">
<span class="path">&gt; run /srv/{{lowercase card.type}}/program</span>
<span class="bandwidth-chip" title="Bandwidth cost">
<span class="bandwidth-value">{{card.bandwidth}}</span>
<span class="bandwidth-label">Gb</span>
</span>
</div>
<!-- Art viewport -->
<div class="viewport">
<div class="art"></div>
<div class="scan"></div>
</div>
<!-- Console output / description -->
<div class="console">
<span class="prompt">proc&gt;</span>
<p class="description">{{card.description}}</p>
</div>
<!-- Status bar footer -->
<div class="statusbar">
<span class="run">RUNS ON SERVER</span>
<span class="model">FILES-TCG · PROGRAM</span>
</div>
</div>
</div>

View file

@ -1,6 +1,6 @@
/* ======================================================
Program card — software / terminal-window
Accent color driven by Type (V/B/G/P), matching Avatars.
Accent color driven by Type (V/B/G/P), matching Anomalies.
====================================================== */
.card {
@ -32,7 +32,7 @@
box-shadow: 0 0 16px var(--accent), 0 0 6px var(--accent), inset 0 0 16px rgba(0,0,0,0.4);
}
/* Type-driven accent palette (shared with Avatar cards) */
/* Type-driven accent palette (shared with Anomaly cards) */
.type-v { --accent: #3fb950; --accent-dk: #176b2c; } /* Virus */
.type-b { --accent: #ff5c5c; --accent-dk: #a11a1a; } /* Bug */
.type-g { --accent: #d264ff; --accent-dk: #7a1fb0; } /* Glitch */
@ -107,7 +107,7 @@
box-shadow: 0 0 16px var(--accent);
}
/* ----- Toolbar: exec path + RAM chip ----- */
/* ----- Toolbar: exec path + Bandwidth chip ----- */
.toolbar {
position: relative;
display: flex;
@ -129,7 +129,7 @@
overflow: hidden;
text-overflow: ellipsis;
}
.ram-chip {
.bandwidth-chip {
flex: none;
min-width: 96px;
height: 60px;
@ -144,13 +144,13 @@
border: 3px solid var(--accent);
box-shadow: inset 0 0 10px rgba(0,0,0,0.6);
}
.ram-value {
.bandwidth-value {
font-size: 40px;
font-weight: 800;
line-height: 1;
text-shadow: 0 2px 3px rgba(0,0,0,0.7);
}
.ram-label {
.bandwidth-label {
font-size: 20px;
font-weight: 700;
letter-spacing: 2px;

View file

@ -1,8 +1,8 @@
<!--
Program-Front template — software / terminal-window theme
Card size: 750 x 1050 px (2.5in x 3.5in @ 300 DPI)
Attributes: {{card.name}} {{card.ram}} {{card.type}} {{card.image}} {{card.description}}
Accent color is driven by Type (V/B/G/P), matching the Avatar cards.
Attributes: {{card.name}} {{card.bandwidth}} {{card.type}} {{card.image}} {{card.description}}
Accent color is driven by Type (V/B/G/P), matching the Anomaly cards.
Programs are installed on Servers — reinforced by the "RUNS ON SERVER" status line.
-->
<div class="card type-{{lowercase card.type}}">
@ -16,12 +16,12 @@
<span class="type-badge">{{card.type}}</span>
</div>
<!-- Toolbar: exec path + RAM cost chip -->
<!-- Toolbar: exec path + Bandwidth cost chip -->
<div class="toolbar">
<span class="path">&gt; run /srv/{{lowercase card.type}}/program</span>
<span class="ram-chip" title="RAM cost">
<span class="ram-value">{{card.ram}}</span>
<span class="ram-label">RAM</span>
<span class="bandwidth-chip" title="Bandwidth cost">
<span class="bandwidth-value">{{card.bandwidth}}</span>
<span class="bandwidth-label">Gb</span>
</span>
</div>

View file

@ -1,6 +1,6 @@
/* ======================================================
Server card — full-bleed cyber HUD node
Matches the Avatar frame: full-bleed art, neon HUD, corner
Matches the Anomaly frame: full-bleed art, neon HUD, corner
badges. Server identity = green accent + rack-glyph badge.
====================================================== */
@ -108,7 +108,7 @@
box-shadow: 0 0 6px var(--accent);
}
/* SRV glyph under the rack badge (mirrors avatar type glyph) */
/* SRV glyph under the rack badge (mirrors anomaly type glyph) */
.srvchip {
position: absolute;
z-index: 5;
@ -144,7 +144,7 @@
box-shadow: 0 0 14px var(--accent);
}
/* status badge (mirrors avatar ports slot) */
/* status badge (mirrors anomaly slots badge) */
.status {
position: absolute;
z-index: 5;

View file

@ -1,7 +1,7 @@
<!--
Server-Front template — full-bleed cyber HUD node (matches the Avatar family)
Server-Front template — full-bleed cyber HUD node (matches the Anomaly family)
Card size: 750 x 1050 px (2.5in x 3.5in @ 300 DPI)
Attributes: {{card.name}} {{card.image}} {{card.description}} (Servers have no RAM/Cores)
Attributes: {{card.name}} {{card.image}} {{card.description}} (Servers have no Bandwidth/Cores)
Green signature accent. Server identity: rack-glyph badge + status LEDs.
-->
<div class="card">

View file

@ -1,6 +1,6 @@
/* ======================================================
Server card — full-bleed cyber HUD node
Matches the Avatar frame: full-bleed art, neon HUD, corner
Matches the Anomaly frame: full-bleed art, neon HUD, corner
badges. Server identity = green accent + rack-glyph badge.
====================================================== */
@ -43,7 +43,6 @@
opacity: 0.9;
}
/* ----- Angular neon HUD frame (open chamfered corners) ----- */
.neon {
position: absolute;
@ -108,7 +107,7 @@
box-shadow: 0 0 6px var(--accent);
}
/* SRV glyph under the rack badge (mirrors avatar type glyph) */
/* SRV glyph under the rack badge (mirrors anomaly type glyph) */
.srvchip {
position: absolute;
z-index: 5;
@ -144,7 +143,7 @@
box-shadow: 0 0 14px var(--accent);
}
/* status badge (mirrors avatar ports slot) */
/* status badge (mirrors anomaly slots badge) */
.status {
position: absolute;
z-index: 5;

View file

@ -1,7 +1,7 @@
<!--
Server-Front template — full-bleed cyber HUD node (matches the Avatar family)
Server-Front template — full-bleed cyber HUD node (matches the Anomaly family)
Card size: 750 x 1050 px (2.5in x 3.5in @ 300 DPI)
Attributes: {{card.name}} {{card.image}} {{card.description}} (Servers have no RAM/Cores)
Attributes: {{card.name}} {{card.image}} {{card.description}} (Servers have no Bandwidth/Cores)
Green signature accent. Server identity: rack-glyph badge + status LEDs.
-->
<div class="card">

View file

@ -35,7 +35,7 @@
<div class="label">// your first command each round</div>
<div class="tags">
<span class="tag">Draw a Card</span>
<span class="tag">Refresh Avatars</span>
<span class="tag">Refresh Anomalies</span>
</div>
</div>
@ -52,7 +52,7 @@
<!-- The limits -->
<div class="limits">
<div>1 advance <b>or</b> 1 attack per command</div>
<div>each Avatar acts once per round</div>
<div>each Anomaly acts once per round</div>
</div>
<!-- Combat in one breath -->

View file

@ -13,23 +13,23 @@ the expansion and sketches directions per type. No cards are added here; that's
| Kind | Count | Typed? | Notes |
| ------------- | ----- | ----------------------- | --------------------------------------------------------- |
| Avatars | 8 | yes, 2 per type | 4 per deck, so no mono-type Avatar lineup is possible yet |
| Anomalies | 8 | yes, 2 per type | 4 per deck, so no mono-type Anomaly lineup is possible yet |
| Programs | 28 | yes: V 7, B 8, G 7, P 6 | Patch is one or two short |
| Hardware | 16 | no | Template has no Type field |
| Executions | 18 | no | Template has no Type field |
| Servers | 13 | no | Deck needs 20, so at least 7 must be doubles |
| Turn Sequence | 1 | reference card | not in a deck |
Deck rules that shape the design: 4 Avatars, 20 Servers, 45 main-deck cards (Programs, Hardware,
Executions), at most 2 copies of any card. Salvage pays **full printed RAM**, so an expensive card
in hand is never dead: it is that much RAM.
Deck rules that shape the design: 4 Anomalies, 20 Servers, 45 main-deck cards (Programs, Hardware,
Executions), at most 2 copies of any card. Salvage pays **full printed Bandwidth**, so an expensive card
in hand is never dead: it is that much Bandwidth.
### Avatar stat lines
### Anomaly stat lines
Every Avatar sums Cores + Expansion Slots to 6, except Code Zero (3 + 4 = 7, after the v0.8 bump to
Every Anomaly sums Cores + Expansion Slots to 6, except Code Zero (3 + 4 = 7, after the v0.8 bump to
3 Cores). This can be modified as needed Only three lines exist: 2/4, 3/3 and 4/2. Ability costs run 3 to 5 but can be modified for different abilities.
| Type | Avatar | Cores/Slots | Ability (cost) | Role |
| Type | Anomaly | Cores/Slots | Ability (cost) | Role |
| ---- | ----------------- | ----------- | ------------------------------------------------------------ | ---------------- |
| V | Corrupt Driver | 3/3 | Driver Fault (4): disable enemy Hardware in combat | Hardware denial |
| V | Code Zero | 3/4 | Patient Zero (4): Infection on foes; 1+ Infection = −1 Core | Infection payoff |
@ -37,7 +37,7 @@ Every Avatar sums Cores + Expansion Slots to 6, except Code Zero (3 + 4 = 7, aft
| B | Broken Bits | 4/2 | Bit Flip (4): reroll own dice | Dice control |
| G | Pixelated Picture | 3/3 | Low Resolution (3): attacker −1 Core | Defensive combat |
| G | Data Leaker | 3/3 | Exfiltrate (3): hand peek + targeted discard, draw on breach | Information |
| P | Beta Version 1.0 | 4/2 | Push Update (4): temp Hardware mid-combat, ignoring ports | Burst |
| P | Beta Version 1.0 | 4/2 | Push Update (4): temp Hardware mid-combat, ignoring Expansion Slots | Burst |
| P | Backup Machine | 3/3 | Restore Point (5): heal 3, or recover Hardware/Program | Recovery, healing |
## 2. What Each Type Is For
@ -46,13 +46,13 @@ Every Avatar sums Cores + Expansion Slots to 6, except Code Zero (3 + 4 = 7, aft
type-focused design.
**Virus (V): hurts the attacker and the enemy's stuff.** Infection counters, Hardware disabling,
RAM gained from enemy losses, spreading effects to adjacent locations. Current pieces: Recursive
Bandwidth gained from enemy losses, spreading effects to adjacent locations. Current pieces: Recursive
Infection, Persistent Infection, Code Zero (placers and payoffs), Memory Parasite, Corrupt Driver
(Hardware denial), Resource Leech (RAM from kills), Worm Protocol and Replication Routine
(Hardware denial), Resource Leech (Bandwidth from kills), Worm Protocol and Replication Routine
(spreading and installing). Payload Injector is the odd one, a cost reducer.
**Bug (B): warps the combat.** Dice, Cores, hidden choices, loops, and suppression of Hardware.
Current pieces: Stack Overflow, Race Condition, Memory Leak, Stock Rice, Infinite Loop, Broken Bits,
Current pieces: Stack Overflow, Race Condition, Bloatware, Stock Rice, Infinite Loop, Broken Bits,
Overflow Error, Undefined Behavior. **Bug counters** exist in the engine and are referenced by ECC
Memory and Error Correction, but no card places them. This is the biggest unused mechanic in the
game and belongs to this type.
@ -77,8 +77,8 @@ neutral Hardware and Executions. Type focus is mostly flavor. The expansion shou
**Structural gaps**
1. **Avatars:** 2 per type makes mono-type lineups impossible. 4 per type is the minimum; 5 or 6
gives a real choice. Every new Avatar also needs art.
1. **Anomalies:** 2 per type makes mono-type lineups impossible. 4 per type is the minimum; 5 or 6
gives a real choice. Every new Anomaly also needs art.
2. **Bug counters:** the mechanic is wired up but has no placers and no payoffs.
3. **Firewalls:** only Network Throttle interacts with them. Firewalls block card movement too
(Trace Route, Disconnect), so a "tunnel through a Firewall" effect would be new design space.
@ -91,18 +91,18 @@ neutral Hardware and Executions. Type focus is mostly flavor. The expansion shou
make a type deck feel different from the first capture.
7. **Hardware and Executions are untyped.** Two options: add a Type column value and a small type
chip to those two templates, or keep them typeless and give them type affinity through text ("If
a Virus Avatar you control is at the target Server..."). Text affinity needs no template work and
a Virus Anomaly you control is at the target Server..."). Text affinity needs no template work and
is the assumption below; a type chip can come later.
**Card text and numbers to fix while adding cards**
- ~~RAM Expansion (+2 Cores, 5 RAM) strictly dominates Additional Core (+1 Core, 5 RAM).~~ Resolved
- ~~RAM Expansion (+2 Cores, 5 Gb) strictly dominates Additional Core (+1 Core, 5 Gb).~~ Resolved
2026-09-29: RAM Expansion is now "+2 Health" (section 8).
- Cloud Compute gives +4 Cores. In this dice system +2 Cores is a 90 to 99% edge, so +4 makes a
location nearly untouchable. It's a Server, so both players can draw it, but it swings games.
- Typos listed in `rules.md` Open Questions: Packet Accelerator "hen attacking", Null Pointer "it's
effect", Push Update "If there no ports", Memory Parasite "owners choosing". Network Interface
Upgrade text should say it adds a port.
effect", Memory Parasite "owners choosing". Network Interface
Upgrade text should say it adds an Expansion Slot.
- The CSV switched Servers to the "Server Front Alt" template. The sim's loader didn't know that
name and loaded zero Servers; it now accepts both names (`sim/src/cards.ts`).
- `cards.md` is out of date against the CSV (the rules already say so).
@ -113,22 +113,22 @@ Derived from the current pool. Use these as the starting point; the sim can then
| What you buy | Going rate | Evidence |
| ----------------------------------------------------------- | -------------------------------------------------------------- | ------------------------------------------------ |
| +1 Core, permanent, unconditional (Hardware) | 4 to 5 RAM | Additional Core 5; the RAM Expansion clash above |
| +1 Core, conditional (attacking only, defending only) | 4 RAM | Packet Accelerator |
| +2 Health, permanent (Hardware) | 5 RAM (neutral in the sim; 4 would be fair) | RAM Expansion since v0.9 |
| Heal 3 damage (Ability) | 5 RAM | Restore Point |
| +2 Cores with a drawback | 6 RAM | Overclocked CPU |
| −1 Core to an enemy for one combat (Ability) | 3 RAM | Low Resolution |
| Reroll own dice (Ability) | 4 RAM | Bit Flip |
| Disable one enemy Hardware, one combat or one turn | 4 RAM ability, 5 RAM Program, 7 RAM Execution (destroy option) | Driver Fault, Memory Parasite, Sabotage |
| Disable one Program until next command | 5 RAM | Kill Process, Override |
| Draw 2 | 4 RAM | Ping Sweep |
| Copy a Program effect for one command | 7 RAM | Fork, Process Clone |
| Move an Avatar out of turn | 4 to 5 RAM | Disconnect, Trace Route |
| Counter-style one-shot (negate an Execution once per round) | 5 RAM | Null Pointer |
| +1 Core, permanent, unconditional (Hardware) | 4 to 5 Gb | Additional Core 5; the RAM Expansion clash above |
| +1 Core, conditional (attacking only, defending only) | 4 Gb | Packet Accelerator |
| +2 Health, permanent (Hardware) | 5 Gb (neutral in the sim; 4 would be fair) | RAM Expansion since v0.9 |
| Heal 3 damage (Ability) | 5 Gb | Restore Point |
| +2 Cores with a drawback | 6 Gb | Overclocked CPU |
| −1 Core to an enemy for one combat (Ability) | 3 Gb | Low Resolution |
| Reroll own dice (Ability) | 4 Gb | Bit Flip |
| Disable one enemy Hardware, one combat or one turn | 4 Gb ability, 5 Gb Program, 7 Gb Execution (destroy option) | Driver Fault, Memory Parasite, Sabotage |
| Disable one Program until next command | 5 Gb | Kill Process, Override |
| Draw 2 | 4 Gb | Ping Sweep |
| Copy a Program effect for one command | 7 Gb | Fork, Process Clone |
| Move an Anomaly out of turn | 4 to 5 Gb | Disconnect, Trace Route |
| Counter-style one-shot (negate an Execution once per round) | 5 Gb | Null Pointer |
| Extra slot or extra Program capacity | 4 (Hardware), 6 (Program) | Network Interface Upgrade, Compatibility Layer |
Anchors: a capture pays 4 RAM, a Lv 1 Firewall costs 2, a Lv 3 costs 8. Programs sit at 4 to 8
Anchors: a capture pays 4 Gb, a Lv 1 Firewall costs 2, a Lv 3 costs 8. Programs sit at 4 to 8
(avg 5.5), Hardware 4 to 9 (avg 5.75), Executions 4 to 7 (avg 5.1). Type averages for Programs
are all within 5.4 to 5.7, so no type is currently priced as premium. Keep it that way.
@ -144,7 +144,7 @@ fight, so a 2-Core swing is about 3.5 damage more or less, and dice tricks that
From 3,000 greedy-vs-greedy games with random legal decks (`node src/cli.ts -n 3000 --card-report`
in `sim/`). Win rate is for the player whose deck held the card, one standard error is about 1
point for Avatars and 0.8 for the rest. "Played" is how often the bot got the card into play, so a
point for Anomalies and 0.8 for the rest. "Played" is how often the bot got the card into play, so a
low number can mean a weak card or a bot that doesn't know how to use it.
### How games actually go
@ -157,8 +157,8 @@ low number can mean a weak card or a bot that doesn't know how to use it.
| Programs installed / lost | 7.5 / 5.2 |
| Hardware installed / lost in combat | 6.7 / 4.1 |
| Executions played | 2.2 |
| Ability uses / RAM on Abilities | 13.3 / 42 RAM |
| RAM from captures / from salvage | 142 / 32 |
| Ability uses / Bandwidth on Abilities | 13.3 / 42 Gb |
| Bandwidth from captures / from salvage | 142 / 32 |
| Firewalls placed / cleared | 10.7 / 9.1 |
Four things follow for the expansion:
@ -174,23 +174,23 @@ Four things follow for the expansion:
Pointer, Latency Spike, Firewall Appliance, False Positive and Desynchronization fired 0.0 to 0.03
times per game they were in play. Either new Executions need to be cheaper and more decisive so
they get played, or the expansion should stop adding anti-Execution cards. Both, ideally.
4. **Abilities are the main interaction.** Thirteen uses a game and 42 RAM spent. Avatar Ability
4. **Abilities are the main interaction.** Thirteen uses a game and 42 Gb spent. Anomaly Ability
design is the highest-leverage part of the batch.
### Cards that stand out
| Card | Win rate | Read |
| --------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| Broken Bits | 55.1% | Bit Flip at 4 RAM is the best card in the game. Rerolling losing dice on a 4-Core body wins fights. Consider 5 RAM or "reroll up to 2 dice". |
| RAM Expansion | 52.6% | +2 Cores for 5 RAM, fired 7.6 times a game. Confirms the price clash with Additional Core (50.6%). |
| Broken Bits | 55.1% | Bit Flip at 4 Gb is the best card in the game. Rerolling losing dice on a 4-Core body wins fights. Consider 5 Gb or "reroll up to 2 dice". |
| RAM Expansion | 52.6% | +2 Cores for 5 Gb, fired 7.6 times a game. Confirms the price clash with Additional Core (50.6%). |
| Overclocked CPU | 52.2% | +2 Cores in combat; the Program-disable drawback rarely matters because bots have few Programs. |
| Execute: Packet Flood | 52.2% | The most-played Execution (59%) and the strongest. Pinning Avatars is worth 5 RAM. |
| Execute: Packet Flood | 52.2% | The most-played Execution (59%) and the strongest. Pinning Anomalies is worth 5 Gb. |
| Data Leaker | 52.0% | Exfiltrate used 8 times a game. Cheap targeted discard adds up. |
| Backup Machine | 45.2% | Restore Point at 5 RAM, used 6 times a game, loses. Recovery is worth less than tempo here. Candidate for 3 RAM, or add a Core. |
| Pixelated Picture | 48.0% | −1 Core to the attacker for 3 RAM only while defending. Defensive-only Abilities underperform. |
| Backup Machine | 45.2% | Restore Point at 5 Gb, used 6 times a game, loses. Recovery is worth less than tempo here. Candidate for 3 Gb, or add a Core. |
| Pixelated Picture | 48.0% | −1 Core to the attacker for 3 Gb only while defending. Defensive-only Abilities underperform. |
| Corrupt Driver | 48.3% | Driver Fault only bites when the enemy wears Hardware in that fight. |
| Hardware Sandbox | 48.0% | Protects a Program that will likely be lost to capture anyway. |
| Garbage Collection | 48.2% | Sacrificing Programs for RAM is worse than salvaging from hand. |
| Garbage Collection | 48.2% | Sacrificing Programs for Bandwidth is worse than salvaging from hand. |
### Cards the bots can't use (no verdict yet)
@ -202,21 +202,21 @@ either bot logic or a human playtest before they're judged.
### Type scorecard
Averaging the typed cards: Bug Avatars 52.4%, Glitch 50.0%, Virus 49.2%, Patch 48.1%. Programs by
type are all within 48.7 to 49.8%. Patch is the weakest type today, on both Avatars and Programs
Averaging the typed cards: Bug Anomalies 52.4%, Glitch 50.0%, Virus 49.2%, Patch 48.1%. Programs by
type are all within 48.7 to 49.8%. Patch is the weakest type today, on both Anomalies and Programs
(Garbage Collection, Version Control, Compatibility Layer all under 49%). The expansion should give
Patch tempo, not just recovery.
## 6. Proposed Shape of the Expansion
Target: a player can build a deck where type matters from Avatar slot 1 to the last Program, and
Target: a player can build a deck where type matters from Anomaly slot 1 to the last Program, and
every type has a distinct way to win fights.
| Kind | Add | Result | Why |
| ---------- | ------------------------------ | ---------------------- | ---------------------------------------------------------- |
| Avatars | +8 (2 per type), +12 preferred | 4 to 5 per type | Mono-type lineups; each type gets a 2/4, 3/3 and 4/2 body |
| Anomalies | +8 (2 per type), +12 preferred | 4 to 5 per type | Mono-type lineups; each type gets a 2/4, 3/3 and 4/2 body |
| Programs | +17 (V 4, B 4, G 4, P 5) | V 11, B 12, G 11, P 11 | Evens the types; adds offense and Bug counters |
| Hardware | +8 (2 per type, text affinity) | 24 | Type payoffs on the Avatar side |
| Hardware | +8 (2 per type, text affinity) | 24 | Type payoffs on the Anomaly side |
| Executions | +8 (2 per type, text affinity) | 26 | Type payoffs at instant speed |
| Servers | +7 | 20 | An all-unique pile becomes possible; 4 of them type-themed |
| **Total** | **+48** | **131** | |
@ -225,98 +225,98 @@ every type has a distinct way to win fights.
**Virus: the Infection engine, on offense too.**
Design goals: more ways to place Infection when _you_ attack (today it's defensive), payoffs that
scale with counters, and RAM drain. Keep the −1 Core payoff unique to Code Zero; new payoffs should
scale with counters, and Bandwidth drain. Keep the −1 Core payoff unique to Code Zero; new payoffs should
do other things (deny abilities, deny Hardware, punish movement).
Sketches:
- Avatar, 4/2, _Ransomware_: ability pays you RAM equal to the target's Hardware count, or the
- Anomaly, 4/2, _Ransomware_: ability pays you Bandwidth equal to the target's Hardware count, or the
enemy loses one Hardware, their choice.
- Avatar, 2/4, _Botnet_: when an enemy Avatar with Infection is defeated anywhere, gain 2 RAM.
- Program (V), _Zero-Day_: when your Avatar attacks from this Server, place an Infection counter on
- Anomaly, 2/4, _Botnet_: when an enemy Anomaly with Infection is defeated anywhere, gain 2 Gb.
- Program (V), _Zero-Day_: when your Anomaly attacks from this Server, place an Infection counter on
the defender before the roll.
- Program (V), _Keylogger_: whenever an enemy Avatar with an Infection counter plays an Execution,
- Program (V), _Keylogger_: whenever an enemy Anomaly with an Infection counter plays an Execution,
look at their hand.
- Execution (affinity), _Execute: Quarantine_: target Avatar with Infection can't advance or attack
until its controller's next command; if a Virus Avatar you control is at the target Server, it
- Execution (affinity), _Execute: Quarantine_: target Anomaly with Infection can't advance or attack
until its controller's next command; if a Virus Anomaly you control is at the target Server, it
also loses 1 Core this combat.
- Hardware (affinity), _Payload Module_: when the wearer wins a roll, place an Infection counter on
every enemy Avatar adjacent to it. (Better under v0.9: winning a roll without a kill is the common
every enemy Anomaly adjacent to it. (Better under v0.9: winning a roll without a kill is the common
case.)
- Program (V), _Rootkit_: at the start of your first command each round, each enemy Avatar with an
- Program (V), _Rootkit_: at the start of your first command each round, each enemy Anomaly with an
Infection counter that is adjacent to this Server takes 1 damage. Damage over time gives Infection
a payoff that isn't another −1 Core.
**Bug: dice, not Cores.**
Design goals: give Bug counters a payoff that is _not_ Core loss, so they feel different from
Infection. Suggested rule to add to `rules.md`: an Avatar with Bug counters rerolls nothing, but for
Infection. Suggested rule to add to `rules.md`: an Anomaly with Bug counters rerolls nothing, but for
each Bug counter one of its dice showing 6 counts as 1 (or: its highest die is removed at 3+). Bug
cards then place counters and manipulate dice, and ECC Memory finally has a job.
Sketches:
- Avatar, 3/3, _Fuzzer_: ability places a Bug counter on each enemy Avatar in combat with it.
- Avatar, 4/2, _Off By One_: ability sets one of your dice to 6, or one enemy die to 1, after the
- Anomaly, 3/3, _Fuzzer_: ability places a Bug counter on each enemy Anomaly in combat with it.
- Anomaly, 4/2, _Off By One_: ability sets one of your dice to 6, or one enemy die to 1, after the
roll. (±1 on one die is one point of damage under v0.9, not a flipped fight.)
- Avatar, 2/4, _Heisenbug_: ability swaps which side is "attacker" for Program effects this combat.
- Program (B), _Segmentation Fault_: when an enemy Avatar with 2+ Bug counters attacks this Server,
- Anomaly, 2/4, _Heisenbug_: ability swaps which side is "attacker" for Program effects this combat.
- Program (B), _Segmentation Fault_: when an enemy Anomaly with 2+ Bug counters attacks this Server,
it rolls one die fewer.
- Program (B), _Unhandled Exception_: when a combat at this Server ends in a stalemate, place a Bug
counter on the attacker and gain 2 RAM; when an attacker here loses a roll by exactly 1, it takes
counter on the attacker and gain 2 Gb; when an attacker here loses a roll by exactly 1, it takes
1 more damage. (Ties no longer reroll under v0.9; stalemates are about 0.3 a game per player, so
the card needs the second trigger.)
- Execution (affinity), _Execute: Fuzz_: after the roll, reroll all dice showing 1 on one side; if
a Bug Avatar you control is in the combat, choose the side.
a Bug Anomaly you control is in the combat, choose the side.
- Hardware (affinity), _Watchdog Timer_: the wearer's first combat each round, a natural 1 counts
as 6 (once).
- Execution (affinity), _Execute: Segfault_: deal 2 damage to one Avatar at the target Server, 3 if
a Bug Avatar you control is in combat there; 4 RAM. A cheap finisher for wounded Avatars, and the
first Execution under 5 RAM that changes a fight directly.
- Execution (affinity), _Execute: Segfault_: deal 2 damage to one Anomaly at the target Server, 3 if
a Bug Anomaly you control is in combat there; 4 Gb. A cheap finisher for wounded Anomalies, and the
first Execution under 5 Gb that changes a fight directly.
**Glitch: reach and Firewalls.**
Design goals: own the adjacency rules. Move through or ignore Firewalls, act at range, see hidden
information (face-down Avatars, Server piles), and discount your own Firewalls.
information (face-down Anomalies, Server piles), and discount your own Firewalls.
Sketches:
- Avatar, 3/3, _Screen Tear_: ability lets it attack a location two lines away this command,
- Anomaly, 3/3, _Screen Tear_: ability lets it attack a location two lines away this command,
through no more than one Firewall.
- Avatar, 2/4, _Phantom Cursor_: ability looks at the top 2 Servers of the enemy pile and puts one
- Anomaly, 2/4, _Phantom Cursor_: ability looks at the top 2 Servers of the enemy pile and puts one
on the bottom.
- Avatar, 4/2, _Dead Pixel_: while it defends, the location counts as adjacent to nothing for enemy
- Anomaly, 4/2, _Dead Pixel_: while it defends, the location counts as adjacent to nothing for enemy
Executions (no Ghost Process reach in).
- Program (G), _Tunnel_: your Avatars may advance or attack along one Firewalled line touching
- Program (G), _Tunnel_: your Anomalies may advance or attack along one Firewalled line touching
this Server, ignoring the Firewall.
- Program (G), _Mirror Site_: this Server counts as adjacent to one non-adjacent location you
choose on install, for your Avatars only.
- Execution (affinity), _Execute: Port Scan_: look at both face-down Avatars of your opponent's
choice; draw a card if a Glitch Avatar you control is at the target Server.
choose on install, for your Anomalies only.
- Execution (affinity), _Execute: Port Scan_: look at both face-down Anomalies of your opponent's
choice; draw a card if a Glitch Anomaly you control is at the target Server.
- Hardware (affinity), _Spoofed MAC_: the wearer is treated as being on an adjacent location you
control when enemy Programs check "attacking this Server".
- Program (G), _Session Hijack_: whenever an enemy Avatar is recalled from a location adjacent to
- Program (G), _Session Hijack_: whenever an enemy Anomaly is recalled from a location adjacent to
this Server, draw a card. Recall is free today; Glitch should be the type that taxes it.
**Patch: protection, uptime and economy.**
Design goals: protect Hardware, keep Avatars from losing Hardware on defeat, refunds, and make
Design goals: protect Hardware, keep Anomalies from losing Hardware on defeat, refunds, and make
long games favor the Patch player. Patch should also get the only reliable "return a defeated
Avatar to the board this round" effect.
Anomaly to the board this round" effect.
Sketches:
- Avatar, 3/3, _Service Pack_: ability re-enables all your disabled Hardware and Programs at this
- Anomaly, 3/3, _Service Pack_: ability re-enables all your disabled Hardware and Programs at this
Server.
- Avatar, 4/2, _Long Term Support_: the first time each round it would take damage, it takes 2
- Anomaly, 4/2, _Long Term Support_: the first time each round it would take damage, it takes 2
less. (Keeping Hardware on defeat is what recall already does for free.)
- Avatar, 2/4, _Checksum_: ability names a card type; the next enemy Execution of that... (keep
- Anomaly, 2/4, _Checksum_: ability names a card type; the next enemy Execution of that... (keep
simple: the next enemy Execution targeting this Server costs 3 more).
- Program (P), _Uptime Monitor_: at the start of your first command each round, gain 1 RAM for
- Program (P), _Uptime Monitor_: at the start of your first command each round, gain 1 Gb for
each Patch Program you control (cap 3).
- Program (P), _Warm Standby_: when your defending Avatar here is defeated, you may place it back
- Program (P), _Warm Standby_: when your defending Anomaly here is defeated, you may place it back
on a location you control this command.
- Execution (affinity), _Execute: Snapshot_: until end of command, one Hardware on your Avatar at
- Execution (affinity), _Execute: Snapshot_: until end of command, one Hardware on your Anomaly at
the target Server is protected (Root Access's missing partner).
- Hardware (affinity), _Surge Protector_: the first Core penalty on the wearer each round is
ignored; if a Patch Avatar wears it, the second is too.
ignored; if a Patch Anomaly wears it, the second is too.
- Program (P), _Hot Patch_: at the start of your first command each round, remove 1 damage from
each Avatar you control at this Server (2 if it's a Patch Avatar). The healing lane Health opened.
- Execution (affinity), _Execute: Snapshot Restore_: remove 4 damage from one Avatar you control at
the target Server; 4 RAM.
each Anomaly you control at this Server (2 if it's a Patch Anomaly). The healing lane Health opened.
- Execution (affinity), _Execute: Snapshot Restore_: remove 4 damage from one Anomaly you control at
the target Server; 4 Gb.
**Servers (untyped but themed), +7.**
Four type-themed and three neutral. Themed ones reward a type without requiring it:
@ -325,24 +325,24 @@ Four type-themed and three neutral. Themed ones reward a type without requiring
- _Test Bench_: Bug Programs here also place a Bug counter on the attacker at combat start.
- _Proxy Node_: Executions you play targeting this Server may target an adjacent one instead.
- _Stable Release_: Patch Programs here can't be disabled.
- Neutral: _Cache Server_ (+2 RAM when you recapture), _Honeypot_ (attacker −1 Core for the first
combat here), _Load Balancer_ (your Avatar here may swap with another of yours once per round).
- Neutral: _Cache Server_ (+2 Gb when you recapture), _Honeypot_ (attacker −1 Core for the first
combat here), _Load Balancer_ (your Anomaly here may swap with another of yours once per round).
### Guardrails for the batch
- Every Avatar stays at Cores + Slots = 6-9, unless the outlier is the point of the card.
- Every Anomaly stays at Cores + Slots = 6-9, unless the outlier is the point of the card.
- Programs cost 4 to 6 and do something when installed, when breached, or when they leave play.
No 7 or 8 RAM Programs unless they return to hand.
No 7 or 8 Gb Programs unless they return to hand.
- New Executions cost 3 to 5 and change a fight or a capture directly. No more cards that only
answer Executions until Executions are played more than twice a game.
- New Hardware favors triggers and utility over flat Cores. The pool already has four Core sticks.
- No new card gives more than +2 Cores in a single combat without a real drawback.
- Each type gets at least one card that places its counter (Infection or Bug) on **offense**.
- Triggers key off "takes damage" or "loses a roll", not "is destroyed". Under v0.9 an Avatar is
- Triggers key off "takes damage" or "loses a roll", not "is destroyed". Under v0.9 an Anomaly is
destroyed about 7 times a player a game and most of those are one-shots, so a destroy trigger
fires almost never (section 8).
- Health-based effects: 3 damage healed or dealt is about one lost roll's worth; +2 Health is worth
about 4 RAM. No card heals more than 4 in one go.
about 4 Gb. No card heals more than 4 in one go.
- Every new Program should be answerable by an existing Execution (Kill Process, Override,
Rollback), and every new Hardware by Sabotage or Driver Fault.
- Text uses the v0.8 vocabulary: _command_, _round_, _breach_, _this Server_, _at this Server_.
@ -353,7 +353,7 @@ Four type-themed and three neutral. Themed ones reward a type without requiring
1. Type chip on Hardware and Execution templates, or text affinity only? Text affinity only
2. Bug counter rule: "6s count as 1" per counter, or "lose highest die at 3+"? lose highest die
3. Avatar count: +8 or +12? Art is the constraint. +12
3. Anomaly count: +8 or +12? Art is the constraint. +12
4. Fix RAM Expansion vs Additional Core by price, or by changing one card's effect? price → done
by effect instead (RAM Expansion = +2 Health), since that also gave Health its first Hardware.
@ -373,14 +373,14 @@ their answers are barely played, Abilities are the main interaction.
| Card | v0.9 | Health off | Read |
| --- | --- | --- | --- |
| Carbon NanoBots | 55.4% | 49.3% | Replicate bought a second 12-Health body for 5 RAM, and damage spread over two bodies rarely destroyed either. |
| Carbon NanoBots | 55.4% | 49.3% | Replicate bought a second 12-Health body for 5 Gb, and damage spread over two bodies rarely destroyed either. |
| Broken Bits | 53.1% | 54.1% | Bit Flip softened as intended: rerolls shift damage instead of flipping the fight. |
| Overclocked CPU | 52.5% | 53.4% | +2 Cores is also +2 dice of damage. The Program-disable drawback almost never bites. |
| RAM Expansion | 52.4% | 52.6% | Still dominated Additional Core (50.0%). |
| Backup Machine | 44.0% | 46.6% | Hardware is lost less often (3.4 vs 4.1 a game), so Restore Point had fewer targets. |
| Beta Version 1.0 | 47.6% | 49.4% | Health 9 makes it a glass cannon and the bot still never uses Push Update. Needs a human read. |
**Destroy triggers went nearly dead.** Avatars are destroyed 6.7 times per player per game, half the
**Destroy triggers went nearly dead.** Anomalies are destroyed 6.7 times per player per game, half the
old rate, and most are one-shots. Fires per game in play, v0.9 vs Health off: Resource Leech
0.03 / 0.05, Overflow Error 0.03 / 0.05, Persistent Infection 0.03 / 0.04, RAID Array 0.27 / 0.76,
Redundant Power Supply 0.67 / 0.72. Redundant Power Supply and RAID Array are also undercut by
@ -391,11 +391,11 @@ recall, which keeps Hardware for free.
| Change | Result |
| --- | --- |
| NanoBots Health 12 → 10 | 53.9% |
| NanoBots Health 10 and Replicate 6 RAM | 51.8% ← adopted |
| Restore Point 5 → 3 RAM | 45.3% |
| NanoBots Health 10 and Replicate 6 Gb | 51.8% ← adopted |
| Restore Point 5 → 3 Gb | 45.3% |
| Backup Machine Health 14 | 46.4% |
| Bit Flip 4 → 5 RAM | 52.4% (left at 4) |
| Additional Core 5 → 4 RAM | 50.2% (left at 5) |
| Bit Flip 4 → 5 Gb | 52.4% (left at 4) |
| Additional Core 5 → 4 Gb | 50.2% (left at 5) |
| RAM Expansion as +2 Health instead of +2 Cores | 49.2% ← adopted |
Backup Machine could not be fixed by price or Health; its ability was the wrong shape for the
@ -403,14 +403,13 @@ ruleset, so Restore Point gained the heal option instead.
### Changes made
1. **Carbon NanoBots:** Health 10, Replicate 6 RAM.
2. **Backup Machine:** "Remove 3 damage from this Avatar, or return one Hardware or Program from
1. **Carbon NanoBots:** Health 10, Replicate 6 Gb.
2. **Backup Machine:** "Remove 3 damage from this Anomaly, or return one Hardware or Program from
your discard pile to your hand..."
3. **RAM Expansion:** "Avatar gains +2 Health."
4. **Resource Leech:** "Whenever an enemy Avatar takes damage while attacking this Server, gain 3
RAM." **Overflow Error:** "When an enemy Avatar takes damage while attacking this Server, disable
one Program its controller has in play until their next command. If the Avatar was destroyed, you
may destroy that Program instead." **Persistent Infection:** "Whenever an enemy Avatar takes
3. **RAM Expansion:** "Anomaly gains +2 Health."
4. **Resource Leech:** "Whenever an enemy Anomaly takes damage while attacking this Server, gain 3 Gb." **Overflow Error:** "When an enemy Anomaly takes damage while attacking this Server, disable
one Program its controller has in play until their next command. If the Anomaly was destroyed, you
may destroy that Program instead." **Persistent Infection:** "Whenever an enemy Anomaly takes
damage at this Server, place an Infection counter on it permanently."
5. The sketches for Unhandled Exception, Off By One and Long Term Support were rewritten (section
6), and one healing and one direct-damage card were added per lane: Hot Patch and Snapshot
@ -430,12 +429,12 @@ to 0.1%, first player 51.3%, 27.5 combats a game, 30% of enemy captures won in c
| Card | Before | After | Note |
| --- | --- | --- | --- |
| Carbon NanoBots | 55.4% | 54.5% | Health 10 and Replicate 6 barely moved it. The strength is the copy itself: a second body with its own Health. Tested Health 8: 52.9%; Replicate 7: 53.4%. A real fix is a rules reading: the copy shares the original's damage, or has half its Health. |
| Backup Machine | 44.0% | 44.8% | The heal is legal and the bot uses it at 3+ damage, but Restore Point is still used 4.6 times a game for little. Earlier tests: Restore Point 3 RAM +1.3, Health 14 +2.4. Needs a human playtest before another number changes. |
| Backup Machine | 44.0% | 44.8% | The heal is legal and the bot uses it at 3+ damage, but Restore Point is still used 4.6 times a game for little. Earlier tests: Restore Point 3 Gb +1.3, Health 14 +2.4. Needs a human playtest before another number changes. |
| RAM Expansion | 52.4% | 49.5% | Neutral as +2 Health, and Additional Core (50.7%) is a real card again. |
| Resource Leech | 48.5% | 49.5% | Fires 0.17 a game in play, five times the old rate. |
| Overflow Error | 48.8% | 49.4% | Fires 0.16 a game in play. |
| Persistent Infection | 49.7% | 50.0% | Fires 0.12 a game in play; the bot installs it in only 6% of games. |
| Broken Bits | 53.1% | 55.0% | Up 2 points, most likely from the bot's new long shots: reroll control is worth more when you attack at worse odds. Now the top card. Bit Flip at 5 RAM was worth −0.7 before; worth retesting. |
| Broken Bits | 53.1% | 55.0% | Up 2 points, most likely from the bot's new long shots: reroll control is worth more when you attack at worse odds. Now the top card. Bit Flip at 5 Gb was worth −0.7 before; worth retesting. |
The cards that were the point of this pass, the destroy triggers and the RAM Expansion clash, are
fixed. NanoBots and Backup Machine are structural and need a reading or a redesign rather than a
@ -446,21 +445,21 @@ number.
_2026-09-29. 52 cards, tagged `Set` = 2 in `decks/files-deck-1/cards.csv` (the base game is
`Set` = 1). Card text lives in the CSV; this is the index. None has a simulator script yet, so
`loadCards()` skips set 2 unless asked, and the card report can't judge them until `sim/src/cards/`
gains their scripts and `test/` their tests. Avatar art doesn't exist: the Image column holds slugs._
gains their scripts and `test/` their tests. Anomaly art doesn't exist: the Image column holds slugs._
Rule added for the batch (rules.md → Terms): an Avatar with 3+ Bug counters removes its highest die
Rule added for the batch (rules.md → Terms): an Anomaly with 3+ Bug counters removes its highest die
after every roll.
| Kind | Virus | Bug | Glitch | Patch | Neutral |
| --- | --- | --- | --- | --- | --- |
| Avatars (Cores/Slots, Ability RAM) | Ransomware 4/2 (4), Botnet 2/4 (3), Trojan Horse 3/3 (4) | Fuzzer 3/3 (3), Off By One 4/2 (4), Heisenbug 2/4 (3) | Screen Tear 3/3 (4), Phantom Cursor 2/4 (3), Dead Pixel 4/2 (3) | Service Pack 3/3 (4), Long Term Support 4/2 (3), Checksum 2/4 (4) | |
| Programs (RAM) | Zero-Day 5, Keylogger 5, Rootkit 6, Drive-By Download 4 | Segmentation Fault 5, Unhandled Exception 4, Heap Corruption 5, Bit Rot 5 | Tunnel 5, Mirror Site 6, Session Hijack 4, Packet Sniffer 4 | Uptime Monitor 5, Warm Standby 5, Hot Patch 5, Failover 4, Sandbox Mode 5 | |
| Hardware (RAM, text affinity) | Payload Module 5, Exploit Kit 5 | Watchdog Timer 5, Bug Injector 4 | Spoofed MAC 5, Proxy Relay 4 | Surge Protector 5, Heat Sink 6 | |
| Executions (RAM, text affinity) | Quarantine 4, Data Siphon 4 | Fuzz 4, Segfault 4 | Port Scan 3, Lag Spike 4 | Snapshot 4, Snapshot Restore 4 | |
| Anomalies (Cores/Slots, Ability Bandwidth) | Ransomware 4/2 (4), Botnet 2/4 (3), Trojan Horse 3/3 (4) | Fuzzer 3/3 (3), Off By One 4/2 (4), Heisenbug 2/4 (3) | Screen Tear 3/3 (4), Phantom Cursor 2/4 (3), Dead Pixel 4/2 (3) | Service Pack 3/3 (4), Long Term Support 4/2 (3), Checksum 2/4 (4) | |
| Programs (Bandwidth) | Zero-Day 5, Keylogger 5, Rootkit 6, Drive-By Download 4 | Segmentation Fault 5, Unhandled Exception 4, Heap Corruption 5, Bit Rot 5 | Tunnel 5, Mirror Site 6, Session Hijack 4, Packet Sniffer 4 | Uptime Monitor 5, Warm Standby 5, Hot Patch 5, Failover 4, Sandbox Mode 5 | |
| Hardware (Bandwidth, text affinity) | Payload Module 5, Exploit Kit 5 | Watchdog Timer 5, Bug Injector 4 | Spoofed MAC 5, Proxy Relay 4 | Surge Protector 5, Heat Sink 6 | |
| Executions (Bandwidth, text affinity) | Quarantine 4, Data Siphon 4 | Fuzz 4, Segfault 4 | Port Scan 3, Lag Spike 4 | Snapshot 4, Snapshot Restore 4 | |
| Servers | Quarantine Host | Test Bench | Proxy Node | Stable Release | Cache Server, Honeypot, Load Balancer |
Totals with set 1: Avatars 20 (5 per type), Programs 45 (V 11, B 12, G 11, P 11), Hardware 24,
Executions 26, Servers 20. Every Avatar keeps Cores + Slots = 6 and the v0.9 Health line (4-Core 9,
Totals with set 1: Anomalies 20 (5 per type), Programs 45 (V 11, B 12, G 11, P 11), Hardware 24,
Executions 26, Servers 20. Every Anomaly keeps Cores + Slots = 6 and the v0.9 Health line (4-Core 9,
3-Core 10, 2-Core 12). Every Program costs 4 to 6 and either triggers when attacked, when breached,
or at the start of your round; every Execution costs 3 to 4. Each type has an offensive counter
placer (Zero-Day, Heap Corruption, Bug Injector, Payload Module) and a Health-lane card (Rootkit
@ -468,9 +467,9 @@ and Trojan Horse deal damage; Hot Patch, Snapshot Restore, Service Pack heal; He
Differences from the section 6 sketches: Heisenbug prevents damage instead of swapping combat
roles; Dead Pixel's blackout is an Ability with a duration rather than a passive; Checksum moves
Hardware between your Avatars instead of taxing Executions; Payload Module fires on a won roll.
Botnet's RAM trigger is "takes damage", not "is defeated". Names still open to change.
Hardware between your Anomalies instead of taxing Executions; Payload Module fires on a won roll.
Botnet's Bandwidth trigger is "takes damage", not "is defeated". Names still open to change.
Next steps: scripts and one test per card in `sim/`, then a `--set all` card report; art for the
twelve Avatars; a Type chip is still not needed on Hardware and Executions (text affinity only).
twelve Anomalies; a Type chip is still not needed on Hardware and Executions (text affinity only).

View file

@ -2,7 +2,7 @@
*Draft 1, 2026-09-28. Follows `expansion-plan.md`. Nothing here is in `cards.csv` yet.*
48 new cards: 12 Avatars, 17 Programs, 8 Hardware, 8 Executions, 7 Servers. Each entry has the
48 new cards: 12 Anomalies, 17 Programs, 8 Hardware, 8 Executions, 7 Servers. Each entry has the
card text as it would print, then a one-line design note in italics. Text uses the v0.8 vocabulary
(command, round, breach, this Server).
@ -12,76 +12,76 @@ These are the four open decisions from the plan, resolved as recommended. Any of
flipped; the affected cards are marked.
1. **Hardware and Executions stay untyped on the card.** Type affinity is in the text ("If a Virus
Avatar you control..."). No template changes needed.
Anomaly you control..."). No template changes needed.
2. **Bug counter rule** (new text for `rules.md` → Card Rules → Terms):
> **Bug counters** come off when the Avatar is defeated. After an Avatar with Bug counters
> **Bug counters** come off when the Anomaly is defeated. After an Anomaly with Bug counters
> rolls, for each Bug counter on it, one of its dice showing 6 counts as 1 instead.
Infection makes you roll fewer dice; Bugs make your good dice go bad. Big rollers suffer most,
which is a natural brake on Core stacking. ECC Memory finally does something.
3. **12 Avatars**, three per type, one on each body (2/4, 3/3, 4/2). Cut to 8 by dropping one per
3. **12 Anomalies**, three per type, one on each body (2/4, 3/3, 4/2). Cut to 8 by dropping one per
type if art is the constraint; the 2/4 bodies are the easiest cuts.
4. **Additional Core goes to 4 RAM.** See "Changes to Existing Cards" at the end.
4. **Additional Core goes to 4 Gb.** See "Changes to Existing Cards" at the end.
---
## Avatars (12)
## Anomalies (12)
Cores/Slots always sum to 6. Ability costs 3 to 5, once per round, Execution timing, only in play.
### Virus
**Ransomware** (V) · 4 Cores / 2 Slots
Ability **Encrypt** · 4 RAM
> Choose an enemy Avatar in combat with this Avatar. Its controller chooses: pay you 3 RAM, or one
Ability **Encrypt** · 4 Gb
> Choose an enemy Anomaly in combat with this Anomaly. Its controller chooses: pay you 3 Gb, or one
> Hardware on it (your choice) is disabled until the end of your next command.
*A 4-Core body with a Driver Fault that the victim can buy off. Either outcome is worth the 4.*
**Rootkit** (V) · 3 Cores / 3 Slots
Ability **Privilege Escalation** · 3 RAM
> During a combat this Avatar is in, enemy Avatars in that combat that have an Infection counter
Ability **Privilege Escalation** · 3 Gb
> During a combat this Anomaly is in, enemy Anomalies in that combat that have an Infection counter
> can't use Abilities or Hardware abilities this combat.
*An Infection payoff that isn't Core loss. Shuts off Bit Flip, Hot-Swap Bay and friends.*
**Botnet** (V) · 2 Cores / 4 Slots
Ability **Recruit Node** · 3 RAM
> Place an Infection counter on one enemy Avatar at a location adjacent to this Avatar's location.
> If it already had an Infection counter, gain 2 RAM.
Ability **Recruit Node** · 3 Gb
> Place an Infection counter on one enemy Anomaly at a location adjacent to this Anomaly's location.
> If it already had an Infection counter, gain 2 Gb.
*Infection outside combat, on offense. The 2-Core body wants Hardware, hence 4 slots.*
### Bug
**Off By One** (B) · 4 Cores / 2 Slots
Ability **Increment** · 3 RAM
> After the roll in a combat this Avatar is in, change one of its dice by 1, up or down.
Ability **Increment** · 3 Gb
> After the roll in a combat this Anomaly is in, change one of its dice by 1, up or down.
*A guaranteed +1 to the total, or a tiebreaker. Weaker than Bit Flip on purpose.*
**Fuzzer** (B) · 3 Cores / 3 Slots
Ability **Fuzz Input** · 3 RAM
> Place a Bug counter on each enemy Avatar in combat with this Avatar.
Ability **Fuzz Input** · 3 Gb
> Place a Bug counter on each enemy Anomaly in combat with this Anomaly.
*The Bug type's Patient Zero. Cheaper because the counter rule is the only payoff built in.*
**Heisenbug** (B) · 2 Cores / 4 Slots
Ability **Observer Effect** · 5 RAM
> After the roll in a combat this Avatar is in, swap one of its dice with one die of an enemy
> Avatar in that combat.
Ability **Observer Effect** · 5 Gb
> After the roll in a combat this Anomaly is in, swap one of its dice with one die of an enemy
> Anomaly in that combat.
*Up to a 10-point swing, so it costs 5 and sits on the weakest body. Watch this one in the sim.*
### Glitch
**Dead Pixel** (G) · 4 Cores / 2 Slots
Ability **Clip Through** · 4 RAM
> This command, this Avatar may advance or attack along one Firewalled line, ignoring the
Ability **Clip Through** · 4 Gb
> This command, this Anomaly may advance or attack along one Firewalled line, ignoring the
> Firewall.
*The first card that beats a Firewall without paying to clear it. A Lv 3 costs 8 to clear.*
**Screen Tear** (G) · 3 Cores / 3 Slots
Ability **Tear** · 3 RAM
> This command, this Avatar may attack a defended enemy location adjacent to any location you
Ability **Tear** · 3 Gb
> This command, this Anomaly may attack a defended enemy location adjacent to any location you
> control, instead of one adjacent to its own.
*Attacks get the reach that advances already have. Reach is Glitch's whole lane.*
**Phantom Cursor** (G) · 2 Cores / 4 Slots
Ability **Ghost Input** · 3 RAM
Ability **Ghost Input** · 3 Gb
> Look at the top 2 cards of your opponent's Server pile and put one on the bottom. Then look at
> the top card of your deck; you may put it on the bottom.
*Denies them Cloud Compute, smooths your draw. Information for 3.*
@ -89,22 +89,22 @@ Ability **Ghost Input** · 3 RAM
### Patch
**Long Term Support** (P) · 4 Cores / 2 Slots
Ability **Extended Support** · 4 RAM
> During a combat an Avatar you control is in, if it loses, it keeps its Hardware.
Ability **Extended Support** · 4 Gb
> During a combat an Anomaly you control is in, if it loses, it keeps its Hardware.
*Hardware loss is the real cost of losing a fight. This is Redundant Power Supply on demand, for any
of your Avatars.*
of your Anomalies.*
**Service Pack** (P) · 3 Cores / 3 Slots
Ability **Apply Patch** · 3 RAM
> Re-enable every disabled Hardware on Avatars you control and every disabled Program at this
> Server. Gain 1 RAM for each card re-enabled.
*Recovery that pays. Turns Driver Fault and Kill Process into RAM.*
Ability **Apply Patch** · 3 Gb
> Re-enable every disabled Hardware on Anomalies you control and every disabled Program at this
> Server. Gain 1 Gb for each card re-enabled.
*Recovery that pays. Turns Driver Fault and Kill Process into Bandwidth.*
**Checksum** (P) · 2 Cores / 4 Slots
Ability **Verify** · 3 RAM
> After the roll in a combat an Avatar you control is in, reroll one of its dice. If the new result
Ability **Verify** · 3 Gb
> After the roll in a combat an Anomaly you control is in, reroll one of its dice. If the new result
> is lower, keep the original.
*One safe reroll for any Avatar you control. Protects the roll rather than warping it.*
*One safe reroll for any Anomaly you control. Protects the roll rather than warping it.*
---
@ -115,43 +115,43 @@ sim shows 70% of Programs are lost to capture.
### Virus (4)
**Zero-Day** (V) · 5 RAM
> When an Avatar you control attacks from this Server, place an Infection counter on each defending
> Avatar before the roll.
**Zero-Day** (V) · 5 Gb
> When an Anomaly you control attacks from this Server, place an Infection counter on each defending
> Anomaly before the roll.
*Infection on offense. With Code Zero in play that's −1 Core on every defender you hit.*
**Keylogger** (V) · 4 RAM
> Whenever an enemy Avatar attacks or breaches this Server, gain 1 RAM for each Infection counter on
**Keylogger** (V) · 4 Gb
> Whenever an enemy Anomaly attacks or breaches this Server, gain 1 Gb for each Infection counter on
> it (up to 3).
*Pays out even when you lose the location. Rewards stacking counters.*
**Trojan Horse** (V) · 5 RAM
> When this Server is breached, place 2 Infection counters on the breaching Avatar and return this
**Trojan Horse** (V) · 5 Gb
> When this Server is breached, place 2 Infection counters on the breaching Anomaly and return this
> Program to your hand instead of discarding it.
*A Program that wants to be captured. Comes back every time.*
**Malware Spread** (V) · 5 RAM
> At the start of your first command each round, place an Infection counter on one enemy Avatar at
**Malware Spread** (V) · 5 Gb
> At the start of your first command each round, place an Infection counter on one enemy Anomaly at
> a location adjacent to this Server.
*A slow, steady placer. Forces the enemy to rotate Avatars or eat penalties.*
*A slow, steady placer. Forces the enemy to rotate Anomalies or eat penalties.*
### Bug (4)
**Segmentation Fault** (B) · 5 RAM
> When an enemy Avatar attacks this Server, place a Bug counter on it. If it loses that combat, its
**Segmentation Fault** (B) · 5 Gb
> When an enemy Anomaly attacks this Server, place a Bug counter on it. If it loses that combat, its
> controller discards a card at random.
*Placer plus punishment. Pairs with Fuzzer.*
**Core Dump** (B) · 4 RAM
> When this Server is breached, place 2 Bug counters on the breaching Avatar and draw a card.
**Core Dump** (B) · 4 Gb
> When this Server is breached, place 2 Bug counters on the breaching Anomaly and draw a card.
*The Bug version of Trojan Horse: a card instead of a return to hand.*
**Busy Wait** (B) · 5 RAM
> Enemy Avatars with a Bug counter can't advance into this Server. They must attack it, or can't
**Busy Wait** (B) · 5 Gb
> Enemy Anomalies with a Bug counter can't advance into this Server. They must attack it, or can't
> take it while it's undefended.
*Turns an undefended location into a wall against bugged Avatars. Conditional, so 5.*
*Turns an undefended location into a wall against bugged Anomalies. Conditional, so 5.*
**Integer Overflow** (B) · 5 RAM
**Integer Overflow** (B) · 5 Gb
> During a combat at this Server, a dice total of 20 or more counts as 0 before the totals are
> compared.
*The anti-Core-stack card. Cloud Compute plus two Core Hardware has to think twice. If both sides
@ -159,51 +159,51 @@ overflow it's a tie and they reroll.*
### Glitch (4)
**Tunnel** (G) · 5 RAM
> Your Avatars may advance or attack along Firewalled lines touching this Server, ignoring the
**Tunnel** (G) · 5 Gb
> Your Anomalies may advance or attack along Firewalled lines touching this Server, ignoring the
> Firewall.
*Permanent Clip Through for one location. Makes Firewalls a Glitch player's asset.*
**Mirror Site** (G) · 6 RAM
> When you install this, choose a location that isn't adjacent to this Server. For your Avatars, this
**Mirror Site** (G) · 6 Gb
> When you install this, choose a location that isn't adjacent to this Server. For your Anomalies, this
> Server and that location count as adjacent.
*Builds a private road across the board. 6 because it opens attacks the enemy can't see coming.*
**Cache Poisoning** (G) · 4 RAM
**Cache Poisoning** (G) · 4 Gb
> When this Server is breached, look at the breaching player's hand and choose a card. They put it
> on the bottom of their deck.
*Breach payoff with information. Bottoming beats discarding here because discarding pays them
nothing anyway and this also denies the salvage.*
**Packet Sniffer** (G) · 4 RAM
**Packet Sniffer** (G) · 4 Gb
> While you control this Server, your opponent plays with their hand revealed.
*Cheap, simple, and the strongest information effect in the game. Lost when the location flips.*
### Patch (5)
**Uptime Monitor** (P) · 5 RAM
> At the start of your first command each round, gain 1 RAM for each Patch Program you control (up
**Uptime Monitor** (P) · 5 Gb
> At the start of your first command each round, gain 1 Gb for each Patch Program you control (up
> to 3).
*Economy for the Patch deck. Pays for itself in two or three rounds.*
**Warm Standby** (P) · 5 RAM
> When an Avatar you control defending this Server is defeated, you may place it on a location you
**Warm Standby** (P) · 5 Gb
> When an Anomaly you control defending this Server is defeated, you may place it on a location you
> control right away, and it keeps its Hardware.
*Fires once, then it's discarded with the captured location, but that one fire saves a fight's worth
of Hardware and a round of tempo.*
**Rolling Deploy** (P) · 4 RAM
**Rolling Deploy** (P) · 4 Gb
> Once per round, move one Program from this Server to another location you control, respecting
> Program limits.
*Program mobility. The direct answer to Programs dying on captured locations.*
**Hardening** (P) · 5 RAM
> Hardware on Avatars you control at this Server is protected and can't be disabled by enemy
**Hardening** (P) · 5 Gb
> Hardware on Anomalies you control at this Server is protected and can't be disabled by enemy
> effects.
*The protected Hardware that Root Access already refers to.*
**Graceful Degradation** (P) · 4 RAM
> When this Server is breached, gain 3 RAM and draw a card.
**Graceful Degradation** (P) · 4 Gb
> When this Server is breached, gain 3 Gb and draw a card.
*Insurance. The location was going to fall; now that costs the enemy something.*
---
@ -212,45 +212,45 @@ of Hardware and a round of tempo.*
Untyped on the card. Type affinity in text (assumption 1).
**Payload Module** (Virus) · 5 RAM
> When the wearer wins a combat, place an Infection counter on each enemy Avatar at a location
**Payload Module** (Virus) · 5 Gb
> When the wearer wins a combat, place an Infection counter on each enemy Anomaly at a location
> adjacent to the wearer.
*Winning spreads the disease. Strong on a 4-Core Avatar, so 5.*
*Winning spreads the disease. Strong on a 4-Core Anomaly, so 5.*
**Leech Cable** (Virus) · 4 RAM
> Whenever an enemy Avatar with an Infection counter is defeated in a combat with the wearer, gain
> 3 RAM. If the wearer is a Virus Avatar, also draw a card.
*Resource Leech on an Avatar, gated on Infection.*
**Leech Cable** (Virus) · 4 Gb
> Whenever an enemy Anomaly with an Infection counter is defeated in a combat with the wearer, gain
> 3 Gb. If the wearer is a Virus Anomaly, also draw a card.
*Resource Leech on an Anomaly, gated on Infection.*
**Watchdog Timer** (Bug) · 5 RAM
**Watchdog Timer** (Bug) · 5 Gb
> Once per round, in a combat the wearer is in, one of its dice showing 1 counts as 6.
*About +2 on average, with a jackpot feel. Cooling System can double it.*
**Fault Injector** (Bug) · 4 RAM
> When the wearer attacks, place a Bug counter on each defending Avatar. If the wearer is a Bug
> Avatar, place two.
*Offensive Bug placer. Once per round in practice, since each Avatar attacks once per round.*
**Fault Injector** (Bug) · 4 Gb
> When the wearer attacks, place a Bug counter on each defending Anomaly. If the wearer is a Bug
> Anomaly, place two.
*Offensive Bug placer. Once per round in practice, since each Anomaly attacks once per round.*
**Range Extender** (Glitch) · 5 RAM
**Range Extender** (Glitch) · 5 Gb
> Once per round, the wearer may attack a defended enemy location adjacent to any location you
> control.
*Screen Tear's Tear as a permanent install, for anyone.*
**Sniffer Dongle** (Glitch) · 5 RAM
**Sniffer Dongle** (Glitch) · 5 Gb
> When the wearer attacks, look at the defending player's hand before the roll. If the wearer is a
> Glitch Avatar, they discard one card of your choice that costs 4 RAM or less.
> Glitch Anomaly, they discard one card of your choice that costs 4 Gb or less.
*Information every attack; disruption if you're on-type. The cost cap keeps it off their bombs.*
**Surge Protector** (Patch) · 4 RAM
**Surge Protector** (Patch) · 4 Gb
> The first Core penalty applied to the wearer each round is ignored. If the wearer is a Patch
> Avatar, so is the second.
> Anomaly, so is the second.
*Answers Low Resolution, Visual Artifact and Code Zero. Cheap because it does nothing against raw
Cores.*
**Recovery Partition** (Patch) · 5 RAM
**Recovery Partition** (Patch) · 5 Gb
> When the wearer is defeated, return all its other Hardware to your hand instead of discarding it.
> Then discard this.
*Hardware comes back as cards, not as RAM. Pairs with Backup Machine and Warm Standby.*
*Hardware comes back as cards, not as Bandwidth. Pairs with Backup Machine and Warm Standby.*
---
@ -259,49 +259,49 @@ Cores.*
All cost 3 to 5 and change a fight or a capture directly. Untyped on the card, type affinity in
text. "Target Server" as in the existing set.
**Execute: Quarantine** (Virus) · 4 RAM
> Choose an enemy Avatar with an Infection counter at or attacking the target Server. It can't
> advance or attack until its controller's next command. If a Virus Avatar you control is at the
**Execute: Quarantine** (Virus) · 4 Gb
> Choose an enemy Anomaly with an Infection counter at or attacking the target Server. It can't
> advance or attack until its controller's next command. If a Virus Anomaly you control is at the
> target Server, it also has −1 Core this combat.
*A conditional Packet Flood, the sim's best Execution, with a combat kicker on-type.*
**Execute: Outbreak** (Virus) · 3 RAM
> Place an Infection counter on every enemy Avatar at a location adjacent to the target Server, and
> on any enemy Avatar attacking it.
**Execute: Outbreak** (Virus) · 3 Gb
> Place an Infection counter on every enemy Anomaly at a location adjacent to the target Server, and
> on any enemy Anomaly attacking it.
*Wide, cheap placer. With Code Zero out it's −1 Core to the whole front line.*
**Execute: Fuzz** (Bug) · 4 RAM
**Execute: Fuzz** (Bug) · 4 Gb
> During a combat at the target Server, after the roll, reroll every die showing 1 on one side of
> your choice. If a Bug Avatar you control is in the combat, also place a Bug counter on each enemy
> Avatar there.
> your choice. If a Bug Anomaly you control is in the combat, also place a Bug counter on each enemy
> Anomaly there.
*Fix your 1s or force them to reroll a lucky nothing. Bit Flip for anyone, one-shot.*
**Execute: Crash** (Bug) · 4 RAM
> During a combat at the target Server, after the roll, choose an enemy Avatar there with a Bug
**Execute: Crash** (Bug) · 4 Gb
> During a combat at the target Server, after the roll, choose an enemy Anomaly there with a Bug
> counter. Its highest die counts as 1.
*The Bug finisher. Needs setup, so it's a swing of up to 5 for 4 RAM.*
*The Bug finisher. Needs setup, so it's a swing of up to 5 for 4 Gb.*
**Execute: Port Scan** (Glitch) · 3 RAM
> Look at your opponent's hand and their face-down Avatars, then draw a card. If a Glitch Avatar
**Execute: Port Scan** (Glitch) · 3 Gb
> Look at your opponent's hand and their face-down Anomalies, then draw a card. If a Glitch Anomaly
> you control is at the target Server, put one card from their hand on the bottom of their deck.
*Ping Sweep with eyes. Seeing their locked Avatars tells you which row to deny.*
*Ping Sweep with eyes. Seeing their locked Anomalies tells you which row to deny.*
**Execute: Backdoor** (Glitch) · 4 RAM
> Remove one Firewall from a line touching the target Server. If a Glitch Avatar you control is at
**Execute: Backdoor** (Glitch) · 4 Gb
> Remove one Firewall from a line touching the target Server. If a Glitch Anomaly you control is at
> the target Server, you may instead move that Firewall to another empty gateway on a line touching
> that Server.
*Clears a Lv 3 Firewall for 4 instead of 8, or turns the enemy's wall into yours.*
**Execute: Snapshot** (Patch) · 3 RAM
> Until the end of this command, Hardware on Avatars you control at or attacking the target Server
> is protected and can't be disabled or destroyed. If a Patch Avatar you control is there, draw a
**Execute: Snapshot** (Patch) · 3 Gb
> Until the end of this command, Hardware on Anomalies you control at or attacking the target Server
> is protected and can't be disabled or destroyed. If a Patch Anomaly you control is there, draw a
> card.
*The answer to Sabotage, Driver Fault and Memory Parasite, at a price you'll actually pay.*
**Execute: Hot Patch** (Patch) · 4 RAM
> Install one Hardware from your hand on an Avatar you control at or attacking the target Server,
> paying 2 less RAM for it. If a combat is going on there, it works in that combat.
*Hardware at instant speed. Two RAM more than installing normally, for surprise.*
**Execute: Hot Patch** (Patch) · 4 Gb
> Install one Hardware from your hand on an Anomaly you control at or attacking the target Server,
> paying 2 less Gb for it. If a combat is going on there, it works in that combat.
*Hardware at instant speed. Two Bandwidth more than installing normally, for surprise.*
---
@ -311,23 +311,23 @@ Untyped like the existing 13. Four are themed to reward a type without requiring
neutral. Brings the pool to 20 so a Server pile can be all distinct.
**Quarantine Host**
> Virus Programs installed here cost 2 less RAM.
> Virus Programs installed here cost 2 less Gb.
*Upgraded Hardware, for Virus Programs.*
**Test Bench**
> When a combat starts here with your Avatar defending, place a Bug counter on the attacking Avatar.
> When a combat starts here with your Anomaly defending, place a Bug counter on the attacking Anomaly.
*A free Fuzz Input every defense.*
**Proxy Node**
> Firewalls on lines touching this Server don't block your Avatars.
> Firewalls on lines touching this Server don't block your Anomalies.
*Tunnel as a location. Whoever holds it owns the gateways around it.*
**Stable Release**
> Patch Programs here can't be disabled, and Hardware on your Avatars here can't be disabled.
> Patch Programs here can't be disabled, and Hardware on your Anomalies here can't be disabled.
*Hardening as a location.*
**Cache Server**
> Gain 2 RAM each time you capture a location adjacent to this Server.
> Gain 2 Gb each time you capture a location adjacent to this Server.
*Rewards pushing out from it. Watch for recapture farming with a friendly neighbor.*
**Honeypot**
@ -346,9 +346,9 @@ Suggested alongside the new cards, from the sim data in `expansion-plan.md`:
| Card | Now | Proposed | Why |
|---|---|---|---|
| Additional Core | +1 Core, 5 RAM | 4 RAM | RAM Expansion gives +2 for the same 5 |
| Broken Bits, Bit Flip | 4 RAM | 5 RAM | 55% win rate, best card in the pool |
| Backup Machine, Restore Point | 5 RAM | 3 RAM | 45% win rate, worst in the pool |
| Additional Core | +1 Core, 5 Gb | 4 Gb | RAM Expansion gives +2 for the same 5 |
| Broken Bits, Bit Flip | 4 Gb | 5 Gb | 55% win rate, best card in the pool |
| Backup Machine, Restore Point | 5 Gb | 3 Gb | 45% win rate, worst in the pool |
| ECC Memory | unchanged | unchanged | Now has a job once Bug counters exist |
| Cloud Compute | +4 Cores | +3 Cores | Integer Overflow answers it, but +4 still swings games. Optional. |
@ -356,7 +356,7 @@ Suggested alongside the new cards, from the sim data in `expansion-plan.md`:
| Kind | Before | Added | After |
|---|---|---|---|
| Avatars | 8 (2 per type) | 12 | 20 (5 per type) |
| Anomalies | 8 (2 per type) | 12 | 20 (5 per type) |
| Programs | 28 (V7 B8 G7 P6) | 17 | 45 (V11 B12 G11 P11) |
| Hardware | 16 | 8 | 24 |
| Executions | 18 | 8 | 26 |

View file

@ -5,7 +5,7 @@
## Turn
1. Draw Card
2. Place Avatars on controlled servers
2. Place Anomalies on controlled servers
3. Play cards from hand
4. Attack unowned servers or enemy owned servers
5. Resolve Abilities

230
rules.md
View file

@ -1,13 +1,15 @@
# Files TCG Rules
*Draft v0.9 — 2026-09-29.* The basic game rules are complete. v0.9 gives Avatars
*Draft v0.9 — 2026-09-29.* The basic game rules are complete. v0.9 gives Anomalies
[Health](#combat): the roll is unchanged, but the loser takes the difference as damage instead of
being knocked out, and a location falls only when its last defender is destroyed. To keep the seats
even under Health, the first player now leads every round and draws in round 1. Six cards changed
with it (Carbon NanoBots, Backup Machine, RAM Expansion, Resource Leech, Overflow Error, Persistent
Infection; see [Readings](#readings) and the [Watch List](#simulation-watch-list)). v0.8 replaced
whole turns with [rounds of alternating commands](#rounds-and-commands). Card text and stats come from
`decks/files-deck-1/cards.csv` (`cards.md` is out of date). [Card Rules](#card-rules) says how card
`decks/files-deck-1/cards.csv` (`cards.md` is out of date). On 2026-09-30 three terms were renamed
to set the game apart from Neuroscape TCG: RAM is now [Bandwidth](#bandwidth), counted in Gb; Hardware
"ports" are Expansion Slots; and the Bug Program Memory Leak is Bloatware. [Card Rules](#card-rules) says how card
text is read; readings marked ⚠ are the simulator's guesses and are listed in
[Open Questions](#open-questions).
@ -20,7 +22,7 @@ The first player to control **10 Server locations** wins. Starting Servers don't
Each player brings:
- **4 Avatars**
- **4 Anomalies**
- **20 Servers**
- **45 cards**: any mix of Executions, Hardware and Programs
@ -28,14 +30,14 @@ A deck can hold at most **2 copies** of any one card.
## Setup
1. Shuffle your 4 Avatars and place them face down in your 4 Avatar slots (the ✚ icons), numbered 1–4.
1. Shuffle your 4 Anomalies and place them face down in your 4 Anomaly slots (the ✚ icons), numbered 1–4.
2. Shuffle your Servers face down into your Server pile.
3. Shuffle your 45 cards face down into your Deck.
4. Place 1 Server from your pile face down on your starting Server (the ■ icon). Reveal it when the
game starts; its ability applies.
5. Draw 7 cards.
6. Start with **4 RAM**. This is the capture payout for your starting Server, not an extra 4.
7. Flip Avatar 1 face up. It is available from the start.
6. Start with **4 Gb**. This is the capture payout for your starting Server, not an extra 4.
7. Flip Anomaly 1 face up. It is available from the start.
The first player is chosen at random. They take the first command of every round, and both players
draw at their first command of round 1.
@ -97,7 +99,7 @@ and `E2–S2`) have no gateways, so they can never be firewalled. A2 and E2 don'
A location's level depends on **who captures it**: deeper into enemy territory means a higher level.
Your starting Server and your first row are Lv 1, and each row after that is one level higher.
Levels decide which Avatars unlock. Every capture pays the same **4 RAM**, whatever the level.
Levels decide which Anomalies unlock. Every capture pays the same **4 Gb**, whatever the level.
| Row | South player's level | North player's level |
|---|---|---|
@ -109,12 +111,12 @@ Levels decide which Avatars unlock. Every capture pays the same **4 RAM**, whate
| E1–E3 | Lv 5 | Lv 1 |
| S2 | — | Lv 1 (start) |
### Avatar unlocks
### Anomaly unlocks
The first time you capture a Lv N location, flip Avatar N face up, plus any lower-numbered Avatar
that's still face down. Your first row (Lv 1) unlocks nothing; Avatar 2 unlocks in your second row.
Capturing Lv 3 before Lv 2 unlocks Avatars 2 and 3. Unlocks are permanent, even if you later lose
the location. An Avatar unlocked during a round can enter play from the next round.
The first time you capture a Lv N location, flip Anomaly N face up, plus any lower-numbered Anomaly
that's still face down. Your first row (Lv 1) unlocks nothing; Anomaly 2 unlocks in your second row.
Capturing Lv 3 before Lv 2 unlocks Anomalies 2 and 3. Unlocks are permanent, even if you later lose
the location. An Anomaly unlocked during a round can enter play from the next round.
## Rounds and Commands
@ -132,33 +134,33 @@ draws and refreshes between those two commands, since the second one starts a ne
**Your first command of a round** starts with:
1. **Draw** a card. If your Deck is empty, skip this. There's no maximum hand size.
2. **Refresh:** each of your Avatars can act and be placed again this round. Effects that happen
2. **Refresh:** each of your Anomalies can act and be placed again this round. Effects that happen
"at the start of your turn" happen now.
**A command:**
1. **Deploy & Move.**
- First, place any of your face-up Avatars onto locations you control. This includes Avatars
entering play from a slot and Avatars repositioning. Placement is free and doesn't count as a
move. Each Avatar can be placed once per round.
- **Recall:** instead of placing an Avatar that's on the board, you may return it to its slot.
- First, place any of your face-up Anomalies onto locations you control. This includes Anomalies
entering play from a slot and Anomalies repositioning. Placement is free and doesn't count as a
move. Each Anomaly can be placed once per round.
- **Recall:** instead of placing an Anomaly that's on the board, you may return it to its slot.
It heals to full Health and keeps its Hardware, but the recall counts as its placement for the
round, and the location it left is now undefended. An Avatar that can't move (Packet Flood,
round, and the location it left is now undefended. An Anomaly that can't move (Packet Flood,
Emergency Shutdown) can't be recalled.
- Then you may **advance** one Avatar: move it to an unowned location, or an undefended enemy
- Then you may **advance** one Anomaly: move it to an unowned location, or an undefended enemy
location, that is adjacent to any location you control.
- Each location holds 1 of your Avatars. Cluster Server and Pingable Server raise this to 2.
- Each location holds 1 of your Anomalies. Cluster Server and Pingable Server raise this to 2.
2. **Play cards** from your hand.
3. **Attack.** If you didn't advance, one Avatar may attack one **defended** enemy location adjacent
3. **Attack.** If you didn't advance, one Anomaly may attack one **defended** enemy location adjacent
to **the location it's on**. It gets the Core bonus of the Server it attacks from.
4. **Resolve** the advance or attack right away, with the capture or combat and Server placement.
5. **Play additional cards**, including with RAM gained in step 4.
5. **Play additional cards**, including with Bandwidth gained in step 4.
A command is **one advance or one attack**, or neither (a pass). Each Avatar can advance or attack
only **once per round**, so with one Avatar in play your second command of a round can play cards but
can't act. Copies are Avatars: each can act once per round, but they don't add commands.
A command is **one advance or one attack**, or neither (a pass). Each Anomaly can advance or attack
only **once per round**, so with one Anomaly in play your second command of a round can play cards but
can't act. Copies are Anomalies: each can act once per round, but they don't add commands.
There's no limit on how many cards you can play, other than the RAM you have.
There's no limit on how many cards you can play, other than the Bandwidth you have.
### "Turn" on cards
@ -173,81 +175,83 @@ Card text is written for turns. With commands it reads like this:
## Capturing Locations
- **Unowned location:** your Avatar moves in. Draw the top Server from your pile, place it face up
there, and gain RAM.
- **Undefended enemy location:** your Avatar moves in. The enemy puts their Server card on the bottom
- **Unowned location:** your Anomaly moves in. Draw the top Server from your pile, place it face up
there, and gain Bandwidth.
- **Undefended enemy location:** your Anomaly moves in. The enemy puts their Server card on the bottom
of their pile, and Programs there go to their discard pile. Then place your own Server and gain
RAM, as above.
Bandwidth, as above.
- **Defended enemy location:** combat. If the combat destroys every defender there, capture it as
an undefended location. Otherwise the location holds and your Avatar stays where it attacked from.
an undefended location. Otherwise the location holds and your Anomaly stays where it attacked from.
- **Starting Servers** can't be attacked or captured.
## Combat
Every Avatar has printed **Health**. Damage stays on an Avatar for as long as it's on the board, so
Every Anomaly has printed **Health**. Damage stays on an Anomaly for as long as it's on the board, so
a defended location usually takes more than one attack to fall. Track damage with counters or a
dial on the card.
1. Both players roll 1d6 per Core, counting Cores from the Avatar, Hardware, Programs, effects, and
the Server each Avatar is on: the attacker's origin, and the location being defended. Each side
1. Both players roll 1d6 per Core, counting Cores from the Anomaly, Hardware, Programs, effects, and
the Server each Anomaly is on: the attacker's origin, and the location being defended. Each side
always rolls at least 1 die.
2. The higher total wins the roll. **The loser takes damage equal to the difference.** The winner
takes none. **On a tie, nothing happens:** no reroll and no damage. The combat is over.
3. If several Avatars defend, the attacker splits the damage among them as it likes.
4. An Avatar whose damage reaches its Health is **destroyed**. It returns to its Avatar slot, face
3. If several Anomalies defend, the attacker splits the damage among them as it likes.
4. An Anomaly whose damage reaches its Health is **destroyed**. It returns to its Anomaly slot, face
up, at full Health. Its Hardware goes to its owner's discard pile and all counters and effects on
it are removed, debuffs included. It can be placed again from its owner's next command, if it
hasn't been placed yet this round.
5. Nobody else moves. A losing attacker stays where it attacked from, carrying its damage. A winning
attacker moves into the location only if every defender was destroyed, and captures it.
An Avatar heals by leaving the board: by being destroyed, or by a **recall** in the Deploy step
An Anomaly heals by leaving the board: by being destroyed, or by a **recall** in the Deploy step
(which keeps its Hardware). Backup Machine's Restore Point is the one card that heals in place (3
damage), and RAM Expansion is the one Hardware that adds Health (+2). Both are Patch-flavoured
design space for more cards.
## RAM
## Bandwidth
- RAM carries over between commands and rounds, and there's no cap.
- Avatars cost 0 RAM. Other cards cost their printed RAM value.
- **Capture:** gain **4 RAM**, paid once when you capture a location, whatever its level. You get
paid again every time you recapture a location. A Server card's RAM bonus (for example "+4 RAM") is
also paid once, when the card is placed, on top of the capture RAM. A Server's Core bonus applies to your Avatar
Bandwidth is the game's one resource, counted in **Gb**.
- Bandwidth carries over between commands and rounds, and there's no cap.
- Anomalies cost 0 Gb. Other cards cost the Gb printed on them.
- **Capture:** gain **4 Gb**, paid once when you capture a location, whatever its level. You get
paid again every time you recapture a location. A Server card's Bandwidth bonus (for example "+4 Gb") is
also paid once, when the card is placed, on top of the capture Bandwidth. A Server's Core bonus applies to your Anomaly
at that location.
- **Salvage:** discard a card from your hand to gain its printed RAM value. You can salvage any time
- **Salvage:** discard a card from your hand to gain its printed Bandwidth value. You can salvage any time
you need to pay a cost. Installed cards can't be salvaged.
- **Firewalls:** you spend RAM to place, upgrade and clear them.
- **Firewalls:** you spend Bandwidth to place, upgrade and clear them.
## Firewalls
Firewalls are bought with RAM and placed on a gateway (`o`). They aren't cards. A Firewall blocks
Firewalls are bought with Bandwidth and placed on a gateway (`o`). They aren't cards. A Firewall blocks
**all** movement and attacks along its line: for both players, and for card effects that move
Avatars (such as Trace Route and Disconnect).
Anomalies (such as Trace Route and Disconnect).
| Firewall | Cost |
|---|---|
| Lv 1 | 2 RAM |
| Lv 2 | 4 RAM |
| Lv 3 | 8 RAM |
| Lv 1 | 2 Gb |
| Lv 2 | 4 Gb |
| Lv 3 | 8 Gb |
- **Placing:** in your command (steps 2 and 5), on an empty gateway whose line touches a location you
control. Pay the cost of the level you place. Each gateway holds 1 Firewall, and there's no limit on
how many you can place.
- **Upgrading:** same timing and placement rules as placing. Pay the **full cost** of the new level;
for example, Lv 1 → Lv 2 costs 4 RAM.
for example, Lv 1 → Lv 2 costs 4 Gb.
- **Clearing:** in your command, in steps 1 and 3, before you advance or attack, on a line touching a
location you control. Pay the Firewall's **current level cost**. This applies to everyone, including
the player who placed it; there's no free removal. Clearing doesn't use an Avatar's action.
the player who placed it; there's no free removal. Clearing doesn't use an Anomaly's action.
- **Permanent:** a Firewall stays until someone pays to clear it, even if the locations at either end
change hands. Once placed, it doesn't belong to either player.
## Playing Cards
- **Programs:** in your command (steps 2 and 5), on a location you control. Maximum 2 per location.
- **Hardware:** in your command (steps 2 and 5), on one of your Avatars that's in play (not in its
- **Hardware:** in your command (steps 2 and 5), on one of your Anomalies that's in play (not in its
slot), up to its Expansion Slots.
- **Executions:** at any time, by either player (see [Timing](#timing)).
- **Avatar abilities:** Execution timing, once per turn (per round), only while the Avatar is in
- **Anomaly abilities:** Execution timing, once per turn (per round), only while the Anomaly is in
play.
- **Other activated abilities** (Garbage Collection, Rollback Routine, Undefined Behavior, Hot-Swap
Bay, Backup Server): the same, Execution timing and once per turn (per round). Using one isn't
@ -271,45 +275,45 @@ Avatars (such as Trace Route and Disconnect).
### Terms
- **"This Server"** on a Program or Server is the location it's on. Avatars **"at"** a location are
the ones standing on it, plus an enemy attacking it in the current combat. Enemy Avatars never
- **"This Server"** on a Program or Server is the location it's on. Anomalies **"at"** a location are
the ones standing on it, plus an enemy attacking it in the current combat. Enemy Anomalies never
stand on your locations.
- **"A combat at this Server"** on an Avatar Ability means any combat that Avatar is fighting in,
- **"A combat at this Server"** on an Anomaly Ability means any combat that Anomaly is fighting in,
attacking or defending.
- **Health / damage:** an Avatar's Health is printed on it. Damage is marked on the Avatar and
- **Health / damage:** an Anomaly's Health is printed on it. Damage is marked on the Anomaly and
stays while it's on the board. Copies have the original's Health and their own damage.
- **Destroyed / defeated** (Avatars) means its damage reached its Health, so it left the board.
- **Destroyed / defeated** (Anomalies) means its damage reached its Health, so it left the board.
Losing a roll without being destroyed is not a defeat. A Program or Hardware is destroyed when an
effect sends it to the discard pile (Overflow Error, Sabotage). Programs on a captured location
are discarded, not destroyed.
- **Leaving the board** (destroyed or recalled) removes an Avatar's damage, counters and temporary
effects. Persistent Infection's counters stay. A recalled Avatar keeps its Hardware. ⚠
- **Leaving the board** (destroyed or recalled) removes an Anomaly's damage, counters and temporary
effects. Persistent Infection's counters stay. A recalled Anomaly keeps its Hardware. ⚠
- **Breach:** capture an enemy-owned location, by advancing into it or winning an attack on it.
- **Disabled Hardware or Program:** its effect stops. With no duration on the card, it stays
disabled until something re-enables it (Execute: Defragment) or it leaves play.
- **Disabled Avatar** (Emergency Shutdown): can't advance, attack, move or use its Ability. It still
- **Disabled Anomaly** (Emergency Shutdown): can't advance, attack, move or use its Ability. It still
defends. ⚠
- **Infection counters** come off when the Avatar leaves the board, except the ones Persistent
- **Infection counters** come off when the Anomaly leaves the board, except the ones Persistent
Infection places. Code Zero (1+ counters: −1 Core) and Recursive Infection (3+: −2 Cores) apply everywhere
while the card is in play, once each no matter how many copies are in play.
- **Bug counters** work like Infection counters, for Bug cards. They come off when the Avatar leaves
the board, and Error Correction can remove one. **An Avatar with 3 or more Bug counters removes
- **Bug counters** work like Infection counters, for Bug cards. They come off when the Anomaly leaves
the board, and Error Correction can remove one. **An Anomaly with 3 or more Bug counters removes
its highest die after every roll** (one die, however many counters). ECC Memory stops opponents
from placing them. Purge removes only Virus/Infection counters. The Set 2 cards in `cards.csv`
place them (Fuzzer, Heap Corruption, Bit Rot, Bug Injector, Test Bench); no Set 1 card does.
- **Temporary bonuses and penalties** are Core changes from Abilities, Executions and Program
triggers that last one combat or one turn: Memory Leak, Visual Artifact, Race Condition, Low
triggers that last one combat or one turn: Bloatware, Visual Artifact, Race Condition, Low
Resolution, Trace Route. Force Reboot removes them; Rollback Routine undoes the most recent penalty.
- **Copies** (Carbon NanoBots, Backup Server): a copy is an extra Avatar with the original's printed
Cores and the original's Hardware bonuses, but no Hardware or Ability of its own. Each Avatar can
- **Copies** (Carbon NanoBots, Backup Server): a copy is an extra Anomaly with the original's printed
Cores and the original's Hardware bonuses, but no Hardware or Ability of its own. Each Anomaly can
have one copy at a time. It enters play on any location you control with room, can advance, attack
and defend, and is removed if it's defeated or its original is. ⚠
- **Mid-combat:** no Avatar can enter a location while a combat is going on there, whether it's a
new copy or an Avatar moved by Disconnect. It wouldn't be in the combat, and the location could be
- **Mid-combat:** no Anomaly can enter a location while a combat is going on there, whether it's a
new copy or an Anomaly moved by Disconnect. It wouldn't be in the combat, and the location could be
captured with it still standing there. ⚠
- **Executions are performed by Servers**, never by Avatars. When you play one, one of your Servers
performs it (you pick which). Three cards were written for Avatars performing Executions, and read
it through the Server the Avatar stands on: Dedicated GPU and Quantum Coprocessor work for
- **Executions are performed by Servers**, never by Anomalies. When you play one, one of your Servers
performs it (you pick which). Three cards were written for Anomalies performing Executions, and read
it through the Server the Anomaly stands on: Dedicated GPU and Quantum Coprocessor work for
Executions that Server performs, and Force Reboot stops that Server from performing Executions for
the rest of the turn.
- **Protected** (Execute: Root Access) means the Program Hardware Sandbox protects. No card protects
@ -317,7 +321,7 @@ Avatars (such as Trace Route and Disconnect).
- **Two defenders** (Cluster Server, Pingable Server): both roll together as one side. If they lose,
the attacker splits the damage between them. The location falls only when both are destroyed. ⚠
- **Cores that change after the roll** change the dice: each Core gained rolls one more die, and each
Core lost removes one of that Avatar's rolled dice, the one showing the highest number.
Core lost removes one of that Anomaly's rolled dice, the one showing the highest number.
- **Once per turn** means once per round, counting uses in both players' commands (see
["Turn" on cards](#turn-on-cards)).
@ -328,21 +332,21 @@ Cards not listed here work exactly as printed.
| Card | How the simulator reads it |
|---|---|
| **Servers** | |
| Cluster Server, Pingable Server | Two of your Avatars fit; both defend together (see Terms). |
| Backup Server | Once per turn, at any time, make a copy of your Avatar standing here (see Copies). |
| Upgraded Hardware | −2 RAM for Hardware installed on your Avatar standing here. |
| Network Throttle | −1 RAM for Firewalls you place or upgrade on a line touching it. Clearing costs full price. |
| Duplicate Server | When placed, pick one adjacent Server (either player's) and gain its ability while this card stays. A copied RAM bonus is paid at once. ⚠ |
| Protected Server | +2 RAM each time a combat starts here with your Avatar defending. ⚠ |
| Cluster Server, Pingable Server | Two of your Anomalies fit; both defend together (see Terms). |
| Backup Server | Once per turn, at any time, make a copy of your Anomaly standing here (see Copies). |
| Upgraded Hardware | −2 Gb for Hardware installed on your Anomaly standing here. |
| Network Throttle | −1 Gb for Firewalls you place or upgrade on a line touching it. Clearing costs full price. |
| Duplicate Server | When placed, pick one adjacent Server (either player's) and gain its ability while this card stays. A copied Bandwidth bonus is paid at once. ⚠ |
| Protected Server | +2 Gb each time a combat starts here with your Anomaly defending. ⚠ |
| Callable Server | Every draw after the opening hand, once per card drawn. A second Callable Server doesn't add more. |
| **Programs** | |
| Recursive Infection | One counter per attack declared on this location, or per capture of it without an attack. ⚠ |
| Memory Parasite | "The owner" is the attacking Avatar's owner, who picks which of its Hardware is off for that combat. |
| Memory Parasite | "The owner" is the attacking Anomaly's owner, who picks which of its Hardware is off for that combat. |
| Replication Routine | Installing this card counts, so it can bring a second Virus with it. Program slots still apply. |
| Worm Protocol | Its other Programs' effects also apply at the adjacent location chosen on install (any owner's). |
| Resource Leech | Pays on every roll the attacker loses here, destroyed or not. |
| Persistent Infection | Fires on every roll an attacker loses here. Enemy Avatars are only ever at your location while attacking it. |
| Infinite Loop | Your Avatar attacking from here may declare a second attack on another adjacent location. Both attacks come from here, even if the first one moved it. If it loses the first, the second is off. ⚠ |
| Persistent Infection | Fires on every roll an attacker loses here. Enemy Anomalies are only ever at your location while attacking it. |
| Infinite Loop | Your Anomaly attacking from here may declare a second attack on another adjacent location. Both attacks come from here, even if the first one moved it. If it loses the first, the second is off. ⚠ |
| Stack Overflow | Counts Programs installed here, including Process Clone and Remote Access copies. |
| Race Condition | The attacker picks first, hidden from the defender. The +2 goes to the defending side. |
| Null Pointer | Automatic: the first enemy Execution targeting this location each turn does nothing. The card is still spent. |
@ -351,46 +355,46 @@ Cards not listed here work exactly as printed.
| Undefined Behavior | The copy is yours, works on this location, and lasts until your next turn. ⚠ |
| Desynchronization | The once-per-turn Hardware abilities are Hot-Swap Bay and Quantum Coprocessor. |
| Visual Artifact | Once per installation, since "each turn" was removed from the card. ⚠ |
| Ghost Process | An Execution you play on this location may pick its Avatar, Program or Hardware at one adjacent location. |
| False Positive | Redirect to any other Avatar the Execution could legally hit at another location. |
| Ghost Process | An Execution you play on this location may pick its Anomaly, Program or Hardware at one adjacent location. |
| False Positive | Redirect to any other Anomaly the Execution could legally hit at another location. |
| Latency Spike | "The first step" is the window before the roll. Abilities still work. |
| Hotfix | Only effects destroy Programs (Overflow Error); capture doesn't. |
| Error Correction | Removes one of: an Infection counter, a permanent counter, disabled Hardware, the latest penalty, Packet Flood, Disabled. |
| Garbage Collection | It can sacrifice itself. |
| Version Control | On capture, one Program goes back to your hand; on destruction, the destroyed Program does. |
| Compatibility Layer | +1 Program slot here; −2 RAM for Patch Programs installed here after it. |
| Compatibility Layer | +1 Program slot here; −2 Gb for Patch Programs installed here after it. |
| **Hardware** | |
| RAM Expansion | +2 Health for the wearer. It adds no Cores. |
| Overclocked CPU | After each combat, one of your Programs on the location it fought from is disabled through the end of the next turn. ⚠ |
| Solid-State Cache | −3 RAM for the first Program you install each turn on the location the wearer stands on. |
| Solid-State Cache | −3 Gb for the first Program you install each turn on the location the wearer stands on. |
| Redundant Power Supply | The first time the wearer is destroyed, all its Hardware stays on it, in its slot. ⚠ |
| Network Interface Upgrade | Takes no port and adds one, so the wearer nets +1 Expansion Slot. The card text should say so. If it leaves (Sabotage, Rollback), the wearer discards Hardware until it fits, newest first. ⚠ |
| Dedicated GPU | +1 to the number an Execution uses (cards drawn, Cores, RAM) when the Server the wearer stands on performs it. |
| ECC Memory | Opponents can't give the wearer Bug counters. "Bug status effects" are opponents' Bug Program effects on it (Memory Leak, Stock Rice). ⚠ |
| Cooling System | One other Hardware on the same Avatar gets two uses a turn of its once-per-turn or first-each-turn effect. |
| RAID Array | Half the combined printed RAM of its Hardware, rounded up. ⚠ |
| Firewall Appliance | Programs never target Avatars, so this taxes the first enemy Execution each turn that targets the wearer or its Hardware. |
| Network Interface Upgrade | Takes no Expansion Slot and adds one, so the wearer nets +1. The card text should say so. If it leaves (Sabotage, Rollback), the wearer discards Hardware until it fits, newest first. ⚠ |
| Dedicated GPU | +1 to the number an Execution uses (cards drawn, Cores, Bandwidth) when the Server the wearer stands on performs it. |
| ECC Memory | Opponents can't give the wearer Bug counters. "Bug status effects" are opponents' Bug Program effects on it (Bloatware, Stock Rice). ⚠ |
| Cooling System | One other Hardware on the same Anomaly gets two uses a turn of its once-per-turn or first-each-turn effect. |
| RAID Array | Half the combined printed Bandwidth of its Hardware, rounded up. ⚠ |
| Firewall Appliance | Programs never target Anomalies, so this taxes the first enemy Execution each turn that targets the wearer or its Hardware. |
| Hardware Sandbox | Pick the Program on install, and again at the start of your turn if the wearer has moved. It's protected only while the wearer stands with it. ⚠ |
| Diagnostic Module | At the start of your turn, look at your top card and you may put it on the bottom; then draw normally. ⚠ |
| Hot-Swap Bay | Swap Hardware on this Avatar, at any time, paying the difference in printed RAM (no refund). The result must fit the ports. ⚠ |
| Hot-Swap Bay | Swap Hardware on this Anomaly, at any time, paying the difference in printed Bandwidth (no refund). The result must fit its Expansion Slots. ⚠ |
| Quantum Coprocessor | Works for Executions performed by the Server the wearer stands on. "Disable this Hardware" lasts until your next turn, as the card used to say. |
| **Executions** | |
| Execute: Disconnect | Moves to a location you control with room. An attacker can retreat to where it stands. If the last defender leaves, the attacker takes the location. ⚠ |
| Execute: Sabotage | "Disable" lasts until re-enabled. |
| Execute: Force Reboot | Clears every temporary effect on the Avatar. The Server it stands on can't perform Executions for the rest of the turn. |
| Execute: Force Reboot | Clears every temporary effect on the Anomaly. The Server it stands on can't perform Executions for the rest of the turn. |
| Execute: Fork | The copy is yours, works on the target location until end of turn, and doesn't count as installed. |
| Execute: Trace Route | Resolves right away, only while no combat is going on. Into your own location it's a move, into an unowned or undefended one a capture, into a defended one an attack with +1 Core from the location it left. It works in either player's command. |
| Execute: Rollback | Programs installed on the target this turn, or Hardware installed this turn on an Avatar there. |
| Execute: Packet Flood | Affected Avatars can't advance, attack, reposition or be moved, and moves they already declared fail. ⚠ |
| Execute: Emergency Shutdown | Nobody moves; Disabled Avatars still defend (see Terms). ⚠ |
| Execute: Rollback | Programs installed on the target this turn, or Hardware installed this turn on an Anomaly there. |
| Execute: Packet Flood | Affected Anomalies can't advance, attack, reposition or be moved, and moves they already declared fail. ⚠ |
| Execute: Emergency Shutdown | Nobody moves; Disabled Anomalies still defend (see Terms). ⚠ |
| Execute: Process Clone | The second copy counts as installed. |
| Execute: Remote Access | The Program keeps its owner and works at both locations until end of turn. ⚠ |
| Execute: Purge | Removes Infection (permanent too), opponents' penalties, Packet Flood, Disabled, and disabled Hardware. |
| **Avatar Abilities** | |
| **Anomaly Abilities** | |
| Carbon NanoBots (Replicate) | See Copies. Two NanoBots in a deck can have two copies. ⚠ |
| Backup Machine (Restore Point) | Either heal 3 damage on it, or recover a card; not both. |
| Pixelated Picture (Low Resolution) | Only while it defends: −1 Core for the attacker, that combat. ⚠ |
| Beta Version 1.0 (Push Update) | During a combat it's in, install a Hardware from hand (paying for it), ignoring ports. That Hardware is discarded at the end of your turn. |
| Beta Version 1.0 (Push Update) | During a combat it's in, install a Hardware from hand (paying for it), ignoring Expansion Slots. That Hardware is discarded at the end of your turn. |
| Data Leaker (Exfiltrate) | "Breached a Server this turn" = captured an enemy location this turn. |
| Broken Bits (Bit Flip) | Rerolls its dice showing a chosen number or less, which is always the best set to reroll. |
@ -400,22 +404,22 @@ Cards not listed here work exactly as printed.
For the basic game (v0.9 Health):
1. **Health values** are a first guess: 4-Core Avatars 9, 3-Core 10, and Carbon NanoBots 10 (it
was 12, but with a copy that shares its Health it won 55% of sim games; at 10 Health and a 6 RAM
1. **Health values** are a first guess: 4-Core Anomalies 9, 3-Core 10, and Carbon NanoBots 10 (it
was 12, but with a copy that shares its Health it won 55% of sim games; at 10 Health and a 6 Gb
Replicate it's 52%).
2. **Recall** clears counters and effects, like a defeat does. That makes it a slow Purge. Intended? ⚠
3. **Split damage** with two defenders is the attacker's choice. ⚠
4. **RAM Expansion** now gives +2 Health (it said "+2 Core capacity" and was read as +2 Cores, which
made Additional Core pointless). In the sim it's a neutral card at 5 RAM.
made Additional Core pointless). In the sim it's a neutral card at 5 Gb.
For the cards:
1. **Bug counters** are placed by Set 2 cards and punished by the 3+ rule above and by Segmentation
Fault. Set 2 (52 cards, `Set` = 2 in `cards.csv`, see `expansion-plan.md` section 9) has no
simulator scripts yet, so the sim loads set 1 unless asked (`--set 2`, `--set all`).
2. Card text to update for rulings already made: Network Interface Upgrade (+1 port), and the
typos Packet Accelerator "hen attacking" (when), Null Pointer "it's effect" (its), Push Update "If
there no ports" (there are), Memory Parasite "owners choosing" (owner's).
2. Card text to update for rulings already made: Network Interface Upgrade (+1 Expansion Slot), and the
typos Packet Accelerator "hen attacking" (when), Null Pointer "it's effect" (its),
Memory Parasite "owners choosing" (owner's).
3. The other ⚠ readings above are smaller guesses. Say if any look wrong.
## Simulation Watch List
@ -423,8 +427,8 @@ For the cards:
Things the first sim runs should measure:
- **Salvage efficiency.** Salvage pays full printed value, so any card can pay for another card of
equal or lower cost. Does capture RAM matter?
- **Fight rate.** Undefended locations are free to take. With at most 4 Avatars and 10 locations
equal or lower cost. Does capture Bandwidth matter?
- **Fight rate.** Undefended locations are free to take. With at most 4 Anomalies and 10 locations
needed, is the game a land race with few fights?
- **Recapture farming.** Can players profit by trading the same location back and forth?
- **Firewall stalling.** Can a leading player wall off their side with Lv 3 Firewalls and stall the
@ -433,24 +437,24 @@ Things the first sim runs should measure:
- **Game length.** Deck is 45 cards, 7 of them in the opening hand, so 38 draws. Do games end before
decks run out?
- **First-player advantage.** With whole turns the first player won about 70% of sim games (with
bots that rush Avatar unlocks). Rounds of alternating commands in the snake order brought it to
bots that rush Anomaly unlocks). Rounds of alternating commands in the snake order brought it to
about 50%. A plain alternating lead gave 49%, the first player always leading 51%. Under Health
(v0.9) the alternating lead fell to 48%, so the lead is fixed on the first player again and they
draw in round 1: 51% over 9,000 games (fixed lead alone 50%, fixed lead without snake 53.5%).
- **Game length.** Commands make games longer: a median of 13 rounds (26 commands each), 90% within
35 rounds.
- **Health (v0.9).** 1,000 greedy-vs-greedy games, printed Health against one-roll combats: median
14 rounds (13 before), 24.5 combats a game (27), 4.9 combat captures per player (9.3), 6.4 Avatars
14 rounds (13 before), 24.5 combats a game (27), 4.9 combat captures per player (9.3), 6.4 Anomalies
destroyed per player (13), 34% of enemy locations taken were won in combat (41%). First player
47% (49%). The bot attacks with big Core edges, so its winning margin averages about 10 and
roughly two thirds of its winning rolls destroy the defender outright; the rest take a second
attack. Bots recall under once a game. Every Avatar at Health 8: median 13 rounds, 40% of enemy
attack. Bots recall under once a game. Every Anomaly at Health 8: median 13 rounds, 40% of enemy
captures by combat; at 12: median 14, 30%. Attacking at 50%+ odds instead of 60%+ makes no
difference (48% vs 51%).
- **Cards under Health (2026-09-29).** Destructions halved, so cards keyed to "destroyed" almost
never fired (Resource Leech, Overflow Error, Persistent Infection: 0.03 times a game); they now
fire on every lost roll. Carbon NanoBots rose to 55% (its copy is a second body with its Health)
and Backup Machine fell to 44%, so NanoBots is 10 Health with a 6 RAM Replicate and Restore Point
and Backup Machine fell to 44%, so NanoBots is 10 Health with a 6 Gb Replicate and Restore Point
can heal 3 instead. RAM Expansion became +2 Health. Taking a Core stick out of the pool made the
bot stall more (every location defended, no attack at 60%+ odds), so under Health it now takes
the best long shot at 25%+ odds when it has nothing else to do.
@ -459,7 +463,7 @@ Things the first sim runs should measure:
For each matchup, three exact numbers: the chance the attacker **wins the roll**, the **average
damage** a win deals (the margin), and the chance one roll deals **10 or more**, enough to destroy a
10-Health Avatar outright. Rows are the attacker's Cores, columns the defender's. Ties are neither a
10-Health Anomaly outright. Rows are the attacker's Cores, columns the defender's. Ties are neither a
win nor a loss: 1 vs 1 ties 17% of the time, 3 vs 3 9%, 6 vs 6 7%.
| Atk \ Def | 1 | 2 | 3 | 4 | 5 | 6 |

View file

@ -13,6 +13,8 @@ npm run sim -- -n 5000 # 5,000 greedy-vs-greedy games
npm run sim -- -n 5000 --card-report # plus how each card did
npm run sim -- --south greedy --north nocards # does playing cards help?
npm run sim -- --rule secondPlayer.cards=2 # try a rule variant (see src/rules.ts)
npm run sim -- --rule board=grid4 # the 4×4 test board (win with 12 of 16)
npm run sim -- --rule board=lanes # three lanes, linked only across the middle (11 of 15)
npm run sim -- --log --seed 7 # watch one game, play by play
npm run sim -- --json out/run.json # also save every game's result
npm run sim -- --help # all options and bots
@ -29,13 +31,13 @@ of how much a card helps.
- **Rules:** everything in `rules.md`: setup, rounds of alternating commands (or whole turns, with
`--rule commands.on=false`), placement, recall and advancing, attacks, combat with Health and
damage (or one-roll combats with tie rerolls, with `--rule health.on=false`; `health.override=8`
gives every Avatar the same Health), captures, levels and RAM, Avatar unlocks, Firewalls,
gives every Anomaly the same Health), captures, levels and Bandwidth, Anomaly unlocks, Firewalls,
Salvage, response windows and chains, and the win condition.
- **Every card:** all 83 set 1 cards in `../decks/files-deck-1/cards.csv` have a script, including
Avatar Abilities. The 52 set 2 cards (`Set` = 2) have none yet, so they're skipped unless you pass
Anomaly Abilities. The 52 set 2 cards (`Set` = 2) have none yet, so they're skipped unless you pass
`--set 2` or `--set all`; the bots never play an unscripted card. Unclear card text follows the readings in `rules.md` → Card Rules; the ones marked ⚠
are guesses waiting for a decision.
- **Card edits:** stats (RAM, Cores, Health, slots) come straight from the CSV. Each script records the text
- **Card edits:** stats (Bandwidth, Cores, Health, slots) come straight from the CSV. Each script records the text
it was written for, so if you reword a card the sim warns you, and `npm test` fails until the
script is updated.
@ -47,6 +49,20 @@ captures, card triggers) until it needs a player again: a turn step, a response
a card asks for. Each card's effect lives in one script (`src/cards/`), which the engine calls at
fixed hooks: Core totals, costs, combat start, defeat, capture, draws, installs, and so on.
The browser app in `../app` plays on this engine directly. For it:
- `parseCards(csvText)` in `cards.ts` reads the card CSV without Node; `loadCards()` in `load.ts`
reads the file from disk for the CLI and tests.
- `describeAction(s, a)` in `describe.ts` labels every action for people, e.g.
`Play Execute: Force Reboot on D2: Anomaly 2 (Glitch) (5 Gb)`.
- Log lines carry a tag (combat, capture, card, move…) and what they're about. A line naming a card
only one player may see goes to that player, and `logFor(s, p)` gives the other player its public
version. Choices marked `secret` (Callable Server, Diagnostic Module, Race Condition) log that way,
and `viewFor` hides their prompt from the opponent.
- `coresOf` can list where an Anomaly's Cores come from, `rollOdds` in `odds.ts` gives a roll's win,
tie and loss chances with the average damage, and `combatWatch` in `flow.ts` lets an app see
every stage of a combat, even one that starts and ends inside a single `applyAction`.
## Layout
| Path | What it holds |
@ -54,19 +70,20 @@ fixed hooks: Core totals, costs, combat start, defeat, capture, draws, installs,
| `src/engine.ts` | Decisions, legal actions, response windows, the turn loop, player views |
| `src/flow.ts` | Combat, defeat, capture, drawing, copies |
| `src/query.ts` | What's in play, Cores, costs, capacity, protection |
| `src/cards/` | One script per card: `servers`, `programs`, `hardware`, `executions`, `avatars` |
| `src/cards/` | One script per card: `servers`, `programs`, `hardware`, `executions`, `anomalies` |
| `src/scripts.ts` | The script interface and registry, and the stale-text check |
| `src/map.ts`, `src/rules.ts` | Playmat lines and levels; every rules number, for testing variants |
| `src/map.ts`, `src/rules.ts` | Playmats (the rules.md one plus 4×4 and three-lane test boards), lines and levels; every rules number, for testing variants |
| `src/bots/` | `greedy` (with style presets), `random`, and the combat math they share |
| `src/cli.ts`, `src/stats.ts` | Batch runner, summary and card report |
| `src/describe.ts` | Readable labels for actions and their arguments |
| `src/cli.ts`, `src/stats.ts`, `src/load.ts` | Batch runner, summary and card report; reading the card CSV from disk |
| `test/` | Rules tests, one test per card, and fuzz games that check invariants after every action |
## Bots
- **greedy** plans each command: takes the best single advance or attack (open locations first,
rushing the ones that unlock Avatars; attacks at 60%+ odds), guards threatened locations, installs
Hardware and Programs where they help, walls off undefended locations, and keeps RAM for tricks.
With whole turns it plans every Avatar's move at once. On the opponent's commands it answers after the dice are rolled with whichever
rushing the ones that unlock Anomalies; attacks at 60%+ odds), guards threatened locations, installs
Hardware and Programs where they help, walls off undefended locations, and keeps Bandwidth for tricks.
With whole turns it plans every Anomaly's move at once. On the opponent's commands it answers after the dice are rolled with whichever
Execution or Ability most improves the combat, and tries to stop advances into its locations.
- **nocards** is greedy but only uses Core Hardware, like the first version of the sim.
- **bold / cautious / nowall / wall3** change one greedy setting each; **random** picks any legal

View file

@ -3,34 +3,34 @@ import { isStart, levelFor, type LocId } from '../map.ts';
import { winChance } from '../odds.ts';
import { bugImmune, coresOf, fighterOf, hardwareActive, healthLeft, sources } from '../query.ts';
import { scriptOf } from '../scripts.ts';
import { avatar, defOf, defendersAt, fightersOf, hardwareOf, refKey } from '../state.ts';
import type { AvatarRef, GameState, PlayerId } from '../types.ts';
import { anomaly, defOf, defendersAt, fightersOf, hardwareOf, refKey } from '../state.ts';
import type { AnomalyRef, GameState, PlayerId } from '../types.ts';
// A location is worth about 10 points, plus 8 more when it's taken from the opponent. RAM counts
// half a point per RAM, a card in hand about 2.
// A location is worth about 10 points, plus 8 more when it's taken from the opponent. Bandwidth counts
// half a point per Bandwidth, a card in hand about 2.
export const LOCATION_POINTS = 10;
export const ENEMY_LOCATION_POINTS = 8;
export const RAM_POINTS = 0.5;
export const BANDWIDTH_POINTS = 0.5;
export const LOSS_POINTS = 4;
export const CARD_POINTS = 2;
export function locationValue(v: GameState, p: PlayerId, loc: LocId): number {
if (isStart(loc)) return 0; // starting Servers can't be captured
const taken = v.locations[loc].owner === null ? 0 : ENEMY_LOCATION_POINTS;
return LOCATION_POINTS + taken + v.rules.levelRam[levelFor(p, loc)] * RAM_POINTS;
return LOCATION_POINTS + taken + v.rules.levelBandwidth[levelFor(p, loc)] * BANDWIDTH_POINTS;
}
/** How many Avatars capturing `loc` would unlock for `p` (level unlocks only). */
/** How many Anomalies capturing `loc` would unlock for `p` (level unlocks only). */
export function unlocksAt(v: GameState, p: PlayerId, loc: LocId): number {
if (v.rules.recruit.on || v.rules.buyAvatars.on || isStart(loc)) return 0;
if (v.rules.recruit.on || v.rules.buyAnomalies.on || isStart(loc)) return 0;
const level = levelFor(p, loc);
if (level <= v.players[p].unlockedLevel) return 0;
return v.players[p].avatars.slice(0, Math.min(level, 4)).filter((a) => !a.faceUp).length;
return v.players[p].anomalies.slice(0, Math.min(level, 4)).filter((a) => !a.faceUp).length;
}
/** What losing an Avatar costs: the tempo, plus its Hardware. */
export function avatarStake(v: GameState, r: AvatarRef): number {
return LOSS_POINTS + hardwareOf(v, r).reduce((t, h) => t + (h < 0 ? 0 : defOf(v, h).ram), 0) * RAM_POINTS;
/** What losing an Anomaly costs: the tempo, plus its Hardware. */
export function anomalyStake(v: GameState, r: AnomalyRef): number {
return LOSS_POINTS + hardwareOf(v, r).reduce((t, h) => t + (h < 0 ? 0 : defOf(v, h).bandwidth), 0) * BANDWIDTH_POINTS;
}
// ---------------------------------------------------------------------------------------------
@ -93,7 +93,7 @@ function mixDist(...dists: Map<number, number>[]): Map<number, number> {
}
/** The dice each side of the current combat still has to roll (or has rolled), for the odds. */
function combatDice(v: GameState, reroll?: { ref: AvatarRef; k: number }): { fa: number; ka: number; fd: number; kd: number } {
function combatDice(v: GameState, reroll?: { ref: AnomalyRef; k: number }): { fa: number; ka: number; fd: number; kd: number } {
const c = v.combat!;
let fa = 0;
let ka = 0;
@ -125,7 +125,7 @@ function combatDice(v: GameState, reroll?: { ref: AvatarRef; k: number }): { fa:
* the dice on the table count: Core changes add dice or drop the highest ones, and `reroll` lets a
* fighter reroll its dice showing k or less (Bit Flip).
*/
export function combatOdds(v: GameState, reroll?: { ref: AvatarRef; k: number }): number {
export function combatOdds(v: GameState, reroll?: { ref: AnomalyRef; k: number }): number {
const c = v.combat!;
let atk = 0;
let def = 0;
@ -141,17 +141,17 @@ export function combatOdds(v: GameState, reroll?: { ref: AvatarRef; k: number })
}
/** Health rule: the margin distribution of the current combat, given the dice on the table. */
export function combatDist(v: GameState, reroll?: { ref: AvatarRef; k: number }): Map<number, number> {
export function combatDist(v: GameState, reroll?: { ref: AnomalyRef; k: number }): Map<number, number> {
const { fa, ka, fd, kd } = combatDice(v, reroll);
return marginDist(fa, ka, fd, kd);
}
/**
* Cores each side would have if `ref` attacked `target` from `origin` now, counting what the
* target's Programs do when a combat starts there (Memory Leak, Visual Artifact, Memory Parasite),
* target's Programs do when a combat starts there (Bloatware, Visual Artifact, Memory Parasite),
* and whether Race Condition may add +2 to the defence.
*/
function attackCores(v: GameState, ref: AvatarRef, origin: LocId, target: LocId, bonus: number): { atk: number; def: number; race: boolean } {
function attackCores(v: GameState, ref: AnomalyRef, origin: LocId, target: LocId, bonus: number): { atk: number; def: number; race: boolean } {
let atk = coresOf(v, { ref, role: 'attack', at: origin, loc: target, combat: null }) + bonus;
const defs = defendersAt(v, target);
let def = defs.reduce((t, d) => t + coresOf(v, { ref: d, role: 'defend', at: target, loc: target, combat: null }), 0);
@ -159,7 +159,7 @@ function attackCores(v: GameState, ref: AvatarRef, origin: LocId, target: LocId,
for (const x of sources(v)) {
if (x.at !== target || x.controller === ref.player) continue;
const hw = hardwareOf(v, ref);
if (x.name === 'Memory Leak' && !bugImmune(v, ref, x.controller)) atk -= hw.length;
if (x.name === 'Bloatware' && !bugImmune(v, ref, x.controller)) atk -= hw.length;
if (x.name === 'Visual Artifact' && !v.cards[x.id].spent) atk -= 1;
if (x.name === 'Race Condition') race = true;
if (x.name === 'Memory Parasite') {
@ -171,13 +171,13 @@ function attackCores(v: GameState, ref: AvatarRef, origin: LocId, target: LocId,
}
/** Chance an attack would win the roll if declared now. */
export function attackOdds(v: GameState, ref: AvatarRef, origin: LocId, target: LocId, bonus = 0): number {
export function attackOdds(v: GameState, ref: AnomalyRef, origin: LocId, target: LocId, bonus = 0): number {
const { atk, def, race } = attackCores(v, ref, origin, target, bonus);
return race ? (winChance(atk, def) + winChance(atk, def + 2)) / 2 : winChance(atk, def);
}
/** Health rule: margin distribution of an attack declared now. */
export function attackDist(v: GameState, ref: AvatarRef, origin: LocId, target: LocId, bonus = 0): Map<number, number> {
export function attackDist(v: GameState, ref: AnomalyRef, origin: LocId, target: LocId, bonus = 0): Map<number, number> {
const { atk, def, race } = attackCores(v, ref, origin, target, bonus);
const plain = marginDist(0, atk, 0, def);
return race ? mixDist(plain, marginDist(0, atk, 0, def + 2)) : plain;
@ -192,14 +192,14 @@ export function attackDist(v: GameState, ref: AvatarRef, origin: LocId, target:
export function damageValue(
v: GameState,
me: PlayerId,
attacker: AvatarRef,
defenders: AvatarRef[],
attacker: AnomalyRef,
defenders: AnomalyRef[],
dist: Map<number, number>,
locValue: number,
): number {
const sumLeft = Math.max(1, defenders.reduce((t, d) => t + healthLeft(v, d), 0));
const stakeD = defenders.reduce((t, d) => t + avatarStake(v, d), 0);
const stakeA = avatarStake(v, attacker);
const stakeD = defenders.reduce((t, d) => t + anomalyStake(v, d), 0);
const stakeA = anomalyStake(v, attacker);
const leftA = Math.max(1, healthLeft(v, attacker));
let total = 0;
for (const [m, p] of dist) {
@ -211,18 +211,18 @@ export function damageValue(
/**
* Points for the attacking player from declaring an attack now: under the health rule the expected
* damage value, otherwise the odds of taking the location against losing the Avatar.
* damage value, otherwise the odds of taking the location against losing the Anomaly.
*/
export function attackValue(v: GameState, ref: AvatarRef, origin: LocId, target: LocId, locValue: number, bonus = 0): number {
export function attackValue(v: GameState, ref: AnomalyRef, origin: LocId, target: LocId, locValue: number, bonus = 0): number {
if (!v.rules.health.on) {
const chance = attackOdds(v, ref, origin, target, bonus);
return chance * locValue - (1 - chance) * avatarStake(v, ref);
return chance * locValue - (1 - chance) * anomalyStake(v, ref);
}
return damageValue(v, ref.player, ref, defendersAt(v, target), attackDist(v, ref, origin, target, bonus), locValue);
}
/** Chance `target` falls to this attack: the win odds, or under the health rule the odds of destroying every defender. */
export function fallChance(v: GameState, ref: AvatarRef, origin: LocId, target: LocId, bonus = 0): number {
export function fallChance(v: GameState, ref: AnomalyRef, origin: LocId, target: LocId, bonus = 0): number {
if (!v.rules.health.on) return attackOdds(v, ref, origin, target, bonus);
const need = defendersAt(v, target).reduce((t, d) => t + healthLeft(v, d), 0);
let p = 0;
@ -248,8 +248,8 @@ export function hardwareHealth(v: GameState, hw: number): number {
export function stakes(v: GameState, me: PlayerId): { win: number; lose: number } {
const c = v.combat!;
const loc = locationValue(v, c.attacker.player, c.loc);
const atk = avatarStake(v, c.attacker);
const def = c.defenders.reduce((t, d) => t + avatarStake(v, d), 0);
const atk = anomalyStake(v, c.attacker);
const def = c.defenders.reduce((t, d) => t + anomalyStake(v, d), 0);
return c.attacker.player === me
? { win: loc + def / 2, lose: -atk }
: { win: atk / 2, lose: -(loc + def) };
@ -259,13 +259,13 @@ export function stakes(v: GameState, me: PlayerId): { win: number; lose: number
* Expected points for `me` from the current combat, or from how it ended. `reroll` values a Bit
* Flip of one fighter's dice showing k or less.
*/
export function combatValue(v: GameState, me: PlayerId, reroll?: { ref: AvatarRef; k: number }): number {
export function combatValue(v: GameState, me: PlayerId, reroll?: { ref: AnomalyRef; k: number }): number {
const c = v.combat;
if (!c) return 0;
const iAttack = c.attacker.player === me;
if (c.ended) {
// Ended early: the attacker takes the location only if every defender left.
const taken = c.defenders.length === 0 && avatar(v, c.attacker).at !== null;
const taken = c.defenders.length === 0 && anomaly(v, c.attacker).at !== null;
if (!taken) return 0;
return iAttack ? locationValue(v, me, c.loc) : -locationValue(v, c.attacker.player, c.loc);
}
@ -279,5 +279,5 @@ export function combatValue(v: GameState, me: PlayerId, reroll?: { ref: AvatarRe
}
export const cardName = (v: GameState, id: number): string => (id < 0 ? '' : v.cards[id].name);
export const printedRam = (v: GameState, id: number): number => (id < 0 ? 0 : defOf(v, id).ram);
export const printedBandwidth = (v: GameState, id: number): number => (id < 0 ? 0 : defOf(v, id).bandwidth);
export const scriptFor = (v: GameState, id: number) => scriptOf(cardName(v, id));

View file

@ -8,15 +8,15 @@ import {
firewallCost,
hardwareCost,
openWindow,
avatarForSale,
anomalyForSale,
programCost,
recruitSlots,
} from '../engine.ts';
import { GRID, LINES_AT, LOCATIONS, otherEnd, type LocId } from '../map.ts';
import { avatarRoom, coresOf, hardwareActive, hasRoom, healthLeft, healthOf, portsFree, programSlots, sources } from '../query.ts';
import { anomalyRoom, coresOf, hardwareActive, hasRoom, healthLeft, healthOf, slotsFree, programSlots, sources } from '../query.ts';
import { scriptOf } from '../scripts.ts';
import {
avatar,
anomaly,
canAct,
controls,
defendersAt,
@ -30,11 +30,11 @@ import {
refsInPlay,
removeFrom,
} from '../state.ts';
import type { Action, AvatarRef, Choice, GameState, PlayerId, StackItem } from '../types.ts';
import type { Action, AnomalyRef, Choice, GameState, PlayerId, StackItem } from '../types.ts';
import type { Bot } from './bot.ts';
import {
CARD_POINTS,
RAM_POINTS,
BANDWIDTH_POINTS,
attackOdds,
attackValue,
cardName,
@ -43,7 +43,7 @@ import {
hardwareCores,
hardwareHealth,
locationValue,
printedRam,
printedBandwidth,
unlocksAt,
} from './eval.ts';
@ -53,11 +53,11 @@ export interface GreedyParams {
/** Firewall level used to wall off undefended frontier locations; 0 = never place Firewalls. */
firewallLevel: number;
maxFirewallsPerTurn: number;
/** RAM, counting salvageable cards, kept back after spending in step 6. */
ramReserve: number;
/** Bandwidth, counting salvageable cards, kept back after spending in step 6. */
bandwidthReserve: number;
/** Play Programs, Executions and Abilities. Off plays like the Phase 2 bot: Core Hardware only. */
useCards: boolean;
/** Extra value of a capture per Avatar it unlocks (a location is worth about 12). 0 ignores unlocks. */
/** Extra value of a capture per Anomaly it unlocks (a location is worth about 12). 0 ignores unlocks. */
unlockPoints: number;
}
@ -65,7 +65,7 @@ export const DEFAULT_GREEDY: GreedyParams = {
minWinChance: 0.6,
firewallLevel: 1,
maxFirewallsPerTurn: 2,
ramReserve: 6,
bandwidthReserve: 6,
useCards: true,
unlockPoints: 15,
};
@ -74,17 +74,15 @@ export const DEFAULT_GREEDY: GreedyParams = {
* Board order as seen from `me`'s side. North gets South's order rotated 180°, which maps the
* board onto itself, so tie-breaks never favor a seat.
*/
const REVERSED_GRID = [...GRID].reverse();
const REVERSED_LOCATIONS = [...LOCATIONS].reverse();
const gridFrom = (me: PlayerId) => (me === 0 ? GRID : REVERSED_GRID);
const locationsFrom = (me: PlayerId) => (me === 0 ? LOCATIONS : REVERSED_LOCATIONS);
const gridFrom = (me: PlayerId) => (me === 0 ? GRID : [...GRID].reverse());
const locationsFrom = (me: PlayerId) => (me === 0 ? LOCATIONS : [...LOCATIONS].reverse());
// ---------------------------------------------------------------------------------------------
// How much the bot wants each card
/** Programs by how much they help where they're installed, roughly in points per turn. */
const PROGRAM_WEIGHT: Record<string, number> = {
'Stack Overflow': 4, 'Race Condition': 3, 'Memory Leak': 3, 'Visual Artifact': 2, 'Memory Parasite': 2,
'Stack Overflow': 4, 'Race Condition': 3, 'Bloatware': 3, 'Visual Artifact': 2, 'Memory Parasite': 2,
'Recursive Infection': 2, 'Resource Leech': 2, 'Overflow Error': 2, 'Persistent Infection': 1, 'Stock Rice': 1.5,
'Packet Loss': 1.5, 'Null Pointer': 1.5, Fragmentation: 1, 'Latency Spike': 1, Desynchronization: 0.5,
'False Positive': 0.5, Hotfix: 0.5, 'Version Control': 1.5, 'Compatibility Layer': 1.5, 'Replication Routine': 1,
@ -93,7 +91,7 @@ const PROGRAM_WEIGHT: Record<string, number> = {
};
/** Programs that only matter when an enemy attacks their location. */
const DEFENSIVE = new Set([
'Stack Overflow', 'Race Condition', 'Memory Leak', 'Visual Artifact', 'Memory Parasite', 'Recursive Infection',
'Stack Overflow', 'Race Condition', 'Bloatware', 'Visual Artifact', 'Memory Parasite', 'Recursive Infection',
'Resource Leech', 'Overflow Error', 'Persistent Infection', 'Stock Rice', 'Packet Loss', 'Null Pointer',
'Fragmentation', 'Latency Spike', 'Desynchronization', 'False Positive', 'Version Control', 'Undefined Behavior',
]);
@ -115,7 +113,7 @@ const COMBAT_TRICKS = new Set([
/** How much the bot wants to keep a card rather than salvage it. Below 3 is fodder. */
function keepScore(v: GameState, id: number): number {
const def = defOf(v, id);
if (def.kind === 'avatar') return recruitSlot(v, v.cards[id].owner, id) === null ? 1 : 7;
if (def.kind === 'anomaly') return recruitSlot(v, v.cards[id].owner, id) === null ? 1 : 7;
if (def.kind === 'hardware') {
if (hardwareCores(v, id) > 0 || hardwareHealth(v, id) > 0) return 6;
return (UTILITY_HARDWARE[def.name] ?? 0) * 2;
@ -125,23 +123,23 @@ function keepScore(v: GameState, id: number): number {
return 1.5;
}
/** RAM available this turn, counting cards the bot is willing to salvage. */
/** Bandwidth available this turn, counting cards the bot is willing to salvage. */
function spendable(v: GameState, me: PlayerId): number {
const pl = v.players[me];
return pl.ram + pl.hand.filter((id) => keepScore(v, id) < 3).reduce((t, id) => t + printedRam(v, id), 0);
return pl.bandwidth + pl.hand.filter((id) => keepScore(v, id) < 3).reduce((t, id) => t + printedBandwidth(v, id), 0);
}
/** The salvage that best covers `cost`, never the card being paid for. Null if none is needed or possible. */
function salvageFor(v: GameState, me: PlayerId, cost: number, except: number | null = null): Action | null {
const pl = v.players[me];
const need = cost - pl.ram;
const need = cost - pl.bandwidth;
if (need <= 0) return null;
const hand = pl.hand.filter((id) => id !== except && id >= 0);
if (hand.reduce((t, id) => t + printedRam(v, id), 0) < need) return null;
const order = [...hand].sort((a, b) => keepScore(v, a) - keepScore(v, b) || printedRam(v, b) - printedRam(v, a));
if (hand.reduce((t, id) => t + printedBandwidth(v, id), 0) < need) return null;
const order = [...hand].sort((a, b) => keepScore(v, a) - keepScore(v, b) || printedBandwidth(v, b) - printedBandwidth(v, a));
const fodder = order.filter((id) => keepScore(v, id) < 3);
const from = fodder.reduce((t, id) => t + printedRam(v, id), 0) >= need ? fodder : order;
const card = from.find((id) => printedRam(v, id) >= need) ?? from[0];
const from = fodder.reduce((t, id) => t + printedBandwidth(v, id), 0) >= need ? fodder : order;
const card = from.find((id) => printedBandwidth(v, id) >= need) ?? from[0];
return { type: 'salvage', card };
}
@ -153,18 +151,18 @@ const spentCard = (a: Action): number | null =>
// Recruiting (recruit rule)
/**
* Where the bot would recruit Avatar `id`: an empty slot while there's room, otherwise over a
* weaker Avatar (fewer Cores) that carries no Hardware, preferring one sitting in its slot.
* Where the bot would recruit Anomaly `id`: an empty slot while there's room, otherwise over a
* weaker Anomaly (fewer Cores) that carries no Hardware, preferring one sitting in its slot.
* `taken` are slots already planned this step.
*/
function recruitSlot(v: GameState, me: PlayerId, id: number, taken: number[] = []): number | null {
if (!v.rules.recruit.on) return null;
const avs = v.players[me].avatars;
const avs = v.players[me].anomalies;
const cores = (card: number) => defOf(v, card).cores;
const empty = avs.findIndex((a, i) => i < 4 && a.card < 0 && !taken.includes(i + 1));
const planned = taken.filter((slot) => avs[slot - 1].card < 0).length;
const inUse = avs.filter((a, i) => (i < 4 ? a.card >= 0 : a.at !== null)).length;
if (empty >= 0 && avatarRoom(v, me) && inUse + planned < 4) return empty + 1;
if (empty >= 0 && anomalyRoom(v, me) && inUse + planned < 4) return empty + 1;
const weaker = recruitSlots(v, me)
.filter((slot) => !taken.includes(slot) && avs[slot - 1].card >= 0 && avs[slot - 1].hardware.length === 0)
.filter((slot) => cores(avs[slot - 1].card) < cores(id))
@ -172,15 +170,15 @@ function recruitSlot(v: GameState, me: PlayerId, id: number, taken: number[] = [
return weaker[0] ?? null;
}
/** Recruit the strongest Avatars in hand that fit, within `budget`. */
/** Recruit the strongest Anomalies in hand that fit, within `budget`. */
function recruitPlan(v: GameState, me: PlayerId, budget: number): Action[] {
if (!v.rules.recruit.on) return [];
const hand = v.players[me].hand
.filter((id) => id >= 0 && defOf(v, id).kind === 'avatar')
.filter((id) => id >= 0 && defOf(v, id).kind === 'anomaly')
.sort((a, b) => defOf(v, b).cores - defOf(v, a).cores);
const out: Extract<Action, { type: 'recruit' }>[] = [];
for (const card of hand) {
const price = printedRam(v, card);
const price = printedBandwidth(v, card);
const slot = price <= budget ? recruitSlot(v, me, card, out.map((a) => a.slot)) : null;
if (slot === null) continue;
out.push({ type: 'recruit', card, slot });
@ -190,7 +188,7 @@ function recruitPlan(v: GameState, me: PlayerId, budget: number): Action[] {
}
const reach = (v: GameState, me: PlayerId) =>
v.players[me].ram + v.players[me].hand.reduce((t, id) => t + printedRam(v, id), 0);
v.players[me].bandwidth + v.players[me].hand.reduce((t, id) => t + printedBandwidth(v, id), 0);
// ---------------------------------------------------------------------------------------------
// The board
@ -204,9 +202,9 @@ function threatened(v: GameState, me: PlayerId): LocId[] {
).sort((a, b) => worth(b) - worth(a));
}
/** Avatars `me` can place, advance or attack with this turn. */
function readyAvatars(v: GameState, me: PlayerId): { at: LocId | null; slot: number }[] {
return v.players[me].avatars
/** Anomalies `me` can place, advance or attack with this turn. */
function readyAnomalies(v: GameState, me: PlayerId): { at: LocId | null; slot: number }[] {
return v.players[me].anomalies
.map((a, i) => ({ a, slot: i + 1 }))
.filter(({ a, slot }) => a.faceUp && !a.advanced && a.attacks === 0 &&
(a.at === null || canAct(v, { player: me, slot })))
@ -235,20 +233,20 @@ interface TurnPlan {
attackers: Set<number>;
}
/** Infinite Loop: extra attacks for my Avatars attacking from `loc`. */
/** Infinite Loop: extra attacks for my Anomalies attacking from `loc`. */
const extraAttacksAt = (v: GameState, me: PlayerId, loc: LocId): number =>
Math.max(0, ...sources(v).filter((x) => x.at === loc && x.controller === me).map((x) => scriptOf(x.name)?.extraAttacks ?? 0));
/**
* Deploy-step plan for the whole turn: which Avatars advance, which attack and from where, and
* Deploy-step plan for the whole turn: which Anomalies advance, which attack and from where, and
* where the rest stand guard.
*/
function planTurn(v: GameState, me: PlayerId, params: GreedyParams): TurnPlan {
const pl = v.players[me];
const mine = locationsFrom(me).filter((l) => controls(v, me, l));
const ready = readyAvatars(v, me);
const ready = readyAnomalies(v, me);
const occupant = new Map<LocId, number>();
pl.avatars.forEach((a, i) => {
pl.anomalies.forEach((a, i) => {
if (a.at) occupant.set(a.at, i + 1);
});
for (const { at, slot } of ready) if (at) occupant.set(at, slot);
@ -271,23 +269,23 @@ function planTurn(v: GameState, me: PlayerId, params: GreedyParams): TurnPlan {
const ref = { player: me, slot };
if (freshCopy(v, ref)) continue;
if (!defended) {
// Advancing needs no dice, so prefer weak Avatars and save strong ones for attacks.
// Advancing needs no dice, so prefer weak Anomalies and save strong ones for attacks.
const weakness = 0.01 * coresOf(v, { ref, role: 'attack', at: null, loc: null, combat: null });
options.push({ kind: 'advance', slot, to, clear, score: value - clearCost * RAM_POINTS - weakness });
options.push({ kind: 'advance', slot, to, clear, score: value - clearCost * BANDWIDTH_POINTS - weakness });
continue;
}
const holder = occupant.get(from);
if (holder !== undefined && holder !== slot) continue;
const chance = attackOdds(v, ref, from, to);
if (chance < params.minWinChance) {
// Health rule: a lost roll only costs damage, so a healthy Avatar keeps a long shot in
// Health rule: a lost roll only costs damage, so a healthy Anomaly keeps a long shot in
// reserve for when there's nothing better to do (see below).
if (v.rules.health.on && chance >= 0.25 && healthLeft(v, ref) * 2 >= healthOf(v, ref)) {
longShots.push({ kind: 'attack', slot, to, origin: from, clear, score: chance });
}
continue;
}
const score = attackValue(v, ref, from, to, value) - clearCost * RAM_POINTS;
const score = attackValue(v, ref, from, to, value) - clearCost * BANDWIDTH_POINTS;
options.push({ kind: 'attack', slot, to, origin: from, clear, score });
}
}
@ -371,7 +369,7 @@ function planTurn(v: GameState, me: PlayerId, params: GreedyParams): TurnPlan {
}
}
const busy = new Set(final.map((o) => o.slot));
// Health rule: a badly hurt Avatar with nothing to do goes back to its slot to heal.
// Health rule: a badly hurt Anomaly with nothing to do goes back to its slot to heal.
if (v.rules.health.on && v.rules.health.recall) {
for (const { slot } of ready) {
const cur = pos.get(slot) ?? null;
@ -410,12 +408,12 @@ const inHand = (v: GameState, me: PlayerId, name: string): number | undefined =>
/** How much a performing Server adds: Dedicated GPU power, and a Quantum Coprocessor copy. */
function fromValue(v: GameState, me: PlayerId, from: LocId | null): number {
if (from === null) return 0;
const qc = refsInPlay(v, me).some((r) => avatar(v, r).at === from &&
const qc = refsInPlay(v, me).some((r) => anomaly(v, r).at === from &&
hardwareOf(v, r).some((h) => cardName(v, h) === 'Quantum Coprocessor' && hardwareActive(v, h)));
return executionPower(v, me, from) + (qc ? 0.5 : 0);
}
/** A legal play of a named Execution matching `pick`, ignoring RAM, from the best Server. */
/** A legal play of a named Execution matching `pick`, ignoring Bandwidth, from the best Server. */
function findPlay(v: GameState, me: PlayerId, name: string, pick: (a: Extract<Action, { type: 'play' }>) => boolean): Action | null {
if (inHand(v, me, name) === undefined) return null;
let best: Extract<Action, { type: 'play' }> | null = null;
@ -426,7 +424,7 @@ function findPlay(v: GameState, me: PlayerId, name: string, pick: (a: Extract<Ac
return best;
}
/** A legal use of a named card's Ability matching `pick`, ignoring RAM. */
/** A legal use of a named card's Ability matching `pick`, ignoring Bandwidth. */
function findUse(v: GameState, me: PlayerId, name: string, pick: (a: Extract<Action, { type: 'activate' }>) => boolean = () => true): Action | null {
for (const a of abilityActions(v, me, 'any')) if (a.type === 'activate' && a.name === name && pick(a)) return a;
return null;
@ -453,42 +451,42 @@ function hardwarePlan(v: GameState, me: PlayerId, attackers: Set<number>, budget
const out: Action[] = [];
const wearers = refsInPlay(v, me).filter((r) => !isCopy(r))
.sort((x, y) => Number(attackers.has(y.slot)) - Number(attackers.has(x.slot)));
const ports = new Map(wearers.map((r) => [r.slot, portsFree(v, r)]));
const fights = (r: AvatarRef) => attackers.has(r.slot) || risky.includes(avatar(v, r).at!);
const freeSlots = new Map(wearers.map((r) => [r.slot, slotsFree(v, r)]));
const fights = (r: AnomalyRef) => attackers.has(r.slot) || risky.includes(anomaly(v, r).at!);
const hasExecutions = pl.hand.some((id) => defOf(v, id).kind === 'execution');
// Network Interface Upgrade first, since it opens a port for the rest.
// Network Interface Upgrade first, since it opens an Expansion Slot for the rest.
const niuFirst = (id: number) => (cardName(v, id) === 'Network Interface Upgrade' ? 1 : 0);
const hand = [...pl.hand].sort((a, b) => niuFirst(b) - niuFirst(a) || hardwareCores(v, b) - hardwareCores(v, a));
for (const card of hand) {
const def = defOf(v, card);
if (def.kind !== 'hardware') continue;
const cores = hardwareCores(v, card) + hardwareHealth(v, card);
let target: AvatarRef | undefined;
let target: AnomalyRef | undefined;
if (cores > 0) {
// Core Hardware, and Health Hardware (RAM Expansion), go on Avatars that fight.
// Core Hardware, and Health Hardware (RAM Expansion), go on Anomalies that fight.
const attackOnly = def.name === 'Packet Accelerator';
target = wearers.find((r) => ports.get(r.slot)! > 0 && fights(r) && (!attackOnly || attackers.has(r.slot)));
target = wearers.find((r) => freeSlots.get(r.slot)! > 0 && fights(r) && (!attackOnly || attackers.has(r.slot)));
} else if (def.name === 'Network Interface Upgrade') {
// Adds a port: best on a fighter whose ports are full.
target = [...wearers].sort((x, y) => ports.get(x.slot)! - ports.get(y.slot)!).find((r) => fights(r)) ?? wearers[0];
// Adds an Expansion Slot: best on a fighter whose slots are full.
target = [...wearers].sort((x, y) => freeSlots.get(x.slot)! - freeSlots.get(y.slot)!).find((r) => fights(r)) ?? wearers[0];
} else if (useCards && (UTILITY_HARDWARE[def.name] ?? 0) > 0) {
if (['Dedicated GPU', 'Quantum Coprocessor'].includes(def.name) && !hasExecutions) continue;
const protects = ['Redundant Power Supply', 'RAID Array'].includes(def.name);
target = wearers.find((r) => (protects ? avatar(v, r).hardware.length > 0 && ports.get(r.slot)! > 0 : ports.get(r.slot)! > 1));
target = wearers.find((r) => (protects ? anomaly(v, r).hardware.length > 0 && freeSlots.get(r.slot)! > 0 : freeSlots.get(r.slot)! > 1));
}
if (!target) continue;
const cost = hardwareCost(v, card, target);
if (cost > budget) continue;
budget -= cost;
ports.set(target.slot, ports.get(target.slot)! + (def.name === 'Network Interface Upgrade' ? 1 : -1));
freeSlots.set(target.slot, freeSlots.get(target.slot)! + (def.name === 'Network Interface Upgrade' ? 1 : -1));
out.push({ type: 'installHardware', card, slot: target.slot });
}
return out;
}
/** Negative effects on an Avatar that Error Correction or Purge could clear. */
const afflicted = (v: GameState, r: AvatarRef): boolean => {
const av = avatar(v, r);
/** Negative effects on an Anomaly that Error Correction or Purge could clear. */
const afflicted = (v: GameState, r: AnomalyRef): boolean => {
const av = anomaly(v, r);
return av.infection + av.permanentInfection > 0 || hardwareOf(v, r).some((h) => !hardwareActive(v, h));
};
@ -516,10 +514,10 @@ function programValue(v: GameState, me: PlayerId, name: string, at: LocId, risky
case 'Hotfix':
return here.length > 0 ? w * threat : 0;
case 'Error Correction':
return refsInPlay(v, me).some((r) => avatar(v, r).at === at && afflicted(v, r)) ? 2 : 0;
return refsInPlay(v, me).some((r) => anomaly(v, r).at === at && afflicted(v, r)) ? 2 : 0;
case 'Rollback Routine': {
// Helps my Avatars attacking from here into Programs that cut Cores.
const cutters = enemyNear.some((l) => v.locations[l].programs.some((id) => ['Memory Leak', 'Visual Artifact'].includes(cardName(v, id))));
// Helps my Anomalies attacking from here into Programs that cut Cores.
const cutters = enemyNear.some((l) => v.locations[l].programs.some((id) => ['Bloatware', 'Visual Artifact'].includes(cardName(v, id))));
return guarded && cutters ? w * 1.5 : 0;
}
case 'Payload Injector':
@ -552,7 +550,7 @@ function programPlan(v: GameState, me: PlayerId, budget: number): Action[] {
for (const at of mine) {
if (room.get(at)! <= 0 || v.locations[at].programs.some((id) => cardName(v, id) === name)) continue;
const value = programValue(v, me, name, at, risky);
picks.push({ card, at, value: value - programCost(v, me, card, at) * RAM_POINTS * 0.3 });
picks.push({ card, at, value: value - programCost(v, me, card, at) * BANDWIDTH_POINTS * 0.3 });
}
}
picks.sort((a, b) => b.value - a.value);
@ -571,7 +569,7 @@ function programPlan(v: GameState, me: PlayerId, budget: number): Action[] {
}
/** Enemy Programs that make an attack on `target` harder. */
const HARD_TARGET = new Set(['Stack Overflow', 'Race Condition', 'Memory Leak', 'Visual Artifact', 'Memory Parasite', 'Stock Rice']);
const HARD_TARGET = new Set(['Stack Overflow', 'Race Condition', 'Bloatware', 'Visual Artifact', 'Memory Parasite', 'Stock Rice']);
/** Step 3: switch off a Program that guards a location I'm about to attack, when it's worth it. */
function clearTheWay(v: GameState, me: PlayerId, plan: TurnPlan | null): Action[] {
@ -580,9 +578,9 @@ function clearTheWay(v: GameState, me: PlayerId, plan: TurnPlan | null): Action[
for (const a of plan.attacks) {
if (a.type !== 'attack') continue;
const ref = { player: me, slot: a.slot };
if (avatar(v, ref).at === null) continue; // the planned attacker left play (a copy removed by a recall)
if (anomaly(v, ref).at === null) continue; // the planned attacker left play (a copy removed by a recall)
const origin = [...plan.deploy].reverse().find((d) => d.type === 'place' && d.slot === a.slot);
const from = origin?.type === 'place' ? origin.to : avatar(v, ref).at;
const from = origin?.type === 'place' ? origin.to : anomaly(v, ref).at;
if (!from) continue;
const before = attackOdds(v, ref, from, a.to);
let best: { play: Action; gain: number } | null = null;
@ -603,7 +601,7 @@ function clearTheWay(v: GameState, me: PlayerId, plan: TurnPlan | null): Action[
return out;
}
/** Step 3: extra captures with Trace Route, and cleaning up Avatars before they fight. */
/** Step 3: extra captures with Trace Route, and cleaning up Anomalies before they fight. */
function preAttackPlays(v: GameState, me: PlayerId, plan: TurnPlan | null): Action[] {
const out: Action[] = [];
const planned = new Set(plan?.turn === v.turn ? [...plan.attackers] : []);
@ -613,7 +611,7 @@ function preAttackPlays(v: GameState, me: PlayerId, plan: TurnPlan | null): Acti
for (const a of executionActions(v, me, 'any')) {
if (a.type !== 'play' || a.card !== trace) continue;
const ref = a.args.ref!;
const av = avatar(v, ref);
const av = anomaly(v, ref);
const t = a.target!;
if (planned.has(ref.slot) || av.advanced || av.attacks > 0 || controls(v, me, t)) continue;
// Don't pull a guard off a threatened location.
@ -623,14 +621,14 @@ function preAttackPlays(v: GameState, me: PlayerId, plan: TurnPlan | null): Acti
const bonus = 1 + executionPower(v, me, a.from);
const defended = defendersAt(v, t).length > 0;
const chance = defended ? attackOdds(v, ref, av.at!, t, bonus) : 1;
const score = (defended ? attackValue(v, ref, av.at!, t, value, bonus) : value) - 5 * RAM_POINTS - CARD_POINTS;
const score = (defended ? attackValue(v, ref, av.at!, t, value, bonus) : value) - 5 * BANDWIDTH_POINTS - CARD_POINTS;
if (chance >= 0.6 && score > 0 && (!best || score > best.score)) best = { a, score };
}
if (best) out.push(best.a);
}
// Clean up Avatars carrying Infection or disabled Hardware.
// Clean up Anomalies carrying Infection or disabled Hardware.
for (const r of refsInPlay(v, me)) {
const av = avatar(v, r);
const av = anomaly(v, r);
const disabled = hardwareOf(v, r).filter((h) => !hardwareActive(v, h));
if (av.infection + av.permanentInfection < 2 && disabled.length === 0) continue;
const purge = findPlay(v, me, 'Execute: Purge', (a) => (a.args.to ?? a.target) === av.at);
@ -643,7 +641,7 @@ function preAttackPlays(v: GameState, me: PlayerId, plan: TurnPlan | null): Acti
return out;
}
/** Step 6: card draw, Exfiltrate, Restore Point and Undefined Behavior, when RAM is spare. */
/** Step 6: card draw, Exfiltrate, Restore Point and Undefined Behavior, when Bandwidth is spare. */
function utilityPlays(v: GameState, me: PlayerId, budget: number): Action[] {
const out: Action[] = [];
const add = (a: Action | null, cost: number) => {
@ -658,8 +656,8 @@ function utilityPlays(v: GameState, me: PlayerId, budget: number): Action[] {
// Restore Point: heal a wounded Backup Machine first, otherwise recover a good card.
add(findUse(v, me, 'Backup Machine', (a) => {
if (!a.args.heal) return false;
const ref = refsInPlay(v, me).find((r) => avatar(v, r).card === a.card && !isCopy(r));
return !!ref && avatar(v, ref).damage >= 3;
const ref = refsInPlay(v, me).find((r) => anomaly(v, r).card === a.card && !isCopy(r));
return !!ref && anomaly(v, ref).damage >= 3;
}), 5);
add(findUse(v, me, 'Backup Machine', (a) => {
if (a.args.heal) return false;
@ -668,7 +666,7 @@ function utilityPlays(v: GameState, me: PlayerId, budget: number): Action[] {
}), 5);
// Undefined Behavior: copy a strong defensive Program onto its own location.
add(findUse(v, me, 'Undefined Behavior', (a) =>
['Stack Overflow', 'Race Condition', 'Memory Leak'].includes(cardName(v, a.args.card!))), 0);
['Stack Overflow', 'Race Condition', 'Bloatware'].includes(cardName(v, a.args.card!))), 0);
return out;
}
@ -681,11 +679,11 @@ function firewallPlan(v: GameState, me: PlayerId, params: GreedyParams, budget:
const cost = firewallCost(v, params.firewallLevel);
let left = params.maxFirewallsPerTurn;
for (const loc of threatened(v, me)) {
if (pl.avatars.some((a) => a.at === loc)) continue;
if (pl.anomalies.some((a) => a.at === loc)) continue;
const exposed = LINES_AT.get(loc)!.filter((l) => isOpen(v, l) && controls(v, opp, otherEnd(l, loc)));
// A location reachable along a gateway-free line can't be walled off.
if (exposed.some((l) => !l.gateway) || exposed.length > left) continue;
if (budget - cost * exposed.length < params.ramReserve) break;
if (budget - cost * exposed.length < params.bandwidthReserve) break;
for (const line of exposed) out.push({ type: 'firewall', line: line.id, level: params.firewallLevel });
budget -= cost * exposed.length;
left -= exposed.length;
@ -693,10 +691,10 @@ function firewallPlan(v: GameState, me: PlayerId, params: GreedyParams, budget:
return out;
}
/** RAM to keep for the opponent's turn: enough for the best trick held. */
/** Bandwidth to keep for the opponent's turn: enough for the best trick held. */
function heldReserve(v: GameState, me: PlayerId, params: GreedyParams): number {
if (!params.useCards) return 0;
const held = v.players[me].hand.filter((id) => HELD.has(cardName(v, id))).map((id) => printedRam(v, id));
const held = v.players[me].hand.filter((id) => HELD.has(cardName(v, id))).map((id) => printedBandwidth(v, id));
return Math.max(0, ...held);
}
@ -705,8 +703,8 @@ const totalCost = (v: GameState, list: Action[]) => list.reduce((t, a) => t + ac
function planPlay(v: GameState, me: PlayerId, params: GreedyParams, plan: TurnPlan | null): Action[] {
const budget = spendable(v, me);
const attackers = v.step === 'play' && plan?.turn === v.turn ? plan.attackers : new Set<number>();
const sale = avatarForSale(v, me);
const recruits = [...recruitPlan(v, me, budget), ...(sale && sale.price <= budget ? [{ type: 'buyAvatar', slot: sale.slot } as const] : [])];
const sale = anomalyForSale(v, me);
const recruits = [...recruitPlan(v, me, budget), ...(sale && sale.price <= budget ? [{ type: 'buyAnomaly', slot: sale.slot } as const] : [])];
if (v.step === 'play') {
const early = params.useCards ? [...clearTheWay(v, me, plan), ...preAttackPlays(v, me, plan)] : [];
return [...recruits, ...early, ...hardwarePlan(v, me, attackers, budget - totalCost(v, [...recruits, ...early]), params.useCards)];
@ -714,11 +712,11 @@ function planPlay(v: GameState, me: PlayerId, params: GreedyParams, plan: TurnPl
const keep = heldReserve(v, me, params);
const hw = hardwarePlan(v, me, attackers, budget - keep - totalCost(v, recruits), params.useCards);
let left = budget - keep - totalCost(v, [...recruits, ...hw]);
const progs = params.useCards ? programPlan(v, me, left - params.ramReserve) : [];
const progs = params.useCards ? programPlan(v, me, left - params.bandwidthReserve) : [];
left -= totalCost(v, progs);
const walls = firewallPlan(v, me, params, left);
left -= totalCost(v, walls);
const extra = params.useCards ? utilityPlays(v, me, left - params.ramReserve) : [];
const extra = params.useCards ? utilityPlays(v, me, left - params.bandwidthReserve) : [];
return [...recruits, ...hw, ...progs, ...walls, ...extra];
}
@ -784,7 +782,7 @@ function combatTrick(v: GameState, me: PlayerId): Action | null {
const c = v.combat!;
if (!c.rolled) return null;
const base = combatValue(v, me);
const price = (a: Action) => actionCost(v, a) * RAM_POINTS +
const price = (a: Action) => actionCost(v, a) * BANDWIDTH_POINTS +
(a.type === 'play' || (a.type === 'activate' && a.name === 'Beta Version 1.0') ? CARD_POINTS : 0);
let best: Action | null = null;
let bestGain = 0.25;
@ -798,7 +796,7 @@ function combatTrick(v: GameState, me: PlayerId): Action | null {
for (const a of [...executionActions(v, me, 'reachable'), ...abilityActions(v, me, 'reachable')]) {
if (!touchesCombat(v, a)) continue;
if (a.type === 'activate' && a.name === 'Broken Bits') {
const ref = refsInPlay(v, me).find((r) => avatar(v, r).card === a.card && !isCopy(r))!;
const ref = refsInPlay(v, me).find((r) => anomaly(v, r).card === a.card && !isCopy(r))!;
consider(a, combatValue(v, me, { ref, k: a.args.k! }));
continue;
}
@ -812,14 +810,14 @@ function combatTrick(v: GameState, me: PlayerId): Action | null {
function stopDeclaration(v: GameState, me: PlayerId): Action | null {
const d = v.declarations[v.declarations.length - 1];
if (!d || d.ref.player === me || !controls(v, me, d.to)) return null;
const at = avatar(v, d.ref).at;
const at = anomaly(v, d.ref).at;
if (at === null) return null;
const defended = defendersAt(v, d.to).length > 0;
const risk = defended ? fallChance(v, d.ref, d.from, d.to) : 1;
const stake = risk * locationValue(v, d.ref.player, d.to);
// Root the Avatar that declared, so it can't move.
// Root the Anomaly that declared, so it can't move.
const flood = findPlay(v, me, 'Execute: Packet Flood', (a) => (a.args.to ?? a.target) === at);
if (flood && stake > 5 * RAM_POINTS + CARD_POINTS + 2) return flood;
if (flood && stake > 5 * BANDWIDTH_POINTS + CARD_POINTS + 2) return flood;
if (defended) return null;
// Put a copy in the way.
const replicate = findUse(v, me, 'Carbon NanoBots', (a) => a.args.to === d.to);
@ -829,16 +827,16 @@ function stopDeclaration(v: GameState, me: PlayerId): Action | null {
// Or cash in the Programs there before they're lost.
const progs = v.locations[d.to].programs;
if (progs.length === 0) return null;
const top = Math.max(...progs.map((p) => printedRam(v, p)));
const gc = findUse(v, me, 'Garbage Collection', (a) => programLocation(v, a.args.card!) === d.to && printedRam(v, a.args.card!) === top);
const top = Math.max(...progs.map((p) => printedBandwidth(v, p)));
const gc = findUse(v, me, 'Garbage Collection', (a) => programLocation(v, a.args.card!) === d.to && printedBandwidth(v, a.args.card!) === top);
if (gc) return gc;
const reset = findPlay(v, me, 'Execute: Hard Reset', (a) => a.target === d.to && a.args.cards!.length === progs.length);
return reset && progs.reduce((t, p) => t + printedRam(v, p), 0) >= 8 ? reset : null;
return reset && progs.reduce((t, p) => t + printedBandwidth(v, p), 0) >= 8 ? reset : null;
}
/** Sends back an expensive enemy Program or Hardware installed this turn. */
function rollbackInstall(v: GameState, me: PlayerId): Action | null {
return findPlay(v, me, 'Execute: Rollback', (a) => v.cards[a.args.card!].owner !== me && printedRam(v, a.args.card!) >= 7);
return findPlay(v, me, 'Execute: Rollback', (a) => v.cards[a.args.card!].owner !== me && printedBandwidth(v, a.args.card!) >= 7);
}
// ---------------------------------------------------------------------------------------------
@ -852,22 +850,24 @@ function choose(v: GameState, me: PlayerId, ch: Choice): number {
for (let i = 1; i < opts.length; i++) if (score(i) > score(b)) b = i;
return b;
};
const cardVal = (id: number) => keepScore(v, id) + printedRam(v, id) * 0.2;
const cardVal = (id: number) => keepScore(v, id) + printedBandwidth(v, id) * 0.2;
const yesIfAffordable = (yes: unknown) => {
const i = opts.findIndex((o) => o.value === yes);
return i >= 0 && (opts[i].cost ?? 0) <= v.players[me].ram ? i : opts.findIndex((o) => o.value !== yes);
return i >= 0 && (opts[i].cost ?? 0) <= v.players[me].bandwidth ? i : opts.findIndex((o) => o.value !== yes);
};
switch (ch.kind) {
case 'Callable Server:redraw': {
const card = v.players[me].hand[v.players[me].hand.length - 1];
return opts.findIndex((o) => o.value === (keepScore(v, card) < 2));
// The drawn card, unless it has left the hand since (salvaged while choosing).
const card = (ch.resume.data as { card: number }).card;
const redraw = v.players[me].hand.includes(card) && keepScore(v, card) < 2;
return opts.findIndex((o) => o.value === redraw);
}
case 'Diagnostic Module:bottom': {
const weak = opts.some((o) => /Network Interface|Root Access|Execute: Rollback|Ping Sweep/.test(o.label));
return opts.findIndex((o) => o.value === weak);
}
case 'Duplicate Server:copy': {
const rank = ['Cloud Compute', 'Server Farm', 'MultiCore Server', 'High Efficiency RAM Server', 'Power Server',
const rank = ['Cloud Compute', 'Server Farm', 'MultiCore Server', 'High Bandwidth Server', 'Power Server',
'Cluster Server', 'Pingable Server', 'Backup Server', 'Protected Server'];
return best((i) => -((rank.indexOf(String(val(i))) + 1) || 99));
}
@ -885,7 +885,7 @@ function choose(v: GameState, me: PlayerId, ch: Choice): number {
case 'Overflow Error:hit':
return best((i) => {
const x = val(i) as { card: number; mode: string };
return printedRam(v, x.card) + (x.mode === 'destroy' ? 0.5 : 0);
return printedBandwidth(v, x.card) + (x.mode === 'destroy' ? 0.5 : 0);
});
case 'Error Correction:remove':
return best((i) => {
@ -895,7 +895,7 @@ function choose(v: GameState, me: PlayerId, ch: Choice): number {
});
case 'Version Control:save':
case 'Hardware Sandbox:protect':
return best((i) => printedRam(v, val(i) as number) + (PROGRAM_WEIGHT[cardName(v, val(i) as number)] ?? 0));
return best((i) => printedBandwidth(v, val(i) as number) + (PROGRAM_WEIGHT[cardName(v, val(i) as number)] ?? 0));
case 'RAID Array:keep':
return yesIfAffordable(true);
case 'Backup Machine:install':
@ -906,7 +906,7 @@ function choose(v: GameState, me: PlayerId, ch: Choice): number {
case 'Execute: Memory Dump:discard':
return best((i) => -cardVal(val(i) as number));
case 'Data Leaker:discard':
return best((i) => printedRam(v, val(i) as number));
return best((i) => printedBandwidth(v, val(i) as number));
default:
return 0;
}
@ -932,7 +932,7 @@ export function greedyBot(params: GreedyParams = DEFAULT_GREEDY): Bot {
/** The next action toward `a`: a Salvage to afford it, or `a` itself. Null if it can't happen. */
function toward(v: GameState, me: PlayerId, a: Action, legal: Map<string, Action>): Action | null {
const cost = actionCost(v, a);
if (cost > v.players[me].ram) return salvageFor(v, me, cost, spentCard(a));
if (cost > v.players[me].bandwidth) return salvageFor(v, me, cost, spentCard(a));
return legal.get(actionKey(a)) ?? null;
}
@ -995,7 +995,7 @@ export function greedyBot(params: GreedyParams = DEFAULT_GREEDY): Bot {
while (queue.length > 0) {
const next = queue[0];
const cost = actionCost(v, next);
if (cost > v.players[me].ram) {
if (cost > v.players[me].bandwidth) {
const salvage = salvageFor(v, me, cost, spentCard(next));
if (salvage) return salvage;
queue.shift();

View file

@ -1,22 +1,20 @@
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { parseCsvObjects } from './csv.ts';
export type CardKind = 'avatar' | 'server' | 'program' | 'hardware' | 'execution';
export type CardKind = 'anomaly' | 'server' | 'program' | 'hardware' | 'execution';
export interface CardDef {
name: string;
kind: CardKind;
/** Printed RAM: play cost and salvage value. Avatars and Servers print none. */
ram: number;
/** Printed Bandwidth: play cost and salvage value. Anomalies and Servers print none. */
bandwidth: number;
cores: number;
/** Avatar Health: the damage that destroys it (health rule). 0 when not printed. */
/** Anomaly Health: the damage that destroys it (health rule). 0 when not printed. */
health: number;
/** Expansion Slots (Hardware ports). */
/** Expansion Slots (how much Hardware an Anomaly holds). */
slots: number;
/** V / B / G / P, when printed. */
type: string;
/** Card text; flavor text for Avatars. */
/** Card text; flavor text for Anomalies. */
text: string;
ability?: { name: string; cost: number; text: string };
/** Card set: 1 is the base game, 2 the expansion. Rows without a Set column are set 1. */
@ -29,7 +27,7 @@ export interface CardPool {
}
const KIND_BY_TEMPLATE: Record<string, CardKind> = {
'Avatar Front': 'avatar',
'Anomaly Front': 'anomaly',
'Server Front': 'server',
'Server Front Alt': 'server',
'Program Front': 'program',
@ -37,20 +35,17 @@ const KIND_BY_TEMPLATE: Record<string, CardKind> = {
'Execution Front': 'execution',
};
export const DEFAULT_CARDS_CSV = fileURLToPath(
new URL('../../decks/files-deck-1/cards.csv', import.meta.url),
);
const num = (s: string | undefined): number => (s ? Number(s) : 0);
/**
* Loads the Cider deck CSV. Reference cards (Turn Sequence) are skipped. By default only set 1 (the
* base game) is loaded; `sets` picks others, or 'all'. Set 2 cards have no scripts yet.
* Reads the Cider deck CSV's text. Reference cards (Turn Sequence) are skipped. By default only set
* 1 (the base game) is loaded; `sets` picks others, or 'all'. Set 2 cards have no scripts yet.
* `source` names the file in errors. Node code can use `loadCards` in load.ts to read the file.
*/
export function loadCards(path = DEFAULT_CARDS_CSV, sets: number[] | 'all' = [1]): CardPool {
export function parseCards(csv: string, sets: number[] | 'all' = [1], source = 'cards.csv'): CardPool {
const all: CardDef[] = [];
const byName = new Map<string, CardDef>();
for (const row of parseCsvObjects(readFileSync(path, 'utf8'))) {
for (const row of parseCsvObjects(csv)) {
const kind = KIND_BY_TEMPLATE[row['Front Template']];
if (!kind) continue;
const set = row['Set'] ? Number(row['Set']) : 1;
@ -58,7 +53,7 @@ export function loadCards(path = DEFAULT_CARDS_CSV, sets: number[] | 'all' = [1]
const card: CardDef = {
name: row['Name'],
kind,
ram: num(row['RAM']),
bandwidth: num(row['Bandwidth']),
cores: num(row['Cores']),
health: num(row['Health']),
slots: num(row['Expansion Slots']),
@ -73,7 +68,7 @@ export function loadCards(path = DEFAULT_CARDS_CSV, sets: number[] | 'all' = [1]
text: row['Ability Description'],
};
}
if (byName.has(card.name)) throw new Error(`Duplicate card name in ${path}: ${card.name}`);
if (byName.has(card.name)) throw new Error(`Duplicate card name in ${source}: ${card.name}`);
all.push(card);
byName.set(card.name, card);
}

View file

@ -1,17 +1,17 @@
/**
* Avatar Abilities. Each costs the RAM printed on the card, can be used once per turn at
* Execution timing, and only while the Avatar is in play. For Abilities, "a combat at this
* Server" means any combat the Avatar is fighting in, attacking or defending.
* Anomaly Abilities. Each costs the Bandwidth printed on the card, can be used once per turn at
* Execution timing, and only while the Anomaly is in play. For Abilities, "a combat at this
* Server" means any combat the Anomaly is fighting in, attacking or defending.
*/
import { createCopy, drawCards } from '../flow.ts';
import { LOCATIONS } from '../map.ts';
import { canCopy, costOf, hardwareActive, hasRoom, portsFree } from '../query.ts';
import { canCopy, costOf, hardwareActive, hasRoom, slotsFree } from '../query.ts';
import type { Script } from '../scripts.ts';
import {
addMod,
ask,
avatar,
avatarName,
anomaly,
anomalyName,
copyOf,
defOf,
endOf,
@ -31,27 +31,27 @@ import {
toDiscard,
toHand,
} from '../state.ts';
import type { AvatarRef, GameState } from '../types.ts';
import type { AnomalyRef, GameState } from '../types.ts';
import { attachHardware } from './hardware.ts';
import { cardOptions } from './util.ts';
/** Hardware cost after discounts (Upgraded Hardware), for Abilities that install Hardware. */
const installCost = (s: GameState, card: number, ref: AvatarRef) =>
costOf(s, { kind: 'hardware', player: ref.player, card, ref, at: avatar(s, ref).at });
const installCost = (s: GameState, card: number, ref: AnomalyRef) =>
costOf(s, { kind: 'hardware', player: ref.player, card, ref, at: anomaly(s, ref).at });
export const AVATARS: Record<string, Script> = {
export const ANOMALIES: Record<string, Script> = {
// The copy has the same Cores and uses the original's Hardware bonuses, but no Hardware or
// Ability of its own. It enters play on a location you control with room.
'Carbon NanoBots': {
text: 'Avatar may create a copy of itself. Only one copy is allowed at a time. If the copy is defeated the original does not lose any hardware upgrades. If the original is defeated the replicate is as well.',
text: 'Anomaly may create a copy of itself. Only one copy is allowed at a time. If the copy is defeated the original does not lose any hardware upgrades. If the original is defeated the replicate is as well.',
ability: {
uses(s, src) {
if (avatar(s, copyOf(src.ref!)).at !== null || !canCopy(s, src.controller)) return [];
if (anomaly(s, copyOf(src.ref!)).at !== null || !canCopy(s, src.controller)) return [];
return LOCATIONS.filter((l) => hasRoom(s, src.controller, l)).map((to) => ({ to }));
},
resolve(s, item, src) {
const to = item.args.to!;
if (avatar(s, copyOf(src.ref!)).at !== null || !canCopy(s, src.controller) || !hasRoom(s, src.controller, to)) return;
if (anomaly(s, copyOf(src.ref!)).at !== null || !canCopy(s, src.controller) || !hasRoom(s, src.controller, to)) return;
fired(s, 'Carbon NanoBots', src.controller);
createCopy(s, src.ref!, to);
},
@ -59,7 +59,7 @@ export const AVATARS: Record<string, Script> = {
},
'Corrupt Driver': {
text: 'Choose one Hardware on an enemy Avatar in combat with this Avatar. It is disabled until the end of your next command.',
text: 'Choose one Hardware on an enemy Anomaly in combat with this Anomaly. It is disabled until the end of your next command.',
ability: {
uses: (s, src) =>
[...new Set(opponentsInCombat(s, src.ref!).flatMap((r) => hardwareOf(s, r)))]
@ -75,7 +75,7 @@ export const AVATARS: Record<string, Script> = {
},
'Pixelated Picture': {
text: 'Attacking Avatars have -1 cores against this Avatar.',
text: 'Attacking Anomalies have -1 cores against this Anomaly.',
ability: {
uses: (s, src) => (inCombat(s, src.ref!) && s.combat!.defenders.some((d) => refKey(d) === refKey(src.ref!)) ? [{}] : []),
resolve(s, _item, src) {
@ -83,15 +83,15 @@ export const AVATARS: Record<string, Script> = {
if (!c || c.ended) return;
addMod(s, c.attacker, -1, 'Low Resolution', src.controller, { combat: c.id });
fired(s, 'Pixelated Picture', src.controller);
say(s, `Low Resolution: ${avatarName(s, c.attacker)} gets -1 Core.`);
say(s, `Low Resolution: ${anomalyName(s, c.attacker)} gets -1 Core.`);
},
},
},
// Reading: during a combat it's in, install one Hardware from hand on it (paying its cost),
// ignoring ports. That Hardware is discarded at the end of your turn.
// ignoring Expansion Slots. That Hardware is discarded at the end of your turn.
'Beta Version 1.0': {
text: 'While in combat an additional piece of hardware can be placed on this avatar until the end of your command. If there no ports available this can still be attached.',
text: 'While in combat an additional piece of hardware can be placed on this anomaly until the end of your command. If there are no Expansion Slots available this can still be attached.',
ability: {
uses: (s, src) =>
inCombat(s, src.ref!)
@ -105,28 +105,28 @@ export const AVATARS: Record<string, Script> = {
const turn = s.active === src.controller ? s.turn : nextTurnOf(s, src.controller);
s.cards[card].pushedUntil = endOf(turn);
fired(s, 'Beta Version 1.0', src.controller);
say(s, `Push Update attaches ${nameOf(s, card)} to ${avatarName(s, src.ref!)} until the end of ${playerName(src.controller)}'s turn.`);
say(s, `Push Update attaches ${nameOf(s, card)} to ${anomalyName(s, src.ref!)} until the end of ${playerName(src.controller)}'s turn.`);
},
},
},
'Code Zero': {
text: 'Place an Infection counter on every enemy Avatar in combat at this Server. While this Avatar is in play, an Avatar with 1+ Infection counters has -1 Core.',
globalCores: (s, f) => (infectionOf(avatar(s, f.ref)) >= 1 ? -1 : 0),
text: 'Place an Infection counter on every enemy Anomaly in combat at this Server. While this Anomaly is in play, an Anomaly with 1+ Infection counters has -1 Core.',
globalCores: (s, f) => (infectionOf(anomaly(s, f.ref)) >= 1 ? -1 : 0),
ability: {
uses: (s, src) => (opponentsInCombat(s, src.ref!).length ? [{}] : []),
resolve(s, _item, src) {
const foes = opponentsInCombat(s, src.ref!);
for (const r of foes) avatar(s, r).infection++;
for (const r of foes) anomaly(s, r).infection++;
fired(s, 'Code Zero', src.controller);
say(s, `Patient Zero infects ${foes.map((r) => `${avatarName(s, r)} (${infectionOf(avatar(s, r))})`).join(', ')}.`);
say(s, `Patient Zero infects ${foes.map((r) => `${anomalyName(s, r)} (${infectionOf(anomaly(s, r))})`).join(', ')}.`);
},
},
},
// "Breached a Server" = captured an enemy location this turn.
'Data Leaker': {
text: "Look at your opponent's hand and choose one card in it. They must discard that card without gaining RAM. If this Avatar breached a Server this command, draw a card.",
text: "Look at your opponent's hand and choose one card in it. They must discard that card without gaining Bandwidth. If this Anomaly breached a Server this command, draw a card.",
ability: {
uses: (s, src) => (s.players[other(src.controller)].hand.length ? [{}] : []),
resolve(s, _item, src) {
@ -143,35 +143,35 @@ export const AVATARS: Record<string, Script> = {
},
},
resume: {
discard(s, data: { ref: AvatarRef }, card: number) {
discard(s, data: { ref: AnomalyRef }, card: number) {
const p = data.ref.player;
if (removeFrom(s.players[other(p)].hand, card)) {
toDiscard(s, card);
say(s, `Exfiltrate: ${playerName(other(p))} discards ${nameOf(s, card)}.`);
}
if (avatar(s, data.ref).breachedTurn === s.turn) drawCards(s, p, 1);
if (anomaly(s, data.ref).breachedTurn === s.turn) drawCards(s, p, 1);
},
},
},
// Restore Point either heals 3 damage (health rule) or recovers a card from the discard pile.
'Backup Machine': {
text: 'Remove 3 damage from this Avatar, or return one Hardware or Program from your discard pile to your hand. If it is a Hardware and this Avatar has an open port, you may install it immediately for 2 less RAM.',
text: 'Remove 3 damage from this Anomaly, or return one Hardware or Program from your discard pile to your hand. If it is a Hardware and this Anomaly has an open Expansion Slot, you may install it immediately for 2 less Gb.',
ability: {
uses: (s, src) => [
...(s.rules.health.on && avatar(s, src.ref!).damage > 0 ? [{ heal: true }] : []),
...(s.rules.health.on && anomaly(s, src.ref!).damage > 0 ? [{ heal: true }] : []),
...cardOptions(s, s.players[src.controller].discard.filter((id) => ['hardware', 'program'].includes(defOf(s, id).kind)))
.map((o) => ({ card: o.value as number })),
],
resolve(s, item, src) {
const p = src.controller;
if (item.args.heal) {
const av = avatar(s, src.ref!);
const av = anomaly(s, src.ref!);
if (av.at === null || av.damage === 0) return;
const healed = Math.min(3, av.damage);
av.damage -= healed;
fired(s, 'Backup Machine', p);
say(s, `Restore Point heals ${healed} damage on ${avatarName(s, src.ref!)}.`);
say(s, `Restore Point heals ${healed} damage on ${anomalyName(s, src.ref!)}.`);
return;
}
const card = item.args.card!;
@ -179,34 +179,34 @@ export const AVATARS: Record<string, Script> = {
toHand(s, card);
fired(s, 'Backup Machine', p);
say(s, `Restore Point returns ${nameOf(s, card)} to ${playerName(p)}'s hand.`);
if (defOf(s, card).kind !== 'hardware' || portsFree(s, src.ref!) <= 0) return;
if (defOf(s, card).kind !== 'hardware' || slotsFree(s, src.ref!) <= 0) return;
const cost = Math.max(0, installCost(s, card, src.ref!) - 2);
ask(s, {
player: p,
kind: 'Backup Machine:install',
prompt: `Restore Point: install ${nameOf(s, card)} on ${avatarName(s, src.ref!)} now for ${cost} RAM?`,
prompt: `Restore Point: install ${nameOf(s, card)} on ${anomalyName(s, src.ref!)} now for ${cost} Gb?`,
options: [
{ label: 'Keep it in hand', value: false },
{ label: `Install it for ${cost} RAM`, value: true, cost },
{ label: `Install it for ${cost} Gb`, value: true, cost },
],
resume: { name: 'Backup Machine', fn: 'install', data: { card, ref: src.ref! as never, cost } },
});
},
},
resume: {
install(s, data: { card: number; ref: AvatarRef; cost: number }, yes: boolean) {
if (!yes || avatar(s, data.ref).at === null || !s.players[data.ref.player].hand.includes(data.card)) return;
s.players[data.ref.player].ram -= data.cost;
s.stats.ramOnCards[data.ref.player] += data.cost;
install(s, data: { card: number; ref: AnomalyRef; cost: number }, yes: boolean) {
if (!yes || anomaly(s, data.ref).at === null || !s.players[data.ref.player].hand.includes(data.card)) return;
s.players[data.ref.player].bandwidth -= data.cost;
s.stats.bandwidthOnCards[data.ref.player] += data.cost;
attachHardware(s, data.card, data.ref);
say(s, `${nameOf(s, data.card)} is installed on ${avatarName(s, data.ref)}.`);
say(s, `${nameOf(s, data.card)} is installed on ${anomalyName(s, data.ref)}.`);
},
},
},
// Rerolls this Avatar's dice showing k or less; that's always the best way to pick dice.
// Rerolls this Anomaly's dice showing k or less; that's always the best way to pick dice.
'Broken Bits': {
text: "During a combat at this Server, reroll any number of this Avatar's Core dice.",
text: "During a combat at this Server, reroll any number of this Anomaly's Core dice.",
ability: {
uses(s, src) {
const c = s.combat;

View file

@ -2,7 +2,7 @@
* Executions. Each targets a location (the "target Server") and resolves there, then goes to the
* discard pile. Ghost Process lets its controller's Executions reach one adjacent location too.
*/
import { dropFromCombat, endCombat, moveAvatar } from '../flow.ts';
import { dropFromCombat, endCombat, moveAnomaly } from '../flow.ts';
import { LOCATIONS, isStart } from '../map.ts';
import { canTargetProgram, emit, hardwareActive, hasRoom, programActive } from '../query.ts';
import type { Play, Script } from '../scripts.ts';
@ -11,16 +11,16 @@ import {
addMod,
adjacent,
ask,
avatar,
avatarName,
avatarsAt,
anomaly,
anomalyName,
anomaliesAt,
canAct,
controls,
defendersAt,
endOfTurn,
fightersOf,
fired,
gainRam,
gainBandwidth,
hardwareOf,
inCombat,
later,
@ -47,14 +47,14 @@ import {
uninstallProgram,
wearerOf,
} from '../state.ts';
import { FOREVER, type AvatarRef, type GameState, type PlayerId, type Task } from '../types.ts';
import { FOREVER, type AnomalyRef, type GameState, type PlayerId, type Task } from '../types.ts';
import { shedHardware } from './hardware.ts';
import { cardOptions, ghostsOf, mine, programsOn, scopeOf, subsets } from './util.ts';
const liveCombat = (s: GameState) => (s.combat && !s.combat.ended ? s.combat : null);
/** Unique Avatar refs. */
function uniq(refs: AvatarRef[]): AvatarRef[] {
/** Unique Anomaly refs. */
function uniq(refs: AnomalyRef[]): AnomalyRef[] {
const seen = new Set<string>();
return refs.filter((r) => !seen.has(refKey(r)) && !!seen.add(refKey(r)));
}
@ -73,42 +73,42 @@ function acrossScope(s: GameState, p: PlayerId, argsAt: (loc: string) => Play['a
return out;
}
const wearerList = (s: GameState, hw: number | undefined): AvatarRef[] => {
const wearerList = (s: GameState, hw: number | undefined): AnomalyRef[] => {
const r = hw === undefined ? null : wearerOf(s, hw);
return r ? [r] : [];
};
export const EXECUTIONS: Record<string, Script> = {
// Reading: the Avatar moves to a location you control with room. An attacker "at" the target
// Reading: the Anomaly moves to a location you control with room. An attacker "at" the target
// (attacking it) can retreat back to where it stands.
'Execute: Disconnect': {
text: 'Move one Avatar you control at the target Server to an adjacent Server, removing it from any combat there.',
text: 'Move one Anomaly you control at the target Server to an adjacent Server, removing it from any combat there.',
execution: {
plays: (s, p) =>
acrossScope(s, p, (loc) =>
mine(s, p, loc)
.filter((ref) => canAct(s, ref))
.flatMap((ref) => {
const at = avatar(s, ref).at!;
const at = anomaly(s, ref).at!;
const dests = neighbors(s, loc).filter((d) => d !== at && hasRoom(s, p, d));
if (inCombat(s, ref) && at !== loc) dests.push(at);
return dests.map((to) => ({ ref, to }));
})),
targetsAvatars: (_s, item) => (item.args.ref ? [item.args.ref] : []),
targetsAnomalies: (_s, item) => (item.args.ref ? [item.args.ref] : []),
resolve(s, item) {
const { ref, to } = item.args as { ref: AvatarRef; to: string };
const av = avatar(s, ref);
const { ref, to } = item.args as { ref: AnomalyRef; to: string };
const av = anomaly(s, ref);
if (av.at === null || !canAct(s, ref) || (to !== av.at && !hasRoom(s, ref.player, to))) return;
fired(s, item.name, item.player);
if (inCombat(s, ref)) dropFromCombat(s, ref);
if (to !== av.at) moveAvatar(s, ref, to);
if (to !== av.at) moveAnomaly(s, ref, to);
},
},
},
// Reading: an unspecified disable lasts until something re-enables it (Execute: Defragment).
'Execute: Sabotage': {
text: 'Destroy or disable one Hardware on an enemy Avatar in combat at the target Server.',
text: 'Destroy or disable one Hardware on an enemy Anomaly in combat at the target Server.',
execution: {
plays(s, p) {
const c = liveCombat(s);
@ -120,7 +120,7 @@ export const EXECUTIONS: Record<string, Script> = {
...(hardwareActive(s, card) ? [{ target, args: { card, mode: 'disable' as const } }] : []),
]));
},
targetsAvatars: (s, item) => wearerList(s, item.args.card),
targetsAnomalies: (s, item) => wearerList(s, item.args.card),
resolve(s, item) {
const hw = item.args.card!;
const owner = wearerOf(s, hw);
@ -156,10 +156,10 @@ export const EXECUTIONS: Record<string, Script> = {
},
},
// Ruling: Servers perform Executions, so "that Avatar cannot play another Execution" stops the
// Ruling: Servers perform Executions, so "that Anomaly cannot play another Execution" stops the
// Server it stands on from performing Executions for the rest of the turn.
'Execute: Force Reboot': {
text: 'Remove all temporary bonuses and penalties from one Avatar you control at the target Server, or one Avatar attacking it. That Avatar cannot play another Execution until end of current command.',
text: 'Remove all temporary bonuses and penalties from one Anomaly you control at the target Server, or one Anomaly attacking it. That Anomaly cannot play another Execution until end of current command.',
execution: {
plays: (s, p) =>
acrossScope(s, p, (loc) => {
@ -167,17 +167,17 @@ export const EXECUTIONS: Record<string, Script> = {
const attacker = c && c.loc === loc ? [c.attacker] : [];
return uniq([...mine(s, p, loc), ...attacker]).map((ref) => ({ ref }));
}),
targetsAvatars: (_s, item) => (item.args.ref ? [item.args.ref] : []),
targetsAnomalies: (_s, item) => (item.args.ref ? [item.args.ref] : []),
resolve(s, item) {
const ref = item.args.ref!;
const av = avatar(s, ref);
const av = anomaly(s, ref);
if (av.at === null) return;
const live = activeMods(s, av);
av.mods = av.mods.filter((m) => !live.includes(m));
// Servers perform Executions: the Server this Avatar stands on can't for the rest of the turn.
// Servers perform Executions: the Server this Anomaly stands on can't for the rest of the turn.
markUsed(s, `noExec:${av.at}`);
fired(s, item.name, item.player);
say(s, `Force Reboot clears ${live.length} temporary effect(s) from ${avatarName(s, ref)}.`);
say(s, `Force Reboot clears ${live.length} temporary effect(s) from ${anomalyName(s, ref)}.`);
},
},
},
@ -213,7 +213,7 @@ export const EXECUTIONS: Record<string, Script> = {
// Reading: resolves right away, only while no combat is going on. Into your own location it's a
// move; into an unowned or undefended one it's a capture; into a defended one it's an attack.
'Execute: Trace Route': {
text: 'Move one Avatar you control from an adjacent Server to the target Server. If the target Server is enemy-controlled, your Avatar attacks it with +1 Core for the resulting combat.',
text: 'Move one Anomaly you control from an adjacent Server to the target Server. If the target Server is enemy-controlled, your Anomaly attacks it with +1 Core for the resulting combat.',
execution: {
plays(s, p) {
if (liveCombat(s)) return [];
@ -223,22 +223,22 @@ export const EXECUTIONS: Record<string, Script> = {
const mineThere = controls(s, p, target);
if (mineThere && !hasRoom(s, p, target)) continue;
for (const ref of refsInPlay(s, p)) {
const at = avatar(s, ref).at!;
const at = anomaly(s, ref).at!;
if (at !== target && canAct(s, ref) && adjacent(s, at, target)) out.push({ target, args: { ref } });
}
}
return out;
},
targetsAvatars: (_s, item) => (item.args.ref ? [item.args.ref] : []),
targetsAnomalies: (_s, item) => (item.args.ref ? [item.args.ref] : []),
resolve(s, item) {
const ref = item.args.ref!;
const t = item.target!;
const av = avatar(s, ref);
const av = anomaly(s, ref);
if (av.at === null || !canAct(s, ref) || !adjacent(s, av.at, t) || liveCombat(s)) return;
const owner = s.locations[t].owner;
fired(s, item.name, item.player);
if (owner === item.player) {
if (hasRoom(s, item.player, t)) moveAvatar(s, ref, t);
if (hasRoom(s, item.player, t)) moveAnomaly(s, ref, t);
} else if (owner === null) {
pushCapture(s, ref, t, 'capturesUnowned');
} else if (defendersAt(s, t).length === 0) {
@ -307,10 +307,10 @@ export const EXECUTIONS: Record<string, Script> = {
plays: (s, p) =>
acrossScope(s, p, (loc) => {
const progs = s.locations[loc].programs.filter((id) => s.cards[id].installedTurn === s.turn && canTargetProgram(s, id, p));
const hws = [...new Set(avatarsAt(s, loc).flatMap((r) => avatar(s, r).hardware))].filter((id) => s.cards[id].installedTurn === s.turn);
const hws = [...new Set(anomaliesAt(s, loc).flatMap((r) => anomaly(s, r).hardware))].filter((id) => s.cards[id].installedTurn === s.turn);
return [...progs, ...hws].map((card) => ({ card }));
}),
targetsAvatars: (s, item) => wearerList(s, item.args.card),
targetsAnomalies: (s, item) => wearerList(s, item.args.card),
resolve(s, item) {
const card = item.args.card!;
const wearer = wearerOf(s, card);
@ -335,28 +335,28 @@ export const EXECUTIONS: Record<string, Script> = {
},
},
// Rooted Avatars can't advance, attack, reposition, or be moved; their declared moves fail.
// Rooted Anomalies can't advance, attack, reposition, or be moved; their declared moves fail.
'Execute: Packet Flood': {
text: "Avatars based at the target Server cannot move or retreat until the start of their controller's next command.",
text: "Anomalies based at the target Server cannot move or retreat until the start of their controller's next command.",
execution: {
plays: (s, p) => acrossScope(s, p, (loc) => (avatarsAt(s, loc).length ? [{ to: loc }] : [])),
plays: (s, p) => acrossScope(s, p, (loc) => (anomaliesAt(s, loc).length ? [{ to: loc }] : [])),
resolve(s, item) {
const loc = item.args.to ?? item.target!;
const here = avatarsAt(s, loc);
const here = anomaliesAt(s, loc);
if (here.length === 0) return;
for (const r of here) {
const av = avatar(s, r);
const av = anomaly(s, r);
av.rootedUntil = Math.max(av.rootedUntil, startOf(nextTurnOf(s, r.player)));
}
fired(s, item.name, item.player);
say(s, `Packet Flood: ${here.map((r) => avatarName(s, r)).join(', ')} can't move.`);
say(s, `Packet Flood: ${here.map((r) => anomalyName(s, r)).join(', ')} can't move.`);
},
},
},
// Reading: Disabled Avatars still defend, but can't advance, attack, move or use Abilities.
// Reading: Disabled Anomalies still defend, but can't advance, attack, move or use Abilities.
'Execute: Emergency Shutdown': {
text: 'End any combat at the target Server immediately. All Avatars there remain and become Disabled until end of current command.',
text: 'End any combat at the target Server immediately. All Anomalies there remain and become Disabled until end of current command.',
execution: {
plays(s, p) {
const c = liveCombat(s);
@ -365,9 +365,9 @@ export const EXECUTIONS: Record<string, Script> = {
resolve(s, item) {
const c = liveCombat(s);
if (!c || !scopeOf(s, item.player, item.target!).includes(c.loc)) return;
const everyone = uniq([...fightersOf(c), ...avatarsAt(s, c.loc)]);
const everyone = uniq([...fightersOf(c), ...anomaliesAt(s, c.loc)]);
endCombat(s, 'Emergency Shutdown');
for (const r of everyone) avatar(s, r).disabledUntil = Math.max(avatar(s, r).disabledUntil, endOfTurn(s));
for (const r of everyone) anomaly(s, r).disabledUntil = Math.max(anomaly(s, r).disabledUntil, endOfTurn(s));
fired(s, item.name, item.player);
},
},
@ -392,12 +392,12 @@ export const EXECUTIONS: Record<string, Script> = {
},
'Execute: Defragment': {
text: 'Re-enable one Disabled Program on the target Server, or one Disabled Hardware on an Avatar there.',
text: 'Re-enable one Disabled Program on the target Server, or one Disabled Hardware on an Anomaly there.',
execution: {
plays: (s, p) =>
acrossScope(s, p, (loc) => {
const progs = s.locations[loc].programs.filter((id) => running(s, s.cards[id].disabledUntil));
const hws = [...new Set(avatarsAt(s, loc).flatMap((r) => hardwareOf(s, r)))].filter((id) => !hardwareActive(s, id));
const hws = [...new Set(anomaliesAt(s, loc).flatMap((r) => hardwareOf(s, r)))].filter((id) => !hardwareActive(s, id));
return [...progs, ...hws].map((card) => ({ card }));
}),
resolve(s, item) {
@ -430,7 +430,7 @@ export const EXECUTIONS: Record<string, Script> = {
},
'Execute: Purge': {
text: 'Remove all Virus/Infection counters and hostile persistent effects from every Avatar you control at the target Server.',
text: 'Remove all Virus/Infection counters and hostile persistent effects from every Anomaly you control at the target Server.',
execution: {
plays: (s, p) =>
acrossScope(s, p, (loc) => (mine(s, p, loc).some((r) => hasNegatives(s, r)) ? [{ to: loc }] : [])),
@ -438,7 +438,7 @@ export const EXECUTIONS: Record<string, Script> = {
const loc = item.args.to ?? item.target!;
const here = mine(s, item.player, loc);
for (const r of here) {
const av = avatar(s, r);
const av = anomaly(s, r);
av.infection = 0;
av.permanentInfection = 0;
av.mods = av.mods.filter((m) => m.cores >= 0 || m.by === item.player);
@ -447,13 +447,13 @@ export const EXECUTIONS: Record<string, Script> = {
for (const hw of hardwareOf(s, r)) s.cards[hw].disabledUntil = 0;
}
fired(s, item.name, item.player);
say(s, `Purge cleans ${here.map((r) => avatarName(s, r)).join(', ')}.`);
say(s, `Purge cleans ${here.map((r) => anomalyName(s, r)).join(', ')}.`);
},
},
},
'Execute: Hard Reset': {
text: 'Uninstall any number of Programs from the target Server you control. For each card returned to your hand this way, recover 1 RAM.',
text: 'Uninstall any number of Programs from the target Server you control. For each card returned to your hand this way, recover 1 Gb.',
execution: {
plays: (s, p) =>
LOCATIONS.filter((t) => controls(s, p, t) && s.locations[t].programs.length > 0).flatMap((target) =>
@ -464,9 +464,9 @@ export const EXECUTIONS: Record<string, Script> = {
uninstallProgram(s, id);
toHand(s, id);
}
gainRam(s, item.player, back.length * (1 + item.power));
gainBandwidth(s, item.player, back.length * (1 + item.power));
fired(s, item.name, item.player);
say(s, `Hard Reset returns ${back.map((id) => nameOf(s, id)).join(', ')} to hand (+${back.length * (1 + item.power)} RAM).`);
say(s, `Hard Reset returns ${back.map((id) => nameOf(s, id)).join(', ')} to hand (+${back.length * (1 + item.power)} Gb).`);
},
},
},
@ -476,8 +476,8 @@ function drawN(s: GameState, p: PlayerId, n: number): void {
pushTasks(s, ...Array.from({ length: n }, (): Task => ({ t: 'draw', player: p })));
}
function hasNegatives(s: GameState, r: AvatarRef): boolean {
const av = avatar(s, r);
function hasNegatives(s: GameState, r: AnomalyRef): boolean {
const av = anomaly(s, r);
return av.infection > 0 || av.permanentInfection > 0 || running(s, av.rootedUntil) || running(s, av.disabledUntil) ||
activeMods(s, av).some((m) => m.cores < 0) || hardwareOf(s, r).some((hw) => !hardwareActive(s, hw));
}

View file

@ -2,13 +2,14 @@
* Hardware. It works while its wearer is in play. "The occupied Server" is the location the
* wearer stands on.
*/
import { describeArgs } from '../describe.ts';
import { knockOut } from '../flow.ts';
import { desynced, hardwareActive, portsFit, takesPort } from '../query.ts';
import { desynced, hardwareActive, slotsFit, takesSlot } from '../query.ts';
import { scriptOf, type Script } from '../scripts.ts';
import {
ask,
avatar,
avatarName,
anomaly,
anomalyName,
defOf,
fired,
isCopy,
@ -30,12 +31,12 @@ import {
usedThisTurn,
wearerOf,
} from '../state.ts';
import type { AvatarRef, GameState, LocationState, PlayerId, StackItem } from '../types.ts';
import type { AnomalyRef, GameState, LocationState, PlayerId, StackItem } from '../types.ts';
import { cardOptions, programsOn } from './util.ts';
/**
* Uses a Hardware card has left this turn. Its "once per turn" or "first ... each turn" effect gets
* one use, or two when Cooling System on the same Avatar picks it (Cooling helps one Hardware a turn).
* one use, or two when Cooling System on the same Anomaly picks it (Cooling helps one Hardware a turn).
*/
export function hardwareUsesLeft(s: GameState, hw: number): number {
const used = usedThisTurn(s, `hw:${hw}`);
@ -46,7 +47,7 @@ export function hardwareUsesLeft(s: GameState, hw: number): number {
function coolerFor(s: GameState, hw: number): number | null {
const ref = wearerOf(s, hw);
if (!ref) return null;
for (const id of avatar(s, ref).hardware) {
for (const id of anomaly(s, ref).hardware) {
if (id === hw || s.cards[id].name !== 'Cooling System' || !hardwareActive(s, id)) continue;
const pickedFor = s.used[`cool:${id}`];
if (pickedFor === undefined || pickedFor === hw) return id;
@ -55,16 +56,16 @@ function coolerFor(s: GameState, hw: number): number | null {
}
/**
* Reading: an Avatar that loses a port (Network Interface Upgrade removed) discards Hardware until it
* Reading: an Anomaly that loses an Expansion Slot (Network Interface Upgrade removed) discards Hardware until it
* fits, the most recently installed first.
*/
export function shedHardware(s: GameState, r: AvatarRef): void {
while (!portsFit(s, r)) {
const hw = avatar(s, r).hardware.findLast((id) => takesPort(s, id))!;
export function shedHardware(s: GameState, r: AnomalyRef): void {
while (!slotsFit(s, r)) {
const hw = anomaly(s, r).hardware.findLast((id) => takesSlot(s, id))!;
uninstallHardware(s, hw);
toDiscard(s, hw);
stat(s, 'hardwareLost', r.player);
say(s, `${avatarName(s, r)} is out of ports and discards ${nameOf(s, hw)}.`);
say(s, `${anomalyName(s, r)} is out of Expansion Slots and discards ${nameOf(s, hw)}.`);
}
}
@ -77,13 +78,13 @@ export function useHardware(s: GameState, hw: number): void {
}
}
const wearing = (ref: AvatarRef | undefined, f: { ref: AvatarRef }) =>
const wearing = (ref: AnomalyRef | undefined, f: { ref: AnomalyRef }) =>
!!ref && ref.player === f.ref.player && (ref.slot === f.ref.slot || ref.slot + 4 === f.ref.slot);
/** Installs a Hardware card from its owner's hand onto an Avatar, without paying. */
export function attachHardware(s: GameState, card: number, ref: AvatarRef): void {
/** Installs a Hardware card from its owner's hand onto an Anomaly, without paying. */
export function attachHardware(s: GameState, card: number, ref: AnomalyRef): void {
removeFrom(s.players[ref.player].hand, card);
avatar(s, ref).hardware.push(card);
anomaly(s, ref).hardware.push(card);
s.cards[card].installedTurn = s.turn;
stat(s, 'hardwareInstalled', ref.player);
played(s, nameOf(s, card), ref.player);
@ -92,18 +93,18 @@ export function attachHardware(s: GameState, card: number, ref: AvatarRef): void
export const HARDWARE: Record<string, Script> = {
// Health rule: the wearer's Health goes up by 2 (query.ts healthOf). Without the rule it does nothing.
'RAM Expansion': {
text: 'Avatar gains +2 Health.',
text: 'Anomaly gains +2 Health.',
health: 2,
},
'Additional Core': {
text: 'Avatar gains +1 Core.',
text: 'Anomaly gains +1 Core.',
cores: () => 1,
},
// Reading: the Program is one on the location the wearer fought from, the owner picks it, and it
// stays disabled through the end of the next turn.
'Overclocked CPU': {
text: 'Avatar gains +2 Cores during combat, but one installed Program at the current server becomes disabled afterward for 2 commands.',
text: 'Anomaly gains +2 Cores during combat, but one installed Program at the current server becomes disabled afterward for 2 commands.',
cores: (_s, _src, f) => (f.role !== null ? 2 : 0),
onCombatEnd(s, src) {
const c = s.combat!;
@ -132,7 +133,7 @@ export const HARDWARE: Record<string, Script> = {
},
'Solid-State Cache': {
text: 'The first Program installed on the occupied Server each round costs 3 less RAM.',
text: 'The first Program installed on the occupied Server each round costs 3 less Gb.',
costMod: (s, src, pay) =>
pay.kind === 'program' && pay.player === src.controller && pay.at === src.at && hardwareUsesLeft(s, src.id) > 0 ? -3 : 0,
onPaid(s, src) {
@ -144,36 +145,36 @@ export const HARDWARE: Record<string, Script> = {
// Reading: the first time the wearer is defeated with this installed, all its Hardware stays on
// it (in its slot) instead of being discarded.
'Redundant Power Supply': {
text: 'The first time this Avatar would be destroyed, do not destroy the Hardware.',
text: 'The first time this Anomaly would be destroyed, do not destroy the Hardware.',
savePriority: 0,
onWearerDefeated(s, hw, ev) {
if (s.cards[hw].spent) return false;
s.cards[hw].spent = true;
fired(s, 'Redundant Power Supply', ev.ref.player);
say(s, `Redundant Power Supply: ${avatarName(s, ev.ref)} keeps its Hardware.`);
say(s, `Redundant Power Supply: ${anomalyName(s, ev.ref)} keeps its Hardware.`);
knockOut(s, ev.ref, ev.loc, ev.role, true);
return true;
},
},
// Ruling: it takes no port and adds one, so the wearer nets +1 Expansion Slot.
// Ruling: it takes no Expansion Slot and adds one, so the wearer nets +1 Expansion Slot.
'Network Interface Upgrade': {
text: 'This Hardware can be played without taking an upgrade port on the Avatar.',
noPort: true,
text: 'This Hardware can be played without taking an Expansion Slot on the Anomaly.',
noSlot: true,
extraSlots: 1,
},
// Ruling: Servers perform Executions, so this works for Executions performed by the Server the
// wearer stands on. +1 to the number the Execution uses (cards drawn, Cores, RAM recovered).
// wearer stands on. +1 to the number the Execution uses (cards drawn, Cores, Bandwidth recovered).
'Dedicated GPU': {
text: 'Executions performed by this Avatar receive +1 effectiveness or combat strength.',
text: 'Executions performed by this Anomaly receive +1 effectiveness or combat strength.',
executionPower: 1,
},
// Blocks opponents' Bug counters (see addBugs in util.ts; no card places them yet) and their
// Bug Program effects on the wearer (Memory Leak, Stock Rice).
// Bug Program effects on the wearer (Bloatware, Stock Rice).
'ECC Memory': {
text: 'Opponents cannot place Bug counters or Bug status effects on this Avatar.',
text: 'Opponents cannot place Bug counters or Bug status effects on this Anomaly.',
bugImmunity: true,
},
@ -182,19 +183,19 @@ export const HARDWARE: Record<string, Script> = {
text: 'Allow one Hardware to activate twice per round.',
},
// Reading: half the combined printed RAM of its Hardware, rounded up.
// Reading: half the combined printed Bandwidth of its Hardware, rounded up.
'RAID Array': {
text: 'When this Avatar is destroyed, all hardware can be kept by paying half the RAM cost.',
text: 'When this Anomaly is destroyed, all hardware can be kept by paying half the Bandwidth cost.',
savePriority: 1,
onWearerDefeated(s, hw, ev) {
const av = avatar(s, ev.ref);
const cost = Math.ceil(av.hardware.reduce((t, h) => t + defOf(s, h).ram, 0) / 2);
const av = anomaly(s, ev.ref);
const cost = Math.ceil(av.hardware.reduce((t, h) => t + defOf(s, h).bandwidth, 0) / 2);
ask(s, {
player: ev.ref.player,
kind: 'RAID Array:keep',
prompt: `RAID Array: pay ${cost} RAM to keep ${av.hardware.map((h) => nameOf(s, h)).join(', ')}?`,
prompt: `RAID Array: pay ${cost} Gb to keep ${av.hardware.map((h) => nameOf(s, h)).join(', ')}?`,
options: [
{ label: `Keep all Hardware for ${cost} RAM`, value: true, cost },
{ label: `Keep all Hardware for ${cost} Gb`, value: true, cost },
{ label: 'Lose the Hardware', value: false },
],
resume: { name: 'RAID Array', fn: 'keep', data: { ref: ev.ref as never, loc: ev.loc, role: ev.role, cost } },
@ -202,10 +203,10 @@ export const HARDWARE: Record<string, Script> = {
return true;
},
resume: {
keep(s, data: { ref: AvatarRef; loc: string; role: 'attack' | 'defend'; cost: number }, keep: boolean) {
keep(s, data: { ref: AnomalyRef; loc: string; role: 'attack' | 'defend'; cost: number }, keep: boolean) {
if (keep) {
s.players[data.ref.player].ram -= data.cost;
stat(s, 'ramOnCards', data.ref.player, data.cost);
s.players[data.ref.player].bandwidth -= data.cost;
stat(s, 'bandwidthOnCards', data.ref.player, data.cost);
fired(s, 'RAID Array', data.ref.player);
}
knockOut(s, data.ref, data.loc, data.role, keep);
@ -214,13 +215,13 @@ export const HARDWARE: Record<string, Script> = {
},
'Packet Accelerator': {
text: 'This Avatar gains +1 Core hen attacking.',
text: 'This Anomaly gains +1 Core hen attacking.',
cores: (_s, _src, f) => (f.role === 'attack' ? 1 : 0),
},
// Programs never target Avatars, so this taxes Executions (and Hardware they hit).
// Programs never target Anomalies, so this taxes Executions (and Hardware they hit).
'Firewall Appliance': {
text: 'The first hostile Program or Execution targeting this Avatar each round costs the opponent +3 RAM.',
text: 'The first hostile Program or Execution targeting this Anomaly each round costs the opponent +3 Gb.',
costMod: (s, src, pay) =>
pay.kind === 'execution' && pay.player !== src.controller && hardwareUsesLeft(s, src.id) > 0 &&
(pay.hostile ?? []).some((r) => wearing(src.ref, { ref: r })) ? 3 : 0,
@ -262,6 +263,7 @@ export const HARDWARE: Record<string, Script> = {
ask(s, {
player: src.controller,
kind: 'Diagnostic Module:bottom',
secret: true,
prompt: `Diagnostic Module: the top card of your deck is ${nameOf(s, deck[0])}. Put it on the bottom?`,
options: [
{ label: `Keep ${nameOf(s, deck[0])} on top`, value: false },
@ -278,44 +280,44 @@ export const HARDWARE: Record<string, Script> = {
},
},
// Reading: swap Hardware on this Avatar, paying the difference in printed RAM (no refund).
// Reading: swap Hardware on this Anomaly, paying the difference in printed Bandwidth (no refund).
'Hot-Swap Bay': {
text: 'Once per round, return one Hardware to your hand and install another Hardware from your hand, paying the difference in cost.',
ability: {
hardwareOncePerTurn: true,
uses(s, src) {
const av = avatar(s, src.ref!);
const av = anomaly(s, src.ref!);
const hand = s.players[src.controller].hand.filter((id) => defOf(s, id).kind === 'hardware');
return av.hardware.flatMap((out) => cardOptions(s, hand)
.filter((o) => portsFit(s, src.ref!, out, o.value as number))
.filter((o) => slotsFit(s, src.ref!, out, o.value as number))
.map((o) => ({ card: out, cards: [o.value as number] })));
},
extraCost: (s, _src, args) => Math.max(0, defOf(s, args.cards![0]).ram - defOf(s, args.card!).ram),
extraCost: (s, _src, args) => Math.max(0, defOf(s, args.cards![0]).bandwidth - defOf(s, args.card!).bandwidth),
resolve(s, item, src) {
const out = item.args.card!;
const into = item.args.cards![0];
const ref = src.ref!;
if (!avatar(s, ref).hardware.includes(out) || !s.players[src.controller].hand.includes(into)) return;
if (!portsFit(s, ref, out, into)) return;
if (!anomaly(s, ref).hardware.includes(out) || !s.players[src.controller].hand.includes(into)) return;
if (!slotsFit(s, ref, out, into)) return;
uninstallHardware(s, out);
toHand(s, out);
attachHardware(s, into, ref);
fired(s, 'Hot-Swap Bay', src.controller);
say(s, `Hot-Swap Bay swaps ${nameOf(s, out)} for ${nameOf(s, into)} on ${avatarName(s, ref)}.`);
say(s, `Hot-Swap Bay swaps ${nameOf(s, out)} for ${nameOf(s, into)} on ${anomalyName(s, ref)}.`);
},
},
},
// Ruling: Servers perform Executions, so "this Avatar uses an Execution" means one performed by
// Ruling: Servers perform Executions, so "this Anomaly uses an Execution" means one performed by
// the Server the wearer stands on. "Disable this Hardware" lasts until your next turn.
'Quantum Coprocessor': {
text: "Once per round when this Avatar uses an Execution, you may copy that Execution's effect with a different legal target, then disable this Hardware.",
text: "Once per round when this Anomaly uses an Execution, you may copy that Execution's effect with a different legal target, then disable this Hardware.",
copiesExecutions: true,
resume: {
offer(s, data: { item: StackItem }) {
const item = data.item;
const wearers = refsInPlay(s, item.player).filter((r) => !isCopy(r) && avatar(s, r).at === item.from && !desynced(s, r));
const qc = wearers.flatMap((r) => avatar(s, r).hardware)
const wearers = refsInPlay(s, item.player).filter((r) => !isCopy(r) && anomaly(s, r).at === item.from && !desynced(s, r));
const qc = wearers.flatMap((r) => anomaly(s, r).hardware)
.find((hw) => s.cards[hw].name === 'Quantum Coprocessor' && hardwareActive(s, hw) && hardwareUsesLeft(s, hw) > 0);
if (qc === undefined) return;
const ex = scriptOf(item.name)?.execution;
@ -329,7 +331,7 @@ export const HARDWARE: Record<string, Script> = {
prompt: `Quantum Coprocessor: copy ${item.name} with a different target?`,
options: [
{ label: "Don't copy", value: null },
...plays.map((p) => ({ label: `${p.target ?? 'no target'} ${describeArgs(s, p.args)}`, value: { target: p.target, args: p.args as never } })),
...plays.map((p) => ({ label: `${p.target ?? 'no target'} ${describeArgs(s, p.args, item.player)}`, value: { target: p.target, args: p.args as never } })),
],
resume: { name: 'Quantum Coprocessor', fn: 'copy', data: { item: item as never, qc } },
});
@ -346,15 +348,6 @@ export const HARDWARE: Record<string, Script> = {
},
};
function describeArgs(s: GameState, a: StackItem['args']): string {
const parts: string[] = [];
if (a.ref) parts.push(avatarName(s, a.ref));
if (a.card !== undefined) parts.push(nameOf(s, a.card));
if (a.to) parts.push(`→ ${a.to}`);
if (a.mode) parts.push(a.mode);
return parts.join(' ');
}
function disableForTwoTurns(s: GameState, id: number): void {
s.cards[id].disabledUntil = Math.max(s.cards[id].disabledUntil, endOf(s.turn + 1));
say(s, `Overclocked CPU: ${nameOf(s, id)} is disabled for 2 turns.`);
@ -362,7 +355,7 @@ function disableForTwoTurns(s: GameState, id: number): void {
function askSandbox(s: GameState, card: number): void {
const ref = wearerOf(s, card);
const at = ref ? avatar(s, ref).at : null;
const at = ref ? anomaly(s, ref).at : null;
if (!ref || !at) return;
const progs = (s.locations[at] as LocationState).programs.filter((id) => ownerOf(s, id) === ref.player);
if (progs.length === 0) return;

View file

@ -1,6 +1,6 @@
/**
* Programs. A Program sits on a location its owner controls and its effect is local: "this
* Server" is the location it's on (or where Worm Protocol spreads it). Enemy Avatars are only
* Server" is the location it's on (or where Worm Protocol spreads it). Enemy Anomalies are only
* ever "at" your location while attacking or capturing it.
*/
import { LOCATIONS, type LocId } from '../map.ts';
@ -20,12 +20,12 @@ import {
activeMods,
addMod,
ask,
avatar,
avatarName,
anomaly,
anomalyName,
controls,
defOf,
fired,
gainRam,
gainBandwidth,
hardwareOf,
infectionOf,
isCopy,
@ -52,10 +52,10 @@ import {
usedThisTurn,
} from '../state.ts';
import { randInt } from '../rng.ts';
import { type AvatarRef, type GameState, type PlayerId, type Source, type Task } from '../types.ts';
import { type AnomalyRef, type GameState, type PlayerId, type Source, type Task } from '../types.ts';
import { cardOptions, infect, isPatch, isVirus, programsOn } from './util.ts';
const enemyOf = (src: Source, ref: AvatarRef) => ref.player !== src.controller;
const enemyOf = (src: Source, ref: AnomalyRef) => ref.player !== src.controller;
/** The first active source with this name at the location, so duplicates don't double up. */
const firstHere = (s: GameState, src: Source, loc: LocId) => {
const first = sourcesNamed(s, src.name, loc)[0];
@ -103,9 +103,9 @@ function installFree(s: GameState, card: number, at: LocId): void {
emit(s, 'onInstall', { card, at, ref: null });
}
/** Negative things on an Avatar that Error Correction can remove, one at a time. */
function negatives(s: GameState, ref: AvatarRef): { label: string; value: string }[] {
const av = avatar(s, ref);
/** Negative things on an Anomaly that Error Correction can remove, one at a time. */
function negatives(s: GameState, ref: AnomalyRef): { label: string; value: string }[] {
const av = anomaly(s, ref);
const out: { label: string; value: string }[] = [];
if (av.infection > 0) out.push({ label: 'an Infection counter', value: 'infection' });
if (av.bugs > 0) out.push({ label: 'a Bug counter', value: 'bug' });
@ -120,8 +120,8 @@ function negatives(s: GameState, ref: AvatarRef): { label: string; value: string
return out;
}
function removeNegative(s: GameState, ref: AvatarRef, what: string): void {
const av = avatar(s, ref);
function removeNegative(s: GameState, ref: AnomalyRef, what: string): void {
const av = anomaly(s, ref);
if (what === 'infection') av.infection--;
else if (what === 'bug') av.bugs--;
else if (what === 'permanent') av.permanentInfection--;
@ -135,22 +135,22 @@ export const PROGRAMS: Record<string, Script> = {
// Reading: one counter per attack declared on this Server, or per capture of it that wasn't an
// attack. The -2 applies anywhere while this Program is in play, and doesn't stack with copies.
'Recursive Infection': {
text: 'Whenever an enemy Avatar attacks or breaches this Server, place an Infection counter on it. An Avatar with 3+ Infection counters has -2 Core.',
onAttackDeclared(s, src, ev: { ref: AvatarRef; to: LocId }) {
text: 'Whenever an enemy Anomaly attacks or breaches this Server, place an Infection counter on it. An Anomaly with 3+ Infection counters has -2 Core.',
onAttackDeclared(s, src, ev: { ref: AnomalyRef; to: LocId }) {
if (ev.to === src.at && enemyOf(src, ev.ref)) infect(s, ev.ref, 1, 'Recursive Infection', src.controller);
},
onBreach(s, src, ev: { ref: AvatarRef; loc: LocId }) {
onBreach(s, src, ev: { ref: AnomalyRef; loc: LocId }) {
if (ev.loc !== src.at || !enemyOf(src, ev.ref)) return;
const attacked = s.declarations.some((d) => d.kind === 'attack' && sameRef(d.ref, ev.ref) && d.to === ev.loc);
if (!attacked) infect(s, ev.ref, 1, 'Recursive Infection', src.controller);
},
globalCores: (s, f) => (infectionOf(avatar(s, f.ref)) >= 3 ? -2 : 0),
globalCores: (s, f) => (infectionOf(anomaly(s, f.ref)) >= 3 ? -2 : 0),
},
// Reading: "owner" is the attacking Avatar's owner, who picks which of its Hardware is disabled
// Reading: "owner" is the attacking Anomaly's owner, who picks which of its Hardware is disabled
// for that combat.
'Memory Parasite': {
text: "Enemy Avatars attacking this Server have 1 hardware component disabled of the owners choosing.",
text: "Enemy Anomalies attacking this Server have 1 hardware component disabled of the owners choosing.",
onCombatStart(s, src) {
const c = s.combat!;
if (c.loc !== src.at || !enemyOf(src, c.attacker)) return;
@ -179,7 +179,7 @@ export const PROGRAMS: Record<string, Script> = {
// Reading: installing this card counts, so it can bring a second Virus with it.
'Replication Routine': {
text: 'When you install a Virus Program on this Server, you may install a second Virus Program from your hand here for no RAM cost.',
text: 'When you install a Virus Program on this Server, you may install a second Virus Program from your hand here for no Bandwidth cost.',
onInstall(s, src, ev: { card: number; at: LocId | null }) {
if (!src.at || ev.at !== src.at || src.virtual !== undefined || !isVirus(s, ev.card)) return;
if (s.locations[src.at].programs.length >= programSlots(s, src.at)) return;
@ -205,12 +205,12 @@ export const PROGRAMS: Record<string, Script> = {
// Fires on every roll the attacker loses here (with the health rule off, that's every defeat).
'Resource Leech': {
text: 'Whenever an enemy Avatar takes damage while attacking this Server, gain 3 RAM.',
text: 'Whenever an enemy Anomaly takes damage while attacking this Server, gain 3 Gb.',
onDamage(s, src, ev) {
if (ev.loc !== src.at || ev.role !== 'attack' || !enemyOf(src, ev.ref)) return;
gainRam(s, src.controller, 3);
gainBandwidth(s, src.controller, 3);
fired(s, 'Resource Leech', src.controller);
say(s, `Resource Leech: ${playerName(src.controller)} gains 3 RAM.`);
say(s, `Resource Leech: ${playerName(src.controller)} gains 3 Gb.`);
},
},
@ -237,7 +237,7 @@ export const PROGRAMS: Record<string, Script> = {
},
'Payload Injector': {
text: 'The first Execution you play targeting this Server each round costs 2 less RAM.',
text: 'The first Execution you play targeting this Server each round costs 2 less Gb.',
costMod: (s, src, pay) =>
pay.kind === 'execution' && pay.player === src.controller && pay.at === src.at &&
usedThisTurn(s, `payload:${src.id}`) === 0 ? -2 : 0,
@ -247,24 +247,24 @@ export const PROGRAMS: Record<string, Script> = {
},
},
// Enemy Avatars are only ever at this location while attacking it. The counter survives defeat.
// Enemy Anomalies are only ever at this location while attacking it. The counter survives defeat.
'Persistent Infection': {
text: 'Whenever an enemy Avatar takes damage at this Server, place an Infection counter on it permanently.',
text: 'Whenever an enemy Anomaly takes damage at this Server, place an Infection counter on it permanently.',
onDamage(s, src, ev) {
if (ev.loc !== src.at || !enemyOf(src, ev.ref) || isCopy(ev.ref)) return;
infect(s, ev.ref, 1, 'Persistent Infection', src.controller, true);
},
},
// Reading: your Avatar attacking from this Server may declare a second attack on another
// Reading: your Anomaly attacking from this Server may declare a second attack on another
// adjacent location. Both come from this Server, even if the first one moved it.
'Infinite Loop': {
text: 'If the attacking Avatar is controlled by the owner of this Program, it may attack a second adjacent Server in the same command.',
text: 'If the attacking Anomaly is controlled by the owner of this Program, it may attack a second adjacent Server in the same command.',
extraAttacks: 1,
},
'Stack Overflow': {
text: 'Avatars you control defending this Server gain +1 Core for each Program installed on this Server (including this one).',
text: 'Anomalies you control defending this Server gain +1 Core for each Program installed on this Server (including this one).',
cores: (s, src, f) =>
f.role === 'defend' && f.at === src.at && f.ref.player === src.controller ? installedCount(s, src.at!) : 0,
},
@ -298,16 +298,16 @@ export const PROGRAMS: Record<string, Script> = {
},
},
'Memory Leak': {
text: 'At the start of any combat at this Server, the attacking Avatar loses 1 Core for each Hardware installed on it.',
'Bloatware': {
text: 'At the start of any combat at this Server, the attacking Anomaly loses 1 Core for each Hardware installed on it.',
onCombatStart(s, src) {
const c = s.combat!;
if (c.loc !== src.at || !enemyOf(src, c.attacker) || bugImmune(s, c.attacker, src.controller)) return;
const n = hardwareOf(s, c.attacker).length;
if (n === 0) return;
addMod(s, c.attacker, -n, 'Memory Leak', src.controller, { combat: c.id });
fired(s, 'Memory Leak', src.controller);
say(s, `Memory Leak: ${avatarName(s, c.attacker)} loses ${n} Core${n === 1 ? '' : 's'}.`);
addMod(s, c.attacker, -n, 'Bloatware', src.controller, { combat: c.id });
fired(s, 'Bloatware', src.controller);
say(s, `Bloatware: ${anomalyName(s, c.attacker)} loses ${n} Core${n === 1 ? '' : 's'}.`);
},
},
@ -324,7 +324,7 @@ export const PROGRAMS: Record<string, Script> = {
// Reading: "Hardware bonuses" are the Cores Hardware adds.
'Stock Rice': {
text: 'Neither Avatar in a combat that takes place at this Server may use any Hardware bonuses.',
text: 'Neither Anomaly in a combat that takes place at this Server may use any Hardware bonuses.',
blocksHardwareInCombat: true,
onCombatStart(s, src) {
if (s.combat!.loc === src.at) fired(s, 'Stock Rice', src.controller);
@ -334,7 +334,7 @@ export const PROGRAMS: Record<string, Script> = {
// Every lost roll disables a Program until its controller's next command; a destroyed attacker
// lets the owner destroy it instead.
'Overflow Error': {
text: 'When an enemy Avatar takes damage while attacking this Server, disable one Program its controller has in play until their next command. If the Avatar was destroyed, you may destroy that Program instead.',
text: 'When an enemy Anomaly takes damage while attacking this Server, disable one Program its controller has in play until their next command. If the Anomaly was destroyed, you may destroy that Program instead.',
onDamage(s, src, ev) {
if (ev.loc !== src.at || ev.role !== 'attack' || !enemyOf(src, ev.ref)) return;
const theirs = LOCATIONS.flatMap((l) => (controls(s, ev.ref.player, l) ? programsOn(s, l) : []))
@ -389,7 +389,7 @@ export const PROGRAMS: Record<string, Script> = {
'Packet Loss': {
text: 'When an enemy successfully breaches this Server, its controller discards a card at random.',
onBreach(s, src, ev: { ref: AvatarRef; loc: LocId }) {
onBreach(s, src, ev: { ref: AnomalyRef; loc: LocId }) {
if (ev.loc !== src.at || !enemyOf(src, ev.ref)) return;
const hand = s.players[ev.ref.player].hand;
if (hand.length === 0) return;
@ -403,57 +403,57 @@ export const PROGRAMS: Record<string, Script> = {
// The once-per-turn Hardware abilities are Hot-Swap Bay's and Quantum Coprocessor's.
Desynchronization: {
text: 'Enemy Avatars attacking this Server cannot use their Hardware\'s "once per round" abilities during that combat.',
text: 'Enemy Anomalies attacking this Server cannot use their Hardware\'s "once per round" abilities during that combat.',
blocksHardwareAbilities: true,
},
// Reading: "each turn" was removed from the card, so this works once per installation.
'Visual Artifact': {
text: 'The first attack made against an Avatar you control at this Server suffers -1 Core.',
text: 'The first attack made against an Anomaly you control at this Server suffers -1 Core.',
onCombatStart(s, src) {
const c = s.combat!;
if (c.loc !== src.at || s.cards[src.id].spent || c.defenders.every((d) => d.player !== src.controller)) return;
s.cards[src.id].spent = true;
addMod(s, c.attacker, -1, 'Visual Artifact', src.controller, { combat: c.id });
fired(s, 'Visual Artifact', src.controller);
say(s, `Visual Artifact: ${avatarName(s, c.attacker)} gets -1 Core.`);
say(s, `Visual Artifact: ${anomalyName(s, c.attacker)} gets -1 Core.`);
},
},
// Executions check for this through scopeOf() in util.ts.
'Ghost Process': {
text: 'Your Executions played targeting this Server may also affect Avatars, Programs, and Hardware at one adjacent Server.',
text: 'Your Executions played targeting this Server may also affect Anomalies, Programs, and Hardware at one adjacent Server.',
},
// Runs from the engine right after an enemy Execution that targets an Avatar is played.
// Runs from the engine right after an enemy Execution that targets an Anomaly is played.
'False Positive': {
text: 'When an enemy Execution targets an Avatar you control at this Server, you may redirect it to another legal Avatar at another Server.',
text: 'When an enemy Execution targets an Anomaly you control at this Server, you may redirect it to another legal Anomaly at another Server.',
resume: {
offer(s, data: { index: number }) {
const item = s.stack[data.index];
if (!item) return;
const ex = scriptOf(item.name)?.execution;
const hit = ex?.targetsAvatars?.(s, item) ?? [];
const hit = ex?.targetsAnomalies?.(s, item) ?? [];
const guarded = hit.find((r) => {
if (r.player === item.player) return false;
const at = avatar(s, r).at;
const at = anomaly(s, r).at;
return sources(s).some((x) => x.name === 'False Positive' && x.at === at && x.controller === r.player);
});
if (!ex || !guarded) return;
const from = avatar(s, guarded).at;
const from = anomaly(s, guarded).at;
const options = ex.plays(s, item.player).filter((play) => {
const refs = ex.targetsAvatars?.(s, { player: item.player, target: play.target, args: play.args }) ?? [];
return refs.length > 0 && refs.every((r) => avatar(s, r).at !== from && !sameRef(r, guarded));
const refs = ex.targetsAnomalies?.(s, { player: item.player, target: play.target, args: play.args }) ?? [];
return refs.length > 0 && refs.every((r) => anomaly(s, r).at !== from && !sameRef(r, guarded));
});
if (options.length === 0) return;
ask(s, {
player: guarded.player,
kind: 'False Positive:redirect',
prompt: `False Positive: redirect ${item.name} away from ${avatarName(s, guarded)}?`,
prompt: `False Positive: redirect ${item.name} away from ${anomalyName(s, guarded)}?`,
options: [
{ label: 'Leave it', value: null },
...options.map((play) => ({
label: `Redirect to ${play.args.ref ? avatarName(s, play.args.ref) : nameOf(s, play.args.card ?? -1)} on ${play.target}`,
label: `Redirect to ${play.args.ref ? anomalyName(s, play.args.ref) : nameOf(s, play.args.card ?? -1)} on ${play.target}`,
value: { index: data.index, target: play.target, args: play.args as never },
})),
],
@ -472,7 +472,7 @@ export const PROGRAMS: Record<string, Script> = {
},
Fragmentation: {
text: 'Executions your opponents play targeting this Server cost +2 RAM.',
text: 'Executions your opponents play targeting this Server cost +2 Gb.',
costMod: (s, src, pay) => (pay.kind === 'execution' && pay.player !== src.controller && pay.at === src.at ? 2 : 0),
onPaid: (s, src) => fired(s, 'Fragmentation', src.controller),
},
@ -489,33 +489,33 @@ export const PROGRAMS: Record<string, Script> = {
},
'Error Correction': {
text: 'At the beginning of your first command each round, remove one negative counter or status from each Avatar you control at this Server.',
text: 'At the beginning of your first command each round, remove one negative counter or status from each Anomaly you control at this Server.',
onTurnStart(s, src) {
if (s.active !== src.controller) return;
const tasks: Task[] = refsInPlay(s, src.controller)
.filter((r) => avatar(s, r).at === src.at)
.filter((r) => anomaly(s, r).at === src.at)
.map((r) => later('Error Correction', 'fix', { ref: r as never }));
pushTasks(s, ...tasks);
},
resume: {
fix(s, data: { ref: AvatarRef }) {
fix(s, data: { ref: AnomalyRef }) {
const list = negatives(s, data.ref);
if (list.length === 0) return;
fired(s, 'Error Correction', data.ref.player);
if (list.length === 1) {
removeNegative(s, data.ref, list[0].value);
say(s, `Error Correction removes ${list[0].label} from ${avatarName(s, data.ref)}.`);
say(s, `Error Correction removes ${list[0].label} from ${anomalyName(s, data.ref)}.`);
return;
}
ask(s, {
player: data.ref.player,
kind: 'Error Correction:remove',
prompt: `Error Correction: remove what from ${avatarName(s, data.ref)}?`,
prompt: `Error Correction: remove what from ${anomalyName(s, data.ref)}?`,
options: list,
resume: { name: 'Error Correction', fn: 'remove', data: { ref: data.ref as never } },
});
},
remove(s, data: { ref: AvatarRef }, what: string) {
remove(s, data: { ref: AnomalyRef }, what: string) {
removeNegative(s, data.ref, what);
},
},
@ -523,7 +523,7 @@ export const PROGRAMS: Record<string, Script> = {
// Reading: it can sacrifice itself.
'Garbage Collection': {
text: 'Once per round, sacrifice one Program installed on this Server to recover its printed RAM value.',
text: 'Once per round, sacrifice one Program installed on this Server to recover its printed Bandwidth value.',
ability: {
uses: (s, src) => (src.kind === 'program' ? s.locations[src.at!].programs.map((card) => ({ card })) : []),
resolve(s, item, src) {
@ -532,9 +532,9 @@ export const PROGRAMS: Record<string, Script> = {
uninstallProgram(s, card);
toDiscard(s, card);
stat(s, 'programsLost', src.controller);
gainRam(s, src.controller, defOf(s, card).ram);
gainBandwidth(s, src.controller, defOf(s, card).bandwidth);
fired(s, 'Garbage Collection', src.controller);
say(s, `Garbage Collection sacrifices ${nameOf(s, card)} for ${defOf(s, card).ram} RAM.`);
say(s, `Garbage Collection sacrifices ${nameOf(s, card)} for ${defOf(s, card).bandwidth} Gb.`);
},
},
},
@ -564,28 +564,28 @@ export const PROGRAMS: Record<string, Script> = {
},
'Rollback Routine': {
text: 'Once per round, undo the most recent temporary stat reduction applied to an Avatar you control at this Server.',
text: 'Once per round, undo the most recent temporary stat reduction applied to an Anomaly you control at this Server.',
ability: {
uses(s, src) {
if (src.kind !== 'program') return [];
return refsInPlay(s, src.controller)
.filter((r) => avatar(s, r).at === src.at && activeMods(s, avatar(s, r)).some((m) => m.cores < 0))
.filter((r) => anomaly(s, r).at === src.at && activeMods(s, anomaly(s, r)).some((m) => m.cores < 0))
.map((ref) => ({ ref }));
},
resolve(s, item, src) {
const av = avatar(s, item.args.ref!);
const av = anomaly(s, item.args.ref!);
if (av.at !== src.at) return;
const last = activeMods(s, av).filter((m) => m.cores < 0).sort((a, b) => b.seq - a.seq)[0];
if (!last) return;
av.mods = av.mods.filter((m) => m !== last);
fired(s, 'Rollback Routine', src.controller);
say(s, `Rollback Routine undoes ${last.cores} Cores from ${last.source} on ${avatarName(s, item.args.ref!)}.`);
say(s, `Rollback Routine undoes ${last.cores} Cores from ${last.source} on ${anomalyName(s, item.args.ref!)}.`);
},
},
},
'Compatibility Layer': {
text: 'This Server may hold one additional Program beyond the normal limit, and Patch Programs installed here cost 2 less RAM.',
text: 'This Server may hold one additional Program beyond the normal limit, and Patch Programs installed here cost 2 less Gb.',
programSlots: 1,
costMod: (s, src, pay) =>
pay.kind === 'program' && pay.player === src.controller && pay.at === src.at && isPatch(s, pay.card!) ? -2 : 0,
@ -597,6 +597,7 @@ function askRace(s: GameState, player: PlayerId): void {
ask(s, {
player,
kind: 'Race Condition:pick',
secret: true,
prompt: 'Race Condition: secretly choose Attack or Defend.',
options: [{ label: 'Attack', value: 'attack' }, { label: 'Defend', value: 'defend' }],
resume: { name: 'Race Condition', fn: 'pick', data: { player } },

View file

@ -8,11 +8,11 @@ import { canCopy, hasRoom, sameSource, sourcesNamed } from '../query.ts';
import type { Fighter, Script } from '../scripts.ts';
import {
ask,
avatar,
anomaly,
copyOf,
defendersAt,
fired,
gainRam,
gainBandwidth,
isCopy,
nameOf,
neighbors,
@ -24,40 +24,40 @@ import {
import { LOCATIONS } from '../map.ts';
import type { GameState, PlayerId, Source } from '../types.ts';
/** Core bonus for the controller's Avatar standing on this Server (attacking from it or defending it). */
/** Core bonus for the controller's Anomaly standing on this Server (attacking from it or defending it). */
const coreBonus = (n: number) => (s: GameState, src: Source, f: Fighter) =>
f.at === src.at && f.ref.player === src.controller ? n : 0;
export const SERVERS: Record<string, Script> = {
'High Efficiency RAM Server': { text: 'Add additional 4 RAM to resource total', ramOnPlace: 4 },
'Power Server': { text: 'Add additional 4 RAM to resource total', ramOnPlace: 4 },
'High Bandwidth Server': { text: 'Add additional 4 Gb to resource total', bandwidthOnPlace: 4 },
'Power Server': { text: 'Add additional 4 Gb to resource total', bandwidthOnPlace: 4 },
'Server Farm': {
text: 'Add 4 RAM to resource total and 2 Cores to any Avatar',
ramOnPlace: 4,
text: 'Add 4 Gb to resource total and 2 Cores to any Anomaly',
bandwidthOnPlace: 4,
cores: coreBonus(2),
},
'MultiCore Server': { text: 'Add 2 Cores to any Avatars', cores: coreBonus(2) },
'Cloud Compute': { text: 'Add 4 Cores to any Avatars', cores: coreBonus(4) },
'Cluster Server': { text: 'Up to 2 Avatars can defend this Server', capacity: 2 },
'Pingable Server': { text: 'Up to 2 Avatars can defend this Server', capacity: 2 },
'MultiCore Server': { text: 'Add 2 Cores to any Anomalies', cores: coreBonus(2) },
'Cloud Compute': { text: 'Add 4 Cores to any Anomalies', cores: coreBonus(4) },
'Cluster Server': { text: 'Up to 2 Anomalies can defend this Server', capacity: 2 },
'Pingable Server': { text: 'Up to 2 Anomalies can defend this Server', capacity: 2 },
// Reading: once per turn, at any time, make a copy of your Avatar based here (Carbon NanoBots'
// Reading: once per turn, at any time, make a copy of your Anomaly based here (Carbon NanoBots'
// copy rules). The copy enters play on any location you control with room.
'Backup Server': {
text: 'Duplicate Avatar based at this Server',
text: 'Duplicate Anomaly based at this Server',
ability: {
uses(s, src) {
const p = src.controller;
if (!canCopy(s, p)) return [];
const spots = LOCATIONS.filter((l) => hasRoom(s, p, l));
return refsInPlay(s, p)
.filter((r) => !isCopy(r) && avatar(s, r).at === src.at && avatar(s, copyOf(r)).at === null)
.filter((r) => !isCopy(r) && anomaly(s, r).at === src.at && anomaly(s, copyOf(r)).at === null)
.flatMap((r) => spots.map((to) => ({ ref: r, to })));
},
resolve(s, item) {
const r = item.args.ref!;
const to = item.args.to!;
if (avatar(s, r).at === null || avatar(s, copyOf(r)).at !== null || !canCopy(s, r.player) || !hasRoom(s, r.player, to)) return;
if (anomaly(s, r).at === null || anomaly(s, copyOf(r)).at !== null || !canCopy(s, r.player) || !hasRoom(s, r.player, to)) return;
fired(s, 'Backup Server', r.player);
createCopy(s, r, to);
},
@ -65,13 +65,13 @@ export const SERVERS: Record<string, Script> = {
},
'Upgraded Hardware': {
text: 'Hardware upgrades cost 2 less RAM to install',
text: 'Hardware upgrades cost 2 less Gb to install',
costMod: (s, src, pay) => (pay.kind === 'hardware' && pay.player === src.controller && pay.at === src.at ? -2 : 0),
onPaid: (s, src) => fired(s, 'Upgraded Hardware', src.controller),
},
'Network Throttle': {
text: 'Firewalls cost 1 less RAM to install',
text: 'Firewalls cost 1 less Gb to install',
costMod(s, src, pay) {
if (pay.kind !== 'firewall' || pay.player !== src.controller) return 0;
const line = LINE_BY_ID.get(pay.line!)!;
@ -81,7 +81,7 @@ export const SERVERS: Record<string, Script> = {
},
// Reading: when placed, pick one adjacent Server (either player's) and gain its ability for as
// long as this card stays. A copied RAM bonus is paid right away.
// long as this card stays. A copied Bandwidth bonus is paid right away.
'Duplicate Server': {
text: 'Copy one adjacent Server ability',
onPlaced(s, src, ev: { card: number }) {
@ -106,23 +106,23 @@ export const SERVERS: Record<string, Script> = {
const p = data.player;
fired(s, 'Duplicate Server', p);
say(s, `Duplicate Server copies ${name}.`);
const bonus = SERVERS[name]?.ramOnPlace ?? 0;
const bonus = SERVERS[name]?.bandwidthOnPlace ?? 0;
if (bonus) {
gainRam(s, p, bonus, 'ramFromCaptures');
say(s, `${playerName(p)} gains ${bonus} RAM from the copied ability.`);
gainBandwidth(s, p, bonus, 'bandwidthFromCaptures');
say(s, `${playerName(p)} gains ${bonus} Gb from the copied ability.`);
}
},
},
},
'Protected Server': {
text: 'Add 2 RAM if defending this Server',
text: 'Add 2 Gb if defending this Server',
onCombatStart(s, src) {
const c = s.combat!;
if (c.loc !== src.at || defendersAt(s, c.loc).every((d) => d.player !== src.controller)) return;
gainRam(s, src.controller, 2);
gainBandwidth(s, src.controller, 2);
fired(s, 'Protected Server', src.controller);
say(s, `Protected Server: ${playerName(src.controller)} gains 2 RAM for defending.`);
say(s, `Protected Server: ${playerName(src.controller)} gains 2 Gb for defending.`);
},
},
@ -137,6 +137,7 @@ export const SERVERS: Record<string, Script> = {
ask(s, {
player: ev.player,
kind: 'Callable Server:redraw',
secret: true,
prompt: `Callable Server: keep ${nameOf(s, ev.card)}, or put it on the bottom and draw another?`,
options: [
{ label: `Keep ${nameOf(s, ev.card)}`, value: false },

View file

@ -3,8 +3,8 @@ import type { LocId } from '../map.ts';
import { bugImmune, hardwareActive, programActive, sources } from '../query.ts';
import {
atServer,
avatar,
avatarName,
anomaly,
anomalyName,
defOf,
fired,
nameOf,
@ -13,7 +13,7 @@ import {
refsInPlay,
say,
} from '../state.ts';
import type { AvatarRef, ChoiceOption, GameState, PlayerId, Source } from '../types.ts';
import type { AnomalyRef, ChoiceOption, GameState, PlayerId, Source } from '../types.ts';
/** Locations where `p` has Ghost Process working. */
export const ghostsOf = (s: GameState, p: PlayerId): Set<LocId> =>
@ -24,7 +24,7 @@ export function scopeOf(s: GameState, p: PlayerId, target: LocId, ghosts = ghost
return ghosts.has(target) ? [target, ...neighbors(s, target)] : [target];
}
export const mine = (s: GameState, p: PlayerId, loc: LocId): AvatarRef[] =>
export const mine = (s: GameState, p: PlayerId, loc: LocId): AnomalyRef[] =>
atServer(s, loc).filter((r) => r.player === p);
/** Active, installed Programs on a location. */
@ -37,24 +37,24 @@ export const activeHardware = (s: GameState, ids: number[]): number[] => ids.fil
* Places Bug counters: like Infection counters, for Bug cards. No card places them yet. ECC Memory
* stops opponents from placing them.
*/
export function addBugs(s: GameState, ref: AvatarRef, n: number, source: string, by: PlayerId): boolean {
export function addBugs(s: GameState, ref: AnomalyRef, n: number, source: string, by: PlayerId): boolean {
if (bugImmune(s, ref, by)) {
say(s, `ECC Memory blocks ${source}'s Bug counters on ${avatarName(s, ref)}.`);
say(s, `ECC Memory blocks ${source}'s Bug counters on ${anomalyName(s, ref)}.`);
fired(s, 'ECC Memory', ref.player);
return false;
}
avatar(s, ref).bugs += n;
anomaly(s, ref).bugs += n;
fired(s, source, by);
say(s, `${source}: ${avatarName(s, ref)} gets ${n} Bug counter${n === 1 ? '' : 's'} (${avatar(s, ref).bugs} total).`);
say(s, `${source}: ${anomalyName(s, ref)} gets ${n} Bug counter${n === 1 ? '' : 's'} (${anomaly(s, ref).bugs} total).`);
return true;
}
export function infect(s: GameState, ref: AvatarRef, n: number, source: string, by: PlayerId, permanent = false): void {
const av = avatar(s, ref);
export function infect(s: GameState, ref: AnomalyRef, n: number, source: string, by: PlayerId, permanent = false): void {
const av = anomaly(s, ref);
if (permanent) av.permanentInfection += n;
else av.infection += n;
fired(s, source, by);
say(s, `${source}: ${avatarName(s, ref)} gets ${n === 1 ? 'an' : n} ${permanent ? 'permanent ' : ''}Infection counter${n === 1 ? '' : 's'} (${av.infection + av.permanentInfection} total).`);
say(s, `${source}: ${anomalyName(s, ref)} gets ${n === 1 ? 'an' : n} ${permanent ? 'permanent ' : ''}Infection counter${n === 1 ? '' : 's'} (${av.infection + av.permanentInfection} total).`);
}
/** One option per distinct card name. */
@ -84,6 +84,6 @@ export function subsets<T>(items: T[]): T[][] {
}
export const srcLabel = (s: GameState, src: Source): string =>
src.kind === 'avatar' ? `${defOf(s, src.id).ability?.name} (${src.name})` : src.name;
src.kind === 'anomaly' ? `${defOf(s, src.id).ability?.name} (${src.name})` : src.name;
export const everyAvatarInPlay = (s: GameState): AvatarRef[] => [...refsInPlay(s, 0), ...refsInPlay(s, 1)];
export const everyAnomalyInPlay = (s: GameState): AnomalyRef[] => [...refsInPlay(s, 0), ...refsInPlay(s, 1)];

View file

@ -4,11 +4,13 @@ import { parseArgs } from 'node:util';
import type { BotFactory } from './bots/bot.ts';
import { DEFAULT_GREEDY, greedyBot } from './bots/greedy.ts';
import { randomBot } from './bots/random.ts';
import { DEFAULT_CARDS_CSV, loadCards, type CardKind } from './cards.ts';
import type { CardKind } from './cards.ts';
import { DEFAULT_CARDS_CSV, loadCards } from './load.ts';
import { playGame } from './play.ts';
import { DEFAULT_RULES, withRule } from './rules.ts';
import { isImplemented, staleScripts } from './scripts.ts';
import { cardReport, formatCardReport, formatSummary, recordOf, summarize, type GameRecord } from './stats.ts';
import { logFor } from './state.ts';
import { PLAYER_NAMES } from './types.ts';
const BOTS: Record<string, { about: string; make: BotFactory }> = {
@ -31,17 +33,19 @@ const USAGE = `Files TCG simulator
--north BOT North's bot (default greedy)
--max-turns N rounds × 2 before a draw (default ${DEFAULT_RULES.maxTurns}, i.e. ${DEFAULT_RULES.maxTurns / 2} rounds)
--rule K=V change a rule in src/rules.ts; repeatable. Examples: winLocations=9,
levelRam=4,4,6,8,10, startingAvatars=4, firstTurn.draw=true, firstTurn.advance=false,
firstTurn.captureRam=false, firstTurn.unlock=false, firstTurn.cards=false,
secondPlayer.ram=4, secondPlayer.avatars=1, secondPlayer.cards=2, secondPlayer.firstDraw=1,
levelBandwidth=4,4,6,8,10, startingAnomalies=4, firstTurn.draw=true, firstTurn.advance=false,
firstTurn.captureBandwidth=false, firstTurn.unlock=false, firstTurn.cards=false,
secondPlayer.bandwidth=4, secondPlayer.anomalies=1, secondPlayer.cards=2, secondPlayer.firstDraw=1,
secondPlayer.locations=1, drawPerTurn=2, deck.main=60,
recruit.on=true (Avatars in the deck; also recruit.avatarsInDeck=5, recruit.price=8),
buyAvatars.on=true (buy Avatars 2-4 instead of unlocking; buyAvatars.prices=8,12,16),
copies.waitATurn=true, copies.needAvatar2=true, copies.allowed=false,
board=grid4 (4×4 squares, win with 12 of 16; also grid4-wide, grid4-one),
board=lanes (three lanes linked across the middle row, win with 11 of 15; also lanes-open),
recruit.on=true (Anomalies in the deck; also recruit.anomaliesInDeck=5, recruit.price=8),
buyAnomalies.on=true (buy Anomalies 2-4 instead of unlocking; buyAnomalies.prices=8,12,16),
copies.waitATurn=true, copies.needAnomaly2=true, copies.allowed=false,
commands.on=false (whole turns instead of rounds of commands),
commands.perPlayer=3, commands.leads=F|FS|FFSS|thue, commands.snake=false,
health.on=false (one roll decides a combat, as before v0.9),
health.override=8 (every Avatar has this Health), health.recall=false
health.override=8 (every Anomaly has this Health), health.recall=false
--log play one game and print the play-by-play
--check check rule invariants after every action (slow)
--json FILE also write the summary and every game's result as JSON
@ -108,7 +112,7 @@ const bots: [BotFactory, BotFactory] = [BOTS[opt.south].make, BOTS[opt.north].ma
for (const warning of staleScripts(pool)) console.warn(`warning: ${warning}`);
const KIND_LABELS: [CardKind, string][] = [
['avatar', 'Avatars'], ['server', 'Servers'], ['hardware', 'Hardware'], ['program', 'Programs'], ['execution', 'Executions'],
['anomaly', 'Anomalies'], ['server', 'Servers'], ['hardware', 'Hardware'], ['program', 'Programs'], ['execution', 'Executions'],
];
const coverage = KIND_LABELS.map(([kind, label]) => {
const cards = pool.all.filter((c) => c.kind === kind);
@ -118,7 +122,7 @@ console.log(`Card effects simulated: ${coverage.join(', ')}.\n`);
if (opt.log) {
const s = playGame({ pool, bots, seed, rules, log: true, check: opt.check });
console.log(s.log!.join('\n'));
console.log(logFor(s, null).join('\n'));
process.exit(0);
}

View file

@ -1,11 +1,11 @@
import type { CardDef, CardKind, CardPool } from './cards.ts';
import { shuffle, type Rng } from './rng.ts';
import { avatarsOutside, type RulesConfig } from './rules.ts';
import { anomaliesOutside, type RulesConfig } from './rules.ts';
export interface DeckList {
avatars: string[];
anomalies: string[];
servers: string[];
/** Executions, Hardware and Programs (and Avatars, when recruiting). */
/** Executions, Hardware and Programs (and Anomalies, when recruiting). */
main: string[];
}
@ -22,11 +22,11 @@ export function validateDeck(pool: CardPool, deck: DeckList, rules: RulesConfig)
else if (!kinds.includes(card.kind)) errors.push(`${label}: "${name}" is a ${card.kind}`);
}
};
part('Avatars', deck.avatars, ['avatar'], avatarsOutside(rules));
part('Anomalies', deck.anomalies, ['anomaly'], anomaliesOutside(rules));
part('Servers', deck.servers, ['server'], rules.deck.servers);
part('Deck', deck.main, rules.recruit.on ? [...MAIN_KINDS, 'avatar'] : MAIN_KINDS, rules.deck.main);
part('Deck', deck.main, rules.recruit.on ? [...MAIN_KINDS, 'anomaly'] : MAIN_KINDS, rules.deck.main);
const copies = new Map<string, number>();
for (const name of [...deck.avatars, ...deck.servers, ...deck.main]) {
for (const name of [...deck.anomalies, ...deck.servers, ...deck.main]) {
copies.set(name, (copies.get(name) ?? 0) + 1);
}
for (const [name, n] of copies) {
@ -50,13 +50,13 @@ export function randomDeck(
return shuffle(rng, names).slice(0, size);
};
if (rules.recruit.on) {
const k = rules.recruit.avatarsInDeck;
const avatars = sample(['avatar'], 1 + k);
const k = rules.recruit.anomaliesInDeck;
const anomalies = sample(['anomaly'], 1 + k);
const servers = sample(['server'], rules.deck.servers);
return { avatars: avatars.slice(0, 1), servers, main: shuffle(rng, [...avatars.slice(1), ...sample(MAIN_KINDS, rules.deck.main - k)]) };
return { anomalies: anomalies.slice(0, 1), servers, main: shuffle(rng, [...anomalies.slice(1), ...sample(MAIN_KINDS, rules.deck.main - k)]) };
}
return {
avatars: sample(['avatar'], rules.deck.avatars),
anomalies: sample(['anomaly'], rules.deck.anomalies),
servers: sample(['server'], rules.deck.servers),
main: sample(MAIN_KINDS, rules.deck.main),
};

129
sim/src/describe.ts Normal file
View file

@ -0,0 +1,129 @@
/**
* Readable labels for actions, for people choosing them (the app's move list, prompts). Labels are
* written for the deciding player: "your" things are unmarked, the opponent's say whose they are.
* Nothing here names a card the decider can't see.
*/
import { abilitySource, actionCost, anomalyForSale, decider } from './engine.ts';
import { LINE_BY_ID } from './map.ts';
import { healthLeft, healthOf } from './query.ts';
import { anomaly, defOf, nameOf, originalOf, playerName, programLocation, wearerOf } from './state.ts';
import type { Action, Args, AnomalyRef, GameState, PlayerId } from './types.ts';
const STEP_NAMES = { deploy: 'Deploy', play: 'Play', attack: 'Attack', resolve: 'Resolve', playAgain: 'Play again' } as const;
/** "A2–B1" for a line id like "A2-B1". */
export const lineName = (line: string): string => {
const l = LINE_BY_ID.get(line);
return l ? `${l.a}–${l.b}` : line;
};
/** "Anomaly 2 (Glitch)", or "the copy of Anomaly 2 (Glitch)"; the opponent's say "North's". */
export function refName(s: GameState, r: AnomalyRef, me: PlayerId | null = decider(s)): string {
const n = originalOf(r).slot;
const card = anomaly(s, r).card;
const name = card < 0 || !anomaly(s, originalOf(r)).faceUp ? 'face down' : nameOf(s, card);
const whose = me !== null && r.player !== me ? `${playerName(r.player)}'s ` : '';
return r.slot > 4 ? `${whose}copy of Anomaly ${n} (${name})` : `${whose}Anomaly ${n} (${name})`;
}
/** Where a card is, for telling two same-named cards apart: "on C2", "on Anomaly 1 (Glitch)", "from hand". */
function cardWhere(s: GameState, id: number, me: PlayerId | null): string {
const loc = programLocation(s, id);
if (loc) return ` on ${loc}`;
const r = wearerOf(s, id);
if (r) return ` on ${refName(s, r, me)}`;
const pl = s.players[s.cards[id].owner];
if (pl.hand.includes(id)) return ' from hand';
if (pl.discard.includes(id)) return ' from the discard pile';
return '';
}
function cardName(s: GameState, id: number, me: PlayerId | null): string {
const owner = s.cards[id]?.owner;
const whose = me !== null && owner !== undefined && owner !== me ? `${playerName(owner)}'s ` : '';
return `${whose}${nameOf(s, id)}${cardWhere(s, id, me)}`;
}
/** Execution and Ability arguments: "Anomaly 2 (Glitch) → C1", "destroy Overclocked CPU on …". */
export function describeArgs(s: GameState, a: Args, me: PlayerId | null = decider(s), toWord = 'at'): string {
const parts: string[] = [];
if (a.heal) parts.push('heal this Anomaly');
if (a.ref) parts.push(refName(s, a.ref, me));
if (a.card !== undefined) {
const name = cardName(s, a.card, me);
parts.push(a.mode ? `${a.mode} ${name}` : a.cards ? `swap out ${name}` : name);
}
if (a.cards?.length) parts.push(`${a.card !== undefined ? 'for ' : ''}${a.cards.map((id) => cardName(s, id, me)).join(', ')}`);
if (a.to) parts.push(a.ref ? `→ ${a.to}` : `${toWord} ${a.to}`);
if (a.k !== undefined) parts.push(`reroll dice showing ${a.k} or less`);
return parts.join(' ');
}
const gb = (n: number): string => ` (${n} Gb)`;
/** A label for one of the current legal actions, e.g. "Play Execute: Force Reboot on D2 (5 Gb)". */
export function describeAction(s: GameState, a: Action): string {
const me = decider(s) ?? s.active;
const ref = (slot: number): AnomalyRef => ({ player: me, slot });
const cost = actionCost(s, a);
switch (a.type) {
case 'end':
if (s.step === 'playAgain') return s.rules.commands.on ? 'End command' : 'End turn';
if (s.step === 'attack') return 'End Attack step and resolve';
return `End ${STEP_NAMES[s.step]} step`;
case 'pass':
return 'Pass';
case 'choose': {
const o = s.choice?.options[a.index];
return `${o?.label ?? `Option ${a.index + 1}`}${o?.cost ? gb(o.cost) : ''}`;
}
case 'place': {
const av = anomaly(s, ref(a.slot));
return av.at === null ? `Place ${refName(s, ref(a.slot), me)} on ${a.to}` : `Move ${refName(s, ref(a.slot), me)} ${av.at} → ${a.to}`;
}
case 'recall': {
const r = ref(a.slot);
const hurt = s.rules.health.on ? healthOf(s, r) - healthLeft(s, r) : 0;
return `Recall ${refName(s, r, me)} from ${anomaly(s, r).at}${hurt ? `, healing ${hurt}` : ''}`;
}
case 'advance':
return `Advance ${refName(s, ref(a.slot), me)} ${anomaly(s, ref(a.slot)).at} → ${a.to}`;
case 'attack':
return `Attack ${a.to} with ${refName(s, ref(a.slot), me)} from ${anomaly(s, ref(a.slot)).at}`;
case 'clearFirewall':
return `Clear the Lv ${s.firewalls[a.line]} Firewall on ${lineName(a.line)}${gb(cost)}`;
case 'firewall':
return s.firewalls[a.line]
? `Upgrade the Firewall on ${lineName(a.line)} to Lv ${a.level}${gb(cost)}`
: `Place a Lv ${a.level} Firewall on ${lineName(a.line)}${gb(cost)}`;
case 'salvage':
return `Salvage ${nameOf(s, a.card)} (+${defOf(s, a.card).bandwidth} Gb)`;
case 'installHardware':
return `Install ${nameOf(s, a.card)} on ${refName(s, ref(a.slot), me)}${gb(cost)}`;
case 'recruit': {
const old = anomaly(s, ref(a.slot));
return `Recruit ${nameOf(s, a.card)} as Anomaly ${a.slot}${old.card >= 0 ? `, retiring ${nameOf(s, old.card)}` : ''}${gb(cost)}`;
}
case 'buyAnomaly':
return `Buy Anomaly ${a.slot} (face down)${gb(anomalyForSale(s, me)?.price ?? cost)}`;
case 'installProgram':
return `Install ${nameOf(s, a.card)} on ${a.at}${gb(cost)}`;
case 'play': {
// Packet Flood and Purge name the location they hit; it's the target unless Ghost Process widens it.
const args = a.args.to === a.target && !a.args.ref ? describeArgs(s, { ...a.args, to: undefined }, me) : describeArgs(s, a.args, me);
const on = a.target ? ` on ${a.target}` : '';
const from = a.from ? `, performed by ${a.from}` : '';
return `Play ${nameOf(s, a.card)}${on}${args ? `: ${args}` : ''}${from}${gb(cost)}`;
}
case 'activate': {
const src = abilitySource(s, a.card, a.name);
const def = defOf(s, a.card);
const label = src?.kind === 'anomaly' && src.ref
? `${def.ability?.name ?? a.name} (${refName(s, src.ref, me).replace(/ \((.*)\)$/, ', $1')})`
: a.name !== def.name ? `${a.name} (copied by ${def.name})` : a.name;
const where = src?.kind === 'hardware' && src.ref ? ` on ${refName(s, src.ref, me)}` : src?.kind !== 'anomaly' && src?.at ? ` on ${src.at}` : '';
const args = describeArgs(s, a.args, me, '→');
return `Use ${label}${where}${args ? `${args.startsWith('→') ? ' ' : ': '}${args}` : ''}${cost ? gb(cost) : ''}`;
}
}
}

View file

@ -14,13 +14,13 @@ import {
defeat,
drawNow,
drawTask,
recallAvatar,
recallAnomaly,
resolveDeclaration,
retireAvatar,
retireAnomaly,
} from './flow.ts';
import { GRID, LINES, LINES_AT, LINE_BY_ID, LOCATIONS, START_LOC, isStart, otherEnd, type LocId } from './map.ts';
import { GRID, LINES, LINES_AT, LINE_BY_ID, LOCATIONS, START_LOC, isStart, otherEnd, useBoard, type LocId } from './map.ts';
import {
avatarRoom,
anomalyRoom,
costOf,
coresOf,
desynced,
@ -28,9 +28,9 @@ import {
enemyFlagAt,
hasRoom,
pay,
portsFree,
slotsFree,
programSlots,
reachableRam,
reachableBandwidth,
sources,
stillActive,
wears,
@ -39,8 +39,8 @@ import { makeRng, randInt, shuffle } from './rng.ts';
import { DEFAULT_RULES, type RulesConfig } from './rules.ts';
import { scriptOf, type Fighter } from './scripts.ts';
import {
avatar,
avatarName,
anomaly,
anomalyName,
canAct,
controls,
defOf,
@ -76,8 +76,8 @@ import {
STAT_KEYS,
type Action,
type Args,
type AvatarRef,
type AvatarState,
type AnomalyRef,
type AnomalyState,
type GameState,
type GameStats,
type LocationState,
@ -98,13 +98,13 @@ export interface NewGame {
export { controls, defOf, firewallCost, gridCount, isOpen, nameOf, other } from './state.ts';
/** Combat Cores for an Avatar standing on `at`, outside any combat. For bots pricing an attack. */
export function avatarCores(
/** Combat Cores for an Anomaly standing on `at`, outside any combat. For bots pricing an attack. */
export function anomalyCores(
s: GameState,
p: PlayerId,
slot: number,
role: 'attack' | 'defend',
at: LocId | null = s.players[p].avatars[slot - 1].at,
at: LocId | null = s.players[p].anomalies[slot - 1].at,
loc: LocId | null = role === 'defend' ? at : null,
): number {
const f: Fighter = { ref: { player: p, slot }, role, at, loc, combat: null };
@ -123,18 +123,18 @@ function newStats(): GameStats {
return Object.fromEntries(STAT_KEYS.map((k) => [k, [0, 0]])) as GameStats;
}
/** Recruit rule: an Avatar's printed RAM is its price, which is also what it salvages for. */
/** Recruit rule: an Anomaly's printed Bandwidth is its price, which is also what it salvages for. */
function withPrice(def: CardDef, rules: RulesConfig): CardDef {
if (!rules.recruit.on || def.kind !== 'avatar') return def;
return { ...def, ram: rules.recruit.price + rules.recruit.pricePerCore * def.cores };
if (!rules.recruit.on || def.kind !== 'anomaly') return def;
return { ...def, bandwidth: rules.recruit.price + rules.recruit.pricePerCore * def.cores };
}
/** Recruit rule: slots `p` can recruit into. The first empty one while there's room, or any Avatar to retire. */
/** Recruit rule: slots `p` can recruit into. The first empty one while there's room, or any Anomaly to retire. */
export function recruitSlots(s: GameState, p: PlayerId): number[] {
const avs = s.players[p].avatars.slice(0, 4);
const avs = s.players[p].anomalies.slice(0, 4);
const out: number[] = [];
const empty = avs.findIndex((a) => a.card < 0);
if (empty >= 0 && avatarRoom(s, p)) out.push(empty + 1);
if (empty >= 0 && anomalyRoom(s, p)) out.push(empty + 1);
avs.forEach((a, i) => {
const declared = s.declarations.some((d) => d.ref.player === p && originalOf(d.ref).slot === i + 1);
if (a.card >= 0 && !declared) out.push(i + 1);
@ -142,14 +142,14 @@ export function recruitSlots(s: GameState, p: PlayerId): number[] {
return out;
}
/** Buy-Avatars rule: the next Avatar `p` can buy (its slot) and its price, or null. */
export function avatarForSale(s: GameState, p: PlayerId): { slot: number; price: number } | null {
if (!s.rules.buyAvatars.on) return null;
const i = s.players[p].avatars.slice(0, 4).findIndex((a) => !a.faceUp);
return i < 1 ? null : { slot: i + 1, price: s.rules.buyAvatars.prices[i - 1] };
/** Buy-Anomalies rule: the next Anomaly `p` can buy (its slot) and its price, or null. */
export function anomalyForSale(s: GameState, p: PlayerId): { slot: number; price: number } | null {
if (!s.rules.buyAnomalies.on) return null;
const i = s.players[p].anomalies.slice(0, 4).findIndex((a) => !a.faceUp);
return i < 1 ? null : { slot: i + 1, price: s.rules.buyAnomalies.prices[i - 1] };
}
function newAvatar(card: number, faceUp: boolean, copyOf: number | null): AvatarState {
function newAnomaly(card: number, faceUp: boolean, copyOf: number | null): AnomalyState {
return {
card,
faceUp,
@ -177,6 +177,7 @@ export function createGame({ pool, decks, seed, rules = DEFAULT_RULES, log = fal
const errors = validateDeck(pool, deck, rules);
if (errors.length) throw new Error(`${playerName(p as PlayerId)} deck is illegal:\n ${errors.join('\n ')}`);
});
useBoard(rules.board);
const rng = makeRng(seed);
const s: GameState = {
rules,
@ -215,18 +216,18 @@ export function createGame({ pool, decks, seed, rules = DEFAULT_RULES, log = fal
};
for (const p of [0, 1] as const) {
const deck = decks[p];
// Recruit rule: slots after the starting Avatar begin empty (-1).
const avatars = shuffle(rng, deck.avatars.map((n) => add(n, p)));
const slots = [0, 1, 2, 3].map((i) => avatars[i] ?? -1);
// Recruit rule: slots after the starting Anomaly begin empty (-1).
const anomalies = shuffle(rng, deck.anomalies.map((n) => add(n, p)));
const slots = [0, 1, 2, 3].map((i) => anomalies[i] ?? -1);
s.players.push({
ram: 0,
bandwidth: 0,
hand: [],
deck: shuffle(rng, deck.main.map((n) => add(n, p))),
discard: [],
serverPile: shuffle(rng, deck.servers.map((n) => add(n, p))),
avatars: [
...slots.map((card, i) => newAvatar(card, card >= 0 && i < rules.startingAvatars, null)),
...slots.map((card, i) => newAvatar(card, false, i + 1)),
anomalies: [
...slots.map((card, i) => newAnomaly(card, card >= 0 && i < rules.startingAnomalies, null)),
...slots.map((card, i) => newAnomaly(card, false, i + 1)),
],
unlockedLevel: 1,
});
@ -237,20 +238,20 @@ export function createGame({ pool, decks, seed, rules = DEFAULT_RULES, log = fal
const server = me.serverPile.shift()!;
start.owner = p;
start.server = server;
me.ram = rules.startingRam + (scriptOf(s.cards[server].name)?.ramOnPlace ?? 0);
me.bandwidth = rules.startingBandwidth + (scriptOf(s.cards[server].name)?.bandwidthOnPlace ?? 0);
played(s, s.cards[server].name, p);
for (let i = 0; i < rules.openingHand; i++) drawNow(s, p);
say(s, `${playerName(p)} starts on ${nameOf(s, server)} with ${me.ram} RAM. Avatar 1: ${nameOf(s, me.avatars[0].card)}.`);
say(s, `${playerName(p)} starts on ${nameOf(s, server)} with ${me.bandwidth} Gb. Anomaly 1: ${nameOf(s, me.anomalies[0].card)}.`, { tag: 'game', player: p });
}
s.firstPlayer = randInt(rng, 2) as PlayerId;
s.active = s.firstPlayer;
const p2 = other(s.firstPlayer);
const second = s.players[p2];
second.ram += rules.secondPlayer.ram;
second.avatars.slice(0, rules.startingAvatars + rules.secondPlayer.avatars).forEach((av) => (av.faceUp = av.card >= 0));
second.bandwidth += rules.secondPlayer.bandwidth;
second.anomalies.slice(0, rules.startingAnomalies + rules.secondPlayer.anomalies).forEach((av) => (av.faceUp = av.card >= 0));
for (let i = 0; i < rules.secondPlayer.cards; i++) drawNow(s, p2);
if (rules.secondPlayer.locations > 0) {
// The location next to the starting Server, with a Server from the pile: no RAM, no unlock.
// The location next to the starting Server, with a Server from the pile: no Bandwidth, no unlock.
const line = LINES_AT.get(START_LOC[p2])![0];
const L = s.locations[otherEnd(line, START_LOC[p2])];
L.owner = p2;
@ -258,7 +259,7 @@ export function createGame({ pool, decks, seed, rules = DEFAULT_RULES, log = fal
played(s, s.cards[L.server].name, p2);
}
s.stats.cardsDrawn = [0, 0];
say(s, `${playerName(s.firstPlayer)} goes first.`);
say(s, `${playerName(s.firstPlayer)} goes first.`, { tag: 'game', player: s.firstPlayer });
beginTurn(s, !rules.firstTurn.draw);
run(s);
return s;
@ -269,7 +270,7 @@ function beginTurn(s: GameState, skipDraw: boolean): void {
if (s.turn >= s.rules.maxTurns * (cmd ? s.rules.commands.perPlayer : 1)) {
s.over = true;
s.endReason = 'turnLimit';
say(s, `Turn limit reached: draw (South ${gridCount(s, 0)}, North ${gridCount(s, 1)} locations).`);
say(s, `Turn limit reached: draw (South ${gridCount(s, 0)}, North ${gridCount(s, 1)} locations).`, { tag: 'game' });
return;
}
s.turn++;
@ -280,7 +281,7 @@ function beginTurn(s: GameState, skipDraw: boolean): void {
tidy(s);
const me = s.players[s.active];
if (fresh) {
for (const av of me.avatars) {
for (const av of me.anomalies) {
av.placed = false;
av.advanced = false;
av.attacks = 0;
@ -289,7 +290,7 @@ function beginTurn(s: GameState, skipDraw: boolean): void {
s.declarations = [];
s.step = 'deploy';
const title = cmd ? `Round ${roundOf(s, s.turn)}, command ${s.turn}` : `Turn ${s.turn}`;
say(s, `\n— ${title}: ${playerName(s.active)} (${me.ram} RAM, ${me.hand.length} cards, ${gridCount(s, s.active)} locations) —`);
say(s, `\n— ${title}: ${playerName(s.active)} (${me.bandwidth} Gb, ${me.hand.length} cards, ${gridCount(s, s.active)} locations) —`, { tag: 'turn', player: s.active });
const draws = s.rules.drawPerTurn + (s.turn === 2 ? s.rules.secondPlayer.firstDraw : 0);
if (fresh && !skipDraw) pushTasks(s, ...Array.from({ length: draws }, (): Task => ({ t: 'draw', player: s.active })));
if (fresh) emit(s, 'onTurnStart', null);
@ -298,15 +299,15 @@ function beginTurn(s: GameState, skipDraw: boolean): void {
/** Command rule: this game turn's command is spent (an advance or attack is declared). */
const commandSpent = (s: GameState): boolean => s.rules.commands.on && s.declarations.length > 0;
/** Command rule: an Avatar unlocked this round waits in its slot until the next round. */
const waitsForRound = (s: GameState, av: AvatarState): boolean =>
/** Command rule: an Anomaly unlocked this round waits in its slot until the next round. */
const waitsForRound = (s: GameState, av: AnomalyState): boolean =>
s.rules.commands.on && av.at === null && av.unlockedTurn > 0 && roundOf(s, av.unlockedTurn) === roundOf(s, s.turn);
function endTurn(s: GameState): void {
s.clock = endOf(s.turn);
// Push Update: the extra Hardware leaves at the end of its controller's turn.
for (const pl of s.players) {
for (const av of pl.avatars) {
for (const av of pl.anomalies) {
for (const hw of [...av.hardware]) {
const until = s.cards[hw].pushedUntil;
if (until !== undefined && !running(s, until)) {
@ -326,7 +327,7 @@ function endTurn(s: GameState): void {
function tidy(s: GameState): void {
s.virtuals = s.virtuals.filter((v) => running(s, v.until));
for (const pl of s.players) {
for (const av of pl.avatars) av.mods = av.mods.filter((m) => m.combat !== undefined || running(s, m.until ?? 0));
for (const av of pl.anomalies) av.mods = av.mods.filter((m) => m.combat !== undefined || running(s, m.until ?? 0));
}
}
@ -363,9 +364,9 @@ export function advanceTargets(s: GameState, p: PlayerId): LocId[] {
});
}
/** Infinite Loop lets an Avatar attacking from its location attack twice. */
export function maxAttacks(s: GameState, ref: AvatarRef): number {
const at = avatar(s, ref).at;
/** Infinite Loop lets an Anomaly attacking from its location attack twice. */
export function maxAttacks(s: GameState, ref: AnomalyRef): number {
const at = anomaly(s, ref).at;
let extra = 0;
for (const x of sources(s)) {
if (x.at === at && x.controller === ref.player) extra = Math.max(extra, scriptOf(x.name)?.extraAttacks ?? 0);
@ -373,8 +374,8 @@ export function maxAttacks(s: GameState, ref: AvatarRef): number {
return 1 + extra;
}
export function attackTargets(s: GameState, ref: AvatarRef): LocId[] {
const av = avatar(s, ref);
export function attackTargets(s: GameState, ref: AnomalyRef): LocId[] {
const av = anomaly(s, ref);
if (!av.faceUp || av.at === null || av.advanced || av.attacks >= maxAttacks(s, ref) || !canAct(s, ref) || freshCopy(s, ref)) return [];
const opp = other(ref.player);
return LINES_AT.get(av.at)!
@ -386,7 +387,7 @@ export function attackTargets(s: GameState, ref: AvatarRef): LocId[] {
function pushClears(s: GameState, p: PlayerId, out: Action[]): void {
for (const [line, level] of Object.entries(s.firewalls)) {
const l = LINE_BY_ID.get(line)!;
if ((controls(s, p, l.a) || controls(s, p, l.b)) && firewallCost(s, level) <= s.players[p].ram) {
if ((controls(s, p, l.a) || controls(s, p, l.b)) && firewallCost(s, level) <= s.players[p].bandwidth) {
out.push({ type: 'clearFirewall', line });
}
}
@ -410,31 +411,31 @@ export const execBlocked = (s: GameState, loc: LocId): boolean => usedThisTurn(s
/**
* Servers worth naming as an Execution's performer: null (any of your Servers), plus each Server
* where one of your Avatars wears Hardware that cares (Dedicated GPU, Quantum Coprocessor).
* where one of your Anomalies wears Hardware that cares (Dedicated GPU, Quantum Coprocessor).
*/
function performers(s: GameState, p: PlayerId): (LocId | null)[] {
const out = new Set<LocId | null>([null]);
for (const r of refsInPlay(s, p)) {
const at = avatar(s, r).at!;
const at = anomaly(s, r).at!;
if (isCopy(r) || !controls(s, p, at) || execBlocked(s, at)) continue;
if (wears(s, r, (sc) => sc.executionPower || sc.copiesExecutions).length) out.add(at);
}
return [...out];
}
/** Dedicated GPU: extra effect for Executions performed by `from`, from its Avatars' Hardware. */
/** Dedicated GPU: extra effect for Executions performed by `from`, from its Anomalies' Hardware. */
export function executionPower(s: GameState, p: PlayerId, from: LocId | null): number {
if (from === null) return 0;
let n = 0;
for (const r of refsInPlay(s, p)) {
if (isCopy(r) || avatar(s, r).at !== from) continue;
if (isCopy(r) || anomaly(s, r).at !== from) continue;
for (const hw of wears(s, r, (sc) => sc.executionPower)) n += scriptOf(s.cards[hw].name)!.executionPower!;
}
return n;
}
export const executionHostiles = (s: GameState, item: Pick<StackItem, 'player' | 'target' | 'args' | 'name'>): AvatarRef[] =>
(scriptOf(item.name)?.execution?.targetsAvatars?.(s, item) ?? []).filter((r) => r.player !== item.player);
export const executionHostiles = (s: GameState, item: Pick<StackItem, 'player' | 'target' | 'args' | 'name'>): AnomalyRef[] =>
(scriptOf(item.name)?.execution?.targetsAnomalies?.(s, item) ?? []).filter((r) => r.player !== item.player);
export function executionCost(s: GameState, p: PlayerId, card: number, target: LocId | null, args: Args, all?: Source[]): number {
const hostile = executionHostiles(s, { player: p, target, args, name: s.cards[card].name });
@ -442,8 +443,8 @@ export function executionCost(s: GameState, p: PlayerId, card: number, target: L
}
/**
* Execution plays for `p`. `budget` 'now' keeps plays affordable with current RAM; 'reachable'
* also counts Salvage; 'any' ignores RAM.
* Execution plays for `p`. `budget` 'now' keeps plays affordable with current Bandwidth; 'reachable'
* also counts Salvage; 'any' ignores Bandwidth.
*/
export function executionActions(s: GameState, p: PlayerId, budget: 'now' | 'reachable' | 'any', limit = Infinity): Action[] {
const out: Action[] = [];
@ -457,8 +458,8 @@ export function executionActions(s: GameState, p: PlayerId, budget: 'now' | 'rea
seen.add(name);
const ex = scriptOf(name)?.execution;
if (!ex) continue;
const cap = budget === 'any' ? Infinity : budget === 'now' ? s.players[p].ram : reachableRam(s, p, card);
if (defOf(s, card).ram - 3 > cap && budget !== 'any') continue; // no discount is bigger than 2
const cap = budget === 'any' ? Infinity : budget === 'now' ? s.players[p].bandwidth : reachableBandwidth(s, p, card);
if (defOf(s, card).bandwidth - 3 > cap && budget !== 'any') continue; // no discount is bigger than 2
all ??= sources(s);
for (const play of ex.plays(s, p)) {
if (executionCost(s, p, card, play.target, play.args, all) > cap) continue;
@ -477,7 +478,7 @@ export const abilitySource = (s: GameState, card: number, name: string): Source
export function abilityCost(s: GameState, src: Source): number {
const script = scriptOf(src.name)!;
if (src.kind === 'avatar') return defOf(s, src.id).ability?.cost ?? 0;
if (src.kind === 'anomaly') return defOf(s, src.id).ability?.cost ?? 0;
return script.ability?.cost ?? 0;
}
@ -489,7 +490,7 @@ export const abilityKey = (src: Source): string => `ability:${src.id}:${src.name
export function abilityReady(s: GameState, src: Source): boolean {
const ab = scriptOf(src.name)?.ability;
if (!ab || !activatable(src)) return false;
if (src.kind === 'avatar' && !canAct(s, src.ref!)) return false;
if (src.kind === 'anomaly' && !canAct(s, src.ref!)) return false;
if (src.kind === 'hardware') {
if (hardwareUsesLeft(s, src.id) <= 0) return false;
return !(ab.hardwareOncePerTurn && desynced(s, src.ref!));
@ -499,7 +500,7 @@ export function abilityReady(s: GameState, src: Source): boolean {
export function abilityActions(s: GameState, p: PlayerId, budget: 'now' | 'reachable' | 'any', limit = Infinity): Action[] {
const out: Action[] = [];
const cap = budget === 'any' ? Infinity : budget === 'now' ? s.players[p].ram : reachableRam(s, p);
const cap = budget === 'any' ? Infinity : budget === 'now' ? s.players[p].bandwidth : reachableBandwidth(s, p);
for (const src of sources(s)) {
if (src.controller !== p || !scriptOf(src.name)?.ability || !abilityReady(s, src)) continue;
const ab = scriptOf(src.name)!.ability!;
@ -518,8 +519,8 @@ function hasResponse(s: GameState, p: PlayerId): boolean {
return executionActions(s, p, 'reachable', 1).length > 0 || abilityActions(s, p, 'reachable', 1).length > 0;
}
export function hardwareCost(s: GameState, card: number, ref: AvatarRef, all?: Source[]): number {
return costOf(s, { kind: 'hardware', player: ref.player, card, ref, at: avatar(s, ref).at }, all);
export function hardwareCost(s: GameState, card: number, ref: AnomalyRef, all?: Source[]): number {
return costOf(s, { kind: 'hardware', player: ref.player, card, ref, at: anomaly(s, ref).at }, all);
}
export function programCost(s: GameState, p: PlayerId, card: number, at: LocId, all?: Source[]): number {
return costOf(s, { kind: 'program', player: p, card, at }, all);
@ -528,10 +529,10 @@ export function placeFirewallCost(s: GameState, p: PlayerId, line: string, level
return costOf(s, { kind: 'firewall', player: p, line, level }, all);
}
/** Whether Hardware can go on an Avatar now (ports permitting). */
export function canWear(s: GameState, card: number, ref: AvatarRef): boolean {
if (isCopy(ref) || avatar(s, ref).at === null) return false;
return !!scriptOf(s.cards[card].name)?.noPort || portsFree(s, ref) > 0;
/** Whether Hardware can go on an Anomaly now (Expansion Slots permitting). */
export function canWear(s: GameState, card: number, ref: AnomalyRef): boolean {
if (isCopy(ref) || anomaly(s, ref).at === null) return false;
return !!scriptOf(s.cards[card].name)?.noSlot || slotsFree(s, ref) > 0;
}
export function legalActions(s: GameState): Action[] {
@ -542,7 +543,7 @@ export function legalActions(s: GameState): Action[] {
if (s.choice) {
const options = s.choice.options.flatMap((o, index): Action[] =>
(o.cost ?? 0) <= me.ram ? [{ type: 'choose', index }] : []);
(o.cost ?? 0) <= me.bandwidth ? [{ type: 'choose', index }] : []);
return [...options, ...salvage];
}
if (openWindow(s)) {
@ -557,7 +558,7 @@ export function legalActions(s: GameState): Action[] {
if (s.step === 'deploy') {
const placementOpen = s.declarations.length === 0;
const targets = s.turn === 1 && !s.rules.firstTurn.advance ? [] : advanceTargets(s, p);
me.avatars.forEach((av, i) => {
me.anomalies.forEach((av, i) => {
const ref = { player: p, slot: i + 1 };
if (!av.faceUp || av.advanced || av.attacks > 0) return;
if (av.at !== null && !canAct(s, ref)) return;
@ -569,7 +570,7 @@ export function legalActions(s: GameState): Action[] {
});
pushClears(s, p, out);
} else if (s.step === 'attack') {
me.avatars.forEach((_, i) => {
me.anomalies.forEach((_, i) => {
if (commandSpent(s)) return;
for (const to of attackTargets(s, { player: p, slot: i + 1 })) out.push({ type: 'attack', slot: i + 1, to });
});
@ -583,26 +584,26 @@ export function legalActions(s: GameState): Action[] {
seen.add(def.name);
if (def.kind === 'hardware') {
for (const ref of refsInPlay(s, p)) {
if (canWear(s, card, ref) && hardwareCost(s, card, ref, all) <= me.ram) {
if (canWear(s, card, ref) && hardwareCost(s, card, ref, all) <= me.bandwidth) {
out.push({ type: 'installHardware', card, slot: ref.slot });
}
}
} else if (def.kind === 'avatar' && s.rules.recruit.on) {
if (def.ram <= me.ram) for (const slot of recruitSlots(s, p)) out.push({ type: 'recruit', card, slot });
} else if (def.kind === 'anomaly' && s.rules.recruit.on) {
if (def.bandwidth <= me.bandwidth) for (const slot of recruitSlots(s, p)) out.push({ type: 'recruit', card, slot });
} else if (def.kind === 'program') {
for (const at of LOCATIONS) {
if (controls(s, p, at) && s.locations[at].programs.length < programSlots(s, at) && programCost(s, p, card, at, all) <= me.ram) {
if (controls(s, p, at) && s.locations[at].programs.length < programSlots(s, at) && programCost(s, p, card, at, all) <= me.bandwidth) {
out.push({ type: 'installProgram', card, at });
}
}
}
}
const sale = avatarForSale(s, p);
if (sale && sale.price <= me.ram) out.push({ type: 'buyAvatar', slot: sale.slot });
const sale = anomalyForSale(s, p);
if (sale && sale.price <= me.bandwidth) out.push({ type: 'buyAnomaly', slot: sale.slot });
for (const line of LINES) {
if (!line.gateway || !(controls(s, p, line.a) || controls(s, p, line.b))) continue;
for (let level = (s.firewalls[line.id] ?? 0) + 1; level <= s.rules.firewallCost.length; level++) {
if (placeFirewallCost(s, p, line.id, level, all) <= me.ram) out.push({ type: 'firewall', line: line.id, level });
if (placeFirewallCost(s, p, line.id, level, all) <= me.bandwidth) out.push({ type: 'firewall', line: line.id, level });
}
}
}
@ -610,7 +611,7 @@ export function legalActions(s: GameState): Action[] {
return out;
}
/** RAM an action costs, before any Salvage. */
/** Bandwidth an action costs, before any Salvage. */
export function actionCost(s: GameState, a: Action): number {
const p = decider(s) ?? s.active;
switch (a.type) {
@ -621,9 +622,9 @@ export function actionCost(s: GameState, a: Action): number {
case 'installHardware':
return hardwareCost(s, a.card, { player: p, slot: a.slot });
case 'recruit':
return defOf(s, a.card).ram;
case 'buyAvatar':
return avatarForSale(s, p)?.price ?? 0;
return defOf(s, a.card).bandwidth;
case 'buyAnomaly':
return anomalyForSale(s, p)?.price ?? 0;
case 'installProgram':
return programCost(s, p, a.card, a.at);
case 'play':
@ -666,7 +667,7 @@ export function actionKey(a: Action): string {
return `hw:${a.card}:${a.slot}`;
case 'recruit':
return `recruit:${a.card}:${a.slot}`;
case 'buyAvatar':
case 'buyAnomaly':
return `buy:${a.slot}`;
case 'installProgram':
return `prog:${a.card}:${a.at}`;
@ -701,7 +702,7 @@ export function applyAction(s: GameState, a: Action, legal: Action[] = legalActi
const p = decider(s)!;
const me = s.players[p];
const who = playerName(p);
const ref = (slot: number): AvatarRef => ({ player: p, slot });
const ref = (slot: number): AnomalyRef => ({ player: p, slot });
switch (a.type) {
case 'end':
@ -717,69 +718,70 @@ export function applyAction(s: GameState, a: Action, legal: Action[] = legalActi
const ch = s.choice!;
const option = ch.options[a.index];
s.choice = null;
say(s, `${who} chooses: ${option.label}.`);
const secret = ch.secret ? { to: p, public: `${who} makes a secret choice (${ch.kind.split(':')[0]}).` } : {};
say(s, `${who} chooses: ${option.label}.`, { tag: 'choice', player: p, ...secret });
const fn = scriptOf(ch.resume.name)?.resume?.[ch.resume.fn];
if (!fn) throw new Error(`No resume ${ch.resume.name}.${ch.resume.fn}`);
fn(s, ch.resume.data, option.value);
break;
}
case 'buyAvatar': {
const { price } = avatarForSale(s, p)!;
const av = me.avatars[a.slot - 1];
me.ram -= price;
stat(s, 'ramOnAvatars', p, price);
stat(s, 'avatarsBought', p);
case 'buyAnomaly': {
const { price } = anomalyForSale(s, p)!;
const av = me.anomalies[a.slot - 1];
me.bandwidth -= price;
stat(s, 'bandwidthOnAnomalies', p, price);
stat(s, 'anomaliesBought', p);
av.faceUp = true;
say(s, `${who} buys Avatar ${a.slot}: ${nameOf(s, av.card)} (-${price} RAM, now ${me.ram}).`);
say(s, `${who} buys Anomaly ${a.slot}: ${nameOf(s, av.card)} (-${price} Gb, now ${me.bandwidth}).`, { tag: 'card', player: p });
break;
}
case 'recruit': {
const cost = defOf(s, a.card).ram;
const av = me.avatars[a.slot - 1];
if (av.card >= 0) retireAvatar(s, ref(a.slot));
const cost = defOf(s, a.card).bandwidth;
const av = me.anomalies[a.slot - 1];
if (av.card >= 0) retireAnomaly(s, ref(a.slot));
removeFrom(me.hand, a.card);
me.ram -= cost;
stat(s, 'ramOnCards', p, cost);
stat(s, 'avatarsRecruited', p);
me.bandwidth -= cost;
stat(s, 'bandwidthOnCards', p, cost);
stat(s, 'anomaliesRecruited', p);
played(s, nameOf(s, a.card), p);
Object.assign(av, newAvatar(a.card, true, null));
me.avatars[a.slot + 3].card = a.card;
say(s, `${who} recruits ${nameOf(s, a.card)} as Avatar ${a.slot} (-${cost} RAM, now ${me.ram}).`);
Object.assign(av, newAnomaly(a.card, true, null));
me.anomalies[a.slot + 3].card = a.card;
say(s, `${who} recruits ${nameOf(s, a.card)} as Anomaly ${a.slot} (-${cost} Gb, now ${me.bandwidth}).`, { tag: 'card', player: p });
break;
}
case 'salvage': {
const gain = defOf(s, a.card).ram;
const gain = defOf(s, a.card).bandwidth;
removeFrom(me.hand, a.card);
toDiscard(s, a.card);
me.ram += gain;
stat(s, 'ramFromSalvage', p, gain);
me.bandwidth += gain;
stat(s, 'bandwidthFromSalvage', p, gain);
stat(s, 'cardsSalvaged', p);
say(s, `${who} salvages ${nameOf(s, a.card)} (+${gain} RAM, now ${me.ram}).`);
say(s, `${who} salvages ${nameOf(s, a.card)} (+${gain} Gb, now ${me.bandwidth}).`, { tag: 'card', player: p });
break;
}
case 'place': {
const av = me.avatars[a.slot - 1];
const av = me.anomalies[a.slot - 1];
say(s, av.at === null
? `${who} places ${avatarName(s, ref(a.slot))} on ${a.to}.`
: `${who} moves ${avatarName(s, ref(a.slot))} ${av.at} → ${a.to}.`);
? `${who} places ${anomalyName(s, ref(a.slot))} on ${a.to}.`
: `${who} moves ${anomalyName(s, ref(a.slot))} ${av.at} → ${a.to}.`, { tag: 'move', player: p, loc: a.to, ref: ref(a.slot) });
av.at = a.to;
av.placed = true;
break;
}
case 'recall':
recallAvatar(s, ref(a.slot));
recallAnomaly(s, ref(a.slot));
break;
case 'advance':
case 'attack': {
const r = ref(a.slot);
const av = avatar(s, r);
const av = anomaly(s, r);
const second = a.type === 'attack' && av.attacks > 0;
if (a.type === 'advance') av.advanced = true;
else av.attacks++;
s.declarations.push({ kind: a.type, ref: r, to: a.to, from: av.at!, second });
say(s, a.type === 'advance'
? `${who}: ${avatarName(s, r)} advances to ${a.to}.`
: `${who}: ${avatarName(s, r)} attacks ${a.to} from ${av.at}${second ? ' (Infinite Loop)' : ''}.`);
? `${who}: ${anomalyName(s, r)} advances to ${a.to}.`
: `${who}: ${anomalyName(s, r)} attacks ${a.to} from ${av.at}${second ? ' (Infinite Loop)' : ''}.`, { tag: 'move', player: p, loc: a.to, ref: r });
respondTo(s, p, s.stack.length);
if (a.type === 'attack') emit(s, 'onAttackDeclared', { ref: r, to: a.to });
break;
@ -787,44 +789,44 @@ export function applyAction(s: GameState, a: Action, legal: Action[] = legalActi
case 'clearFirewall': {
const level = s.firewalls[a.line];
const cost = firewallCost(s, level);
me.ram -= cost;
stat(s, 'ramOnFirewalls', p, cost);
me.bandwidth -= cost;
stat(s, 'bandwidthOnFirewalls', p, cost);
delete s.firewalls[a.line];
stat(s, 'firewallsCleared', p);
say(s, `${who} clears the Lv ${level} Firewall on ${a.line} (-${cost} RAM).`);
say(s, `${who} clears the Lv ${level} Firewall on ${a.line} (-${cost} Gb).`, { tag: 'firewall', player: p });
break;
}
case 'firewall': {
const before = s.firewalls[a.line] ?? 0;
const cost = pay(s, { kind: 'firewall', player: p, line: a.line, level: a.level }, 'ramOnFirewalls');
const cost = pay(s, { kind: 'firewall', player: p, line: a.line, level: a.level }, 'bandwidthOnFirewalls');
s.firewalls[a.line] = a.level;
stat(s, before ? 'firewallsUpgraded' : 'firewallsPlaced', p);
say(s, before
? `${who} upgrades the Firewall on ${a.line} to Lv ${a.level} (-${cost} RAM).`
: `${who} places a Lv ${a.level} Firewall on ${a.line} (-${cost} RAM).`);
? `${who} upgrades the Firewall on ${a.line} to Lv ${a.level} (-${cost} Gb).`
: `${who} places a Lv ${a.level} Firewall on ${a.line} (-${cost} Gb).`, { tag: 'firewall', player: p });
break;
}
case 'installHardware': {
const r = ref(a.slot);
const cost = pay(s, { kind: 'hardware', player: p, card: a.card, ref: r, at: avatar(s, r).at }, 'ramOnCards');
const cost = pay(s, { kind: 'hardware', player: p, card: a.card, ref: r, at: anomaly(s, r).at }, 'bandwidthOnCards');
removeFrom(me.hand, a.card);
avatar(s, r).hardware.push(a.card);
anomaly(s, r).hardware.push(a.card);
s.cards[a.card].installedTurn = s.turn;
stat(s, 'hardwareInstalled', p);
played(s, nameOf(s, a.card), p);
say(s, `${who} installs ${nameOf(s, a.card)} on ${avatarName(s, r)} (-${cost} RAM).`);
say(s, `${who} installs ${nameOf(s, a.card)} on ${anomalyName(s, r)} (-${cost} Gb).`, { tag: 'card', player: p, ref: r, loc: anomaly(s, r).at ?? undefined });
respondTo(s, p, s.stack.length);
emit(s, 'onInstall', { card: a.card, at: avatar(s, r).at, ref: r });
emit(s, 'onInstall', { card: a.card, at: anomaly(s, r).at, ref: r });
break;
}
case 'installProgram': {
const cost = pay(s, { kind: 'program', player: p, card: a.card, at: a.at }, 'ramOnCards');
const cost = pay(s, { kind: 'program', player: p, card: a.card, at: a.at }, 'bandwidthOnCards');
removeFrom(me.hand, a.card);
s.locations[a.at].programs.push(a.card);
s.cards[a.card].installedTurn = s.turn;
stat(s, 'programsInstalled', p);
played(s, nameOf(s, a.card), p);
say(s, `${who} installs ${nameOf(s, a.card)} on ${a.at} (-${cost} RAM).`);
say(s, `${who} installs ${nameOf(s, a.card)} on ${a.at} (-${cost} Gb).`, { tag: 'card', player: p, loc: a.at });
respondTo(s, p, s.stack.length);
emit(s, 'onInstall', { card: a.card, at: a.at, ref: null });
break;
@ -832,7 +834,7 @@ export function applyAction(s: GameState, a: Action, legal: Action[] = legalActi
case 'play': {
const name = nameOf(s, a.card);
const hostile = executionHostiles(s, { player: p, target: a.target, args: a.args, name });
const cost = pay(s, { kind: 'execution', player: p, card: a.card, at: a.target, hostile }, 'ramOnCards');
const cost = pay(s, { kind: 'execution', player: p, card: a.card, at: a.target, hostile }, 'bandwidthOnCards');
removeFrom(me.hand, a.card);
const item: StackItem = {
kind: 'execution', player: p, card: a.card, name, target: a.target, args: a.args, from: a.from,
@ -842,7 +844,7 @@ export function applyAction(s: GameState, a: Action, legal: Action[] = legalActi
if (item.power > 0) fired(s, 'Dedicated GPU', p);
stat(s, 'executionsPlayed', p);
played(s, name, p);
say(s, `${who} plays ${name}${a.target ? ` on ${a.target}` : ''}${a.from ? ` from ${a.from}` : ''} (-${cost} RAM).`);
say(s, `${who} plays ${name}${a.target ? ` on ${a.target}` : ''}${a.from ? ` from ${a.from}` : ''} (-${cost} Gb).`, { tag: 'card', player: p, loc: a.target ?? undefined });
respondTo(s, p, s.stack.length - 1);
if (hostile.length) pushTasks(s, { t: 'call', name: 'False Positive', fn: 'offer', data: { index: s.stack.length - 1 } });
break;
@ -850,15 +852,15 @@ export function applyAction(s: GameState, a: Action, legal: Action[] = legalActi
case 'activate': {
const src = abilitySource(s, a.card, a.name)!;
const cost = abilityCost(s, src) + (scriptOf(src.name)!.ability!.extraCost?.(s, src, a.args) ?? 0);
me.ram -= cost;
stat(s, 'ramOnAbilities', p, cost);
me.bandwidth -= cost;
stat(s, 'bandwidthOnAbilities', p, cost);
if (src.kind === 'hardware') useHardware(s, src.id);
else markUsed(s, abilityKey(src));
const label = src.kind === 'avatar' ? `${defOf(s, src.id).ability!.name} (${src.name})` : src.name;
const label = src.kind === 'anomaly' ? `${defOf(s, src.id).ability!.name} (${src.name})` : src.name;
s.stack.push({ kind: 'ability', player: p, card: src.id, name: src.name, target: null, args: a.args, from: null, power: 0 });
stat(s, 'abilitiesUsed', p);
if (src.kind === 'avatar') played(s, src.name, p);
say(s, `${who} uses ${label}${cost ? ` (-${cost} RAM)` : ''}.`);
if (src.kind === 'anomaly') played(s, src.name, p);
say(s, `${who} uses ${label}${cost ? ` (-${cost} Gb)` : ''}.`, { tag: 'card', player: p, loc: src.at ?? undefined, ref: src.ref });
respondTo(s, p, s.stack.length - 1);
break;
}
@ -999,7 +1001,7 @@ function execute(s: GameState, task: Task): void {
/**
* What player `p` can see. Hidden cards become -1: the opponent's hand, both decks and Server
* piles, and face-down Avatars. The RNG is blanked so bots can't predict dice, the opponent's
* piles, and face-down Anomalies. The RNG is blanked so bots can't predict dice, the opponent's
* choices are hidden, and only open windows are kept from the task queue. Everything else is
* shared with the real state, so treat a view as read-only.
*/
@ -1011,9 +1013,15 @@ export function viewFor(s: GameState, p: PlayerId): GameState {
deck: hide(pl.deck),
serverPile: hide(pl.serverPile),
discard: [...pl.discard],
avatars: pl.avatars.map((av) => ({ ...av, hardware: [...av.hardware], card: av.faceUp ? av.card : -1 })),
anomalies: pl.anomalies.map((av) => ({ ...av, hardware: [...av.hardware], card: av.faceUp ? av.card : -1 })),
}));
const choice = s.choice && s.choice.player !== p ? { ...s.choice, options: s.choice.options.map(() => ({ label: '?', value: null })) } : s.choice;
const choice = s.choice && s.choice.player !== p
? {
...s.choice,
prompt: s.choice.secret ? `${s.choice.kind.split(':')[0]}: ${playerName(s.choice.player)} is choosing.` : s.choice.prompt,
options: s.choice.options.map(() => ({ label: '?', value: null })),
}
: s.choice;
const combat = s.combat ? { ...s.combat, race: s.combat.race.map((r, i) => (i === p ? r : null)) as typeof s.combat.race } : null;
return {
...s,

View file

@ -1,24 +1,24 @@
/**
* The parts of a turn that run on their own once started: resolving declarations, combat,
* defeat, capture and drawing. Card scripts call into these too (Trace Route starts a combat,
* Disconnect pulls an Avatar out of one).
* Disconnect pulls an Anomaly out of one).
*/
import { isStart, levelFor, type LocId } from './map.ts';
import { scriptOf } from './scripts.ts';
import { coresOf, emit, fighterOf, hardwareActive, healthLeft, healthOf, sideCores } from './query.ts';
import {
adjacent,
avatar,
avatarName,
anomaly,
anomalyName,
controls,
copyOf,
defendersAt,
fightersOf,
fired,
gainRam,
gainBandwidth,
gridCount,
isCopy,
isDisabledAvatar,
isDisabledAnomaly,
isRooted,
nameOf,
neighbors,
@ -35,7 +35,7 @@ import {
stat,
toDiscard,
} from './state.ts';
import type { AvatarRef, AvatarState, CaptureStat, Combat, GameState, PlayerId, Task } from './types.ts';
import type { AnomalyRef, AnomalyState, CaptureStat, Combat, GameState, PlayerId, Task } from './types.ts';
// ---------------------------------------------------------------------------------------------
// Drawing
@ -60,9 +60,9 @@ export function drawTask(s: GameState, p: PlayerId): void {
}
// ---------------------------------------------------------------------------------------------
// Avatars leaving and entering play
// Anomalies leaving and entering play
function clearStatus(av: AvatarState): void {
function clearStatus(av: AnomalyState): void {
av.infection = 0;
av.bugs = 0;
av.mods = [];
@ -72,10 +72,10 @@ function clearStatus(av: AvatarState): void {
}
/** A copy leaves play. It has no Hardware of its own. */
export function removeCopy(s: GameState, ref: AvatarRef): void {
const cp = avatar(s, ref);
export function removeCopy(s: GameState, ref: AnomalyRef): void {
const cp = anomaly(s, ref);
if (cp.at === null) return;
say(s, `${avatarName(s, ref)} is removed.`);
say(s, `${anomalyName(s, ref)} is removed.`, { tag: 'move', player: ref.player, ref });
clearStatus(cp);
cp.permanentInfection = 0;
cp.at = null;
@ -83,53 +83,53 @@ export function removeCopy(s: GameState, ref: AvatarRef): void {
dropFromCombat(s, ref);
}
/** Recruit rule: an Avatar recruited over leaves for the discard pile with its Hardware, and its copy leaves play. */
export function retireAvatar(s: GameState, ref: AvatarRef): void {
const av = avatar(s, ref);
/** Recruit rule: an Anomaly recruited over leaves for the discard pile with its Hardware, and its copy leaves play. */
export function retireAnomaly(s: GameState, ref: AnomalyRef): void {
const av = anomaly(s, ref);
removeCopy(s, copyOf(ref));
if (av.hardware.length) stat(s, 'hardwareLost', ref.player, av.hardware.length);
for (const hw of av.hardware) toDiscard(s, hw);
say(s, `${playerName(ref.player)} retires ${avatarName(s, ref)}${av.at ? ` from ${av.at}` : ''}.`);
say(s, `${playerName(ref.player)} retires ${anomalyName(s, ref)}${av.at ? ` from ${av.at}` : ''}.`, { tag: 'card', player: ref.player, ref });
dropFromCombat(s, ref);
toDiscard(s, av.card);
stat(s, 'avatarsRetired', ref.player);
stat(s, 'anomaliesRetired', ref.player);
}
/**
* The loser of a combat goes back to its slot. Its Hardware is discarded unless `keepHardware`,
* and its counters and effects are removed (Persistent Infection's counters stay).
*/
export function knockOut(s: GameState, ref: AvatarRef, loc: LocId, role: 'attack' | 'defend', keepHardware: boolean): void {
const av = avatar(s, ref);
export function knockOut(s: GameState, ref: AnomalyRef, loc: LocId, role: 'attack' | 'defend', keepHardware: boolean): void {
const av = anomaly(s, ref);
if (av.at === null) return;
if (isCopy(ref)) {
removeCopy(s, ref);
} else {
if (!keepHardware && av.hardware.length) {
say(s, `${playerName(ref.player)} loses ${av.hardware.map((h) => nameOf(s, h)).join(', ')}.`);
say(s, `${playerName(ref.player)} loses ${av.hardware.map((h) => nameOf(s, h)).join(', ')}.`, { tag: 'combat', player: ref.player, ref, loc });
stat(s, 'hardwareLost', ref.player, av.hardware.length);
for (const hw of av.hardware) toDiscard(s, hw);
av.hardware = [];
}
clearStatus(av);
av.at = null;
say(s, `${avatarName(s, ref)} returns to its slot.`);
say(s, `${anomalyName(s, ref)} returns to its slot.`, { tag: 'combat', player: ref.player, ref, loc });
removeCopy(s, copyOf(ref));
}
stat(s, 'avatarsDestroyed', ref.player);
stat(s, 'anomaliesDestroyed', ref.player);
emit(s, 'onDefeat', { ref, loc, role });
}
/**
* Health rule: an Avatar returns to its slot by its owner's choice, as its placement for the
* Health rule: an Anomaly returns to its slot by its owner's choice, as its placement for the
* round. It heals fully and keeps its Hardware; like a defeat, its counters and effects come off
* (Persistent Infection's stay) and its copy leaves play.
*/
export function recallAvatar(s: GameState, ref: AvatarRef): void {
const av = avatar(s, ref);
export function recallAnomaly(s: GameState, ref: AnomalyRef): void {
const av = anomaly(s, ref);
if (av.at === null) return;
const healed = av.damage;
say(s, `${playerName(ref.player)} recalls ${avatarName(s, ref)} from ${av.at} to its slot${healed ? `, healing ${healed} damage` : ''}.`);
say(s, `${playerName(ref.player)} recalls ${anomalyName(s, ref)} from ${av.at} to its slot${healed ? `, healing ${healed} damage` : ''}.`, { tag: 'move', player: ref.player, ref, loc: av.at });
clearStatus(av);
av.at = null;
av.placed = true;
@ -138,11 +138,11 @@ export function recallAvatar(s: GameState, ref: AvatarRef): void {
}
/** Places a copy of `original` on `to`. */
export function createCopy(s: GameState, original: AvatarRef, to: LocId): void {
export function createCopy(s: GameState, original: AnomalyRef, to: LocId): void {
const ref = copyOf(original);
const cp = avatar(s, ref);
const cp = anomaly(s, ref);
Object.assign(cp, {
card: avatar(s, original).card,
card: anomaly(s, original).card,
faceUp: true,
at: to,
hardware: [],
@ -158,14 +158,14 @@ export function createCopy(s: GameState, original: AvatarRef, to: LocId): void {
rootedUntil: 0,
breachedTurn: 0,
createdTurn: s.turn,
} satisfies Partial<AvatarState>);
say(s, `${playerName(ref.player)} creates ${avatarName(s, ref)} on ${to}.`);
} satisfies Partial<AnomalyState>);
say(s, `${playerName(ref.player)} creates ${anomalyName(s, ref)} on ${to}.`, { tag: 'card', player: ref.player, ref, loc: to });
}
/** Moves an Avatar by a card effect. Callers check the move is legal. */
export function moveAvatar(s: GameState, ref: AvatarRef, to: LocId): void {
const av = avatar(s, ref);
say(s, `${avatarName(s, ref)} moves ${av.at} → ${to}.`);
/** Moves an Anomaly by a card effect. Callers check the move is legal. */
export function moveAnomaly(s: GameState, ref: AnomalyRef, to: LocId): void {
const av = anomaly(s, ref);
say(s, `${anomalyName(s, ref)} moves ${av.at} → ${to}.`, { tag: 'move', player: ref.player, ref, loc: to });
av.at = to;
}
@ -175,11 +175,11 @@ export function moveAvatar(s: GameState, ref: AvatarRef, to: LocId): void {
export function resolveDeclaration(s: GameState, index: number): void {
const d = s.declarations[index];
const p = d.ref.player;
const av = avatar(s, d.ref);
const who = avatarName(s, d.ref);
const av = anomaly(s, d.ref);
const who = anomalyName(s, d.ref);
if (av.at === null) return;
if (isRooted(s, d.ref) || isDisabledAvatar(s, d.ref)) {
say(s, `${who} can't move, so its ${d.kind} on ${d.to} fails.`);
if (isRooted(s, d.ref) || isDisabledAnomaly(s, d.ref)) {
say(s, `${who} can't move, so its ${d.kind} on ${d.to} fails.`, { tag: 'move', player: p, ref: d.ref, loc: d.to });
return;
}
if (controls(s, p, d.to)) return;
@ -187,7 +187,7 @@ export function resolveDeclaration(s: GameState, index: number): void {
const how: CaptureStat = s.locations[d.to].owner === null ? 'capturesUnowned' : 'capturesUndefended';
if (d.kind === 'advance') {
if (!neighbors(s, d.to).some((n) => controls(s, p, n))) {
say(s, `${who} can no longer reach ${d.to}.`);
say(s, `${who} can no longer reach ${d.to}.`, { tag: 'move', player: p, ref: d.ref, loc: d.to });
return;
}
if (defended) startCombat(s, d.ref, av.at, d.to, 'advance');
@ -195,7 +195,7 @@ export function resolveDeclaration(s: GameState, index: number): void {
return;
}
if ((!d.second && av.at !== d.from) || !controls(s, p, d.from) || !adjacent(s, d.from, d.to)) {
say(s, `${who}'s attack on ${d.to} fails: it's no longer in position.`);
say(s, `${who}'s attack on ${d.to} fails: it's no longer in position.`, { tag: 'move', player: p, ref: d.ref, loc: d.to });
return;
}
if (defended) startCombat(s, d.ref, d.from, d.to, 'attack');
@ -216,7 +216,7 @@ function sideTotals(c: Combat): { atk: number; def: number } {
}
function diceText(s: GameState, c: Combat): string {
const one = (r: AvatarRef) => `${nameOf(s, avatar(s, r).card)} [${(c.dice[refKey(r)] ?? []).join(',')}]`;
const one = (r: AnomalyRef) => `${nameOf(s, anomaly(s, r).card)} [${(c.dice[refKey(r)] ?? []).join(',')}]`;
const t = sideTotals(c);
return `${one(c.attacker)}=${t.atk} vs ${c.defenders.map(one).join(' + ')}=${t.def}`;
}
@ -236,15 +236,15 @@ function rollAll(s: GameState, c: Combat): void {
// Damage (health rule)
/** Health text for the combat log, e.g. "7/10 Health". */
export const healthText = (s: GameState, r: AvatarRef): string => `${healthLeft(s, r)}/${healthOf(s, r)} Health`;
export const healthText = (s: GameState, r: AnomalyRef): string => `${healthLeft(s, r)}/${healthOf(s, r)} Health`;
/** Deals `n` damage to an Avatar. Returns true if that destroys it (its damage reaches its Health). */
export function damageAvatar(s: GameState, ref: AvatarRef, n: number): boolean {
const av = avatar(s, ref);
/** Deals `n` damage to an Anomaly. Returns true if that destroys it (its damage reaches its Health). */
export function damageAnomaly(s: GameState, ref: AnomalyRef, n: number): boolean {
const av = anomaly(s, ref);
if (av.at === null || n <= 0) return false;
av.damage += n;
const dead = av.damage >= healthOf(s, ref);
say(s, `${avatarName(s, ref)} takes ${n} damage${dead ? ' and is destroyed' : ` (${healthText(s, ref)})`}.`);
say(s, `${anomalyName(s, ref)} takes ${n} damage${dead ? ' and is destroyed' : ` (${healthText(s, ref)})`}.`, { tag: 'combat', player: ref.player, ref, amount: n, loc: av.at });
return dead;
}
@ -253,9 +253,9 @@ export function damageAvatar(s: GameState, ref: AvatarRef, n: number): boolean {
* most defenders, weakest first, and puts what's left on the weakest survivor. Returns the
* destroyed defenders.
*/
function allocateDamage(s: GameState, defenders: AvatarRef[], n: number): { ref: AvatarRef; amount: number; destroyed: boolean }[] {
function allocateDamage(s: GameState, defenders: AnomalyRef[], n: number): { ref: AnomalyRef; amount: number; destroyed: boolean }[] {
const order = [...defenders].sort((a, b) => healthLeft(s, a) - healthLeft(s, b));
const hits: { ref: AvatarRef; amount: number; destroyed: boolean }[] = [];
const hits: { ref: AnomalyRef; amount: number; destroyed: boolean }[] = [];
for (const [i, d] of order.entries()) {
if (n <= 0) break;
const left = healthLeft(s, d);
@ -263,35 +263,35 @@ function allocateDamage(s: GameState, defenders: AvatarRef[], n: number): { ref:
if (hit === 0) {
// Can't destroy this one: dump the rest on the weakest.
const first = hits.find((h) => refKey(h.ref) === refKey(order[0]));
damageAvatar(s, order[0], n);
damageAnomaly(s, order[0], n);
if (first) first.amount += n;
else hits.push({ ref: order[0], amount: n, destroyed: false });
break;
}
n -= hit;
hits.push({ ref: d, amount: hit, destroyed: damageAvatar(s, d, hit) });
hits.push({ ref: d, amount: hit, destroyed: damageAnomaly(s, d, hit) });
}
return hits;
}
/** Tells the cards that an Avatar lost a roll (Resource Leech, Overflow Error, Persistent Infection). */
function emitDamage(s: GameState, ref: AvatarRef, loc: LocId, role: 'attack' | 'defend', amount: number, destroyed: boolean): void {
/** Tells the cards that an Anomaly lost a roll (Resource Leech, Overflow Error, Persistent Infection). */
function emitDamage(s: GameState, ref: AnomalyRef, loc: LocId, role: 'attack' | 'defend', amount: number, destroyed: boolean): void {
emit(s, 'onDamage', { ref, loc, role, amount, destroyed });
}
/** Health rule: the loser of the roll takes the difference as damage; destroyed Avatars are defeated. */
/** Health rule: the loser of the roll takes the difference as damage; destroyed Anomalies are defeated. */
function resolveDamage(s: GameState, c: Combat, t: { atk: number; def: number }): void {
if (t.atk === t.def) {
c.ties++;
stat(s, 'combatsTied', c.attacker.player);
say(s, `Tie, ${t.atk} to ${t.def}: a stalemate. Nobody takes damage.`);
say(s, `Tie, ${t.atk} to ${t.def}: a stalemate. Nobody takes damage.`, { tag: 'combat', loc: c.loc });
return;
}
const margin = Math.abs(t.atk - t.def);
const attackerWins = t.atk > t.def;
const defender = s.locations[c.loc].owner!;
const winner = attackerWins ? c.attacker.player : defender;
say(s, `${playerName(winner)} wins the roll, ${t.atk} to ${t.def}: ${margin} damage.`);
say(s, `${playerName(winner)} wins the roll, ${t.atk} to ${t.def}: ${margin} damage.`, { tag: 'combat', player: winner, loc: c.loc });
stat(s, 'damageDealt', winner, margin);
if (attackerWins) {
stat(s, 'attacksWon', c.attacker.player);
@ -300,12 +300,12 @@ function resolveDamage(s: GameState, c: Combat, t: { atk: number; def: number })
const tasks: Task[] = destroyed.map((ref): Task => ({ t: 'defeat', ref, loc: c.loc, role: 'defend' }));
if (destroyed.length === c.defenders.length) {
tasks.push({ t: 'capture', ref: c.attacker, loc: c.loc, stage: 'hooks', how: 'capturesInCombat' });
} else say(s, `${c.loc} holds.`);
} else say(s, `${c.loc} holds.`, { tag: 'combat', player: defender, loc: c.loc });
pushTasks(s, ...tasks);
// Pushed last, so the damage hooks run before the defeats.
for (const h of hits) emitDamage(s, h.ref, c.loc, 'defend', h.amount, h.destroyed);
} else {
const dead = damageAvatar(s, c.attacker, margin);
const dead = damageAnomaly(s, c.attacker, margin);
if (dead) pushTasks(s, { t: 'defeat', ref: c.attacker, loc: c.loc, role: 'attack' });
emitDamage(s, c.attacker, c.loc, 'attack', margin, dead);
}
@ -313,7 +313,7 @@ function resolveDamage(s: GameState, c: Combat, t: { atk: number; def: number })
/**
* Cores that change after the roll change the dice: each Core gained rolls one more die, and each
* Core lost removes that Avatar's highest die.
* Core lost removes that Anomaly's highest die.
*/
export function syncDice(s: GameState, c: Combat): void {
if (!c.rolled) return;
@ -343,18 +343,18 @@ export function endCombat(s: GameState, why: string): void {
if (!c || c.ended) return;
c.ended = true;
stat(s, 'combatsEnded', c.attacker.player);
say(s, `The combat at ${c.loc} ends: ${why}.`);
say(s, `The combat at ${c.loc} ends: ${why}.`, { tag: 'combat', loc: c.loc });
}
/**
* Takes an Avatar out of the current combat. If the attacker leaves, the combat ends. If the last
* Takes an Anomaly out of the current combat. If the attacker leaves, the combat ends. If the last
* defender leaves, the attacker takes the location as undefended.
*/
export function dropFromCombat(s: GameState, ref: AvatarRef): void {
export function dropFromCombat(s: GameState, ref: AnomalyRef): void {
const c = s.combat;
if (!c || c.ended) return;
if (sameRef(c.attacker, ref)) {
endCombat(s, `${avatarName(s, ref)} left it`);
endCombat(s, `${anomalyName(s, ref)} left it`);
return;
}
const i = c.defenders.findIndex((d) => sameRef(d, ref));
@ -363,16 +363,32 @@ export function dropFromCombat(s: GameState, ref: AvatarRef): void {
delete c.dice[refKey(ref)];
if (c.defenders.length === 0) {
endCombat(s, 'no defender is left');
if (avatar(s, c.attacker).at !== null) pushCapture(s, c.attacker, c.loc, 'capturesUndefended');
if (anomaly(s, c.attacker).at !== null) pushCapture(s, c.attacker, c.loc, 'capturesUndefended');
}
}
export function combatStage(s: GameState, stage: 'start' | 'roll' | 'result' | 'end' | 'cleanup'): void {
/** Combat stages an app can watch. */
export type CombatStage = 'start' | 'roll' | 'result' | 'end';
/**
* Lets an app see each combat as it happens, since a whole combat can run inside one applyAction.
* Called after a combat starts, after the roll, before the result is applied (with the final dice),
* and when it ends. Null in the sim.
*/
export const combatWatch: { fn: ((s: GameState, stage: CombatStage) => void) | null } = { fn: null };
export function combatStage(s: GameState, stage: CombatStage | 'cleanup'): void {
const c = s.combat;
if (!c) return;
runStage(s, c, stage);
// 'result' is watched inside runStage, before the damage.
if (stage === 'start' || stage === 'roll' || stage === 'end') combatWatch.fn?.(s, stage);
}
function runStage(s: GameState, c: Combat, stage: CombatStage | 'cleanup'): void {
if (stage === 'cleanup') {
for (const r of fightersOf(c)) {
const av = avatar(s, r);
const av = anomaly(s, r);
av.mods = av.mods.filter((m) => m.combat !== c.id);
}
s.combat = null;
@ -387,9 +403,9 @@ export function combatStage(s: GameState, stage: 'start' | 'roll' | 'result' | '
if (stage === 'start') {
stat(s, 'attacks', c.attacker.player);
const { atk, def } = sideCores(s);
const hp = (r: AvatarRef) => (s.rules.health.on ? `, ${healthText(s, r)}` : '');
const defs = c.defenders.map((d) => `${avatarName(s, d)}${hp(d)}`).join(' and ');
say(s, `Combat at ${c.loc}: ${avatarName(s, c.attacker)} (${atk} Cores, from ${c.origin}${hp(c.attacker)}) vs ${defs} (${def} Cores).`);
const hp = (r: AnomalyRef) => (s.rules.health.on ? `, ${healthText(s, r)}` : '');
const defs = c.defenders.map((d) => `${anomalyName(s, d)}${hp(d)}`).join(' and ');
say(s, `Combat at ${c.loc}: ${anomalyName(s, c.attacker)} (${atk} Cores, from ${c.origin}${hp(c.attacker)}) vs ${defs} (${def} Cores).`, { tag: 'combat', player: c.attacker.player, loc: c.loc, ref: c.attacker });
emit(s, 'onCombatStart', null);
return;
}
@ -405,16 +421,17 @@ export function combatStage(s: GameState, stage: 'start' | 'roll' | 'result' | '
});
}
rollAll(s, c);
say(s, `Roll: ${diceText(s, c)}${c.ties ? ` after ${c.ties} tie reroll(s)` : ''}.`);
say(s, `Roll: ${diceText(s, c)}${c.ties ? ` after ${c.ties} tie reroll(s)` : ''}.`, { tag: 'combat', loc: c.loc });
return;
}
// result
const t = combatTotals(s);
combatWatch.fn?.(s, 'result');
if (s.rules.health.on) return resolveDamage(s, c, t);
if (t.atk === t.def) {
c.ties++;
rollAll(s, c);
say(s, `Tie, so both sides reroll: ${diceText(s, c)}.`);
say(s, `Tie, so both sides reroll: ${diceText(s, c)}.`, { tag: 'combat', loc: c.loc });
pushTasks(
s,
{ t: 'window', kind: 'postRoll', priority: c.attacker.player, passes: 0, base: s.stack.length, resolving: false },
@ -424,7 +441,7 @@ export function combatStage(s: GameState, stage: 'start' | 'roll' | 'result' | '
}
const attackerWins = t.atk > t.def;
const winner = attackerWins ? c.attacker.player : s.locations[c.loc].owner!;
say(s, `${playerName(winner)} wins the combat, ${t.atk} to ${t.def}.`);
say(s, `${playerName(winner)} wins the combat, ${t.atk} to ${t.def}.`, { tag: 'combat', player: winner, loc: c.loc });
if (attackerWins) {
stat(s, 'attacksWon', c.attacker.player);
pushTasks(
@ -443,8 +460,8 @@ export function combatStage(s: GameState, stage: 'start' | 'roll' | 'result' | '
// ---------------------------------------------------------------------------------------------
// Defeat
export function defeat(s: GameState, ref: AvatarRef, loc: LocId, role: 'attack' | 'defend'): void {
const av = avatar(s, ref);
export function defeat(s: GameState, ref: AnomalyRef, loc: LocId, role: 'attack' | 'defend'): void {
const av = anomaly(s, ref);
if (av.at === null) return;
if (!isCopy(ref)) {
// Redundant Power Supply, then RAID Array, may save the Hardware.
@ -461,23 +478,23 @@ export function defeat(s: GameState, ref: AvatarRef, loc: LocId, role: 'attack'
// ---------------------------------------------------------------------------------------------
// Capture
export function captureHooks(s: GameState, ref: AvatarRef, loc: LocId, how: CaptureStat): void {
export function captureHooks(s: GameState, ref: AnomalyRef, loc: LocId, how: CaptureStat): void {
const p = ref.player;
if (avatar(s, ref).at === null || controls(s, p, loc) || isStart(loc)) return;
if (anomaly(s, ref).at === null || controls(s, p, loc) || isStart(loc)) return;
pushTasks(s, { t: 'capture', ref, loc, stage: 'main', how });
const prev = s.locations[loc].owner;
if (prev !== null && prev !== p) {
avatar(s, ref).breachedTurn = s.turn;
anomaly(s, ref).breachedTurn = s.turn;
emit(s, 'onCaptured', { ref, loc });
emit(s, 'onBreach', { ref, loc });
}
}
export function captureMain(s: GameState, ref: AvatarRef, loc: LocId, how: CaptureStat): void {
export function captureMain(s: GameState, ref: AnomalyRef, loc: LocId, how: CaptureStat): void {
const p = ref.player;
const me = s.players[p];
const L = s.locations[loc];
if (avatar(s, ref).at === null || controls(s, p, loc)) return;
if (anomaly(s, ref).at === null || controls(s, p, loc)) return;
const previous = L.owner;
if (L.server !== null) {
resetCard(s, L.server);
@ -488,25 +505,25 @@ export function captureMain(s: GameState, ref: AvatarRef, loc: LocId, how: Captu
L.programs = [];
L.owner = p;
L.server = me.serverPile.shift() ?? null;
avatar(s, ref).at = loc;
anomaly(s, ref).at = loc;
const level = levelFor(p, loc);
const turn1 = s.turn === 1 ? s.rules.firstTurn : null;
const bonus = L.server === null ? 0 : (scriptOf(s.cards[L.server].name)?.ramOnPlace ?? 0);
const ram = (turn1?.captureRam === false ? 0 : s.rules.levelRam[level]) + bonus;
gainRam(s, p, ram, 'ramFromCaptures');
const bonus = L.server === null ? 0 : (scriptOf(s.cards[L.server].name)?.bandwidthOnPlace ?? 0);
const bandwidth = (turn1?.captureBandwidth === false ? 0 : s.rules.levelBandwidth[level]) + bonus;
gainBandwidth(s, p, bandwidth, 'bandwidthFromCaptures');
stat(s, how, p);
const from = previous === null ? '' : ` from ${playerName(previous)}`;
say(s, `${playerName(p)} captures ${loc}${from} (Lv ${level}) with ${L.server === null ? 'no Server' : nameOf(s, L.server)}: +${ram} RAM (now ${me.ram}).`);
say(s, `${playerName(p)} captures ${loc}${from} (Lv ${level}) with ${L.server === null ? 'no Server' : nameOf(s, L.server)}: +${bandwidth} Gb (now ${me.bandwidth}).`, { tag: 'capture', player: p, loc });
const unlocks = !s.rules.recruit.on && !s.rules.buyAvatars.on;
const unlocks = !s.rules.recruit.on && !s.rules.buyAnomalies.on;
if (unlocks && level > me.unlockedLevel && turn1?.unlock !== false) {
me.unlockedLevel = level;
me.avatars.slice(0, 4).forEach((av, i) => {
me.anomalies.slice(0, 4).forEach((av, i) => {
if (i < level && !av.faceUp) {
av.faceUp = true;
av.unlockedTurn = s.turn;
say(s, `${playerName(p)} unlocks Avatar ${i + 1}: ${nameOf(s, av.card)}.`);
say(s, `${playerName(p)} unlocks Anomaly ${i + 1}: ${nameOf(s, av.card)}.`, { tag: 'capture', player: p, loc });
}
});
}
@ -514,7 +531,7 @@ export function captureMain(s: GameState, ref: AvatarRef, loc: LocId, how: Captu
s.over = true;
s.winner = p;
s.endReason = 'win';
say(s, `${playerName(p)} wins with ${gridCount(s, p)} locations.`);
say(s, `${playerName(p)} wins with ${gridCount(s, p)} locations.`, { tag: 'game', player: p });
return;
}
if (L.server !== null) {

View file

@ -1,5 +1,5 @@
import { LOCATIONS } from './map.ts';
import { capacity, healthOf, portsTotal } from './query.ts';
import { capacity, healthOf, slotsTotal } from './query.ts';
import { scriptOf } from './scripts.ts';
import { controls } from './state.ts';
import type { GameState } from './types.ts';
@ -25,37 +25,37 @@ export function checkInvariants(s: GameState): string[] {
own(pl.deck, 'deck');
own(pl.discard, 'discard');
own(pl.serverPile, 'serverPile');
if (pl.ram < 0) errors.push(`p${p} has ${pl.ram} RAM`);
if (pl.bandwidth < 0) errors.push(`p${p} has ${pl.bandwidth} Gb`);
const count = new Map<string, number>();
pl.avatars.forEach((av, i) => {
pl.anomalies.forEach((av, i) => {
const slot = i + 1;
const copy = slot > 4;
if (!copy) {
if (av.card >= 0 || !s.rules.recruit.on) own([av.card], `avatar${slot}`);
if (av.card >= 0 || !s.rules.recruit.on) own([av.card], `anomaly${slot}`);
else if (av.at !== null || av.hardware.length) errors.push(`p${p} empty slot ${slot} is in use`);
own(av.hardware, `avatar${slot}.hardware`);
const ported = av.hardware.filter((h) => !scriptOf(s.cards[h].name)?.noPort && s.cards[h].pushedUntil === undefined);
if (av.card >= 0 && ported.length > portsTotal(s, { player: p as 0 | 1, slot })) errors.push(`p${p} Avatar ${slot} is over its slots`);
own(av.hardware, `anomaly${slot}.hardware`);
const ported = av.hardware.filter((h) => !scriptOf(s.cards[h].name)?.noSlot && s.cards[h].pushedUntil === undefined);
if (av.card >= 0 && ported.length > slotsTotal(s, { player: p as 0 | 1, slot })) errors.push(`p${p} Anomaly ${slot} is over its slots`);
} else {
if (av.hardware.length) errors.push(`p${p} copy ${slot - 4} has Hardware of its own`);
if (av.at !== null && pl.avatars[i - 4].at === null) errors.push(`p${p} copy ${slot - 4} is in play without its original`);
if (av.card !== pl.avatars[i - 4].card) errors.push(`p${p} copy ${slot - 4} doesn't match its original`);
if (av.at !== null && pl.anomalies[i - 4].at === null) errors.push(`p${p} copy ${slot - 4} is in play without its original`);
if (av.card !== pl.anomalies[i - 4].card) errors.push(`p${p} copy ${slot - 4} doesn't match its original`);
}
if (av.damage < 0) errors.push(`p${p} Avatar ${slot} has negative damage`);
if (av.damage < 0) errors.push(`p${p} Anomaly ${slot} has negative damage`);
if (av.at === null) {
if (av.damage !== 0) errors.push(`p${p} Avatar ${slot} is in its slot with ${av.damage} damage`);
if (av.damage !== 0) errors.push(`p${p} Anomaly ${slot} is in its slot with ${av.damage} damage`);
return;
}
if (!av.faceUp) errors.push(`p${p} Avatar ${slot} is in play face down`);
// A destroyed Avatar may still stand there while its defeat is being resolved (RAID Array's choice).
if (!av.faceUp) errors.push(`p${p} Anomaly ${slot} is in play face down`);
// A destroyed Anomaly may still stand there while its defeat is being resolved (RAID Array's choice).
const dying = s.choice !== null || s.tasks.some((t) => t.t === 'defeat' && t.ref.player === p && t.ref.slot === slot);
if (s.rules.health.on && !dying && av.damage >= healthOf(s, { player: p as 0 | 1, slot })) errors.push(`p${p} Avatar ${slot} is in play with no Health left`);
if (!controls(s, p as 0 | 1, av.at)) errors.push(`p${p} Avatar ${slot} is on ${av.at}, which it doesn't control`);
if (s.rules.health.on && !dying && av.damage >= healthOf(s, { player: p as 0 | 1, slot })) errors.push(`p${p} Anomaly ${slot} is in play with no Health left`);
if (!controls(s, p as 0 | 1, av.at)) errors.push(`p${p} Anomaly ${slot} is on ${av.at}, which it doesn't control`);
count.set(av.at, (count.get(av.at) ?? 0) + 1);
});
for (const [loc, n] of count) if (n > capacity(s, loc)) errors.push(`p${p} has ${n} Avatars on ${loc}`);
const total = pl.avatars.filter((av, i) => (i < 4 ? av.card >= 0 : av.at !== null)).length;
if (s.rules.recruit.on && total > 4) errors.push(`p${p} has ${total} Avatars, counting copies`);
for (const [loc, n] of count) if (n > capacity(s, loc)) errors.push(`p${p} has ${n} Anomalies on ${loc}`);
const total = pl.anomalies.filter((av, i) => (i < 4 ? av.card >= 0 : av.at !== null)).length;
if (s.rules.recruit.on && total > 4) errors.push(`p${p} has ${total} Anomalies, counting copies`);
});
for (const loc of LOCATIONS) {

11
sim/src/load.ts Normal file
View file

@ -0,0 +1,11 @@
/** Node-only card loading, for the CLI and tests. Browser code reads the CSV itself and calls parseCards. */
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { parseCards, type CardPool } from './cards.ts';
export const DEFAULT_CARDS_CSV = fileURLToPath(new URL('../../decks/files-deck-1/cards.csv', import.meta.url));
/** Loads the Cider deck CSV from disk. See parseCards for `sets`. */
export function loadCards(path = DEFAULT_CARDS_CSV, sets: number[] | 'all' = [1]): CardPool {
return parseCards(readFileSync(path, 'utf8'), sets, path);
}

View file

@ -4,10 +4,6 @@ import type { PlayerId } from './types.ts';
export type LocId = string;
export const START_LOC: readonly [LocId, LocId] = ['S1', 'S2'];
export const GRID: readonly LocId[] = [
'A1', 'A2', 'A3', 'B1', 'B2', 'C1', 'C2', 'C3', 'D1', 'D2', 'E1', 'E2', 'E3',
];
export const LOCATIONS: readonly LocId[] = [START_LOC[0], ...GRID, START_LOC[1]];
export interface Line {
id: string;
@ -17,44 +13,112 @@ export interface Line {
gateway: boolean;
}
const LINE_DEFS: [LocId, LocId, boolean][] = [
['S1', 'A2', false],
['A1', 'A2', true], ['A2', 'A3', true],
['A1', 'B1', true], ['A2', 'B1', true], ['A2', 'B2', true], ['A3', 'B2', true],
['B1', 'C1', true], ['B1', 'C2', true], ['B2', 'C2', true], ['B2', 'C3', true],
['C1', 'D1', true], ['C2', 'D1', true], ['C2', 'D2', true], ['C3', 'D2', true],
['D1', 'E1', true], ['D1', 'E2', true], ['D2', 'E2', true], ['D2', 'E3', true],
['E1', 'E2', true], ['E2', 'E3', true],
['S2', 'E2', false],
];
interface Board {
/** Grid locations, row by row from South's side. The row is the letter: A is South's first row. */
grid: LocId[];
lines: [LocId, LocId, boolean][];
/** Grid locations needed to win; `board=` sets winLocations to this. */
win: number;
}
export const LINES: readonly Line[] = LINE_DEFS.map(([a, b, gateway]) => ({
id: `${a}-${b}`,
a,
b,
gateway,
}));
/** The playmat in rules.md: rows of 3, 2, 3, 2, 3, entered from the middle of each end row. */
const CLASSIC: Board = {
grid: ['A1', 'A2', 'A3', 'B1', 'B2', 'C1', 'C2', 'C3', 'D1', 'D2', 'E1', 'E2', 'E3'],
lines: [
['S1', 'A2', false],
['A1', 'A2', true], ['A2', 'A3', true],
['A1', 'B1', true], ['A2', 'B1', true], ['A2', 'B2', true], ['A3', 'B2', true],
['B1', 'C1', true], ['B1', 'C2', true], ['B2', 'C2', true], ['B2', 'C3', true],
['C1', 'D1', true], ['C2', 'D1', true], ['C2', 'D2', true], ['C3', 'D2', true],
['D1', 'E1', true], ['D1', 'E2', true], ['D2', 'E2', true], ['D2', 'E3', true],
['E1', 'E2', true], ['E2', 'E3', true],
['S2', 'E2', false],
],
win: 10,
};
export const LINE_BY_ID: ReadonlyMap<string, Line> = new Map(LINES.map((l) => [l.id, l]));
/**
* A 4×4 grid of squares, rows A–D, columns 1–4, joined side to side (not diagonally), with a
* gateway on every line between squares. Each start joins the listed squares of its first row;
* North's are South's rotated 180°. Win with 12 of the 16.
*/
function squares(southEntries: number[]): Board {
const rows = ['A', 'B', 'C', 'D'];
const grid = rows.flatMap((r) => [1, 2, 3, 4].map((c) => `${r}${c}`));
const lines: [LocId, LocId, boolean][] = southEntries.map((c) => ['S1', `A${c}`, false]);
rows.forEach((r, i) => {
for (let c = 1; c <= 4; c++) {
if (c < 4) lines.push([`${r}${c}`, `${r}${c + 1}`, true]);
if (i < 3) lines.push([`${r}${c}`, `${rows[i + 1]}${c}`, true]);
}
});
for (const c of southEntries) lines.push(['S2', `D${5 - c}`, false]);
return { grid, lines, win: 12 };
}
export const LINES_AT: ReadonlyMap<LocId, readonly Line[]> = new Map(
LOCATIONS.map((loc) => [loc, LINES.filter((l) => l.a === loc || l.b === loc)]),
);
/**
* Three lanes of five rows, A–E, joined to each other only across the middle row (C1–C2–C3). Each
* start joins the first location of every lane. With `laneGateways` false the lane lines can't be
* firewalled, so only the two middle cross-links can. Win with 11 of the 15.
*/
function lanes(laneGateways: boolean): Board {
const rows = ['A', 'B', 'C', 'D', 'E'];
const grid = rows.flatMap((r) => [1, 2, 3].map((c) => `${r}${c}`));
const lines: [LocId, LocId, boolean][] = [1, 2, 3].map((c) => ['S1', `A${c}`, false]);
rows.slice(0, -1).forEach((r, i) => {
for (let c = 1; c <= 3; c++) lines.push([`${r}${c}`, `${rows[i + 1]}${c}`, laneGateways]);
});
lines.push(['C1', 'C2', true], ['C2', 'C3', true]);
for (let c = 1; c <= 3; c++) lines.push(['S2', `E${c}`, false]);
return { grid, lines, win: 11 };
}
export const BOARDS = {
classic: CLASSIC,
/** 4×4, each start joins the middle two squares of its first row. */
grid4: squares([2, 3]),
/** 4×4, each start joins all four squares of its first row. */
'grid4-wide': squares([1, 2, 3, 4]),
/** 4×4, each start joins one square: A2 for South, D3 for North. */
'grid4-one': squares([2]),
/** Three lanes, linked only across the middle row; every line between locations has a gateway. */
lanes: lanes(true),
/** Three lanes, but only the two middle cross-links can be firewalled. */
'lanes-open': lanes(false),
} satisfies Record<string, Board>;
export type BoardName = keyof typeof BOARDS;
// The current board. createGame switches it with useBoard, so a process plays one board at a time.
export let GRID: readonly LocId[];
export let LOCATIONS: readonly LocId[];
export let LINES: readonly Line[];
export let LINE_BY_ID: ReadonlyMap<string, Line>;
export let LINES_AT: ReadonlyMap<LocId, readonly Line[]>;
let rowCount = 0;
export function useBoard(name: BoardName): void {
const board: Board | undefined = BOARDS[name];
if (!board) throw new Error(`Unknown board "${name}". Boards: ${Object.keys(BOARDS).join(', ')}`);
GRID = board.grid;
LOCATIONS = [START_LOC[0], ...GRID, START_LOC[1]];
LINES = board.lines.map(([a, b, gateway]) => ({ id: `${a}-${b}`, a, b, gateway }));
LINE_BY_ID = new Map(LINES.map((l) => [l.id, l]));
LINES_AT = new Map(LOCATIONS.map((loc) => [loc, LINES.filter((l) => l.a === loc || l.b === loc)]));
rowCount = new Set(GRID.map((loc) => loc[0])).size;
}
useBoard('classic');
export const otherEnd = (line: Line, loc: LocId): LocId => (line.a === loc ? line.b : line.a);
export const isStart = (loc: LocId): boolean => loc === START_LOC[0] || loc === START_LOC[1];
/** Level by row letter, from each player's side of the mat: your first row is Lv 1, the far row Lv 5. */
const LEVEL_BY_ROW: readonly [Record<string, number>, Record<string, number>] = [
{ A: 1, B: 2, C: 3, D: 4, E: 5 },
{ A: 5, B: 4, C: 3, D: 2, E: 1 },
];
/** A location's level for the player capturing it. Your own start is Lv 1. */
/**
* A location's level for the player capturing it: your first row is Lv 1, counting up to the far
* row (Lv 5 on the classic board, Lv 4 on the 4×4 ones). Your own start is Lv 1.
*/
export function levelFor(p: PlayerId, loc: LocId): number {
if (loc === START_LOC[p]) return 1;
const level = LEVEL_BY_ROW[p][loc[0]];
if (level === undefined) throw new Error(`No level for ${loc} from player ${p}`);
return level;
const row = 'ABCDE'.indexOf(loc[0]);
if (row < 0 || row >= rowCount) throw new Error(`No level for ${loc} from player ${p}`);
return p === 0 ? row + 1 : rowCount - row;
}

View file

@ -34,3 +34,39 @@ export function winChance(atk: number, def: number): number {
cache.set(key, chance);
return chance;
}
export interface RollOdds {
/** Chances the attacker's total is higher, equal, or lower (no rerolls). */
win: number;
tie: number;
lose: number;
/** Expected damage to the defenders and to the attacker under the health rule (margin = damage). */
damageDealt: number;
damageTaken: number;
}
const rollCache = new Map<string, RollOdds>();
/** One roll of `atk` Cores against `def` Cores: win, tie and loss chances, and expected damage. */
export function rollOdds(atk: number, def: number): RollOdds {
const key = `${atk}:${def}`;
const hit = rollCache.get(key);
if (hit) return hit;
const out: RollOdds = { win: 0, tie: 0, lose: 0, damageDealt: 0, damageTaken: 0 };
const a = sumDistribution(Math.max(1, atk));
const d = sumDistribution(Math.max(1, def));
for (const [sa, pa] of a) {
for (const [sd, pd] of d) {
const p = pa * pd;
if (sa > sd) {
out.win += p;
out.damageDealt += p * (sa - sd);
} else if (sa < sd) {
out.lose += p;
out.damageTaken += p * (sd - sa);
} else out.tie += p;
}
}
rollCache.set(key, out);
return out;
}

View file

@ -6,7 +6,7 @@ import { LOCATIONS, type LocId } from './map.ts';
import { scriptOf, type Fighter, type Payment, type Script } from './scripts.ts';
import {
activeMods,
avatar,
anomaly,
controls,
defOf,
firewallCost,
@ -18,23 +18,23 @@ import {
sameRef,
stat,
} from './state.ts';
import type { AvatarRef, GameState, HookName, Json, PlayerId, Source, Task } from './types.ts';
import type { AnomalyRef, GameState, HookName, Json, PlayerId, Source, Task } from './types.ts';
export const programActive = (s: GameState, id: number): boolean =>
!running(s, s.cards[id].disabledUntil) && !running(s, s.cards[id].ignoredUntil);
export const hardwareActive = (s: GameState, id: number): boolean => !running(s, s.cards[id].disabledUntil);
/** Recruit rule: `p` has fewer than 4 Avatars, counting copies. Always true without the rule. */
export function avatarRoom(s: GameState, p: PlayerId): boolean {
/** Recruit rule: `p` has fewer than 4 Anomalies, counting copies. Always true without the rule. */
export function anomalyRoom(s: GameState, p: PlayerId): boolean {
if (!s.rules.recruit.on) return true;
const avs = s.players[p].avatars;
const avs = s.players[p].anomalies;
return avs.slice(0, 4).filter((a) => a.card >= 0).length + avs.slice(4).filter((a) => a.at !== null).length < 4;
}
/** Whether `p` may make a copy now: the copy-rule switches, and room under the recruit rule. */
export function canCopy(s: GameState, p: PlayerId): boolean {
const c = s.rules.copies;
return c.allowed && (!c.needAvatar2 || s.players[p].avatars[1].faceUp) && avatarRoom(s, p);
return c.allowed && (!c.needAnomaly2 || s.players[p].anomalies[1].faceUp) && anomalyRoom(s, p);
}
/** Everything with an effect in play right now. */
@ -66,8 +66,8 @@ export function sources(s: GameState): Source[] {
for (const p of [0, 1] as const) {
for (const r of refsInPlay(s, p)) {
if (isCopy(r)) continue;
const av = avatar(s, r);
out.push({ kind: 'avatar', id: av.card, name: s.cards[av.card].name, controller: p, at: av.at, ref: r });
const av = anomaly(s, r);
out.push({ kind: 'anomaly', id: av.card, name: s.cards[av.card].name, controller: p, at: av.at, ref: r });
for (const hw of av.hardware) {
if (hardwareActive(s, hw)) out.push({ kind: 'hardware', id: hw, name: s.cards[hw].name, controller: p, at: av.at, ref: r });
}
@ -78,7 +78,7 @@ export function sources(s: GameState): Source[] {
export const sameSource = (a: Source, b: Source): boolean =>
a.id === b.id && a.name === b.name && a.at === b.at && a.virtual === b.virtual && sameRefOrNone(a.ref, b.ref);
const sameRefOrNone = (a?: AvatarRef, b?: AvatarRef) => (!a && !b) || sameRef(a, b);
const sameRefOrNone = (a?: AnomalyRef, b?: AnomalyRef) => (!a && !b) || sameRef(a, b);
export const stillActive = (s: GameState, src: Source): boolean => sources(s).some((x) => sameSource(x, src));
@ -97,7 +97,7 @@ export function emit(s: GameState, hook: HookName, data: Json): void {
// ---------------------------------------------------------------------------------------------
// Capacity
/** How many of its owner's Avatars a location holds (Cluster Server, Pingable Server: 2). */
/** How many of its owner's Anomalies a location holds (Cluster Server, Pingable Server: 2). */
export function capacity(s: GameState, loc: LocId): number {
const sv = s.locations[loc].server;
if (sv === null || s.locations[loc].owner === null) return 1;
@ -105,12 +105,12 @@ export function capacity(s: GameState, loc: LocId): number {
return Math.max(1, scriptOf(c.name)?.capacity ?? 1, c.copies ? scriptOf(c.copies)?.capacity ?? 1 : 1);
}
/** Whether `p` can put another Avatar on `loc`. */
/** Whether `p` can put another Anomaly on `loc`. */
export function hasRoom(s: GameState, p: PlayerId, loc: LocId): boolean {
if (!controls(s, p, loc)) return false;
// Nothing enters a location mid-combat (a copy, or an Avatar moved by Disconnect).
// Nothing enters a location mid-combat (a copy, or an Anomaly moved by Disconnect).
if (s.combat && !s.combat.ended && s.combat.loc === loc) return false;
return refsInPlay(s, p).filter((r) => avatar(s, r).at === loc).length < capacity(s, loc);
return refsInPlay(s, p).filter((r) => anomaly(s, r).at === loc).length < capacity(s, loc);
}
/** Program slots on a location: 2, plus active Programs that add slots (Compatibility Layer). */
@ -126,36 +126,36 @@ export function installedCount(s: GameState, loc: LocId): number {
s.virtuals.filter((v) => v.installed && v.at === loc && running(s, v.until)).length;
}
export function portsUsed(s: GameState, r: AvatarRef): number {
return avatar(s, r).hardware.filter((id) => !scriptOf(s.cards[id].name)?.noPort).length;
export function slotsUsed(s: GameState, r: AnomalyRef): number {
return anomaly(s, r).hardware.filter((id) => !scriptOf(s.cards[id].name)?.noSlot).length;
}
/** Expansion Slots an Avatar has: printed, plus Hardware that adds ports (Network Interface Upgrade). */
export const portsTotal = (s: GameState, r: AvatarRef): number =>
defOf(s, avatar(s, r).card).slots +
avatar(s, r).hardware.reduce((t, id) => t + (scriptOf(s.cards[id].name)?.extraSlots ?? 0), 0);
/** Expansion Slots an Anomaly has: printed, plus Hardware that adds some (Network Interface Upgrade). */
export const slotsTotal = (s: GameState, r: AnomalyRef): number =>
defOf(s, anomaly(s, r).card).slots +
anomaly(s, r).hardware.reduce((t, id) => t + (scriptOf(s.cards[id].name)?.extraSlots ?? 0), 0);
export const portsFree = (s: GameState, r: AvatarRef): number => portsTotal(s, r) - portsUsed(s, r);
export const slotsFree = (s: GameState, r: AnomalyRef): number => slotsTotal(s, r) - slotsUsed(s, r);
/** Whether a Hardware takes a port: Network Interface Upgrade and Hardware pushed on over the limit don't. */
export const takesPort = (s: GameState, id: number): boolean =>
!scriptOf(s.cards[id].name)?.noPort && s.cards[id].pushedUntil === undefined;
/** Whether a Hardware takes an Expansion Slot: Network Interface Upgrade and Hardware pushed on over the limit don't. */
export const takesSlot = (s: GameState, id: number): boolean =>
!scriptOf(s.cards[id].name)?.noSlot && s.cards[id].pushedUntil === undefined;
/** Whether an Avatar's Hardware fits its ports, with `out` taken off and `into` put on. */
export function portsFit(s: GameState, r: AvatarRef, out: number | null = null, into: number | null = null): boolean {
const hw = avatar(s, r).hardware.filter((id) => id !== out);
/** Whether an Anomaly's Hardware fits its Expansion Slots, with `out` taken off and `into` put on. */
export function slotsFit(s: GameState, r: AnomalyRef, out: number | null = null, into: number | null = null): boolean {
const hw = anomaly(s, r).hardware.filter((id) => id !== out);
if (into !== null) hw.push(into);
const total = defOf(s, avatar(s, r).card).slots + hw.reduce((t, id) => t + (scriptOf(s.cards[id].name)?.extraSlots ?? 0), 0);
return hw.filter((id) => takesPort(s, id)).length <= total;
const total = defOf(s, anomaly(s, r).card).slots + hw.reduce((t, id) => t + (scriptOf(s.cards[id].name)?.extraSlots ?? 0), 0);
return hw.filter((id) => takesSlot(s, id)).length <= total;
}
// ---------------------------------------------------------------------------------------------
// Cores
/** Where an Avatar would fight from, as a fighter. `combat` is the current one, if it's in it. */
export function fighterOf(s: GameState, ref: AvatarRef): Fighter {
/** Where an Anomaly would fight from, as a fighter. `combat` is the current one, if it's in it. */
export function fighterOf(s: GameState, ref: AnomalyRef): Fighter {
const c = s.combat;
const av = avatar(s, ref);
const av = anomaly(s, ref);
if (c && !c.ended) {
if (sameRef(c.attacker, ref)) return { ref, role: 'attack', at: c.origin, loc: c.loc, combat: c };
if (c.defenders.some((d) => sameRef(d, ref))) return { ref, role: 'defend', at: c.loc, loc: c.loc, combat: c };
@ -163,12 +163,12 @@ export function fighterOf(s: GameState, ref: AvatarRef): Fighter {
return { ref, role: null, at: av.at, loc: null, combat: null };
}
/** Hardware on an Avatar (a copy uses its original's) with a script flag, if active. */
export const wears = (s: GameState, ref: AvatarRef, flag: (sc: Script) => unknown): number[] =>
/** Hardware on an Anomaly (a copy uses its original's) with a script flag, if active. */
export const wears = (s: GameState, ref: AnomalyRef, flag: (sc: Script) => unknown): number[] =>
hardwareOf(s, ref).filter((hw) => hardwareActive(s, hw) && flag(scriptOf(s.cards[hw].name) ?? { text: '' }));
/** Opponents' Bug effects can't touch an Avatar wearing ECC Memory. */
export const bugImmune = (s: GameState, ref: AvatarRef, by: PlayerId): boolean =>
/** Opponents' Bug effects can't touch an Anomaly wearing ECC Memory. */
export const bugImmune = (s: GameState, ref: AnomalyRef, by: PlayerId): boolean =>
by !== ref.player && wears(s, ref, (sc) => sc.bugImmunity).length > 0;
/** An active Program flag at a location, from a player other than `p`. */
@ -182,7 +182,7 @@ function hardwareBlocked(s: GameState, f: Fighter, all: Source[]): boolean {
}
/** Desynchronization: an attacker can't use once-per-turn Hardware abilities in a combat there. */
export function desynced(s: GameState, ref: AvatarRef): boolean {
export function desynced(s: GameState, ref: AnomalyRef): boolean {
const c = s.combat;
if (!c || c.ended || !sameRef(c.attacker, ref)) return false;
return enemyFlagAt(s, c.loc, ref.player, (sc) => sc.blocksHardwareAbilities).length > 0;
@ -195,50 +195,67 @@ export function desynced(s: GameState, ref: AvatarRef): boolean {
export const FALLBACK_HEALTH = 10;
/**
* Health rule: the damage that destroys an Avatar. Printed Health (or the rules' override), plus
* Health rule: the damage that destroys an Anomaly. Printed Health (or the rules' override), plus
* active Hardware that adds Health. A copy has its original's Health.
*/
export function healthOf(s: GameState, r: AvatarRef): number {
const av = avatar(s, r);
export function healthOf(s: GameState, r: AnomalyRef): number {
const av = anomaly(s, r);
let n = s.rules.health.override || (av.card < 0 ? 0 : defOf(s, av.card).health) || FALLBACK_HEALTH;
for (const hw of hardwareOf(s, r)) if (hardwareActive(s, hw)) n += scriptOf(s.cards[hw].name)?.health ?? 0;
return Math.max(1, n);
}
/** Health rule: Health an Avatar has left. */
export const healthLeft = (s: GameState, r: AvatarRef): number => healthOf(s, r) - avatar(s, r).damage;
/** Health rule: Health an Anomaly has left. */
export const healthLeft = (s: GameState, r: AnomalyRef): number => healthOf(s, r) - anomaly(s, r).damage;
/** One source of an Anomaly's Cores, for showing where a total comes from. */
export interface CorePart {
/** The card (or effect) that adds or removes Cores. */
source: string;
kind: 'anomaly' | 'hardware' | 'program' | 'server' | 'modifier';
controller: PlayerId;
cores: number;
}
/**
* Combat Cores for a fighter. `credit` is told about every card that changed the total, so the
* card report can count static effects (Stack Overflow, Server bonuses) as firing.
* card report can count static effects (Stack Overflow, Server bonuses) as firing. `detail`, when
* given, collects every part of the total (the printed Cores first); the total is at least 1.
*/
export function coresOf(s: GameState, f: Fighter, credit?: (name: string, p: PlayerId) => void): number {
const av = avatar(s, f.ref);
export function coresOf(s: GameState, f: Fighter, credit?: (name: string, p: PlayerId) => void, detail?: CorePart[]): number {
const av = anomaly(s, f.ref);
let n = defOf(s, av.card).cores;
detail?.push({ source: defOf(s, av.card).name, kind: 'anomaly', controller: f.ref.player, cores: n });
const all = sources(s);
const add = (d: number, name: string, p: PlayerId) => {
const add = (d: number, name: string, p: PlayerId, kind: CorePart['kind']) => {
n += d;
if (d !== 0) credit?.(name, p);
if (d !== 0) {
credit?.(name, p);
detail?.push({ source: name, kind, controller: p, cores: d });
}
};
if (!hardwareBlocked(s, f, all)) {
for (const hw of hardwareOf(s, f.ref)) {
if (!hardwareActive(s, hw) || f.combat?.suppressed.includes(hw)) continue;
const name = s.cards[hw].name;
const sc = scriptOf(name);
if (sc?.cores) add(sc.cores(s, { kind: 'hardware', id: hw, name, controller: f.ref.player, at: f.at, ref: f.ref }, f), name, f.ref.player);
if (sc?.cores) add(sc.cores(s, { kind: 'hardware', id: hw, name, controller: f.ref.player, at: f.at, ref: f.ref }, f), name, f.ref.player, 'hardware');
}
}
const counted = new Set<string>();
for (const src of all) {
if (src.kind === 'hardware') continue;
const sc = scriptOf(src.name);
if (sc?.cores) add(sc.cores(s, src, f), src.name, src.controller);
if (sc?.cores) add(sc.cores(s, src, f), src.name, src.controller, src.kind);
if (sc?.globalCores && !counted.has(src.name)) {
counted.add(src.name);
add(sc.globalCores(s, f), src.name, src.controller);
add(sc.globalCores(s, f), src.name, src.controller, src.kind);
}
}
for (const m of activeMods(s, av)) n += m.cores;
for (const m of activeMods(s, av)) {
n += m.cores;
if (m.cores !== 0) detail?.push({ source: m.source, kind: 'modifier', controller: m.by, cores: m.cores });
}
return Math.max(1, n);
}
@ -256,11 +273,11 @@ export function sideCores(s: GameState): { atk: number; def: number } {
function baseCost(s: GameState, pay: Payment): number {
if (pay.kind === 'firewall') return firewallCost(s, pay.level ?? 0);
return pay.card === undefined ? 0 : defOf(s, pay.card).ram;
return pay.card === undefined ? 0 : defOf(s, pay.card).bandwidth;
}
/**
* RAM a payment costs after every discount and surcharge in play. Pass `all` (the current
* Bandwidth a payment costs after every discount and surcharge in play. Pass `all` (the current
* sources) when pricing many payments against the same state.
*/
export function costOf(s: GameState, pay: Payment, all: Source[] = sources(s)): number {
@ -273,7 +290,7 @@ export function costOf(s: GameState, pay: Payment, all: Source[] = sources(s)):
}
/** Pays for something, using up once-per-turn discounts. Returns the amount paid. */
export function pay(s: GameState, payment: Payment, statKey: 'ramOnCards' | 'ramOnFirewalls' | 'ramOnAbilities'): number {
export function pay(s: GameState, payment: Payment, statKey: 'bandwidthOnCards' | 'bandwidthOnFirewalls' | 'bandwidthOnAbilities'): number {
let n = baseCost(s, payment);
const touched: Source[] = [];
for (const src of sources(s)) {
@ -284,17 +301,17 @@ export function pay(s: GameState, payment: Payment, statKey: 'ramOnCards' | 'ram
}
}
const cost = Math.max(0, n);
if (cost > s.players[payment.player].ram) throw new Error(`Can't afford ${cost} RAM`);
s.players[payment.player].ram -= cost;
if (cost > s.players[payment.player].bandwidth) throw new Error(`Can't afford ${cost} Gb`);
s.players[payment.player].bandwidth -= cost;
stat(s, statKey, payment.player, cost);
for (const src of touched) scriptOf(src.name)?.onPaid?.(s, src, payment);
return cost;
}
/** RAM a player could have for a payment: current RAM plus the Salvage value of the rest of the hand. */
export function reachableRam(s: GameState, p: PlayerId, except: number | null = null): number {
/** Bandwidth a player could have for a payment: current Bandwidth plus the Salvage value of the rest of the hand. */
export function reachableBandwidth(s: GameState, p: PlayerId, except: number | null = null): number {
const pl = s.players[p];
return pl.ram + pl.hand.reduce((t, id) => t + (id === except || id < 0 ? 0 : defOf(s, id).ram), 0);
return pl.bandwidth + pl.hand.reduce((t, id) => t + (id === except || id < 0 ? 0 : defOf(s, id).bandwidth), 0);
}
// ---------------------------------------------------------------------------------------------

View file

@ -1,9 +1,13 @@
import { BOARDS, type BoardName } from './map.ts';
/**
* Every number from rules.md that a rule variant might change. Pass a modified copy to
* createGame to A/B test a rule.
*/
export interface RulesConfig {
startingRam: number;
/** Which playmat (src/map.ts). Setting it also sets winLocations to the board's own count. */
board: BoardName;
startingBandwidth: number;
openingHand: number;
/** Cards drawn in each turn's draw step. */
drawPerTurn: number;
@ -11,56 +15,56 @@ export interface RulesConfig {
winLocations: number;
/** Player turns before the game is called a draw. */
maxTurns: number;
/** RAM paid on capture, by level. */
levelRam: Record<number, number>;
/** Bandwidth paid on capture, by level. */
levelBandwidth: Record<number, number>;
/** Cost to place, upgrade to, or clear a Firewall of each level; index 0 = Lv 1. */
firewallCost: readonly number[];
maxProgramsPerLocation: number;
deck: { avatars: number; servers: number; main: number; maxCopies: number };
/** Avatars face up at the start (rules: Avatar 1 only). */
startingAvatars: number;
deck: { anomalies: number; servers: number; main: number; maxCopies: number };
/** Anomalies face up at the start (rules: Anomaly 1 only). */
startingAnomalies: number;
/** What the first player may do on turn 1 (the rules since v0.9 allow all of it; v0.8 skipped the draw). */
firstTurn: {
draw: boolean;
advance: boolean;
/** Captures pay capture RAM. A Server card's own RAM bonus is still paid. */
captureRam: boolean;
/** Captures unlock Avatars. They unlock on a later capture instead. */
/** Captures pay capture Bandwidth. A Server card's own Bandwidth bonus is still paid. */
captureBandwidth: boolean;
/** Captures unlock Anomalies. They unlock on a later capture instead. */
unlock: boolean;
/** Playing cards from hand: Hardware, Programs, Executions. */
cards: boolean;
};
/**
* Catch-up for whoever goes second: extra starting RAM, extra Avatars face up, extra cards in the
* Catch-up for whoever goes second: extra starting Bandwidth, extra Anomalies face up, extra cards in the
* opening hand, extra cards in their first draw step, and (0 or 1) owning the location next to
* their starting Server at the start.
*/
secondPlayer: { ram: number; avatars: number; cards: number; firstDraw: number; locations: number };
secondPlayer: { bandwidth: number; anomalies: number; cards: number; firstDraw: number; locations: number };
/**
* Prototype: Avatars in the deck instead of level unlocks. You start with one Avatar; another
* `avatarsInDeck` are shuffled into the main deck (inside its size). On your turn (steps 3 and 6)
* pay an Avatar's price to recruit it from hand into an empty slot, or retire one of yours
* (discarding it and its Hardware) to recruit into its slot. At most 4 Avatars, copies included.
* Prototype: Anomalies in the deck instead of level unlocks. You start with one Anomaly; another
* `anomaliesInDeck` are shuffled into the main deck (inside its size). On your turn (steps 3 and 6)
* pay an Anomaly's price to recruit it from hand into an empty slot, or retire one of yours
* (discarding it and its Hardware) to recruit into its slot. At most 4 Anomalies, copies included.
* Price = `price` + `pricePerCore` × Cores; it's also the card's salvage value.
*/
recruit: { on: boolean; avatarsInDeck: number; price: number; pricePerCore: number };
recruit: { on: boolean; anomaliesInDeck: number; price: number; pricePerCore: number };
/**
* Prototype: buy Avatars instead of level unlocks. On your turn (steps 3 and 6) pay RAM to flip
* your next face-down Avatar; `prices` are for Avatars 2, 3 and 4.
* Prototype: buy Anomalies instead of level unlocks. On your turn (steps 3 and 6) pay Bandwidth to flip
* your next face-down Anomaly; `prices` are for Anomalies 2, 3 and 4.
*/
buyAvatars: { on: boolean; prices: number[] };
buyAnomalies: { on: boolean; prices: number[] };
/**
* Copies (Carbon NanoBots' Replicate, Backup Server), for testing: whether they can be made at
* all; whether a new copy must wait for its owner's next turn to advance or attack (it can
* defend); whether making one needs Avatar 2 unlocked.
* defend); whether making one needs Anomaly 2 unlocked.
*/
copies: { allowed: boolean; waitATurn: boolean; needAvatar2: boolean };
copies: { allowed: boolean; waitATurn: boolean; needAnomaly2: boolean };
/**
* Rounds of alternating commands (the rules since v0.8; off = the old one-turn-each structure).
* Each round both players get `perPlayer` commands, taken in turn. A command is one advance or one attack (or a pass),
* with placement and cards before it and cards after it. A player's "turn" is their commands in
* a round: the draw, turn-start effects and each Avatar's one action a round refresh at their
* first command; once-per-turn effects become once per round. Avatars unlocked during a round
* a round: the draw, turn-start effects and each Anomaly's one action a round refresh at their
* first command; once-per-turn effects become once per round. Anomalies unlocked during a round
* enter play from the next round.
* `leads` says who takes a round's first command, round after round (F = first player, S =
* second; the pattern repeats; "thue" is the Thue–Morse order F S S F S F F S…). `snake` orders
@ -69,42 +73,44 @@ export interface RulesConfig {
commands: { on: boolean; perPlayer: number; leads: string; snake: boolean };
/**
* Health and damage (the rules since v0.9; off = one roll decides the combat and the loser is
* knocked out). Each Avatar has printed Health; `override` (when not 0) gives every Avatar that
* knocked out). Each Anomaly has printed Health; `override` (when not 0) gives every Anomaly that
* Health instead, for A/B tests. The roll is unchanged, but the loser takes damage equal to the
* difference in totals, a tie is a stalemate (no reroll, no damage), and an Avatar is destroyed
* difference in totals, a tie is a stalemate (no reroll, no damage), and an Anomaly is destroyed
* (knocked out as before) only when its damage reaches its Health. A location is captured only
* when its last defender is destroyed. `recall` allows returning an Avatar to its slot in the
* when its last defender is destroyed. `recall` allows returning an Anomaly to its slot in the
* Deploy step (as its placement for the round) to heal it fully; it keeps its Hardware.
*/
health: { on: boolean; override: number; recall: boolean };
}
export const DEFAULT_RULES: RulesConfig = {
startingRam: 4,
board: 'classic',
startingBandwidth: 4,
openingHand: 7,
drawPerTurn: 1,
winLocations: 10,
maxTurns: 200,
levelRam: { 1: 4, 2: 4, 3: 4, 4: 4, 5: 4 },
levelBandwidth: { 1: 4, 2: 4, 3: 4, 4: 4, 5: 4 },
firewallCost: [2, 4, 8],
maxProgramsPerLocation: 2,
deck: { avatars: 4, servers: 20, main: 45, maxCopies: 2 },
startingAvatars: 1,
firstTurn: { draw: true, advance: true, captureRam: true, unlock: true, cards: true },
secondPlayer: { ram: 0, avatars: 0, cards: 0, firstDraw: 0, locations: 0 },
recruit: { on: false, avatarsInDeck: 3, price: 6, pricePerCore: 0 },
buyAvatars: { on: false, prices: [8, 12, 16] },
copies: { allowed: true, waitATurn: false, needAvatar2: false },
deck: { anomalies: 4, servers: 20, main: 45, maxCopies: 2 },
startingAnomalies: 1,
firstTurn: { draw: true, advance: true, captureBandwidth: true, unlock: true, cards: true },
secondPlayer: { bandwidth: 0, anomalies: 0, cards: 0, firstDraw: 0, locations: 0 },
recruit: { on: false, anomaliesInDeck: 3, price: 6, pricePerCore: 0 },
buyAnomalies: { on: false, prices: [8, 12, 16] },
copies: { allowed: true, waitATurn: false, needAnomaly2: false },
commands: { on: true, perPlayer: 2, leads: 'F', snake: true },
health: { on: true, override: 0, recall: true },
};
/** Avatars kept outside the main deck: all of them, or just the starting one when recruiting. */
export const avatarsOutside = (rules: RulesConfig): number => (rules.recruit.on ? 1 : rules.deck.avatars);
/** Anomalies kept outside the main deck: all of them, or just the starting one when recruiting. */
export const anomaliesOutside = (rules: RulesConfig): number => (rules.recruit.on ? 1 : rules.deck.anomalies);
/**
* A copy of `rules` with one setting changed, from text like "winLocations=9",
* "secondPlayer.ram=4", "firstTurn.advance=false" or "levelRam=4,4,4,4,4" (Lv 1 to 5).
* "secondPlayer.bandwidth=4", "firstTurn.advance=false" or "levelBandwidth=4,4,4,4,4" (Lv 1 to 5).
* "board=grid4" also sets winLocations to 12, so give a winLocations after it to change that.
*/
export function withRule(rules: RulesConfig, spec: string): RulesConfig {
const m = spec.match(/^([\w.]+)=(.+)$/);
@ -124,12 +130,16 @@ export function withRule(rules: RulesConfig, spec: string): RulesConfig {
if (!Number.isFinite(n)) throw new Error(`Rule "${key}" needs numbers, got "${x}"`);
return n;
};
if (typeof old === 'number') obj[last] = num(raw);
if (key === 'board') {
if (!(raw in BOARDS)) throw new Error(`Unknown board "${raw}". Boards: ${Object.keys(BOARDS).join(', ')}`);
obj.board = raw;
obj.winLocations = BOARDS[raw as BoardName].win;
} else if (typeof old === 'number') obj[last] = num(raw);
else if (typeof old === 'string') obj[last] = raw;
else if (typeof old === 'boolean') {
if (raw !== 'true' && raw !== 'false') throw new Error(`Rule "${key}" needs true or false`);
obj[last] = raw === 'true';
} else if (key === 'levelRam') {
} else if (key === 'levelBandwidth') {
obj[last] = Object.fromEntries(raw.split(',').map((x, i) => [i + 1, num(x)]));
} else if (Array.isArray(old)) obj[last] = raw.split(',').map(num);
else throw new Error(`Unknown rule "${key}"`);

View file

@ -4,17 +4,17 @@
* cards.csv is reported instead of silently simulated with the old wording.
*/
import type { CardDef, CardPool } from './cards.ts';
import { AVATARS } from './cards/avatars.ts';
import { ANOMALIES } from './cards/anomalies.ts';
import { EXECUTIONS } from './cards/executions.ts';
import { HARDWARE } from './cards/hardware.ts';
import { PROGRAMS } from './cards/programs.ts';
import { SERVERS } from './cards/servers.ts';
import type { LocId } from './map.ts';
import type { Args, AvatarRef, Combat, GameState, PlayerId, Source, StackItem } from './types.ts';
import type { Args, AnomalyRef, Combat, GameState, PlayerId, Source, StackItem } from './types.ts';
/** An Avatar as it fights, or would fight. */
/** An Anomaly as it fights, or would fight. */
export interface Fighter {
ref: AvatarRef;
ref: AnomalyRef;
role: 'attack' | 'defend' | null;
/** Where it stands: an attacker's origin, or the location it defends. */
at: LocId | null;
@ -23,7 +23,7 @@ export interface Fighter {
combat: Combat | null;
}
/** Something a player is paying RAM for. */
/** Something a player is paying Bandwidth for. */
export interface Payment {
kind: 'program' | 'hardware' | 'execution' | 'firewall' | 'ability';
player: PlayerId;
@ -31,11 +31,11 @@ export interface Payment {
/** Program: where it's installed. Execution: its target. */
at?: LocId | null;
/** Hardware: who it's installed on. */
ref?: AvatarRef;
ref?: AnomalyRef;
line?: string;
level?: number;
/** Execution: enemy Avatars it targets. */
hostile?: AvatarRef[];
/** Execution: enemy Anomalies it targets. */
hostile?: AnomalyRef[];
}
export interface Play {
@ -44,19 +44,19 @@ export interface Play {
}
export interface ExecutionScript {
/** Every legal way to play the card now, ignoring RAM. */
/** Every legal way to play the card now, ignoring Bandwidth. */
plays(s: GameState, p: PlayerId): Play[];
resolve(s: GameState, item: StackItem): void;
/** Enemy Avatars (or Avatars whose Hardware) the play targets. */
targetsAvatars?(s: GameState, item: Pick<StackItem, 'player' | 'target' | 'args'>): AvatarRef[];
/** Enemy Anomalies (or Anomalies whose Hardware) the play targets. */
targetsAnomalies?(s: GameState, item: Pick<StackItem, 'player' | 'target' | 'args'>): AnomalyRef[];
}
export interface AbilityScript {
/** RAM cost. Avatars use the Ability Cost printed on the card. */
/** Bandwidth cost. Anomalies use the Ability Cost printed on the card. */
cost?: number;
/** More RAM paid on activation for this particular use (Hot-Swap Bay, Push Update). */
/** More Bandwidth paid on activation for this particular use (Hot-Swap Bay, Push Update). */
extraCost?(s: GameState, src: Source, args: Args): number;
/** Every legal way to use it now, ignoring RAM; empty when it can't be used. */
/** Every legal way to use it now, ignoring Bandwidth; empty when it can't be used. */
uses(s: GameState, src: Source): Args[];
resolve(s: GameState, item: StackItem, src: Source): void;
/** Hardware "once per turn" abilities, which Desynchronization and Cooling System refer to. */
@ -67,19 +67,19 @@ export interface Script {
/** The card text this script implements. */
text: string;
/** Server: RAM gained once, when the card is placed. */
ramOnPlace?: number;
/** Server: Avatars of its controller that fit on the location. */
/** Server: Bandwidth gained once, when the card is placed. */
bandwidthOnPlace?: number;
/** Server: Anomalies of its controller that fit on the location. */
capacity?: number;
/** Server: extra Program slots on its location. */
programSlots?: number;
/** Hardware that doesn't use an Expansion Slot. */
noPort?: boolean;
noSlot?: boolean;
/** Hardware: Expansion Slots it adds to its wearer (Network Interface Upgrade). */
extraSlots?: number;
/** Hardware: Health it adds to its wearer (health rule): RAM Expansion. */
health?: number;
/** Program: extra attacks for its controller's Avatars attacking from this location (Infinite Loop). */
/** Program: extra attacks for its controller's Anomalies attacking from this location (Infinite Loop). */
extraAttacks?: number;
/** Program: no Hardware Core bonuses in combats here (Stock Rice). */
blocksHardwareInCombat?: boolean;
@ -99,36 +99,36 @@ export interface Script {
/** Like `cores`, but counted once no matter how many copies are in play. */
globalCores?(s: GameState, f: Fighter): number;
/** RAM added to (or, negative, taken off) a payment. */
/** Bandwidth added to (or, negative, taken off) a payment. */
costMod?(s: GameState, src: Source, pay: Payment): number;
/** Called after a payment that this source changed. */
onPaid?(s: GameState, src: Source, pay: Payment): void;
onTurnStart?(s: GameState, src: Source): void;
onDraw?(s: GameState, src: Source, ev: { player: PlayerId; card: number }): void;
onAttackDeclared?(s: GameState, src: Source, ev: { ref: AvatarRef; to: LocId }): void;
onAttackDeclared?(s: GameState, src: Source, ev: { ref: AnomalyRef; to: LocId }): void;
/** An enemy is capturing this source's location. Runs before the location's cards leave. */
onBreach?(s: GameState, src: Source, ev: { ref: AvatarRef; loc: LocId }): void;
onBreach?(s: GameState, src: Source, ev: { ref: AnomalyRef; loc: LocId }): void;
/** Like onBreach, for effects that save cards from the capture. */
onCaptured?(s: GameState, src: Source, ev: { ref: AvatarRef; loc: LocId }): void;
onCaptured?(s: GameState, src: Source, ev: { ref: AnomalyRef; loc: LocId }): void;
/** A Server card was just placed. */
onPlaced?(s: GameState, src: Source, ev: { card: number }): void;
onInstall?(s: GameState, src: Source, ev: { card: number; at: LocId | null; ref: AvatarRef | null }): void;
onInstall?(s: GameState, src: Source, ev: { card: number; at: LocId | null; ref: AnomalyRef | null }): void;
/** Reads the combat from s.combat. */
onCombatStart?(s: GameState, src: Source): void;
/** An Avatar was defeated at `loc`. It's already back in its slot. */
onDefeat?(s: GameState, src: Source, ev: { ref: AvatarRef; loc: LocId; role: 'attack' | 'defend' }): void;
/** An Anomaly was defeated at `loc`. It's already back in its slot. */
onDefeat?(s: GameState, src: Source, ev: { ref: AnomalyRef; loc: LocId; role: 'attack' | 'defend' }): void;
/**
* An Avatar lost a roll at `loc`: under the health rule it took `amount` damage (and may be
* An Anomaly lost a roll at `loc`: under the health rule it took `amount` damage (and may be
* `destroyed`); with the rule off, every lost roll destroys it. Runs before the defeat.
*/
onDamage?(s: GameState, src: Source, ev: { ref: AvatarRef; loc: LocId; role: 'attack' | 'defend'; amount: number; destroyed: boolean }): void;
onDamage?(s: GameState, src: Source, ev: { ref: AnomalyRef; loc: LocId; role: 'attack' | 'defend'; amount: number; destroyed: boolean }): void;
onCombatEnd?(s: GameState, src: Source): void;
/**
* Hardware: its wearer was just defeated. Return true to take over what happens to the Hardware
* (the script must then knock the Avatar out itself).
* (the script must then knock the Anomaly out itself).
*/
onWearerDefeated?(s: GameState, hw: number, ev: { ref: AvatarRef; loc: LocId; role: 'attack' | 'defend' }): boolean;
onWearerDefeated?(s: GameState, hw: number, ev: { ref: AnomalyRef; loc: LocId; role: 'attack' | 'defend' }): boolean;
/** Lower goes first among onWearerDefeated Hardware. */
savePriority?: number;
@ -145,15 +145,15 @@ let registry: Record<string, Script> | null = null;
/** All scripts by card name. Built on first use, so card modules can import engine helpers. */
export function scripts(): Record<string, Script> {
return (registry ??= { ...SERVERS, ...PROGRAMS, ...HARDWARE, ...EXECUTIONS, ...AVATARS });
return (registry ??= { ...SERVERS, ...PROGRAMS, ...HARDWARE, ...EXECUTIONS, ...ANOMALIES });
}
export const scriptOf = (name: string): Script | undefined => scripts()[name];
export const isImplemented = (card: CardDef): boolean => card.name in scripts();
/** The text a card's script checks: the Ability for Avatars, the description for everything else. */
export const scriptedText = (card: CardDef): string => (card.kind === 'avatar' ? card.ability?.text ?? '' : card.text).trim();
/** The text a card's script checks: the Ability for Anomalies, the description for everything else. */
export const scriptedText = (card: CardDef): string => (card.kind === 'anomaly' ? card.ability?.text ?? '' : card.text).trim();
/** Scripts whose card is missing from, or worded differently in, the CSV; and cards with no script. */
export function staleScripts(pool: CardPool): string[] {

View file

@ -7,14 +7,15 @@ import { GRID, LINES_AT, otherEnd, type Line, type LocId } from './map.ts';
import { d6 } from './rng.ts';
import {
PLAYER_NAMES,
type AvatarRef,
type AvatarState,
type AnomalyRef,
type AnomalyState,
type CaptureStat,
type Choice,
type Clock,
type Combat,
type GameState,
type Json,
type LogLine,
type Modifier,
type PlayerId,
type StatKey,
@ -27,15 +28,24 @@ export const nameOf = (s: GameState, id: number): string => (id < 0 ? 'a hidden
export const ownerOf = (s: GameState, id: number): PlayerId => s.cards[id].owner;
export const controls = (s: GameState, p: PlayerId, loc: LocId): boolean => s.locations[loc].owner === p;
export const isOpen = (s: GameState, line: Line): boolean => !s.firewalls[line.id];
/** RAM to place, upgrade to, or clear a Firewall of `level`, before discounts; 0 for no Firewall. */
/** Bandwidth to place, upgrade to, or clear a Firewall of `level`, before discounts; 0 for no Firewall. */
export const firewallCost = (s: GameState, level: number): number => s.rules.firewallCost[level - 1] ?? 0;
export const gridCount = (s: GameState, p: PlayerId): number => GRID.filter((loc) => controls(s, p, loc)).length;
/** Rolls a d6 (or takes the next rigged result). */
export const rollDie = (s: GameState): number => (s.rigged?.length ? s.rigged.shift()! : d6(s.rng));
export function say(s: GameState, msg: string): void {
s.log?.push(msg);
/**
* Adds a line to the play-by-play. `meta` tags what it's about; give `to` and `public` when the
* line names cards only one player may see, and the other player reads `public` instead.
*/
export function say(s: GameState, msg: string, meta?: Omit<LogLine, 'text'>): void {
s.log?.push(meta ? { text: msg, ...meta } : { text: msg });
}
/** The play-by-play as `viewer` may read it, or every line in full for null. */
export function logFor(s: GameState, viewer: PlayerId | null): string[] {
return (s.log ?? []).map((l) => (viewer === null || l.to === undefined || l.to === viewer ? l.text : l.public ?? ''));
}
export function stat(s: GameState, key: StatKey, p: PlayerId, n = 1): void {
@ -98,89 +108,89 @@ export function markUsed(s: GameState, key: string): void {
}
// ---------------------------------------------------------------------------------------------
// Avatars
// Anomalies
export const refKey = (r: AvatarRef): string => `${r.player}:${r.slot}`;
export const sameRef = (a: AvatarRef | null | undefined, b: AvatarRef | null | undefined): boolean =>
export const refKey = (r: AnomalyRef): string => `${r.player}:${r.slot}`;
export const sameRef = (a: AnomalyRef | null | undefined, b: AnomalyRef | null | undefined): boolean =>
!!a && !!b && a.player === b.player && a.slot === b.slot;
export const avatar = (s: GameState, r: AvatarRef): AvatarState => s.players[r.player].avatars[r.slot - 1];
export const isCopy = (r: AvatarRef): boolean => r.slot > 4;
/** The printed Avatar a ref belongs to (a copy's original). */
export const originalOf = (r: AvatarRef): AvatarRef => (r.slot > 4 ? { player: r.player, slot: r.slot - 4 } : r);
export const copyOf = (r: AvatarRef): AvatarRef => ({ player: r.player, slot: originalOf(r).slot + 4 });
export const inPlay = (s: GameState, r: AvatarRef): boolean => avatar(s, r).at !== null;
export const avatarDef = (s: GameState, r: AvatarRef): CardDef => defOf(s, avatar(s, r).card);
export const anomaly = (s: GameState, r: AnomalyRef): AnomalyState => s.players[r.player].anomalies[r.slot - 1];
export const isCopy = (r: AnomalyRef): boolean => r.slot > 4;
/** The printed Anomaly a ref belongs to (a copy's original). */
export const originalOf = (r: AnomalyRef): AnomalyRef => (r.slot > 4 ? { player: r.player, slot: r.slot - 4 } : r);
export const copyOf = (r: AnomalyRef): AnomalyRef => ({ player: r.player, slot: originalOf(r).slot + 4 });
export const inPlay = (s: GameState, r: AnomalyRef): boolean => anomaly(s, r).at !== null;
export const anomalyDef = (s: GameState, r: AnomalyRef): CardDef => defOf(s, anomaly(s, r).card);
export function avatarName(s: GameState, r: AvatarRef): string {
export function anomalyName(s: GameState, r: AnomalyRef): string {
const n = originalOf(r).slot;
const card = avatar(s, r).card;
const card = anomaly(s, r).card;
const name = card < 0 ? '?' : nameOf(s, card);
return isCopy(r) ? `the copy of Avatar ${n} (${name})` : `Avatar ${n} (${name})`;
return isCopy(r) ? `the copy of Anomaly ${n} (${name})` : `Anomaly ${n} (${name})`;
}
/** Every Avatar of `p` in play, originals first. */
export function refsInPlay(s: GameState, p: PlayerId): AvatarRef[] {
const out: AvatarRef[] = [];
s.players[p].avatars.forEach((av, i) => {
/** Every Anomaly of `p` in play, originals first. */
export function refsInPlay(s: GameState, p: PlayerId): AnomalyRef[] {
const out: AnomalyRef[] = [];
s.players[p].anomalies.forEach((av, i) => {
if (av.at !== null) out.push({ player: p, slot: i + 1 });
});
return out;
}
/** Avatars standing on `loc`. Only the location's owner can have Avatars there. */
export function avatarsAt(s: GameState, loc: LocId): AvatarRef[] {
/** Anomalies standing on `loc`. Only the location's owner can have Anomalies there. */
export function anomaliesAt(s: GameState, loc: LocId): AnomalyRef[] {
const owner = s.locations[loc].owner;
return owner === null ? [] : refsInPlay(s, owner).filter((r) => avatar(s, r).at === loc);
return owner === null ? [] : refsInPlay(s, owner).filter((r) => anomaly(s, r).at === loc);
}
export const defendersAt = avatarsAt;
export const defendersAt = anomaliesAt;
/** Hardware that counts for an Avatar. A copy uses its original's Hardware. */
export const hardwareOf = (s: GameState, r: AvatarRef): number[] => avatar(s, originalOf(r)).hardware;
/** Hardware that counts for an Anomaly. A copy uses its original's Hardware. */
export const hardwareOf = (s: GameState, r: AnomalyRef): number[] => anomaly(s, originalOf(r)).hardware;
/** The Avatar wearing a Hardware card, if it's installed. */
export function wearerOf(s: GameState, hw: number): AvatarRef | null {
/** The Anomaly wearing a Hardware card, if it's installed. */
export function wearerOf(s: GameState, hw: number): AnomalyRef | null {
const p = ownerOf(s, hw);
const i = s.players[p].avatars.findIndex((a) => a.hardware.includes(hw));
const i = s.players[p].anomalies.findIndex((a) => a.hardware.includes(hw));
return i < 0 ? null : { player: p, slot: i + 1 };
}
export const isRooted = (s: GameState, r: AvatarRef): boolean => running(s, avatar(s, r).rootedUntil);
export const isDisabledAvatar = (s: GameState, r: AvatarRef): boolean => running(s, avatar(s, r).disabledUntil);
export const isRooted = (s: GameState, r: AnomalyRef): boolean => running(s, anomaly(s, r).rootedUntil);
export const isDisabledAnomaly = (s: GameState, r: AnomalyRef): boolean => running(s, anomaly(s, r).disabledUntil);
/** Can act: advance, attack, move, use its Ability. */
/** Copy-rule variant: a copy made this player-turn can't advance or attack yet. It can still defend. */
export const freshCopy = (s: GameState, r: AvatarRef): boolean =>
isCopy(r) && s.rules.copies.waitATurn && avatar(s, r).createdTurn === s.turn;
export const freshCopy = (s: GameState, r: AnomalyRef): boolean =>
isCopy(r) && s.rules.copies.waitATurn && anomaly(s, r).createdTurn === s.turn;
export const canAct = (s: GameState, r: AvatarRef): boolean =>
inPlay(s, r) && !isRooted(s, r) && !isDisabledAvatar(s, r);
export const canAct = (s: GameState, r: AnomalyRef): boolean =>
inPlay(s, r) && !isRooted(s, r) && !isDisabledAnomaly(s, r);
/** Temporary modifiers that currently apply to an Avatar. */
export function activeMods(s: GameState, av: AvatarState): Modifier[] {
/** Temporary modifiers that currently apply to an Anomaly. */
export function activeMods(s: GameState, av: AnomalyState): Modifier[] {
return av.mods.filter((m) =>
m.combat !== undefined ? s.combat?.id === m.combat : running(s, m.until ?? 0));
}
export function addMod(
s: GameState,
r: AvatarRef,
r: AnomalyRef,
cores: number,
source: string,
by: PlayerId,
scope: { combat: number } | { until: Clock },
): void {
avatar(s, r).mods.push({ seq: ++s.seq, cores, source, by, ...scope });
anomaly(s, r).mods.push({ seq: ++s.seq, cores, source, by, ...scope });
}
export const infectionOf = (av: AvatarState): number => av.infection + av.permanentInfection;
export const infectionOf = (av: AnomalyState): number => av.infection + av.permanentInfection;
// ---------------------------------------------------------------------------------------------
// Combat
export const inCombat = (s: GameState, r: AvatarRef): boolean =>
export const inCombat = (s: GameState, r: AnomalyRef): boolean =>
!!s.combat && !s.combat.ended && (sameRef(s.combat.attacker, r) || s.combat.defenders.some((d) => sameRef(d, r)));
/** The other side of the current combat from `r`'s point of view. */
export function opponentsInCombat(s: GameState, r: AvatarRef): AvatarRef[] {
export function opponentsInCombat(s: GameState, r: AnomalyRef): AnomalyRef[] {
const c = s.combat;
if (!c || c.ended) return [];
if (sameRef(c.attacker, r)) return [...c.defenders];
@ -188,14 +198,14 @@ export function opponentsInCombat(s: GameState, r: AvatarRef): AvatarRef[] {
return [];
}
export const fightersOf = (c: Combat): AvatarRef[] => [c.attacker, ...c.defenders];
export const fightersOf = (c: Combat): AnomalyRef[] => [c.attacker, ...c.defenders];
/**
* Avatars "at" a location for card text: the ones standing there, plus an enemy attacking it in the
* Anomalies "at" a location for card text: the ones standing there, plus an enemy attacking it in the
* current combat.
*/
export function atServer(s: GameState, loc: LocId): AvatarRef[] {
const out = avatarsAt(s, loc);
export function atServer(s: GameState, loc: LocId): AnomalyRef[] {
const out = anomaliesAt(s, loc);
const c = s.combat;
if (c && !c.ended && c.loc === loc && !out.some((r) => sameRef(r, c.attacker))) out.push(c.attacker);
return out;
@ -250,9 +260,9 @@ export function uninstallProgram(s: GameState, id: number): LocId | null {
return null;
}
export function uninstallHardware(s: GameState, id: number): AvatarRef | null {
export function uninstallHardware(s: GameState, id: number): AnomalyRef | null {
const r = wearerOf(s, id);
if (r) removeFrom(avatar(s, r).hardware, id);
if (r) removeFrom(anomaly(s, r).hardware, id);
return r;
}
@ -261,9 +271,9 @@ export function programLocation(s: GameState, id: number): LocId | null {
return null;
}
export function gainRam(s: GameState, p: PlayerId, n: number, key: StatKey = 'ramFromEffects'): void {
export function gainBandwidth(s: GameState, p: PlayerId, n: number, key: StatKey = 'bandwidthFromEffects'): void {
if (n <= 0) return;
s.players[p].ram += n;
s.players[p].bandwidth += n;
stat(s, key, p, n);
}
@ -287,7 +297,7 @@ export const later = (name: string, fn: string, data: Json = null): Task => ({ t
export function startCombat(
s: GameState,
attacker: AvatarRef,
attacker: AnomalyRef,
origin: LocId,
loc: LocId,
kind: Combat['kind'],
@ -322,7 +332,7 @@ export function startCombat(
return combat;
}
export const pushCapture = (s: GameState, ref: AvatarRef, loc: LocId, how: CaptureStat): void =>
export const pushCapture = (s: GameState, ref: AnomalyRef, loc: LocId, how: CaptureStat): void =>
pushTasks(s, { t: 'capture', ref, loc, stage: 'hooks', how });
export const playerName = (p: PlayerId): string => PLAYER_NAMES[p];

View file

@ -12,7 +12,7 @@ export interface GameRecord {
locations: [number, number];
stats: Record<StatKey, [number, number]>;
cardUse: Record<string, CardUse>;
/** Card names in each player's decks (Avatars, Servers and main deck). */
/** Card names in each player's decks (Anomalies, Servers and main deck). */
decks: [string[], string[]];
}
@ -92,15 +92,15 @@ export function formatSummary(sum: BatchSummary, labels: [string, string]): stri
row('Attack win rate', pct(g.attacksWon[0], g.attacks[0]), pct(g.attacksWon[1], g.attacks[1])),
both('Combats tied (health rule: stalemates)', 'combatsTied'),
both('Damage dealt (health rule)', 'damageDealt'),
both('Avatars destroyed', 'avatarsDestroyed'),
both('Anomalies destroyed', 'anomaliesDestroyed'),
both('Recalls (health rule)', 'recalls'),
both('Firewalls placed', 'firewallsPlaced'),
both('Firewalls upgraded', 'firewallsUpgraded'),
both('Firewalls cleared', 'firewallsCleared'),
both('RAM from captures', 'ramFromCaptures'),
both('RAM from salvage', 'ramFromSalvage'),
both('RAM spent on Firewalls', 'ramOnFirewalls'),
both('RAM spent on cards', 'ramOnCards'),
both('Bandwidth from captures', 'bandwidthFromCaptures'),
both('Bandwidth from salvage', 'bandwidthFromSalvage'),
both('Bandwidth spent on Firewalls', 'bandwidthOnFirewalls'),
both('Bandwidth spent on cards', 'bandwidthOnCards'),
both('Cards salvaged', 'cardsSalvaged'),
both('Hardware installed', 'hardwareInstalled'),
both('Hardware lost in combat', 'hardwareLost'),
@ -109,8 +109,8 @@ export function formatSummary(sum: BatchSummary, labels: [string, string]): stri
both('Executions played', 'executionsPlayed'),
both('Abilities used', 'abilitiesUsed'),
both('Combats ended early', 'combatsEnded'),
both('RAM from card effects', 'ramFromEffects'),
both('RAM spent on Abilities', 'ramOnAbilities'),
both('Bandwidth from card effects', 'bandwidthFromEffects'),
both('Bandwidth spent on Abilities', 'bandwidthOnAbilities'),
both('Cards drawn', 'cardsDrawn'),
row('Locations at game end', fmt(sum.locations[0]), fmt(sum.locations[1])),
'',
@ -179,7 +179,7 @@ export function formatCardReport(rows: CardReport[]): string {
for (const r of rows) {
if (r.kind !== kind) {
kind = r.kind;
out.push(` ${{ avatar: 'Avatars', server: 'Servers', program: 'Programs', hardware: 'Hardware', execution: 'Executions' }[kind] ?? kind}`);
out.push(` ${{ anomaly: 'Anomalies', server: 'Servers', program: 'Programs', hardware: 'Hardware', execution: 'Executions' }[kind] ?? kind}`);
}
const se = r.inDeck ? Math.sqrt((r.deckWinRate * (1 - r.deckWinRate)) / r.inDeck) : 0;
out.push(

184
sim/src/trace.ts Normal file
View file

@ -0,0 +1,184 @@
/**
* Conformance traces for the Godot port (godot-plan.md §2). Plays games like the CLI and writes one
* JSON file per game: the setup, then a fingerprint of every step. A step is the action taken, the
* legal actions it was picked from (in order), the state after it, the log lines it added and the
* next decider's view. The Godot runner (tests/conformance.gd) replays each file and stops at the
* first step that differs. `--full` also writes every state in full, so the runner can name the
* field, and `--labels` adds the move-list labels (describe.ts) of the legal actions.
*
* node src/trace.ts --out ~/test/tests/traces/stage-a --pool stageA -n 200
* node src/trace.ts --out /tmp/one --seed 17 -n 1 --full
*/
import { createHash } from 'node:crypto';
import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { parseArgs } from 'node:util';
import type { BotFactory } from './bots/bot.ts';
import { DEFAULT_GREEDY, greedyBot } from './bots/greedy.ts';
import { randomBot } from './bots/random.ts';
import type { CardDef } from './cards.ts';
import { randomDeck } from './deck.ts';
import { describeAction } from './describe.ts';
import { actionKey, applyAction, createGame, decider, legalActions, viewFor } from './engine.ts';
import { DEFAULT_CARDS_CSV, loadCards } from './load.ts';
import { makeRng, nextFloat } from './rng.ts';
import { DEFAULT_RULES, withRule, type RulesConfig } from './rules.ts';
import type { GameState } from './types.ts';
const BOTS: Record<string, BotFactory> = {
random: randomBot,
greedy: () => greedyBot(),
nocards: () => greedyBot({ ...DEFAULT_GREEDY, useCards: false }),
};
/**
* Card lists for decks dealt from part of the pool, so the port can be checked before every card
* script is in. Stage A: every Anomaly, plus the Servers and Hardware with simple or no scripts.
*/
const POOLS: Record<string, string[]> = {
stageA: [
'Carbon NanoBots', 'Corrupt Driver', 'Pixelated Picture', 'Beta Version 1.0', 'Code Zero', 'Data Leaker',
'Backup Machine', 'Broken Bits',
'High Bandwidth Server', 'MultiCore Server', 'Cluster Server', 'Power Server', 'Server Farm',
'Network Throttle', 'Cloud Compute', 'Pingable Server', 'Protected Server',
'RAM Expansion', 'Additional Core', 'Network Interface Upgrade', 'Packet Accelerator',
],
};
const { values: opt } = parseArgs({
options: {
out: { type: 'string' },
games: { type: 'string', short: 'n', default: '100' },
seed: { type: 'string', default: '1' },
south: { type: 'string', default: 'random' },
north: { type: 'string', default: 'random' },
rule: { type: 'string', multiple: true, default: [] },
pool: { type: 'string', default: 'all' },
'max-copies': { type: 'string' },
full: { type: 'boolean', default: false },
labels: { type: 'boolean', default: false },
cards: { type: 'string', default: DEFAULT_CARDS_CSV },
},
});
if (!opt.out) {
console.error('trace: --out DIR is required');
process.exit(1);
}
for (const b of [opt.south, opt.north]) {
if (!BOTS[b]) {
console.error(`trace: unknown bot "${b}". Choose from: ${Object.keys(BOTS).join(', ')}`);
process.exit(1);
}
}
const pool = loadCards(opt.cards);
let include: (c: CardDef) => boolean = () => true;
let rules: RulesConfig = DEFAULT_RULES;
let poolNames: string[] | 'all' = 'all';
if (opt.pool !== 'all') {
const names = POOLS[opt.pool] ?? opt.pool.split(',');
poolNames = names;
for (const n of names) if (!pool.byName.has(n)) throw new Error(`trace: unknown card "${n}"`);
const set = new Set(names);
include = (c) => set.has(c.name);
// A small pool needs more copies of each card to fill a deck.
rules = { ...rules, deck: { ...rules.deck, maxCopies: 20 } };
}
if (opt['max-copies']) rules = { ...rules, deck: { ...rules.deck, maxCopies: Number(opt['max-copies']) } };
for (const spec of opt.rule) rules = withRule(rules, spec);
/** JSON with every object's keys sorted and undefined fields dropped, as Godot's JSON.stringify writes it. */
function canon(v: unknown): unknown {
if (Array.isArray(v)) return v.map(canon);
if (v && typeof v === 'object') {
const out: Record<string, unknown> = {};
for (const k of Object.keys(v).sort()) {
const x = (v as Record<string, unknown>)[k];
if (x !== undefined) out[k] = canon(x);
}
return out;
}
return v;
}
const md5 = (text: string) => createHash('md5').update(text).digest('hex').slice(0, 12);
const hash = (v: unknown) => md5(JSON.stringify(canon(v)));
/** The state without its card definitions (fixed for the game) and log (checked line by line). */
const body = (s: GameState) => ({ ...s, defs: undefined, log: undefined });
/** The card CSV the traces were made from, so the runner can tell when Godot's copy is stale. */
const cardsMd5 = md5(readFileSync(opt.cards, 'utf8'));
/** Mulberry32's first 10,000 outputs (as 32-bit ints) for a few seeds, hashed. */
const RNG_SEEDS = [1, 42, 0x9e3779b9, 4294967295];
const rngCheck = md5(RNG_SEEDS.map((seed) => {
const r = makeRng(seed);
return Array.from({ length: 10_000 }, () => Math.round(nextFloat(r) * 4294967296)).join(',');
}).join('\n'));
const MAX_ACTIONS = 200_000;
const first = Number(opt.seed);
const games = Number(opt.games);
rmSync(opt.out, { recursive: true, force: true });
mkdirSync(opt.out, { recursive: true });
const started = performance.now();
let totalSteps = 0;
for (let seed = first; seed < first + games; seed++) {
const deckRng = makeRng(seed ^ 0x9e3779b9);
const decks = [randomDeck(pool, deckRng, rules, include), randomDeck(pool, deckRng, rules, include)] as const;
const s = createGame({ pool, decks: [decks[0], decks[1]], seed, rules, log: true });
const bots = [BOTS[opt.south](seed * 2 + 1), BOTS[opt.north](seed * 2 + 2)];
const steps: Record<string, string>[] = [];
const states: unknown[] = [];
let logged = s.log!.length;
const initial = {
state: hash(body(s)),
log: hash(s.log),
view: s.over ? '' : hash(body(viewFor(s, decider(s)!))),
};
if (opt.full) states.push(canon(body(s)));
while (!s.over) {
if (steps.length > MAX_ACTIONS) throw new Error(`Game ${seed} didn't finish`);
const p = decider(s)!;
const legal = legalActions(s);
const action = bots[p].choose(viewFor(s, p), legal, p);
const labels = opt.labels ? md5(legal.map((a) => describeAction(s, a)).join('\n')) : '';
applyAction(s, action, legal);
const step: Record<string, string> = {
a: actionKey(action),
l: md5(legal.map(actionKey).join('\n')),
s: hash(body(s)),
g: hash(s.log!.slice(logged)),
};
logged = s.log!.length;
if (labels) step.d = labels;
if (!s.over) step.v = hash(body(viewFor(s, decider(s)!)));
steps.push(step);
if (opt.full) states.push(canon(body(s)));
}
totalSteps += steps.length;
const trace = {
version: 1,
seed,
bots: [opt.south, opt.north],
pool: poolNames,
cards: cardsMd5,
rules,
decks,
initial,
steps,
end: { winner: s.winner, turn: s.turn, endReason: s.endReason },
...(opt.full ? { states, defs: s.defs } : {}),
};
writeFileSync(join(opt.out, `game-${seed}.json`), JSON.stringify(trace));
}
writeFileSync(
join(opt.out, 'index.json'),
JSON.stringify({
games, first, bots: [opt.south, opt.north], pool: opt.pool, rules: opt.rule, full: opt.full, labels: opt.labels,
cards: cardsMd5, rngSeeds: RNG_SEEDS, rngCheck,
}, null, 2),
);
const seconds = ((performance.now() - started) / 1000).toFixed(1);
console.log(`Wrote ${games} traces (${totalSteps} steps) to ${opt.out} in ${seconds}s`);

View file

@ -36,13 +36,13 @@ export interface CardInstance {
pushedUntil?: Clock;
}
/** Slots 1–4 are the printed Avatars; slot k + 4 is a copy of Avatar k. */
export interface AvatarRef {
/** Slots 1–4 are the printed Anomalies; slot k + 4 is a copy of Anomaly k. */
export interface AnomalyRef {
player: PlayerId;
slot: number;
}
/** A temporary Core bonus or penalty on one Avatar. */
/** A temporary Core bonus or penalty on one Anomaly. */
export interface Modifier {
/** Increases with every new modifier, so "most recent" is the highest. */
seq: number;
@ -55,24 +55,24 @@ export interface Modifier {
until?: Clock;
}
export interface AvatarState {
/** Card id, or -1 in a player view where the Avatar is still face down. */
export interface AnomalyState {
/** Card id, or -1 in a player view where the Anomaly is still face down. */
card: number;
/** Face up = unlocked. Copies are face up only while they exist. */
faceUp: boolean;
/** null while the Avatar is in its slot (or, for a copy, doesn't exist). */
/** null while the Anomaly is in its slot (or, for a copy, doesn't exist). */
at: LocId | null;
hardware: number[];
/** Health rule: damage taken so far. Cleared when the Avatar leaves play. */
/** Health rule: damage taken so far. Cleared when the Anomaly leaves play. */
damage: number;
/** Placed (entered play or repositioned) this turn. */
placed: boolean;
advanced: boolean;
/** Attacks declared this turn (Infinite Loop allows 2). */
attacks: number;
/** Removed when the Avatar is defeated. */
/** Removed when the Anomaly is defeated. */
infection: number;
/** Bug counters: like Infection, for Bug cards. Removed when the Avatar is defeated. */
/** Bug counters: like Infection, for Bug cards. Removed when the Anomaly is defeated. */
bugs: number;
/** Persistent Infection counters survive defeat. */
permanentInfection: number;
@ -92,14 +92,14 @@ export interface AvatarState {
}
export interface PlayerState {
ram: number;
bandwidth: number;
hand: number[];
deck: number[];
discard: number[];
serverPile: number[];
/** Avatar N is avatars[N - 1]; avatars[N + 3] is its copy slot. */
avatars: AvatarState[];
/** Highest location level captured so far; unlocks Avatars up to this number. */
/** Anomaly N is anomalies[N - 1]; anomalies[N + 3] is its copy slot. */
anomalies: AnomalyState[];
/** Highest location level captured so far; unlocks Anomalies up to this number. */
unlockedLevel: number;
}
@ -116,17 +116,17 @@ export type Step = 'deploy' | 'play' | 'attack' | 'resolve' | 'playAgain';
export interface Declaration {
kind: 'advance' | 'attack';
ref: AvatarRef;
ref: AnomalyRef;
to: LocId;
/** Where the attacker stood when it declared. */
from: LocId;
/** Infinite Loop: this Avatar's second attack this turn. */
/** Infinite Loop: this Anomaly's second attack this turn. */
second: boolean;
}
/** Parameters of an Execution or ability. Each card uses the fields it needs. */
export interface Args {
ref?: AvatarRef;
ref?: AnomalyRef;
card?: number;
cards?: number[];
to?: LocId;
@ -168,12 +168,12 @@ export interface Combat {
id: number;
/** The defended location. */
loc: LocId;
attacker: AvatarRef;
attacker: AnomalyRef;
/** Where the attacker stands, for its Server bonus. */
origin: LocId;
defenders: AvatarRef[];
defenders: AnomalyRef[];
kind: 'attack' | 'advance' | 'traceRoute';
/** Dice by Avatar, keyed `player:slot`. */
/** Dice by Anomaly, keyed `player:slot`. */
dice: Record<string, number[]>;
rolled: boolean;
/** Ended early (Emergency Shutdown, Disconnect). */
@ -191,7 +191,7 @@ export type Json = unknown;
export interface ChoiceOption {
label: string;
value: Json;
/** RAM needed to pick this option. */
/** Bandwidth needed to pick this option. */
cost?: number;
}
@ -202,6 +202,8 @@ export interface Choice {
kind: string;
prompt: string;
options: ChoiceOption[];
/** The prompt or options name cards only the chooser may see (their deck, a secret pick). */
secret?: boolean;
/** Script function that receives the picked value. */
resume: { name: string; fn: string; data: Json };
}
@ -223,7 +225,7 @@ export type HookName =
/** Something that has an effect in play. */
export interface Source {
kind: 'server' | 'program' | 'hardware' | 'avatar';
kind: 'server' | 'program' | 'hardware' | 'anomaly';
/** The card providing it (the original card for copied effects). */
id: number;
/** Script that runs. Differs from the card for copies (Duplicate Server, Fork...). */
@ -231,8 +233,8 @@ export interface Source {
controller: PlayerId;
/** Where the effect applies. */
at: LocId | null;
/** Hardware: its wearer. Avatar: itself. */
ref?: AvatarRef;
/** Hardware: its wearer. Anomaly: itself. */
ref?: AnomalyRef;
/** Virtual copy id, or -1 for a Worm Protocol spread. */
virtual?: number;
}
@ -243,8 +245,8 @@ export type Task =
| { t: 'declaration'; index: number }
| { t: 'afterResolve' }
| { t: 'combat'; stage: 'start' | 'roll' | 'result' | 'end' | 'cleanup' }
| { t: 'defeat'; ref: AvatarRef; loc: LocId; role: 'attack' | 'defend' }
| { t: 'capture'; ref: AvatarRef; loc: LocId; stage: 'hooks' | 'main'; how: CaptureStat }
| { t: 'defeat'; ref: AnomalyRef; loc: LocId; role: 'attack' | 'defend' }
| { t: 'capture'; ref: AnomalyRef; loc: LocId; stage: 'hooks' | 'main'; how: CaptureStat }
| { t: 'hook'; hook: HookName; src: Source; data: Json }
| { t: 'call'; name: string; fn: string; data: Json }
| { t: 'draw'; player: PlayerId }
@ -255,7 +257,7 @@ export type Action =
| { type: 'pass' }
| { type: 'choose'; index: number }
| { type: 'place'; slot: number; to: LocId }
/** Health rule: return an Avatar in play to its slot as its placement for the round; it heals. */
/** Health rule: return an Anomaly in play to its slot as its placement for the round; it heals. */
| { type: 'recall'; slot: number }
| { type: 'advance'; slot: number; to: LocId }
| { type: 'attack'; slot: number; to: LocId }
@ -263,10 +265,10 @@ export type Action =
| { type: 'firewall'; line: string; level: number }
| { type: 'salvage'; card: number }
| { type: 'installHardware'; card: number; slot: number }
/** Recruit rule: an Avatar from hand into `slot`, retiring the Avatar there if there is one. */
/** Recruit rule: an Anomaly from hand into `slot`, retiring the Anomaly there if there is one. */
| { type: 'recruit'; card: number; slot: number }
/** Buy-Avatars rule: flip Avatar `slot`, the next face-down one, for its price. */
| { type: 'buyAvatar'; slot: number }
/** Buy-Anomalies rule: flip Anomaly `slot`, the next face-down one, for its price. */
| { type: 'buyAnomaly'; slot: number }
| { type: 'installProgram'; card: number; at: LocId }
| { type: 'play'; card: number; target: LocId | null; args: Args; from: LocId | null }
| { type: 'activate'; card: number; name: string; args: Args };
@ -279,18 +281,18 @@ export const STAT_KEYS = [
'attacksWon',
'combatsTied',
'damageDealt',
'avatarsDestroyed',
'anomaliesDestroyed',
'recalls',
'combatsEnded',
'firewallsPlaced',
'firewallsUpgraded',
'firewallsCleared',
'ramFromCaptures',
'ramFromSalvage',
'ramFromEffects',
'ramOnFirewalls',
'ramOnCards',
'ramOnAbilities',
'bandwidthFromCaptures',
'bandwidthFromSalvage',
'bandwidthFromEffects',
'bandwidthOnFirewalls',
'bandwidthOnCards',
'bandwidthOnAbilities',
'cardsSalvaged',
'cardsDrawn',
'hardwareInstalled',
@ -299,10 +301,10 @@ export const STAT_KEYS = [
'programsLost',
'executionsPlayed',
'abilitiesUsed',
'avatarsRecruited',
'avatarsRetired',
'avatarsBought',
'ramOnAvatars',
'anomaliesRecruited',
'anomaliesRetired',
'anomaliesBought',
'bandwidthOnAnomalies',
] as const;
export type StatKey = (typeof STAT_KEYS)[number];
@ -315,6 +317,25 @@ export interface CardUse {
fired: [number, number];
}
/** What a log line is about, for filtering. Untagged lines are card effects. */
export type LogTag = 'game' | 'turn' | 'move' | 'combat' | 'capture' | 'card' | 'firewall' | 'choice';
/**
* A play-by-play line. A line with `to` names cards only that player may see: they read `text`,
* and the other player reads `public` instead. The other fields say what it's about, for apps.
*/
export interface LogLine {
text: string;
to?: PlayerId;
public?: string;
tag?: LogTag;
player?: PlayerId;
loc?: LocId;
/** The Anomaly it's about; with `amount`, the damage it took. */
ref?: AnomalyRef;
amount?: number;
}
export interface GameState {
rules: RulesConfig;
rng: Rng;
@ -345,8 +366,8 @@ export interface GameState {
endReason: 'win' | 'turnLimit' | null;
stats: GameStats;
cardUse: Record<string, CardUse>;
/** Play-by-play text, when logging is on. */
log: string[] | null;
/** Play-by-play, when logging is on. Read it with logFor. */
log: LogLine[] | null;
/** Dice results to use before the RNG. Tests set this to script a combat. */
rigged?: number[];
}

View file

@ -1,16 +1,16 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { avatarCores, openWindow } from '../src/engine.ts';
import { anomalyCores, openWindow } from '../src/engine.ts';
import { hasRoom } from '../src/query.ts';
import { withRule } from '../src/rules.ts';
import { card } from './card.ts';
import { Table, type Side } from './table.ts';
/** South's Avatar 1 (`south`) on B1 attacks North's Avatar 1 (`north`) on C1. */
/** South's Anomaly 1 (`south`) on B1 attacks North's Anomaly 1 (`north`) on C1. */
function scene(south: string, north: string, o: { south?: Side; north?: Side } = {}) {
const others = ['Broken Bits', 'Pixelated Picture', 'Corrupt Driver', 'Code Zero', 'Beta Version 1.0', 'Data Leaker'];
const four = (first: string) => [first, ...others.filter((n) => n !== first)].slice(0, 4);
const t = new Table({ south: { ...o.south, avatars: four(south) }, north: { ...o.north, avatars: four(north) } });
const t = new Table({ south: { ...o.south, anomalies: four(south) }, north: { ...o.north, anomalies: four(north) } });
t.own(0, 'B1');
t.own(1, 'C1');
t.place(0, 1, 'B1');
@ -22,30 +22,30 @@ const dice = (t: Table, side: 'atk' | 'def') => {
const m = t.logText().match(/Roll: \S+(?: \S+)* \[([\d,]*)\]=\d+ vs \S+(?: \S+)* \[([\d,]*)\]/)!;
return m[side === 'atk' ? 1 : 2].split(',').length;
};
const avatarCard = (t: Table, p: 0 | 1, slot: number) => t.avatar(p, slot).card;
const anomalyCard = (t: Table, p: 0 | 1, slot: number) => t.anomaly(p, slot).card;
card('Carbon NanoBots', () => {
const t = scene('Carbon NanoBots', 'Broken Bits', { south: { main: ['Additional Core'] } });
t.own(0, 'A2');
t.hardware(0, 1, 'Additional Core');
t.ram(0, 6).use(avatarCard(t, 0, 1), { to: 'A2' }).settle();
assert.equal(t.avatar(0, 5).at, 'A2', 'the copy is in play');
assert.equal(avatarCores(t.s, 0, 5, 'defend'), 3, "2 Cores + the original's Additional Core");
t.bandwidth(0, 6).use(anomalyCard(t, 0, 1), { to: 'A2' }).settle();
assert.equal(t.anomaly(0, 5).at, 'A2', 'the copy is in play');
assert.equal(anomalyCores(t.s, 0, 5, 'defend'), 3, "2 Cores + the original's Additional Core");
// The copy attacks and loses: the original keeps its Hardware.
t.place(0, 1, 'S1');
t.s.players[0].avatars[4].at = 'B1';
t.s.players[0].anomalies[4].at = 'B1';
t.to('attack').go({ type: 'attack', slot: 5, to: 'C1' });
t.rig(1, 1, 1, 6, 6, 6, 6).end();
assert.equal(t.avatar(0, 5).at, null);
assert.equal(t.avatar(0, 1).hardware.length, 1);
assert.equal(t.anomaly(0, 5).at, null);
assert.equal(t.anomaly(0, 1).hardware.length, 1);
});
test('copy rule variants: a new copy defends but only advances or attacks from its next turn', () => {
const t = scene('Carbon NanoBots', 'Broken Bits');
t.s.rules = withRule(t.s.rules, 'copies.waitATurn=true');
t.own(0, 'A2');
t.ram(0, 6).use(avatarCard(t, 0, 1), { to: 'A2' }).settle();
assert.equal(t.avatar(0, 5).at, 'A2', 'the copy is in play, defending A2');
t.bandwidth(0, 6).use(anomalyCard(t, 0, 1), { to: 'A2' }).settle();
assert.equal(t.anomaly(0, 5).at, 'A2', 'the copy is in play, defending A2');
const acts = () => t.legal().filter((a) => (a.type === 'advance' || a.type === 'attack') && a.slot === 5);
assert.deepEqual(acts(), []);
assert.ok(t.legal().some((a) => a.type === 'advance' && a.slot === 1), 'the original still can');
@ -55,15 +55,15 @@ test('copy rule variants: a new copy defends but only advances or attacks from i
assert.ok(acts().length > 0, 'next turn it can advance');
});
test('copy rule variants: copies can need Avatar 2 unlocked, or be off', () => {
test('copy rule variants: copies can need Anomaly 2 unlocked, or be off', () => {
const t = scene('Carbon NanoBots', 'Broken Bits');
t.own(0, 'A2');
t.ram(0, 6);
t.bandwidth(0, 6);
const replicate = () => t.legal().some((a) => a.type === 'activate' && a.name === 'Carbon NanoBots');
assert.ok(replicate());
t.s.rules = withRule(t.s.rules, 'copies.needAvatar2=true');
assert.ok(!replicate(), 'Avatar 2 is still face down');
t.avatar(0, 2).faceUp = true;
t.s.rules = withRule(t.s.rules, 'copies.needAnomaly2=true');
assert.ok(!replicate(), 'Anomaly 2 is still face down');
t.anomaly(0, 2).faceUp = true;
assert.ok(replicate());
t.s.rules = withRule(t.s.rules, 'copies.allowed=false');
assert.ok(!replicate());
@ -73,7 +73,7 @@ test('no copy can enter a location while a combat is going on there', () => {
const t = scene('Broken Bits', 'Carbon NanoBots', { north: { servers: ['Cluster Server'] } });
t.own(1, 'C1', 'Cluster Server');
assert.ok(hasRoom(t.s, 1, 'C1'), 'the Cluster Server has room for a second defender');
t.ram(1, 6);
t.bandwidth(1, 6);
fight(t);
assert.ok(t.s.combat, 'North can Replicate, so the combat stops for a response');
assert.ok(!hasRoom(t.s, 1, 'C1'));
@ -82,21 +82,21 @@ test('no copy can enter a location while a combat is going on there', () => {
card('Corrupt Driver', () => {
const t = scene('Corrupt Driver', 'Broken Bits', { north: { main: ['Additional Core'] } });
const hw = t.hardware(1, 1, 'Additional Core');
t.ram(0, 4);
t.bandwidth(0, 4);
fight(t);
t.rig(1, 1, 1, 6, 6, 6, 6);
t.use(avatarCard(t, 0, 1), { card: hw }).settle();
t.use(anomalyCard(t, 0, 1), { card: hw }).settle();
assert.equal(dice(t, 'def'), 4, 'the Additional Core is off');
assert.ok(t.s.cards[hw].disabledUntil > t.s.clock);
});
card('Pixelated Picture', () => {
const t = scene('Broken Bits', 'Pixelated Picture');
t.ram(1, 3);
t.bandwidth(1, 3);
fight(t);
assert.equal(t.decider, 1);
t.rig(6, 6, 6, 1, 1, 1);
t.use(avatarCard(t, 1, 1)).settle();
t.use(anomalyCard(t, 1, 1)).settle();
assert.equal(dice(t, 'atk'), 3, 'the attacker has -1 Core');
});
@ -105,23 +105,23 @@ card('Beta Version 1.0', () => {
t.hardware(0, 1, 'Overclocked CPU');
t.hardware(0, 1, 'Packet Accelerator');
const [ac] = t.hand(0, 'Additional Core');
t.ram(0, 4 + 5);
t.bandwidth(0, 4 + 5);
fight(t);
t.rig(6, 6, 6, 6, 6, 6, 6, 6, 1, 1, 1, 1);
t.use(avatarCard(t, 0, 1), { card: ac }).settle();
assert.equal(dice(t, 'atk'), 4 + 2 + 1 + 1, 'a third Hardware on a 2-port Avatar');
t.use(anomalyCard(t, 0, 1), { card: ac }).settle();
assert.equal(dice(t, 'atk'), 4 + 2 + 1 + 1, 'a third Hardware on a 2-slot Anomaly');
t.to('playAgain').end();
assert.ok(t.s.players[0].discard.includes(ac), 'gone at the end of the turn');
});
card('Code Zero', () => {
const t = scene('Broken Bits', 'Code Zero');
t.ram(1, 4);
t.bandwidth(1, 4);
fight(t);
assert.equal(t.decider, 1);
t.rig(6, 6, 6, 1, 1, 1);
t.use(avatarCard(t, 1, 1)).settle();
assert.equal(t.avatar(0, 1).infection >= 1 || t.avatar(0, 1).at === null, true);
t.use(anomalyCard(t, 1, 1)).settle();
assert.equal(t.anomaly(0, 1).infection >= 1 || t.anomaly(0, 1).at === null, true);
assert.equal(dice(t, 'atk'), 3, '1 Infection counter: -1 Core while Code Zero is in play');
assert.equal(dice(t, 'def'), 3, 'Code Zero has 3 Cores');
});
@ -130,16 +130,16 @@ card('Data Leaker', () => {
const t = scene('Data Leaker', 'Broken Bits', { south: { main: ['Additional Core'] }, north: { main: ['Cooling System', 'Hotfix'] } });
const [cool] = t.hand(1, 'Cooling System', 'Hotfix');
t.top(0, 'Additional Core');
t.ram(0, 3);
t.bandwidth(0, 3);
// Breach first: take an undefended enemy location this turn.
t.own(1, 'C2');
t.go({ type: 'advance', slot: 1, to: 'C2' }).to('attack').end();
assert.equal(t.s.locations.C2.owner, 0);
t.use(avatarCard(t, 0, 1));
t.use(anomalyCard(t, 0, 1));
assert.equal(t.s.choice?.kind, 'Data Leaker:discard');
t.choose('Cooling System').settle();
assert.ok(t.s.players[1].discard.includes(cool));
assert.equal(t.s.players[1].ram, 0, 'no RAM for the discard');
assert.equal(t.s.players[1].bandwidth, 0, 'no Bandwidth for the discard');
assert.equal(t.s.players[0].hand.length, 1, 'it breached this turn, so it draws');
});
@ -147,21 +147,21 @@ card('Backup Machine', () => {
const t = scene('Backup Machine', 'Broken Bits', { south: { main: ['Additional Core'] } });
const ac = t.take(0, 'Additional Core');
t.s.players[0].discard.push(ac);
t.ram(0, 5 + 3).use(avatarCard(t, 0, 1), { card: ac });
t.bandwidth(0, 5 + 3).use(anomalyCard(t, 0, 1), { card: ac });
assert.equal(t.s.choice?.kind, 'Backup Machine:install');
t.choose('Install').settle();
assert.deepEqual(t.avatar(0, 1).hardware, [ac]);
assert.equal(t.s.players[0].ram, 0, '5 for the Ability, 5 - 2 for the Hardware');
assert.deepEqual(t.anomaly(0, 1).hardware, [ac]);
assert.equal(t.s.players[0].bandwidth, 0, '5 for the Ability, 5 - 2 for the Hardware');
});
card('Broken Bits', () => {
const t = scene('Broken Bits', 'Broken Bits');
t.ram(0, 4);
t.bandwidth(0, 4);
t.rig(1, 1, 2, 2, 3, 3, 3, 3);
fight(t);
assert.equal(openWindow(t.s)?.kind, 'postRoll', 'nothing to do before the roll');
t.rig(6, 6, 6, 6);
t.use(avatarCard(t, 0, 1), { k: 2 }).settle();
t.use(anomalyCard(t, 0, 1), { k: 2 }).settle();
assert.match(t.logText(), /Bit Flip rerolls 4 dice/);
assert.equal(t.s.locations.C1.owner, 0);
});

103
sim/test/app.test.ts Normal file
View file

@ -0,0 +1,103 @@
/** What the app needs from the sim: action labels, private log lines, Cores breakdowns. */
import assert from 'node:assert/strict';
import { test } from 'node:test';
import type { Bot } from '../src/bots/bot.ts';
import { greedyBot } from '../src/bots/greedy.ts';
import { randomBot } from '../src/bots/random.ts';
import { randomDeck } from '../src/deck.ts';
import { describeAction } from '../src/describe.ts';
import { actionKey, applyAction, createGame, decider, legalActions, viewFor } from '../src/engine.ts';
import { coresOf, fighterOf, type CorePart } from '../src/query.ts';
import { loadCards } from '../src/load.ts';
import { makeRng } from '../src/rng.ts';
import { DEFAULT_RULES, withRule, type RulesConfig } from '../src/rules.ts';
import { fightersOf, logFor, nameOf, programLocation, wearerOf } from '../src/state.ts';
import type { Action, GameState } from '../src/types.ts';
const pool = loadCards();
/** Plays a game, calling `each` at every decision with the legal actions. */
function play(seed: number, bots: [Bot, Bot], each: (s: GameState, legal: Action[]) => void, rules: RulesConfig = DEFAULT_RULES): GameState {
const rng = makeRng(seed ^ 0x9e3779b9);
const s = createGame({ pool, decks: [randomDeck(pool, rng, rules), randomDeck(pool, rng, rules)], seed, rules, log: true });
for (let n = 0; !s.over && n < 50_000; n++) {
const p = decider(s)!;
const legal = legalActions(s);
each(s, legal);
applyAction(s, bots[p].choose(viewFor(s, p), legal, p), legal);
}
return s;
}
/**
* Two actions are the same move when they differ only in which of two same-named cards in the same
* place they use: salvaging either copy in hand, swapping out either of two identical Hardware.
*/
function sameMove(s: GameState, a: Action, b: Action): boolean {
const where = (id: number) => {
const wearer = wearerOf(s, id);
return `${nameOf(s, id)}@${programLocation(s, id) ?? (wearer ? `${wearer.player}:${wearer.slot}` : zoneOf(s, id))}`;
};
const canon = (x: Action) =>
JSON.stringify(x, (k, v) => (['card', 'cards'].includes(k) ? (Array.isArray(v) ? v.map(where) : typeof v === 'number' ? where(v) : v) : v));
return canon(a) === canon(b);
}
const zoneOf = (s: GameState, id: number): string => {
const pl = s.players[s.cards[id].owner];
return pl.hand.includes(id) ? 'hand' : pl.discard.includes(id) ? 'discard' : 'elsewhere';
};
function checkLabels(s: GameState, legal: Action[]): void {
const seen = new Map<string, Action>();
for (const a of legal) {
const label = describeAction(s, a);
assert.ok(label.length > 0, `empty label for ${actionKey(a)}`);
assert.ok(!label.includes('undefined') && !label.includes('NaN'), `bad label "${label}" for ${actionKey(a)}`);
const prev = seen.get(label);
if (prev && !sameMove(s, prev, a)) assert.fail(`"${label}" labels both ${actionKey(prev)} and ${actionKey(a)} (turn ${s.turn})`);
seen.set(label, a);
}
}
test('every legal action gets a label, and no two moves in a decision share one', () => {
for (let seed = 1; seed <= 60; seed++) play(seed, [randomBot(seed * 2), randomBot(seed * 2 + 1)], checkLabels);
for (let seed = 1; seed <= 30; seed++) play(seed, [greedyBot(), greedyBot()], checkLabels);
for (const spec of ['recruit.on=true', 'buyAnomalies.on=true', 'commands.on=false']) {
const rules = withRule(DEFAULT_RULES, spec);
for (let seed = 1; seed <= 10; seed++) play(seed, [randomBot(seed * 2), randomBot(seed * 2 + 1)], checkLabels, rules);
}
});
test("a player's log never names the other player's secret choices", () => {
let secrets = 0;
for (let seed = 1; seed <= 80; seed++) {
const s = play(seed, [greedyBot(), greedyBot()], () => {});
for (const l of s.log!) if (l.to !== undefined) secrets++;
for (const p of [0, 1] as const) {
const mine = logFor(s, p);
s.log!.forEach((l, i) => {
if (l.to === undefined) assert.equal(mine[i], l.text);
else assert.equal(mine[i], l.to === p ? l.text : l.public);
});
}
}
assert.ok(secrets > 0, 'no secret lines came up; the check tested nothing');
});
test('a Cores breakdown adds up to the total', () => {
let combats = 0;
for (let seed = 1; seed <= 20; seed++) {
play(seed, [greedyBot(), greedyBot()], (s) => {
if (!s.combat || s.combat.ended) return;
combats++;
for (const r of fightersOf(s.combat)) {
const parts: CorePart[] = [];
const total = coresOf(s, fighterOf(s, r), undefined, parts);
assert.equal(parts[0].kind, 'anomaly');
assert.equal(Math.max(1, parts.reduce((t, x) => t + x.cores, 0)), total);
}
});
}
assert.ok(combats > 50);
});

View file

@ -1,7 +1,7 @@
import assert from 'node:assert/strict';
import { readdirSync, readFileSync } from 'node:fs';
import { test } from 'node:test';
import { loadCards } from '../src/cards.ts';
import { loadCards } from '../src/load.ts';
import { randomDeck, validateDeck } from '../src/deck.ts';
import { makeRng } from '../src/rng.ts';
import { DEFAULT_RULES } from '../src/rules.ts';
@ -11,14 +11,14 @@ const pool = loadCards();
test('cards.csv loads every playable card', () => {
const count = (kind: string) => pool.all.filter((c) => c.kind === kind).length;
assert.equal(count('avatar'), 8);
assert.equal(count('anomaly'), 8);
assert.equal(count('server'), 13);
assert.equal(count('program'), 28);
assert.equal(count('hardware'), 16);
assert.equal(count('execution'), 18);
assert.equal(pool.byName.get('Broken Bits')?.cores, 4);
assert.equal(pool.byName.get('Carbon NanoBots')?.slots, 4);
assert.equal(pool.byName.get('Quantum Coprocessor')?.ram, 9);
assert.equal(pool.byName.get('Quantum Coprocessor')?.bandwidth, 9);
});
test('every card has a script written for its current text', () => {
@ -37,7 +37,7 @@ test('every card has its own test', () => {
test('set 2 loads on request, is well formed, and is unscripted', () => {
const two = loadCards(undefined, [2]);
const count = (kind: string) => two.all.filter((c) => c.kind === kind).length;
assert.equal(count('avatar'), 12);
assert.equal(count('anomaly'), 12);
assert.equal(count('server'), 7);
assert.equal(count('program'), 17);
assert.equal(count('hardware'), 8);
@ -46,16 +46,16 @@ test('set 2 loads on request, is well formed, and is unscripted', () => {
assert.equal(c.set, 2, c.name);
assert.ok(!pool.byName.has(c.name), `${c.name} clashes with a set 1 card`);
assert.ok(c.text || c.ability, `${c.name} has text`);
if (c.kind === 'avatar') {
if (c.kind === 'anomaly') {
assert.equal(c.cores + c.slots, 6, `${c.name}: Cores + Slots = 6`);
assert.equal(c.health, { 4: 9, 3: 10, 2: 12 }[c.cores], `${c.name}: Health by Cores`);
assert.ok(c.type && c.ability && c.ability.cost >= 3 && c.ability.cost <= 5, `${c.name}: typed, Ability 3-5 RAM`);
assert.ok(c.type && c.ability && c.ability.cost >= 3 && c.ability.cost <= 5, `${c.name}: typed, Ability 3-5 Gb`);
} else if (c.kind === 'program') {
assert.ok(c.type && c.ram >= 4 && c.ram <= 6, `${c.name}: typed, 4-6 RAM`);
assert.ok(c.type && c.bandwidth >= 4 && c.bandwidth <= 6, `${c.name}: typed, 4-6 Gb`);
} else if (c.kind === 'execution') {
assert.ok(c.ram >= 3 && c.ram <= 5, `${c.name}: 3-5 RAM`);
assert.ok(c.bandwidth >= 3 && c.bandwidth <= 5, `${c.name}: 3-5 Gb`);
} else if (c.kind === 'hardware') {
assert.ok(c.ram >= 4 && c.ram <= 7, `${c.name}: 4-7 RAM`);
assert.ok(c.bandwidth >= 4 && c.bandwidth <= 7, `${c.name}: 4-7 Gb`);
}
}
const all = loadCards(undefined, 'all');
@ -76,7 +76,7 @@ test('deck validation catches size, kind and copy problems', () => {
const deck = randomDeck(pool, makeRng(1), DEFAULT_RULES);
deck.main[0] = deck.main[1] = deck.main[2] = 'Execute: Fork';
deck.servers.pop();
deck.avatars[0] = 'Cloud Compute';
deck.anomalies[0] = 'Cloud Compute';
const errors = validateDeck(pool, deck, DEFAULT_RULES).join('\n');
assert.match(errors, /Servers: 19 cards/);
assert.match(errors, /"Cloud Compute" is a server/);

View file

@ -1,8 +1,8 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { loadCards } from '../src/cards.ts';
import { loadCards } from '../src/load.ts';
import { randomDeck } from '../src/deck.ts';
import { advanceTargets, avatarCores, createGame, legalActions, viewFor } from '../src/engine.ts';
import { advanceTargets, anomalyCores, createGame, legalActions, viewFor } from '../src/engine.ts';
import { checkInvariants } from '../src/invariants.ts';
import { makeRng } from '../src/rng.ts';
import { DEFAULT_RULES, withRule, type RulesConfig } from '../src/rules.ts';
@ -19,9 +19,9 @@ test('setup follows rules.md', () => {
const pl = s.players[p];
assert.ok(pl.hand.length >= 7, 'opening hand');
assert.equal(pl.serverPile.length, 19);
assert.ok(pl.ram >= 4);
assert.deepEqual(pl.avatars.slice(0, 4).map((a) => a.faceUp), [true, false, false, false]);
assert.ok(pl.avatars.slice(4).every((a) => !a.faceUp && a.at === null), 'no copies yet');
assert.ok(pl.bandwidth >= 4);
assert.deepEqual(pl.anomalies.slice(0, 4).map((a) => a.faceUp), [true, false, false, false]);
assert.ok(pl.anomalies.slice(4).every((a) => !a.faceUp && a.at === null), 'no copies yet');
assert.equal(s.locations[p === 0 ? 'S1' : 'S2'].owner, p);
}
assert.equal(s.turn, 1);
@ -62,53 +62,53 @@ test('rule variants: more cards per draw step', () => {
assert.equal(t.s.players[1].hand.length, 2);
});
test('advancing captures an unowned location in step 5 and pays 4 RAM; Lv 1 unlocks nothing', () => {
test('advancing captures an unowned location in step 5 and pays 4 Gb; Lv 1 unlocks nothing', () => {
const t = new Table();
t.ram(0, 4);
t.bandwidth(0, 4);
assert.deepEqual(advanceTargets(t.s, 0), ['A2']);
t.go({ type: 'place', slot: 1, to: 'S1' }).go({ type: 'advance', slot: 1, to: 'A2' });
t.to('attack');
assert.equal(t.s.locations.A2.owner, null);
t.end();
assert.equal(t.s.locations.A2.owner, 0);
assert.equal(t.avatar(0, 1).at, 'A2');
assert.equal(t.s.players[0].ram, 8, '4 RAM + 4 for the capture');
assert.equal(t.avatar(0, 2).faceUp, false, 'A2 is Lv 1 for South');
assert.equal(t.anomaly(0, 1).at, 'A2');
assert.equal(t.s.players[0].bandwidth, 8, '4 Gb + 4 for the capture');
assert.equal(t.anomaly(0, 2).faceUp, false, 'A2 is Lv 1 for South');
assert.equal(t.s.step, 'playAgain');
});
test('the second row (Lv 2) unlocks Avatar 2; the middle row (Lv 3) unlocks Avatars 2 and 3', () => {
test('the second row (Lv 2) unlocks Anomaly 2; the middle row (Lv 3) unlocks Anomalies 2 and 3', () => {
for (const [from, to, unlocked] of [['A2', 'B1', [true, false]], ['B1', 'C2', [true, true]]] as const) {
const t = new Table();
t.own(0, from);
t.place(0, 1, from);
t.go({ type: 'advance', slot: 1, to }).to('attack').end();
assert.equal(t.s.locations[to].owner, 0);
assert.deepEqual([t.avatar(0, 2).faceUp, t.avatar(0, 3).faceUp], unlocked, to);
assert.deepEqual([t.anomaly(0, 2).faceUp, t.anomaly(0, 3).faceUp], unlocked, to);
}
});
test('rule variants: a turn-1 capture can pay no RAM and unlock nothing', () => {
test('rule variants: a turn-1 capture can pay no Bandwidth and unlock nothing', () => {
const t = new Table();
t.s.rules = withRule(withRule(t.s.rules, 'firstTurn.captureRam=false'), 'firstTurn.unlock=false');
t.ram(0, 4).own(0, 'A2');
t.s.rules = withRule(withRule(t.s.rules, 'firstTurn.captureBandwidth=false'), 'firstTurn.unlock=false');
t.bandwidth(0, 4).own(0, 'A2');
t.place(0, 1, 'A2');
t.go({ type: 'advance', slot: 1, to: 'B1' }).to('attack').end();
assert.equal(t.s.locations.B1.owner, 0);
assert.equal(t.s.players[0].ram, 4);
assert.equal(t.avatar(0, 2).faceUp, false);
assert.equal(t.s.players[0].bandwidth, 4);
assert.equal(t.anomaly(0, 2).faceUp, false);
});
test('rule variants: the first player can be barred from playing cards on turn 1', () => {
const t = new Table({ south: { main: ['Additional Core'] }, north: { main: ['Additional Core'] } });
t.s.rules = withRule(t.s.rules, 'firstTurn.cards=false');
t.hand(0, 'Additional Core');
t.ram(0, 9).place(0, 1, 'S1');
t.bandwidth(0, 9).place(0, 1, 'S1');
t.to('playAgain');
assert.ok(!t.legal().some((a) => a.type === 'installHardware'));
t.end();
t.hand(1, 'Additional Core');
t.ram(1, 9).place(1, 1, 'S2');
t.bandwidth(1, 9).place(1, 1, 'S2');
t.to('playAgain');
assert.ok(t.legal().some((a) => a.type === 'installHardware'), 'the second player can on turn 2');
});
@ -136,21 +136,21 @@ test('a Firewall blocks movement until someone pays to clear it', () => {
const t = new Table();
t.own(0, 'A2');
t.s.firewalls['A1-A2'] = 2;
t.ram(0, 4).go({ type: 'place', slot: 1, to: 'S1' });
t.bandwidth(0, 4).go({ type: 'place', slot: 1, to: 'S1' });
assert.ok(!advanceTargets(t.s, 0).includes('A1'));
assert.ok(!t.can({ type: 'advance', slot: 1, to: 'A1' }));
t.go({ type: 'clearFirewall', line: 'A1-A2' });
assert.equal(t.s.players[0].ram, 0, 'clearing a Lv 2 Firewall costs 4');
assert.equal(t.s.players[0].bandwidth, 0, 'clearing a Lv 2 Firewall costs 4');
assert.ok(advanceTargets(t.s, 0).includes('A1'));
});
test('Firewalls go only on gateways, and upgrades cost the full price of the new level', () => {
const t = new Table({ south: { servers: ['Upgraded Hardware'] } });
t.own(0, 'A2', 'Upgraded Hardware');
t.ram(0, 20).to('play');
t.bandwidth(0, 20).to('play');
assert.ok(!t.can({ type: 'firewall', line: 'S1-A2', level: 1 }));
t.go({ type: 'firewall', line: 'A1-A2', level: 1 }).go({ type: 'firewall', line: 'A1-A2', level: 2 });
assert.equal(t.s.players[0].ram, 20 - 2 - 4);
assert.equal(t.s.players[0].bandwidth, 20 - 2 - 4);
assert.equal(t.s.firewalls['A1-A2'], 2);
});
@ -163,21 +163,21 @@ test('combat: the loser goes back to its slot and loses its Hardware; the winner
t.place(1, 1, 'C1');
const hw = t.hardware(1, 1, 'Additional Core');
t.to('attack').go({ type: 'attack', slot: 1, to: 'C1' });
assert.equal(avatarCores(t.s, 0, 1, 'attack'), 4);
assert.equal(avatarCores(t.s, 1, 1, 'defend'), 5, '4 Cores + Additional Core');
assert.equal(anomalyCores(t.s, 0, 1, 'attack'), 4);
assert.equal(anomalyCores(t.s, 1, 1, 'defend'), 5, '4 Cores + Additional Core');
t.rig(...(attackerWins ? [6, 6, 6, 6, 1, 1, 1, 1, 1] : [1, 1, 1, 1, 6, 6, 6, 6, 6]));
t.end();
if (attackerWins) {
assert.equal(t.s.locations.C1.owner, 0);
assert.equal(t.avatar(0, 1).at, 'C1');
assert.equal(t.avatar(1, 1).at, null);
assert.deepEqual(t.avatar(1, 1).hardware, []);
assert.equal(t.anomaly(0, 1).at, 'C1');
assert.equal(t.anomaly(1, 1).at, null);
assert.deepEqual(t.anomaly(1, 1).hardware, []);
assert.ok(t.s.players[1].discard.includes(hw));
assert.equal(t.s.stats.attacksWon[0], 1);
} else {
assert.equal(t.avatar(0, 1).at, null);
assert.equal(t.avatar(1, 1).at, 'C1');
assert.deepEqual(t.avatar(1, 1).hardware, [hw]);
assert.equal(t.anomaly(0, 1).at, null);
assert.equal(t.anomaly(1, 1).at, 'C1');
assert.deepEqual(t.anomaly(1, 1).hardware, [hw]);
}
assert.equal(t.s.stats.attacks[0], 1);
}
@ -222,15 +222,15 @@ test('reaching the location target wins immediately', () => {
assert.deepEqual(legalActions(t.s), []);
});
test('Salvage pays full printed RAM, from hand only', () => {
test('Salvage pays full printed Bandwidth, from hand only', () => {
const t = new Table({ south: { main: ['Cooling System'] } });
const [card] = t.hand(0, 'Cooling System');
t.go({ type: 'salvage', card });
assert.equal(t.s.players[0].ram, 6);
assert.equal(t.s.players[0].bandwidth, 6);
assert.ok(t.s.players[0].discard.includes(card));
});
test('views hide the opponent hand, both decks, face-down Avatars and the RNG', () => {
test('views hide the opponent hand, both decks, face-down Anomalies and the RNG', () => {
const t = new Table({ south: { main: ['Additional Core'] }, north: { main: ['Additional Core'] } });
t.hand(0, 'Additional Core');
t.hand(1, 'Additional Core');
@ -239,8 +239,8 @@ test('views hide the opponent hand, both decks, face-down Avatars and the RNG',
assert.deepEqual(v.players[0].hand, t.s.players[0].hand);
assert.ok(v.players[0].deck.every((id) => id === -1));
assert.ok(v.players[1].serverPile.every((id) => id === -1));
assert.equal(v.players[0].avatars[1].card, -1);
assert.equal(v.players[1].avatars[1].card, -1);
assert.equal(v.players[0].anomalies[1].card, -1);
assert.equal(v.players[1].anomalies[1].card, -1);
assert.equal(v.rng.s, 0);
assert.notEqual(t.s.rng.s, 0);
});
@ -259,9 +259,9 @@ test('an opponent with a response gets a window after a declaration; without one
t.place(0, 1, 'S1');
t.place(0, 2, 'A2');
t.act({ type: 'advance', slot: 1, to: 'A1' });
assert.equal(t.decider, 0, 'North has no RAM, so no window');
assert.equal(t.decider, 0, 'North has no Bandwidth, so no window');
t.hand(1, 'Execute: Ping Sweep');
t.ram(1, 4);
t.bandwidth(1, 4);
t.act({ type: 'advance', slot: 2, to: 'A3' });
assert.equal(t.decider, 1, 'North may respond');
t.act({ type: 'pass' });
@ -269,17 +269,17 @@ test('an opponent with a response gets a window after a declaration; without one
});
// ---------------------------------------------------------------------------------------------
// Recruit rule (prototype): Avatars in the deck, bought with RAM
// Recruit rule (prototype): Anomalies in the deck, bought with Bandwidth
/** A table under the recruit rule: Avatar 1 stays, Avatars 2–4 move to their owner's hand, priced at 6 RAM. */
/** A table under the recruit rule: Anomaly 1 stays, Anomalies 2–4 move to their owner's hand, priced at 6 Gb. */
function recruitTable(o: ConstructorParameters<typeof Table>[0] = {}): Table {
const t = new Table(o);
t.s.rules = withRule(t.s.rules, 'recruit.on=true');
for (const p of [0, 1] as const) {
const avs = t.s.players[p].avatars;
const avs = t.s.players[p].anomalies;
for (let i = 1; i < 4; i++) {
const name = t.s.cards[avs[i].card].name;
t.s.defs[name] = { ...t.s.defs[name], ram: 6 };
t.s.defs[name] = { ...t.s.defs[name], bandwidth: 6 };
t.s.players[p].hand.push(avs[i].card);
avs[i].card = avs[i + 4].card = -1;
avs[i].faceUp = false;
@ -290,101 +290,101 @@ function recruitTable(o: ConstructorParameters<typeof Table>[0] = {}): Table {
const recruits = (t: Table) => t.legal().filter((a) => a.type === 'recruit');
test('recruit rule: buy an Avatar from hand into an empty slot; it enters play on a later turn', () => {
test('recruit rule: buy an Anomaly from hand into an empty slot; it enters play on a later turn', () => {
const t = recruitTable();
const card = t.s.players[0].hand[0];
t.ram(0, 5).to('play');
assert.equal(recruits(t).length, 0, "can't afford 6 RAM");
t.ram(0, 6);
assert.deepEqual(recruits(t).map((a) => a.type === 'recruit' && a.slot), [2, 1, 2, 1, 2, 1], 'first empty slot, or over Avatar 1');
t.bandwidth(0, 5).to('play');
assert.equal(recruits(t).length, 0, "can't afford 6 Gb");
t.bandwidth(0, 6);
assert.deepEqual(recruits(t).map((a) => a.type === 'recruit' && a.slot), [2, 1, 2, 1, 2, 1], 'first empty slot, or over Anomaly 1');
t.go({ type: 'recruit', card, slot: 2 });
assert.equal(t.s.players[0].ram, 0);
assert.equal(t.avatar(0, 2).card, card);
assert.equal(t.avatar(0, 2).faceUp, true);
assert.equal(t.s.players[0].bandwidth, 0);
assert.equal(t.anomaly(0, 2).card, card);
assert.equal(t.anomaly(0, 2).faceUp, true);
assert.ok(!t.s.players[0].hand.includes(card));
t.to('playAgain').end().to('playAgain').end();
assert.ok(t.can({ type: 'place', slot: 2, to: 'S1' }));
});
test('recruit rule: captures unlock nothing, and a salvaged Avatar pays its price', () => {
test('recruit rule: captures unlock nothing, and a salvaged Anomaly pays its price', () => {
const t = recruitTable();
t.own(0, 'B1');
t.place(0, 1, 'B1');
t.go({ type: 'advance', slot: 1, to: 'C2' }).to('attack').end();
assert.equal(t.s.locations.C2.owner, 0);
assert.equal(t.avatar(0, 2).card, -1);
const ram = t.s.players[0].ram;
assert.equal(t.anomaly(0, 2).card, -1);
const bandwidth = t.s.players[0].bandwidth;
t.go({ type: 'salvage', card: t.s.players[0].hand[0] });
assert.equal(t.s.players[0].ram, ram + 6);
assert.equal(t.s.players[0].bandwidth, bandwidth + 6);
});
test('recruit rule: copies count toward the 4 Avatars', () => {
const t = recruitTable({ south: { avatars: ['Carbon NanoBots', 'Broken Bits', 'Pixelated Picture', 'Corrupt Driver'] } });
test('recruit rule: copies count toward the 4 Anomalies', () => {
const t = recruitTable({ south: { anomalies: ['Carbon NanoBots', 'Broken Bits', 'Pixelated Picture', 'Corrupt Driver'] } });
t.own(0, 'A2');
t.place(0, 1, 'A2');
const [a, b] = t.s.players[0].hand;
t.ram(0, 30).to('play');
t.bandwidth(0, 30).to('play');
t.go({ type: 'recruit', card: a, slot: 2 }).go({ type: 'recruit', card: b, slot: 3 });
const replicate = t.legal().find((x) => x.type === 'activate' && x.name === 'Carbon NanoBots' && x.args.to === 'S1');
assert.ok(replicate, '3 Avatars, so a copy fits');
assert.ok(replicate, '3 Anomalies, so a copy fits');
t.go(replicate).settle();
assert.equal(t.avatar(0, 5).at, 'S1');
assert.equal(t.anomaly(0, 5).at, 'S1');
assert.ok(!recruits(t).some((r) => r.type === 'recruit' && r.slot === 4), 'no room for a fourth with the copy out');
});
test('recruit rule: recruiting over an Avatar retires it and its Hardware', () => {
test('recruit rule: recruiting over an Anomaly retires it and its Hardware', () => {
const t = recruitTable({ south: { main: ['Additional Core'] } });
t.own(0, 'A2');
const ref = t.place(0, 1, 'A2');
const old = t.avatar(0, 1).card;
const old = t.anomaly(0, 1).card;
const hw = t.hardware(ref.player, ref.slot, 'Additional Core');
const card = t.s.players[0].hand.find((id) => t.s.defs[t.s.cards[id].name].kind === 'avatar')!;
t.ram(0, 6).to('play').go({ type: 'recruit', card, slot: 1 });
assert.equal(t.avatar(0, 1).card, card);
assert.equal(t.avatar(0, 1).at, null);
assert.deepEqual(t.avatar(0, 1).hardware, []);
const card = t.s.players[0].hand.find((id) => t.s.defs[t.s.cards[id].name].kind === 'anomaly')!;
t.bandwidth(0, 6).to('play').go({ type: 'recruit', card, slot: 1 });
assert.equal(t.anomaly(0, 1).card, card);
assert.equal(t.anomaly(0, 1).at, null);
assert.deepEqual(t.anomaly(0, 1).hardware, []);
assert.ok(t.s.players[0].discard.includes(old) && t.s.players[0].discard.includes(hw));
assert.equal(t.s.locations.A2.owner, 0, 'the location stays yours');
});
test('recruit rule: decks keep one Avatar outside and shuffle the rest into the main deck', () => {
test('recruit rule: decks keep one Anomaly outside and shuffle the rest into the main deck', () => {
const pool = loadCards();
const rules = withRule(withRule(DEFAULT_RULES, 'recruit.on=true'), 'recruit.avatarsInDeck=5');
const rules = withRule(withRule(DEFAULT_RULES, 'recruit.on=true'), 'recruit.anomaliesInDeck=5');
const deck = randomDeck(pool, makeRng(3), rules);
assert.equal(deck.avatars.length, 1);
assert.equal(deck.anomalies.length, 1);
assert.equal(deck.main.length, 45);
assert.equal(deck.main.filter((n) => pool.byName.get(n)!.kind === 'avatar').length, 5);
assert.equal(deck.main.filter((n) => pool.byName.get(n)!.kind === 'anomaly').length, 5);
const s = createGame({ pool, decks: [deck, randomDeck(pool, makeRng(4), rules)], seed: 1, rules });
assert.deepEqual(s.players[0].avatars.slice(0, 4).map((a) => a.card >= 0), [true, false, false, false]);
assert.deepEqual(s.players[0].anomalies.slice(0, 4).map((a) => a.card >= 0), [true, false, false, false]);
assert.equal(checkInvariants(s).length, 0);
});
// ---------------------------------------------------------------------------------------------
// Buy-Avatars rule (prototype): pay RAM to flip the next Avatar instead of unlocking by level
// Buy-Anomalies rule (prototype): pay Bandwidth to flip the next Anomaly instead of unlocking by level
test('buy rule: pay to flip the next face-down Avatar; it enters play on a later turn', () => {
test('buy rule: pay to flip the next face-down Anomaly; it enters play on a later turn', () => {
const t = new Table();
t.s.rules = withRule(withRule(t.s.rules, 'buyAvatars.on=true'), 'buyAvatars.prices=8,12,16');
t.ram(0, 7).to('play');
assert.ok(!t.can({ type: 'buyAvatar', slot: 2 }), "can't afford 8 RAM");
t.ram(0, 20).go({ type: 'buyAvatar', slot: 2 });
assert.equal(t.avatar(0, 2).faceUp, true);
assert.equal(t.s.players[0].ram, 12);
assert.ok(t.can({ type: 'buyAvatar', slot: 3 }), 'Avatar 3 is next, at 12');
t.go({ type: 'buyAvatar', slot: 3 });
assert.equal(t.s.players[0].ram, 0);
t.s.rules = withRule(withRule(t.s.rules, 'buyAnomalies.on=true'), 'buyAnomalies.prices=8,12,16');
t.bandwidth(0, 7).to('play');
assert.ok(!t.can({ type: 'buyAnomaly', slot: 2 }), "can't afford 8 Gb");
t.bandwidth(0, 20).go({ type: 'buyAnomaly', slot: 2 });
assert.equal(t.anomaly(0, 2).faceUp, true);
assert.equal(t.s.players[0].bandwidth, 12);
assert.ok(t.can({ type: 'buyAnomaly', slot: 3 }), 'Anomaly 3 is next, at 12');
t.go({ type: 'buyAnomaly', slot: 3 });
assert.equal(t.s.players[0].bandwidth, 0);
t.to('playAgain').end().to('playAgain').end();
assert.ok(t.can({ type: 'place', slot: 2, to: 'S1' }));
});
test('buy rule: captures unlock nothing', () => {
const t = new Table();
t.s.rules = withRule(t.s.rules, 'buyAvatars.on=true');
t.s.rules = withRule(t.s.rules, 'buyAnomalies.on=true');
t.own(0, 'B1');
t.place(0, 1, 'B1');
t.go({ type: 'advance', slot: 1, to: 'C2' }).to('attack').end();
assert.equal(t.s.locations.C2.owner, 0);
assert.deepEqual([t.avatar(0, 2).faceUp, t.avatar(0, 3).faceUp], [false, false]);
assert.deepEqual([t.anomaly(0, 2).faceUp, t.anomaly(0, 3).faceUp], [false, false]);
});
// ---------------------------------------------------------------------------------------------
@ -423,7 +423,7 @@ test('command rule: the order of commands can follow a pattern of round leads, o
assert.deepEqual(DEFAULT_RULES.commands, { on: true, perPlayer: 2, leads: 'F', snake: true }, 'the default since v0.9: the first player leads every round, snake order');
});
test('command rule: one advance or attack per command, each Avatar once a round', () => {
test('command rule: one advance or attack per command, each Anomaly once a round', () => {
const t = commandTable();
t.own(0, 'A2');
t.own(0, 'A1');
@ -436,15 +436,15 @@ test('command rule: one advance or attack per command, each Avatar once a round'
t.to('playAgain').end().to('playAgain').end();
assert.equal(t.s.turn, 3);
const movers = new Set(t.legal().filter((a) => a.type === 'advance').map((a) => a.type === 'advance' && a.slot));
assert.deepEqual([...movers], [2], 'Avatar 1 already acted this round');
assert.deepEqual([...movers], [2], 'Anomaly 1 already acted this round');
});
test('command rule: an Avatar unlocked this round enters play next round', () => {
test('command rule: an Anomaly unlocked this round enters play next round', () => {
const t = commandTable();
t.own(0, 'A2');
t.place(0, 1, 'A2');
t.go({ type: 'advance', slot: 1, to: 'B1' }).to('attack').end();
assert.equal(t.avatar(0, 2).faceUp, true);
assert.equal(t.anomaly(0, 2).faceUp, true);
t.to('playAgain').end().to('playAgain').end();
assert.equal(t.s.turn, 3);
assert.ok(!t.legal().some((a) => a.type === 'place' && a.slot === 2));

View file

@ -1,5 +1,5 @@
import assert from 'node:assert/strict';
import { avatarCores, execBlocked, executionActions, openWindow } from '../src/engine.ts';
import { anomalyCores, execBlocked, executionActions, openWindow } from '../src/engine.ts';
import { card } from './card.ts';
import { Table, type Side } from './table.ts';
@ -22,12 +22,12 @@ card('Execute: Disconnect', () => {
t.own(1, 'D1');
const hw = t.hardware(1, 1, 'Additional Core');
t.hand(1, 'Execute: Disconnect');
t.ram(1, 4);
t.bandwidth(1, 4);
fight(t);
assert.equal(t.decider, 1);
t.play(1, 'Execute: Disconnect', 'C1', { ref: { player: 1, slot: 1 }, to: 'D1' }).settle();
assert.equal(t.avatar(1, 1).at, 'D1');
assert.deepEqual(t.avatar(1, 1).hardware, [hw]);
assert.equal(t.anomaly(1, 1).at, 'D1');
assert.deepEqual(t.anomaly(1, 1).hardware, [hw]);
assert.equal(t.s.locations.C1.owner, 0, 'the attacker takes the empty location');
});
@ -35,14 +35,14 @@ card('Execute: Disconnect', () => {
// An attacker retreats after a bad roll and isn't defeated.
const t = scene({ south: { main: ['Execute: Disconnect'] } });
t.hand(0, 'Execute: Disconnect');
t.ram(0, 4);
t.bandwidth(0, 4);
t.rig(1, 1, 1, 1, 6, 6, 6, 6);
fight(t);
assert.equal(openWindow(t.s)?.kind, 'preRoll');
t.act({ type: 'pass' });
assert.equal(openWindow(t.s)?.kind, 'postRoll');
t.play(0, 'Execute: Disconnect', 'C1', { ref: { player: 0, slot: 1 }, to: 'B1' }).settle();
assert.equal(t.avatar(0, 1).at, 'B1');
assert.equal(t.anomaly(0, 1).at, 'B1');
assert.equal(t.s.locations.C1.owner, 1);
assert.match(t.logText(), /combat at C1 ends/);
});
@ -51,7 +51,7 @@ card('Execute: Sabotage', () => {
const t = scene({ south: { main: ['Execute: Sabotage'] }, north: { main: ['Additional Core'] } });
const hw = t.hardware(1, 1, 'Additional Core');
t.hand(0, 'Execute: Sabotage');
t.ram(0, 7);
t.bandwidth(0, 7);
fight(t);
t.rig(6, 6, 6, 6, 1, 1, 1, 1);
t.play(0, 'Execute: Sabotage', 'C1', { card: hw, mode: 'destroy' }).settle();
@ -62,27 +62,27 @@ card('Execute: Sabotage', () => {
card('Execute: Kill Process', () => {
const t = scene({ south: { main: ['Execute: Kill Process'] }, north: { main: ['Stack Overflow'] } });
const so = t.program(1, 'C1', 'Stack Overflow');
assert.equal(avatarCores(t.s, 1, 1, 'defend'), 5);
assert.equal(anomalyCores(t.s, 1, 1, 'defend'), 5);
t.hand(0, 'Execute: Kill Process');
t.ram(0, 5).play(0, 'Execute: Kill Process', 'C1', { card: so }).settle();
assert.equal(avatarCores(t.s, 1, 1, 'defend'), 4);
t.bandwidth(0, 5).play(0, 'Execute: Kill Process', 'C1', { card: so }).settle();
assert.equal(anomalyCores(t.s, 1, 1, 'defend'), 4);
t.to('playAgain').end();
assert.equal(avatarCores(t.s, 1, 1, 'defend'), 5, "back on at its controller's next turn");
assert.equal(anomalyCores(t.s, 1, 1, 'defend'), 5, "back on at its controller's next turn");
});
card('Execute: Force Reboot', () => {
const t = scene({ south: { main: ['Execute: Force Reboot', 'Additional Core', 'Dedicated GPU', 'Execute: Ping Sweep'] }, north: { main: ['Memory Leak'] } });
t.program(1, 'C1', 'Memory Leak');
const t = scene({ south: { main: ['Execute: Force Reboot', 'Additional Core', 'Dedicated GPU', 'Execute: Ping Sweep'] }, north: { main: ['Bloatware'] } });
t.program(1, 'C1', 'Bloatware');
t.hardware(0, 1, 'Additional Core');
t.hardware(0, 1, 'Dedicated GPU');
t.hand(0, 'Execute: Force Reboot', 'Execute: Ping Sweep');
const fromB1 = () => executionActions(t.s, 0, 'any').some((a) => a.type === 'play' && a.from === 'B1');
assert.ok(fromB1(), 'B1 can perform Executions');
t.ram(0, 5);
t.bandwidth(0, 5);
fight(t);
t.rig(6, 6, 6, 6, 6, 1, 1, 1, 1);
t.play(0, 'Execute: Force Reboot', 'C1', { ref: { player: 0, slot: 1 } }).settle();
assert.equal(attackerDice(t), 5, "Memory Leak's penalty is gone");
assert.equal(attackerDice(t), 5, "Bloatware's penalty is gone");
assert.ok(execBlocked(t.s, 'B1'), 'the Server it stands on is blocked for the turn');
assert.ok(!fromB1());
});
@ -91,16 +91,16 @@ card('Execute: Fork', () => {
const t = scene({ south: { main: ['Execute: Fork', 'Stack Overflow'] } });
const so = t.program(0, 'B1', 'Stack Overflow');
t.hand(0, 'Execute: Fork');
t.ram(0, 7).play(0, 'Execute: Fork', 'B1', { card: so }).settle();
assert.equal(avatarCores(t.s, 0, 1, 'defend'), 6, 'two Stack Overflow effects, +1 each');
t.bandwidth(0, 7).play(0, 'Execute: Fork', 'B1', { card: so }).settle();
assert.equal(anomalyCores(t.s, 0, 1, 'defend'), 6, 'two Stack Overflow effects, +1 each');
t.to('playAgain').end();
assert.equal(avatarCores(t.s, 0, 1, 'defend'), 5, 'until end of turn');
assert.equal(anomalyCores(t.s, 0, 1, 'defend'), 5, 'until end of turn');
});
card('Execute: Ping Sweep', () => {
const t = new Table({ south: { main: ['Execute: Ping Sweep'] } });
t.hand(0, 'Execute: Ping Sweep');
t.ram(0, 4).play(0, 'Execute: Ping Sweep', null).settle();
t.bandwidth(0, 4).play(0, 'Execute: Ping Sweep', null).settle();
assert.equal(t.s.players[0].hand.length, 2);
});
@ -108,26 +108,26 @@ card('Execute: Trace Route', () => {
const t = scene({ south: { main: ['Execute: Trace Route'] } });
t.hand(0, 'Execute: Trace Route');
t.rig(6, 6, 6, 6, 6, 1, 1, 1, 1);
t.ram(0, 5).to('play').play(0, 'Execute: Trace Route', 'C1', { ref: { player: 0, slot: 1 } }).settle();
t.bandwidth(0, 5).to('play').play(0, 'Execute: Trace Route', 'C1', { ref: { player: 0, slot: 1 } }).settle();
assert.equal(attackerDice(t), 5, 'attacks right away with +1 Core');
assert.equal(t.s.locations.C1.owner, 0);
assert.equal(t.avatar(0, 1).at, 'C1');
assert.equal(t.anomaly(0, 1).at, 'C1');
});
card('Execute: Override', () => {
const t = scene({ south: { main: ['Execute: Override'] }, north: { main: ['Stack Overflow'] } });
const so = t.program(1, 'C1', 'Stack Overflow');
t.hand(0, 'Execute: Override');
t.ram(0, 5).play(0, 'Execute: Override', 'C1', { card: so }).settle();
assert.equal(avatarCores(t.s, 1, 1, 'defend'), 4);
t.bandwidth(0, 5).play(0, 'Execute: Override', 'C1', { card: so }).settle();
assert.equal(anomalyCores(t.s, 1, 1, 'defend'), 4);
t.to('playAgain').end();
assert.equal(avatarCores(t.s, 1, 1, 'defend'), 5, 'until end of turn');
assert.equal(anomalyCores(t.s, 1, 1, 'defend'), 5, 'until end of turn');
});
card('Execute: Memory Dump', () => {
const t = new Table({ south: { main: ['Execute: Memory Dump', 'Execute: Memory Dump'] } });
t.hand(0, 'Execute: Memory Dump', 'Execute: Memory Dump');
t.ram(0, 8).play(0, 'Execute: Memory Dump', 'C1');
t.bandwidth(0, 8).play(0, 'Execute: Memory Dump', 'C1');
assert.equal(t.s.choice?.kind, 'Execute: Memory Dump:discard', "not South's: draw 2, discard 1");
t.choose('Network Interface Upgrade').settle();
assert.equal(t.s.players[0].hand.length, 1 + 2 - 1);
@ -141,8 +141,8 @@ card('Execute: Rollback', () => {
t.own(1, 'C1');
const [so] = t.hand(1, 'Stack Overflow');
t.hand(0, 'Execute: Rollback');
t.ram(0, 4);
t.ram(1, 7).to('play').act({ type: 'installProgram', card: so, at: 'C1' });
t.bandwidth(0, 4);
t.bandwidth(1, 7).to('play').act({ type: 'installProgram', card: so, at: 'C1' });
assert.equal(t.decider, 0, 'South may respond to the install');
t.play(0, 'Execute: Rollback', 'C1', { card: so }).settle();
assert.deepEqual(t.s.players[1].hand, [so]);
@ -152,7 +152,7 @@ card('Execute: Rollback', () => {
card('Execute: Root Access', () => {
const t = new Table({ south: { main: ['Execute: Root Access'] } });
t.hand(0, 'Execute: Root Access');
t.ram(0, 4).play(0, 'Execute: Root Access', 'C1').settle();
t.bandwidth(0, 4).play(0, 'Execute: Root Access', 'C1').settle();
assert.ok(t.s.locations.C1.rootAccess[0] > t.s.clock);
t.to('playAgain').end();
assert.ok(t.s.locations.C1.rootAccess[0] <= t.s.clock, 'until end of turn');
@ -163,19 +163,19 @@ card('Execute: Packet Flood', () => {
t.own(0, 'B1');
t.place(0, 1, 'B1');
t.hand(1, 'Execute: Packet Flood');
t.ram(1, 5);
t.bandwidth(1, 5);
t.act({ type: 'advance', slot: 1, to: 'C2' });
assert.equal(t.decider, 1);
t.play(1, 'Execute: Packet Flood', 'B1', { to: 'B1' }).settle();
t.to('attack').end();
assert.equal(t.s.locations.C2.owner, null, "the advance fails: it can't move");
assert.equal(t.avatar(0, 1).at, 'B1');
assert.equal(t.anomaly(0, 1).at, 'B1');
});
card('Execute: Emergency Shutdown', () => {
const t = scene({ north: { main: ['Execute: Emergency Shutdown'] } });
t.hand(1, 'Execute: Emergency Shutdown');
t.ram(1, 6);
t.bandwidth(1, 6);
t.rig(6, 6, 6, 6, 1, 1, 1, 1);
fight(t);
assert.equal(openWindow(t.s)?.kind, 'preRoll');
@ -183,17 +183,17 @@ card('Execute: Emergency Shutdown', () => {
assert.equal(openWindow(t.s)?.kind, 'postRoll', 'North waits to see the dice');
t.play(1, 'Execute: Emergency Shutdown', 'C1').settle();
assert.equal(t.s.locations.C1.owner, 1);
assert.equal(t.avatar(0, 1).at, 'B1');
assert.equal(t.avatar(1, 1).at, 'C1');
assert.ok(t.avatar(0, 1).disabledUntil > t.s.clock);
assert.equal(t.anomaly(0, 1).at, 'B1');
assert.equal(t.anomaly(1, 1).at, 'C1');
assert.ok(t.anomaly(0, 1).disabledUntil > t.s.clock);
});
card('Execute: Process Clone', () => {
const t = scene({ south: { main: ['Execute: Process Clone', 'Stack Overflow'] } });
const so = t.program(0, 'B1', 'Stack Overflow');
t.hand(0, 'Execute: Process Clone');
t.ram(0, 7).play(0, 'Execute: Process Clone', 'B1', { card: so }).settle();
assert.equal(avatarCores(t.s, 0, 1, 'defend'), 4 + 2 + 2, 'two copies, each counting 2 Programs');
t.bandwidth(0, 7).play(0, 'Execute: Process Clone', 'B1', { card: so }).settle();
assert.equal(anomalyCores(t.s, 0, 1, 'defend'), 4 + 2 + 2, 'two copies, each counting 2 Programs');
});
card('Execute: Defragment', () => {
@ -201,9 +201,9 @@ card('Execute: Defragment', () => {
const so = t.program(0, 'B1', 'Stack Overflow');
t.s.cards[so].disabledUntil = 1e9;
t.hand(0, 'Execute: Defragment');
t.ram(0, 4).play(0, 'Execute: Defragment', 'B1', { card: so }).settle();
t.bandwidth(0, 4).play(0, 'Execute: Defragment', 'B1', { card: so }).settle();
assert.equal(t.s.cards[so].disabledUntil, 0);
assert.equal(avatarCores(t.s, 0, 1, 'defend'), 5);
assert.equal(anomalyCores(t.s, 0, 1, 'defend'), 5);
});
card('Execute: Remote Access', () => {
@ -211,18 +211,18 @@ card('Execute: Remote Access', () => {
t.own(1, 'D1');
const so = t.program(1, 'D1', 'Stack Overflow');
t.hand(1, 'Execute: Remote Access');
t.ram(1, 6).play(1, 'Execute: Remote Access', 'C1', { card: so }).settle();
assert.equal(avatarCores(t.s, 1, 1, 'defend'), 5, 'Stack Overflow runs on C1 too');
t.bandwidth(1, 6).play(1, 'Execute: Remote Access', 'C1', { card: so }).settle();
assert.equal(anomalyCores(t.s, 1, 1, 'defend'), 5, 'Stack Overflow runs on C1 too');
});
card('Execute: Purge', () => {
const t = scene({ south: { main: ['Execute: Purge', 'Additional Core'] } });
const hw = t.hardware(0, 1, 'Additional Core');
t.s.cards[hw].disabledUntil = 1e9;
Object.assign(t.avatar(0, 1), { infection: 2, permanentInfection: 1 });
Object.assign(t.anomaly(0, 1), { infection: 2, permanentInfection: 1 });
t.hand(0, 'Execute: Purge');
t.ram(0, 4).play(0, 'Execute: Purge', 'B1', { to: 'B1' }).settle();
assert.equal(t.avatar(0, 1).infection + t.avatar(0, 1).permanentInfection, 0);
t.bandwidth(0, 4).play(0, 'Execute: Purge', 'B1', { to: 'B1' }).settle();
assert.equal(t.anomaly(0, 1).infection + t.anomaly(0, 1).permanentInfection, 0);
assert.equal(t.s.cards[hw].disabledUntil, 0);
});
@ -232,8 +232,8 @@ card('Execute: Hard Reset', () => {
const so = t.program(0, 'B1', 'Stack Overflow');
const hf = t.program(0, 'B1', 'Hotfix');
t.hand(0, 'Execute: Hard Reset');
t.ram(0, 6).play(0, 'Execute: Hard Reset', 'B1', { cards: [so, hf] }).settle();
t.bandwidth(0, 6).play(0, 'Execute: Hard Reset', 'B1', { cards: [so, hf] }).settle();
assert.deepEqual(t.s.locations.B1.programs, []);
assert.deepEqual(t.s.players[0].hand.sort(), [so, hf].sort());
assert.equal(t.s.players[0].ram, 2);
assert.equal(t.s.players[0].bandwidth, 2);
});

View file

@ -2,13 +2,13 @@ import assert from 'node:assert/strict';
import { test } from 'node:test';
import { DEFAULT_GREEDY, greedyBot } from '../src/bots/greedy.ts';
import { randomBot } from '../src/bots/random.ts';
import { loadCards } from '../src/cards.ts';
import { loadCards } from '../src/load.ts';
import { playGame } from '../src/play.ts';
import { DEFAULT_RULES, withRule } from '../src/rules.ts';
const pool = loadCards();
// playGame with `check` throws on the first broken invariant (card conservation, RAM, placement).
// playGame with `check` throws on the first broken invariant (card conservation, Bandwidth, placement).
test('random bots play 200 games with every card without breaking a rule', () => {
for (let seed = 1; seed <= 200; seed++) {
const s = playGame({ pool, bots: [randomBot, randomBot], seed, check: true });
@ -29,7 +29,7 @@ test('greedy bots play 200 games without breaking a rule', () => {
test('bots play the recruit rule without breaking a rule', () => {
for (const k of [3, 7]) {
const rules = withRule(withRule(DEFAULT_RULES, 'recruit.on=true'), `recruit.avatarsInDeck=${k}`);
const rules = withRule(withRule(DEFAULT_RULES, 'recruit.on=true'), `recruit.anomaliesInDeck=${k}`);
for (let seed = 1; seed <= 25; seed++) {
assert.ok(playGame({ pool, bots: [randomBot, randomBot], seed, rules, check: true }).over);
assert.ok(playGame({ pool, bots: [() => greedyBot(), () => greedyBot()], seed, rules, check: true }).over);
@ -37,8 +37,8 @@ test('bots play the recruit rule without breaking a rule', () => {
}
});
test('bots play the buy-Avatars rule without breaking a rule', () => {
const rules = withRule(DEFAULT_RULES, 'buyAvatars.on=true');
test('bots play the buy-Anomalies rule without breaking a rule', () => {
const rules = withRule(DEFAULT_RULES, 'buyAnomalies.on=true');
for (let seed = 1; seed <= 25; seed++) {
assert.ok(playGame({ pool, bots: [randomBot, randomBot], seed, rules, check: true }).over);
assert.ok(playGame({ pool, bots: [() => greedyBot(), () => greedyBot()], seed, rules, check: true }).over);
@ -46,7 +46,7 @@ test('bots play the buy-Avatars rule without breaking a rule', () => {
});
test('bots play the copy-rule variants without breaking a rule', () => {
for (const spec of ['copies.waitATurn=true', 'copies.needAvatar2=true', 'copies.allowed=false']) {
for (const spec of ['copies.waitATurn=true', 'copies.needAnomaly2=true', 'copies.allowed=false']) {
const rules = withRule(DEFAULT_RULES, spec);
for (let seed = 1; seed <= 15; seed++) {
assert.ok(playGame({ pool, bots: [randomBot, randomBot], seed, rules, check: true }).over);
@ -81,6 +81,16 @@ test('bots play the command rule without breaking a rule', () => {
}
});
test('bots play the 4×4 and lanes boards without breaking a rule', () => {
for (const board of ['grid4', 'grid4-wide', 'grid4-one', 'lanes', 'lanes-open']) {
const rules = withRule(DEFAULT_RULES, `board=${board}`);
for (let seed = 1; seed <= 15; seed++) {
assert.ok(playGame({ pool, bots: [randomBot, randomBot], seed, rules, check: true }).over);
assert.ok(playGame({ pool, bots: [() => greedyBot(), () => greedyBot()], seed, rules, check: true }).over);
}
}
});
test('greedy beats random', () => {
let wins = 0;
for (let seed = 1; seed <= 100; seed++) {

View file

@ -1,8 +1,8 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { addBugs } from '../src/cards/util.ts';
import { avatarCores, canWear, executionActions, executionCost, programCost } from '../src/engine.ts';
import { healthOf, portsFree } from '../src/query.ts';
import { anomalyCores, canWear, executionActions, executionCost, programCost } from '../src/engine.ts';
import { healthOf, slotsFree } from '../src/query.ts';
import { card } from './card.ts';
import { Table, type Side } from './table.ts';
@ -20,21 +20,21 @@ const attackerDice = (t: Table) => t.logText().match(/Roll: Broken Bits \[([\d,]
card('RAM Expansion', () => {
const t = scene({ south: { main: ['RAM Expansion'] } });
t.hardware(0, 1, 'RAM Expansion');
assert.equal(avatarCores(t.s, 0, 1, 'defend'), 4, 'no Cores');
assert.equal(anomalyCores(t.s, 0, 1, 'defend'), 4, 'no Cores');
assert.equal(healthOf(t.s, { player: 0, slot: 1 }), 9 + 2, 'Broken Bits: 9 Health, +2');
});
card('Additional Core', () => {
const t = scene({ south: { main: ['Additional Core'] } });
t.hardware(0, 1, 'Additional Core');
assert.equal(avatarCores(t.s, 0, 1, 'defend'), 5);
assert.equal(anomalyCores(t.s, 0, 1, 'defend'), 5);
});
card('Overclocked CPU', () => {
const t = scene({ south: { main: ['Overclocked CPU', 'Stack Overflow'] } });
t.hardware(0, 1, 'Overclocked CPU');
const so = t.program(0, 'B1', 'Stack Overflow');
assert.equal(avatarCores(t.s, 0, 1, 'attack'), 6, '+2 in combat');
assert.equal(anomalyCores(t.s, 0, 1, 'attack'), 6, '+2 in combat');
attackC1(t);
t.rig(6, 6, 6, 6, 6, 6, 1, 1, 1, 1).end();
assert.equal(attackerDice(t), 6);
@ -53,7 +53,7 @@ card('Solid-State Cache', () => {
const [so, hf] = t.hand(0, 'Stack Overflow', 'Hotfix');
assert.equal(programCost(t.s, 0, so, 'B1'), 4);
assert.equal(programCost(t.s, 0, so, 'S1'), 7, 'only on the occupied Server');
t.ram(0, 4).to('play').go({ type: 'installProgram', card: so, at: 'B1' });
t.bandwidth(0, 4).to('play').go({ type: 'installProgram', card: so, at: 'B1' });
assert.equal(programCost(t.s, 0, hf, 'B1'), 7, 'first each turn');
});
@ -63,28 +63,28 @@ card('Redundant Power Supply', () => {
const ac = t.hardware(0, 1, 'Additional Core');
attackC1(t);
t.rig(1, 1, 1, 1, 1, 6, 6, 6, 6).end();
assert.equal(t.avatar(0, 1).at, null);
assert.deepEqual(t.avatar(0, 1).hardware, [rps, ac], 'kept, in its slot');
assert.equal(t.anomaly(0, 1).at, null);
assert.deepEqual(t.anomaly(0, 1).hardware, [rps, ac], 'kept, in its slot');
// The second defeat loses it.
t.to('playAgain').end().to('playAgain').end();
t.go({ type: 'place', slot: 1, to: 'B1' });
attackC1(t);
t.rig(1, 1, 1, 1, 1, 6, 6, 6, 6).end();
assert.deepEqual(t.avatar(0, 1).hardware, []);
assert.deepEqual(t.anomaly(0, 1).hardware, []);
});
card('Network Interface Upgrade', () => {
const t = new Table({ south: { avatars: ['Beta Version 1.0', 'Broken Bits', 'Code Zero', 'Pixelated Picture'], main: ['Additional Core', 'RAM Expansion', 'Network Interface Upgrade', 'Packet Accelerator'] } });
const t = new Table({ south: { anomalies: ['Beta Version 1.0', 'Broken Bits', 'Code Zero', 'Pixelated Picture'], main: ['Additional Core', 'RAM Expansion', 'Network Interface Upgrade', 'Packet Accelerator'] } });
const beta = { player: 0 as const, slot: 1 };
t.place(0, 1, 'S1');
t.hardware(0, 1, 'Additional Core');
t.hardware(0, 1, 'RAM Expansion');
const [niu, pa] = t.hand(0, 'Network Interface Upgrade', 'Packet Accelerator');
assert.equal(portsFree(t.s, beta), 0);
assert.equal(slotsFree(t.s, beta), 0);
assert.ok(!canWear(t.s, pa, beta));
assert.ok(canWear(t.s, niu, beta), 'fits with both ports full');
t.ram(0, 4).to('play').go({ type: 'installHardware', card: niu, slot: 1 });
assert.equal(portsFree(t.s, beta), 1, 'and adds a port');
assert.ok(canWear(t.s, niu, beta), 'fits with both Expansion Slots full');
t.bandwidth(0, 4).to('play').go({ type: 'installHardware', card: niu, slot: 1 });
assert.equal(slotsFree(t.s, beta), 1, 'and adds an Expansion Slot');
assert.ok(canWear(t.s, pa, beta));
});
@ -93,22 +93,22 @@ card('Dedicated GPU', () => {
t.place(0, 1, 'S1');
t.hardware(0, 1, 'Dedicated GPU');
t.hand(0, 'Execute: Ping Sweep');
t.ram(0, 4).play(0, 'Execute: Ping Sweep', null, {}, 'S1').settle();
t.bandwidth(0, 4).play(0, 'Execute: Ping Sweep', null, {}, 'S1').settle();
assert.equal(t.s.players[0].hand.length, 3, 'performed by the Server it stands on: draws 2 + 1');
});
card('ECC Memory', () => {
const t = scene({ south: { main: ['ECC Memory', 'Additional Core'] }, north: { main: ['Memory Leak', 'Stock Rice'] } });
const t = scene({ south: { main: ['ECC Memory', 'Additional Core'] }, north: { main: ['Bloatware', 'Stock Rice'] } });
t.hardware(0, 1, 'ECC Memory');
t.hardware(0, 1, 'Additional Core');
t.program(1, 'C1', 'Memory Leak');
t.program(1, 'C1', 'Bloatware');
t.program(1, 'C1', 'Stock Rice');
attackC1(t);
t.rig(6, 6, 6, 6, 6, 1, 1, 1, 1).end();
assert.equal(attackerDice(t), 5, "neither Bug Program touches it");
assert.equal(addBugs(t.s, { player: 0, slot: 1 }, 1, 'a Bug card', 1), false, "and opponents can't give it Bug counters");
assert.equal(t.avatar(0, 1).bugs, 0);
assert.equal(addBugs(t.s, { player: 1, slot: 1 }, 1, 'a Bug card', 0), true, 'Avatars without it can get them');
assert.equal(t.anomaly(0, 1).bugs, 0);
assert.equal(addBugs(t.s, { player: 1, slot: 1 }, 1, 'a Bug card', 0), true, 'Anomalies without it can get them');
});
card('Cooling System', () => {
@ -118,43 +118,43 @@ card('Cooling System', () => {
t.hardware(0, 1, 'Cooling System');
t.hardware(0, 1, 'Solid-State Cache');
const [so, hf] = t.hand(0, 'Stack Overflow', 'Hotfix');
t.ram(0, 20).to('play');
t.bandwidth(0, 20).to('play');
t.go({ type: 'installProgram', card: so, at: 'B1' });
assert.equal(programCost(t.s, 0, hf, 'B1'), 4, 'Solid-State Cache works twice');
t.go({ type: 'installProgram', card: hf, at: 'B1' });
assert.equal(t.s.players[0].ram, 20 - 4 - 4);
assert.equal(t.s.players[0].bandwidth, 20 - 4 - 4);
});
card('RAID Array', () => {
const t = scene({ south: { main: ['RAID Array', 'Additional Core'] } });
t.hardware(0, 1, 'RAID Array');
t.hardware(0, 1, 'Additional Core');
t.ram(0, 5);
t.bandwidth(0, 5);
attackC1(t);
t.rig(1, 1, 1, 1, 1, 6, 6, 6, 6).end();
assert.equal(t.s.choice?.kind, 'RAID Array:keep');
t.choose('Keep').settle();
assert.equal(t.avatar(0, 1).hardware.length, 2);
assert.equal(t.s.players[0].ram, 0, 'half of 5 + 5');
assert.equal(t.anomaly(0, 1).hardware.length, 2);
assert.equal(t.s.players[0].bandwidth, 0, 'half of 5 + 5');
});
card('Packet Accelerator', () => {
const t = scene({ south: { main: ['Packet Accelerator'] } });
t.hardware(0, 1, 'Packet Accelerator');
assert.equal(avatarCores(t.s, 0, 1, 'attack'), 5);
assert.equal(avatarCores(t.s, 0, 1, 'defend'), 4);
assert.equal(anomalyCores(t.s, 0, 1, 'attack'), 5);
assert.equal(anomalyCores(t.s, 0, 1, 'defend'), 4);
});
card('Firewall Appliance', () => {
const t = scene({ south: { main: ['Execute: Sabotage'] }, north: { main: ['Firewall Appliance'] } });
const fa = t.hardware(1, 1, 'Firewall Appliance');
const [sab] = t.hand(0, 'Execute: Sabotage');
t.ram(0, 10);
t.bandwidth(0, 10);
attackC1(t);
t.act({ type: 'end' });
assert.equal(executionCost(t.s, 0, sab, 'C1', { card: fa, mode: 'destroy' }), 10, '+3 for the first hostile Execution');
t.play(0, 'Execute: Sabotage', 'C1', { card: fa, mode: 'destroy' });
assert.equal(t.s.players[0].ram, 0);
assert.equal(t.s.players[0].bandwidth, 0);
});
card('Hardware Sandbox', () => {
@ -164,11 +164,11 @@ card('Hardware Sandbox', () => {
const so = t.program(1, 'C1', 'Stack Overflow');
const hf = t.program(1, 'C1', 'Hotfix');
const [sandbox] = t.hand(1, 'Hardware Sandbox');
t.ram(1, 7).to('play').act({ type: 'installHardware', card: sandbox, slot: 1 });
t.bandwidth(1, 7).to('play').act({ type: 'installHardware', card: sandbox, slot: 1 });
t.choose('Stack Overflow').settle();
t.to('playAgain').end();
t.hand(0, 'Execute: Kill Process', 'Execute: Root Access');
t.ram(0, 9);
t.bandwidth(0, 9);
const kills = () => executionActions(t.s, 0, 'now').filter((a) => a.type === 'play' && t.s.cards[a.card].name === 'Execute: Kill Process').map((a) => a.type === 'play' && a.args.card);
assert.deepEqual(kills(), [hf], 'Stack Overflow is protected');
t.play(0, 'Execute: Root Access', 'C1').settle();
@ -193,16 +193,16 @@ card('Hot-Swap Bay', () => {
const hsb = t.hardware(0, 1, 'Hot-Swap Bay');
const ac = t.hardware(0, 1, 'Additional Core');
const [oc] = t.hand(0, 'Overclocked CPU');
t.ram(0, 1).use(hsb, { card: ac, cards: [oc] }).settle();
assert.deepEqual(t.avatar(0, 1).hardware, [hsb, oc]);
t.bandwidth(0, 1).use(hsb, { card: ac, cards: [oc] }).settle();
assert.deepEqual(t.anomaly(0, 1).hardware, [hsb, oc]);
assert.deepEqual(t.s.players[0].hand, [ac]);
assert.equal(t.s.players[0].ram, 0, 'pays the 1 RAM difference');
assert.equal(t.s.players[0].bandwidth, 0, 'pays the 1 Gb difference');
});
test('Hardware must still fit its ports when Network Interface Upgrade leaves', () => {
test('Hardware must still fit its Expansion Slots when Network Interface Upgrade leaves', () => {
const t = new Table({
south: {
avatars: ['Beta Version 1.0', 'Broken Bits', 'Code Zero', 'Pixelated Picture'],
anomalies: ['Beta Version 1.0', 'Broken Bits', 'Code Zero', 'Pixelated Picture'],
main: ['Network Interface Upgrade', 'Hot-Swap Bay', 'Additional Core', 'Packet Accelerator', 'RAM Expansion', 'Execute: Rollback'],
},
});
@ -212,15 +212,15 @@ test('Hardware must still fit its ports when Network Interface Upgrade leaves',
const ac = t.hardware(0, 1, 'Additional Core');
const pa = t.hardware(0, 1, 'Packet Accelerator');
t.hand(0, 'RAM Expansion', 'Execute: Rollback');
t.ram(0, 20);
// Beta Version 1.0 has 2 ports, +1 from the NIU, and all 3 are in use.
t.bandwidth(0, 20);
// Beta Version 1.0 has 2 Expansion Slots, +1 from the NIU, and all 3 are in use.
const swaps = t.legal().filter((a) => a.type === 'activate' && a.card === hsb);
assert.ok(!swaps.some((a) => a.type === 'activate' && a.args.card === niu), "Hot-Swap Bay can't swap the NIU for a card that needs a port");
assert.ok(!swaps.some((a) => a.type === 'activate' && a.args.card === niu), "Hot-Swap Bay can't swap the NIU for a card that needs an Expansion Slot");
assert.ok(swaps.some((a) => a.type === 'activate' && a.args.card === ac));
// Rollback returns the NIU: the newest Hardware no longer fits and is discarded.
t.s.cards[niu].installedTurn = t.s.turn;
t.play(0, 'Execute: Rollback', 'S1', { card: niu }).settle();
assert.deepEqual(t.avatar(0, 1).hardware, [hsb, ac]);
assert.deepEqual(t.anomaly(0, 1).hardware, [hsb, ac]);
assert.ok(t.s.players[0].discard.includes(pa));
});
@ -232,7 +232,7 @@ card('Quantum Coprocessor', () => {
t.place(0, 1, 'S1');
const qc = t.hardware(0, 1, 'Quantum Coprocessor');
t.hand(0, 'Execute: Kill Process');
t.ram(0, 5).play(0, 'Execute: Kill Process', 'C1', { card: so }, 'S1').settle();
t.bandwidth(0, 5).play(0, 'Execute: Kill Process', 'C1', { card: so }, 'S1').settle();
assert.equal(t.s.choice?.kind, 'Quantum Coprocessor:copy');
t.choose('Hotfix').settle();
assert.ok(t.s.cards[so].disabledUntil > t.s.clock);

View file

@ -14,7 +14,7 @@ function turnOf(t: Table, p: 0 | 1): Table {
return t;
}
/** South's Avatar 1 (Broken Bits, 4 Cores, 9 Health) on B1 facing North's Avatar 1 on C1. */
/** South's Anomaly 1 (Broken Bits, 4 Cores, 9 Health) on B1 facing North's Anomaly 1 on C1. */
function standoff(o: { northMain?: string[]; southMain?: string[] } = {}): Table {
const t = new Table({ health: true, north: { main: o.northMain }, south: { main: o.southMain } });
t.own(0, 'B1');
@ -38,9 +38,9 @@ test('health: the loser takes the margin as damage, and nobody moves', () => {
t.rig(6, 6, 6, 6, 5, 5, 5, 4); // 24 to 19
t.end();
assert.equal(t.s.locations.C1.owner, 1, 'C1 holds');
assert.equal(t.avatar(0, 1).at, 'B1', 'the attacker stays where it attacked from');
assert.equal(t.avatar(1, 1).at, 'C1');
assert.equal(t.avatar(1, 1).damage, 5);
assert.equal(t.anomaly(0, 1).at, 'B1', 'the attacker stays where it attacked from');
assert.equal(t.anomaly(1, 1).at, 'C1');
assert.equal(t.anomaly(1, 1).damage, 5);
assert.equal(healthLeft(t.s, { player: 1, slot: 1 }), 4);
assert.equal(t.s.stats.attacksWon[0], 1);
assert.equal(t.s.stats.damageDealt[0], 5);
@ -48,21 +48,21 @@ test('health: the loser takes the margin as damage, and nobody moves', () => {
assert.equal(t.s.combat, null);
});
test('health: damage adds up; the Avatar is destroyed at 0 Health, loses its Hardware, and the location falls', () => {
test('health: damage adds up; the Anomaly is destroyed at 0 Health, loses its Hardware, and the location falls', () => {
const t = standoff({ northMain: ['Additional Core'] });
const hw = t.hardware(1, 1, 'Additional Core');
t.avatar(1, 1).damage = 6;
t.anomaly(1, 1).damage = 6;
t.to('attack').go({ type: 'attack', slot: 1, to: 'C1' });
t.rig(6, 6, 6, 6, 3, 3, 3, 3, 3); // 24 to 15: 9 damage, 3 was enough
t.end();
assert.equal(t.avatar(1, 1).at, null, 'destroyed: back in its slot');
assert.equal(t.avatar(1, 1).damage, 0, 'a destroyed Avatar comes back at full Health');
assert.deepEqual(t.avatar(1, 1).hardware, []);
assert.equal(t.anomaly(1, 1).at, null, 'destroyed: back in its slot');
assert.equal(t.anomaly(1, 1).damage, 0, 'a destroyed Anomaly comes back at full Health');
assert.deepEqual(t.anomaly(1, 1).hardware, []);
assert.ok(t.s.players[1].discard.includes(hw));
assert.equal(t.s.locations.C1.owner, 0);
assert.equal(t.avatar(0, 1).at, 'C1');
assert.equal(t.anomaly(0, 1).at, 'C1');
assert.equal(t.s.stats.capturesInCombat[0], 1);
assert.equal(t.s.stats.avatarsDestroyed[1], 1);
assert.equal(t.s.stats.anomaliesDestroyed[1], 1);
assert.equal(t.s.stats.damageDealt[0], 9, 'the whole margin counts as dealt');
});
@ -71,18 +71,18 @@ test('health: a losing attacker takes damage and stays put, or is destroyed by a
t.to('attack').go({ type: 'attack', slot: 1, to: 'C1' });
t.rig(3, 3, 3, 3, 4, 4, 4, 4); // 12 to 16
t.end();
assert.equal(t.avatar(0, 1).at, 'B1');
assert.equal(t.avatar(0, 1).damage, 4);
assert.equal(t.avatar(1, 1).damage, 0, 'the winner takes no damage');
assert.equal(t.anomaly(0, 1).at, 'B1');
assert.equal(t.anomaly(0, 1).damage, 4);
assert.equal(t.anomaly(1, 1).damage, 0, 'the winner takes no damage');
assert.equal(t.s.stats.damageDealt[1], 4);
const u = standoff();
u.avatar(0, 1).damage = 5;
u.anomaly(0, 1).damage = 5;
u.to('attack').go({ type: 'attack', slot: 1, to: 'C1' });
u.rig(1, 1, 1, 1, 2, 2, 2, 2); // 4 to 8: 4 damage, 4 left
u.end();
assert.equal(u.avatar(0, 1).at, null, 'destroyed');
assert.equal(u.avatar(0, 1).damage, 0);
assert.equal(u.anomaly(0, 1).at, null, 'destroyed');
assert.equal(u.anomaly(0, 1).damage, 0);
assert.equal(u.s.locations.B1.owner, 0, 'losing an attack never loses the origin');
});
@ -91,10 +91,10 @@ test('health: a tie is a stalemate, with no reroll and no damage', () => {
t.to('attack').go({ type: 'attack', slot: 1, to: 'C1' });
t.rig(3, 3, 3, 3, 4, 4, 2, 2);
t.end();
assert.equal(t.avatar(0, 1).damage, 0);
assert.equal(t.avatar(1, 1).damage, 0);
assert.equal(t.avatar(0, 1).at, 'B1');
assert.equal(t.avatar(1, 1).at, 'C1');
assert.equal(t.anomaly(0, 1).damage, 0);
assert.equal(t.anomaly(1, 1).damage, 0);
assert.equal(t.anomaly(0, 1).at, 'B1');
assert.equal(t.anomaly(1, 1).at, 'C1');
assert.deepEqual(t.s.rigged, [], 'no dice were rerolled');
assert.match(t.logText(), /stalemate/);
assert.equal(t.s.stats.combatsTied[0], 1);
@ -104,13 +104,13 @@ test('health: a tie is a stalemate, with no reroll and no damage', () => {
test('health: recall heals fully, keeps Hardware, counts as the placement, and leaves the location undefended', () => {
const t = standoff({ northMain: ['Additional Core'] });
const hw = t.hardware(1, 1, 'Additional Core');
t.avatar(1, 1).damage = 7;
t.avatar(1, 1).infection = 2;
t.anomaly(1, 1).damage = 7;
t.anomaly(1, 1).infection = 2;
turnOf(t, 1); // South's turn passes without acting
assert.ok(t.can({ type: 'recall', slot: 1 }));
assert.ok(!t.can({ type: 'recall', slot: 2 }), 'only Avatars in play can be recalled');
assert.ok(!t.can({ type: 'recall', slot: 2 }), 'only Anomalies in play can be recalled');
t.go({ type: 'recall', slot: 1 });
const av = t.avatar(1, 1);
const av = t.anomaly(1, 1);
assert.equal(av.at, null);
assert.equal(av.damage, 0);
assert.equal(av.infection, 0, 'leaving play removes counters');
@ -124,26 +124,26 @@ test('health: recall heals fully, keeps Hardware, counts as the placement, and l
assert.ok(t.can({ type: 'advance', slot: 1, to: 'C1' }));
});
test('health: a rooted Avatar can\'t be recalled, and the rule can be switched off', () => {
test('health: a rooted Anomaly can\'t be recalled, and the rule can be switched off', () => {
const t = standoff();
t.avatar(0, 1).rootedUntil = FOREVER;
t.anomaly(0, 1).rootedUntil = FOREVER;
assert.ok(!t.can({ type: 'recall', slot: 1 }), 'Packet Flood: no retreat');
t.avatar(0, 1).rootedUntil = 0;
t.anomaly(0, 1).rootedUntil = 0;
assert.ok(t.can({ type: 'recall', slot: 1 }));
t.s.rules = withRule(t.s.rules, 'health.recall=false');
assert.ok(!t.can({ type: 'recall', slot: 1 }));
});
test('health: Redundant Power Supply still saves the Hardware of a destroyed Avatar', () => {
test('health: Redundant Power Supply still saves the Hardware of a destroyed Anomaly', () => {
const t = standoff({ northMain: ['Redundant Power Supply', 'Additional Core'] });
const rps = t.hardware(1, 1, 'Redundant Power Supply');
const core = t.hardware(1, 1, 'Additional Core');
t.avatar(1, 1).damage = 8;
t.anomaly(1, 1).damage = 8;
t.to('attack').go({ type: 'attack', slot: 1, to: 'C1' });
t.rig(6, 6, 6, 6, 1, 1, 1, 1, 1); // 24 to 5
t.end();
assert.equal(t.avatar(1, 1).at, null);
assert.deepEqual([...t.avatar(1, 1).hardware].sort(), [rps, core].sort());
assert.equal(t.anomaly(1, 1).at, null);
assert.deepEqual([...t.anomaly(1, 1).hardware].sort(), [rps, core].sort());
assert.equal(t.s.locations.C1.owner, 0);
});
@ -154,14 +154,14 @@ test('health: with two defenders the damage destroys the weakest first, and the
t.place(0, 1, 'B1');
t.place(1, 1, 'C1'); // Broken Bits, 4 Cores, 9 Health
t.place(1, 2, 'C1'); // Pixelated Picture, 3 Cores, 10 Health
t.avatar(1, 2).damage = 7; // 3 left
t.anomaly(1, 2).damage = 7; // 3 left
t.to('attack').go({ type: 'attack', slot: 1, to: 'C1' });
t.rig(6, 6, 6, 6, 1, 1, 1, 1, 5, 5, 5); // 24 to 4 + 15 = 19: 5 damage
t.end();
assert.equal(t.avatar(1, 2).at, null, 'the weak one is destroyed with 3 of the damage');
assert.equal(t.avatar(1, 1).damage, 2, 'the other 2 land on the survivor');
assert.equal(t.anomaly(1, 2).at, null, 'the weak one is destroyed with 3 of the damage');
assert.equal(t.anomaly(1, 1).damage, 2, 'the other 2 land on the survivor');
assert.equal(t.s.locations.C1.owner, 1, 'C1 holds with a defender left');
assert.equal(t.avatar(0, 1).at, 'B1');
assert.equal(t.anomaly(0, 1).at, 'B1');
// Enough damage for both takes the location.
const u = new Table({ health: true, north: { servers: ['Cluster Server'] } });
@ -170,29 +170,29 @@ test('health: with two defenders the damage destroys the weakest first, and the
u.place(0, 1, 'B1');
u.place(1, 1, 'C1');
u.place(1, 2, 'C1');
u.avatar(1, 1).damage = 8;
u.avatar(1, 2).damage = 8;
u.anomaly(1, 1).damage = 8;
u.anomaly(1, 2).damage = 8;
u.to('attack').go({ type: 'attack', slot: 1, to: 'C1' });
u.rig(6, 6, 6, 6, 1, 1, 1, 1, 1, 1, 1); // 24 to 7: 17 damage for 1 + 2 left
u.end();
assert.equal(u.avatar(1, 1).at, null);
assert.equal(u.avatar(1, 2).at, null);
assert.equal(u.anomaly(1, 1).at, null);
assert.equal(u.anomaly(1, 2).at, null);
assert.equal(u.s.locations.C1.owner, 0);
assert.equal(u.avatar(0, 1).at, 'C1');
assert.equal(u.anomaly(0, 1).at, 'C1');
});
test('health: Resource Leech and Persistent Infection fire on a lost roll, not only a destruction', () => {
const t = standoff({ northMain: ['Resource Leech', 'Persistent Infection'] });
t.program(1, 'C1', 'Resource Leech');
t.program(1, 'C1', 'Persistent Infection');
const ram = t.s.players[1].ram;
const bandwidth = t.s.players[1].bandwidth;
t.to('attack').go({ type: 'attack', slot: 1, to: 'C1' });
t.rig(3, 3, 3, 3, 4, 4, 4, 4); // 12 to 16: the attacker takes 4 and lives
t.end();
assert.equal(t.avatar(0, 1).at, 'B1');
assert.equal(t.avatar(0, 1).damage, 4);
assert.equal(t.s.players[1].ram, ram + 3, 'Resource Leech pays 3');
assert.equal(t.avatar(0, 1).permanentInfection, 1, 'a permanent Infection counter');
assert.equal(t.anomaly(0, 1).at, 'B1');
assert.equal(t.anomaly(0, 1).damage, 4);
assert.equal(t.s.players[1].bandwidth, bandwidth + 3, 'Resource Leech pays 3');
assert.equal(t.anomaly(0, 1).permanentInfection, 1, 'a permanent Infection counter');
});
test('health: Overflow Error only disables, until the next command, while the attacker lives', () => {
@ -219,19 +219,19 @@ test('health: Overflow Error may destroy a Program when the attacker is destroye
assert.equal(t.s.choice?.kind, 'Overflow Error:hit');
t.choose('Destroy Stack Overflow').settle();
assert.ok(t.s.players[0].discard.includes(so));
assert.equal(t.avatar(0, 1).at, null);
assert.equal(t.anomaly(0, 1).at, null);
});
test("health: Backup Machine's Restore Point heals 3 damage", () => {
const t = new Table({ health: true, south: { avatars: ['Backup Machine', 'Broken Bits', 'Pixelated Picture', 'Corrupt Driver'] } });
const t = new Table({ health: true, south: { anomalies: ['Backup Machine', 'Broken Bits', 'Pixelated Picture', 'Corrupt Driver'] } });
t.own(0, 'B1');
t.place(0, 1, 'B1');
const bm = t.avatar(0, 1).card;
const bm = t.anomaly(0, 1).card;
assert.ok(!t.legal().some((a) => a.type === 'activate' && a.card === bm && a.args.heal), 'nothing to heal yet');
t.avatar(0, 1).damage = 5;
t.ram(0, 5).use(bm, { heal: true }).settle();
assert.equal(t.avatar(0, 1).damage, 2);
assert.equal(t.s.players[0].ram, 0);
t.anomaly(0, 1).damage = 5;
t.bandwidth(0, 5).use(bm, { heal: true }).settle();
assert.equal(t.anomaly(0, 1).damage, 2);
assert.equal(t.s.players[0].bandwidth, 0);
assert.equal(healthLeft(t.s, { player: 0, slot: 1 }), 8);
});
@ -242,6 +242,6 @@ test('health: RAM Expansion adds 2 Health, so a hit that would destroy the weare
t.to('attack').go({ type: 'attack', slot: 1, to: 'C1' });
t.rig(6, 6, 6, 6, 4, 4, 4, 3); // 24 to 15: 9 damage against 11 Health
t.end();
assert.equal(t.avatar(1, 1).at, 'C1', 'C1 holds');
assert.equal(t.anomaly(1, 1).at, 'C1', 'C1 holds');
assert.equal(healthLeft(t.s, { player: 1, slot: 1 }), 2);
});

View file

@ -1,7 +1,9 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { test } from 'node:test';
import { GRID, LINES, LINES_AT, LOCATIONS, levelFor, otherEnd } from '../src/map.ts';
import * as map from '../src/map.ts';
import { GRID, LINES, LINES_AT, LOCATIONS, levelFor, otherEnd, useBoard } from '../src/map.ts';
import { DEFAULT_RULES, withRule } from '../src/rules.ts';
const RULES_MD = readFileSync(new URL('../../rules.md', import.meta.url), 'utf8');
@ -31,3 +33,58 @@ test('levels are mirrored between the players', () => {
assert.equal(levelFor(0, 'D1'), 4);
assert.equal(levelFor(0, 'E3'), 5);
});
test('the 4×4 board: squares joined side to side, levels 1–4, starts join the middle of their row', () => {
useBoard('grid4');
try {
assert.equal(map.GRID.length, 16);
assert.equal(map.LINES.filter((l) => l.gateway).length, 24);
const near = (loc: string) => map.LINES_AT.get(loc)!.map((l) => otherEnd(l, loc)).sort();
assert.deepEqual(near('S1'), ['A2', 'A3']);
assert.deepEqual(near('S2'), ['D2', 'D3']);
assert.deepEqual(near('B2'), ['A2', 'B1', 'B3', 'C2']);
assert.deepEqual(near('A1'), ['A2', 'B1']);
const rotate = (loc: string) =>
({ S1: 'S2', S2: 'S1' })[loc] ?? 'DCBA'['ABCD'.indexOf(loc[0])] + (5 - Number(loc[1]));
for (const loc of map.GRID) {
assert.equal(levelFor(0, loc), levelFor(1, rotate(loc)), loc);
assert.deepEqual(near(loc).map(rotate).sort(), near(rotate(loc)), loc);
}
assert.equal(levelFor(0, 'A4'), 1);
assert.equal(levelFor(0, 'D1'), 4);
assert.equal(levelFor(1, 'A1'), 4);
} finally {
useBoard('classic');
}
});
test('the lanes board: three lanes of five, linked only across the middle row', () => {
useBoard('lanes');
try {
assert.equal(map.GRID.length, 15);
assert.equal(map.LINES.filter((l) => l.gateway).length, 14);
const near = (loc: string) => map.LINES_AT.get(loc)!.map((l) => otherEnd(l, loc)).sort();
assert.deepEqual(near('S1'), ['A1', 'A2', 'A3']);
assert.deepEqual(near('S2'), ['E1', 'E2', 'E3']);
assert.deepEqual(near('B1'), ['A1', 'C1']);
assert.deepEqual(near('C2'), ['B2', 'C1', 'C3', 'D2']);
const rotate = (loc: string) =>
({ S1: 'S2', S2: 'S1' })[loc] ?? 'EDCBA'['ABCDE'.indexOf(loc[0])] + (4 - Number(loc[1]));
for (const loc of map.GRID) {
assert.equal(levelFor(0, loc), levelFor(1, rotate(loc)), loc);
assert.deepEqual(near(loc).map(rotate).sort(), near(rotate(loc)), loc);
}
assert.equal(levelFor(0, 'C1'), 3);
useBoard('lanes-open');
assert.deepEqual(map.LINES.filter((l) => l.gateway).map((l) => l.id), ['C1-C2', 'C2-C3']);
} finally {
useBoard('classic');
}
});
test('board=grid4 wins with 12, unless a later winLocations changes it', () => {
assert.equal(withRule(DEFAULT_RULES, 'board=grid4').winLocations, 12);
assert.equal(withRule(withRule(DEFAULT_RULES, 'board=grid4'), 'winLocations=11').winLocations, 11);
assert.equal(withRule(DEFAULT_RULES, 'board=lanes').winLocations, 11);
assert.throws(() => withRule(DEFAULT_RULES, 'board=hex'), /Unknown board/);
});

View file

@ -1,6 +1,6 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { winChance } from '../src/odds.ts';
import { rollOdds, winChance } from '../src/odds.ts';
test('equal Cores are a coin flip and odds are complementary', () => {
for (let a = 1; a <= 8; a++) {
@ -16,3 +16,17 @@ test('matches the table in rules.md', () => {
assert.equal(Math.round(100 * winChance(6, 4)), 91);
assert.equal(Math.round(100 * winChance(8, 7)), 71);
});
test('one-roll odds add up, agree with winChance, and 1 Core vs 1 Core deals 35/36 damage on average', () => {
for (let a = 1; a <= 6; a++) {
for (let d = 1; d <= 6; d++) {
const o = rollOdds(a, d);
assert.ok(Math.abs(o.win + o.tie + o.lose - 1) < 1e-12);
assert.ok(Math.abs(o.win / (o.win + o.lose) - winChance(a, d)) < 1e-12);
}
}
const one = rollOdds(1, 1);
assert.ok(Math.abs(one.tie - 1 / 6) < 1e-12);
assert.ok(Math.abs(one.damageDealt - 35 / 36) < 1e-12);
assert.ok(Math.abs(one.damageDealt - one.damageTaken) < 1e-12);
});

View file

@ -1,9 +1,9 @@
import assert from 'node:assert/strict';
import { avatarCores, execBlocked, executionActions, executionCost, openWindow } from '../src/engine.ts';
import { anomalyCores, execBlocked, executionActions, executionCost, openWindow } from '../src/engine.ts';
import { card } from './card.ts';
import { Table, type Side } from './table.ts';
/** South's Avatar 1 on B1, North's Avatar 1 on C1 (both Broken Bits, 4 Cores). */
/** South's Anomaly 1 on B1, North's Anomaly 1 on C1 (both Broken Bits, 4 Cores). */
function scene(o: { south?: Side; north?: Side; first?: 0 | 1 } = {}) {
const t = new Table(o);
t.own(0, 'B1');
@ -20,11 +20,11 @@ const defenderDice = (t: Table) => t.logText().match(/Roll: .* vs Broken Bits \[
card('Recursive Infection', () => {
const t = scene({ north: { main: ['Recursive Infection'] } });
t.program(1, 'C1', 'Recursive Infection');
t.avatar(0, 1).infection = 2;
t.anomaly(0, 1).infection = 2;
attackC1(t);
assert.equal(t.avatar(0, 1).infection, 3, 'a counter for attacking');
assert.equal(avatarCores(t.s, 0, 1, 'attack'), 2, '3+ counters: -2 Cores');
assert.equal(avatarCores(t.s, 0, 1, 'attack', 'S1'), 2, 'anywhere, while the Program is in play');
assert.equal(t.anomaly(0, 1).infection, 3, 'a counter for attacking');
assert.equal(anomalyCores(t.s, 0, 1, 'attack'), 2, '3+ counters: -2 Cores');
assert.equal(anomalyCores(t.s, 0, 1, 'attack', 'S1'), 2, 'anywhere, while the Program is in play');
});
card('Recursive Infection', () => {
@ -34,7 +34,7 @@ card('Recursive Infection', () => {
t.program(1, 'C1', 'Recursive Infection');
t.place(0, 1, 'B1');
t.go({ type: 'advance', slot: 1, to: 'C1' }).to('attack').end();
assert.equal(t.avatar(0, 1).infection, 1, 'a counter for breaching');
assert.equal(t.anomaly(0, 1).infection, 1, 'a counter for breaching');
});
card('Memory Parasite', () => {
@ -45,7 +45,7 @@ card('Memory Parasite', () => {
attackC1(t);
t.rig(6, 6, 6, 6, 6, 6, 1, 1, 1, 1).end();
assert.equal(t.s.choice?.kind, 'Memory Parasite:disable');
assert.equal(t.s.choice?.player, 0, "the attacking Avatar's owner chooses");
assert.equal(t.s.choice?.player, 0, "the attacking Anomaly's owner chooses");
t.choose('Additional Core').settle();
assert.equal(attackerDice(t), 6, '4 + Overclocked CPU only');
});
@ -54,11 +54,11 @@ card('Replication Routine', () => {
const t = new Table({ south: { main: ['Replication Routine', 'Resource Leech'] } });
t.own(0, 'B1');
const [rr, leech] = t.hand(0, 'Replication Routine', 'Resource Leech');
t.ram(0, 6).to('play').act({ type: 'installProgram', card: rr, at: 'B1' });
t.bandwidth(0, 6).to('play').act({ type: 'installProgram', card: rr, at: 'B1' });
assert.equal(t.s.choice?.kind, 'Replication Routine:install');
t.choose('Resource Leech').settle();
assert.deepEqual(t.s.locations.B1.programs, [rr, leech]);
assert.equal(t.s.players[0].ram, 0, 'the second Virus is free');
assert.equal(t.s.players[0].bandwidth, 0, 'the second Virus is free');
});
card('Resource Leech', () => {
@ -66,27 +66,27 @@ card('Resource Leech', () => {
t.program(1, 'C1', 'Resource Leech');
attackC1(t);
t.rig(1, 1, 1, 1, 6, 6, 6, 6).end();
assert.equal(t.avatar(0, 1).at, null);
assert.equal(t.s.players[1].ram, 3);
assert.equal(t.anomaly(0, 1).at, null);
assert.equal(t.s.players[1].bandwidth, 3);
});
card('Worm Protocol', () => {
const t = new Table({ first: 1, north: { main: ['Worm Protocol', 'Memory Leak'] }, south: { main: ['Additional Core'] } });
const t = new Table({ first: 1, north: { main: ['Worm Protocol', 'Bloatware'] }, south: { main: ['Additional Core'] } });
t.own(1, 'C1');
t.own(1, 'D1');
t.own(0, 'C2');
t.program(1, 'C1', 'Memory Leak');
t.program(1, 'C1', 'Bloatware');
t.place(1, 1, 'D1');
const [worm] = t.hand(1, 'Worm Protocol');
t.ram(1, 4).to('play').act({ type: 'installProgram', card: worm, at: 'C1' });
t.bandwidth(1, 4).to('play').act({ type: 'installProgram', card: worm, at: 'C1' });
assert.equal(t.s.choice?.kind, 'Worm Protocol:spread');
t.choose('D1').to('playAgain').end();
// South attacks D1, where Memory Leak now also applies.
// South attacks D1, where Bloatware now also applies.
t.place(0, 1, 'C2');
t.hardware(0, 1, 'Additional Core');
t.to('attack').go({ type: 'attack', slot: 1, to: 'D1' });
t.rig(6, 6, 6, 6, 1, 1, 1, 1).end();
assert.match(t.logText(), /Memory Leak: Avatar 1 \(Broken Bits\) loses 1 Core/);
assert.match(t.logText(), /Bloatware: Anomaly 1 \(Broken Bits\) loses 1 Core/);
assert.equal(attackerDice(t), 4, '4 + 1 - 1');
});
@ -97,8 +97,8 @@ card('Payload Injector', () => {
const [ra] = t.hand(0, 'Execute: Root Access', 'Execute: Root Access');
assert.equal(executionCost(t.s, 0, ra, 'B1', {}), 2);
assert.equal(executionCost(t.s, 0, ra, 'A2', {}), 4, 'only when targeting its Server');
t.ram(0, 2).play(0, 'Execute: Root Access', 'B1').settle();
assert.equal(t.s.players[0].ram, 0);
t.bandwidth(0, 2).play(0, 'Execute: Root Access', 'B1').settle();
assert.equal(t.s.players[0].bandwidth, 0);
assert.equal(executionCost(t.s, 0, t.s.players[0].hand[0], 'B1', {}), 4, 'first each turn only');
});
@ -107,8 +107,8 @@ card('Persistent Infection', () => {
t.program(1, 'C1', 'Persistent Infection');
attackC1(t);
t.rig(1, 1, 1, 1, 6, 6, 6, 6).end();
assert.equal(t.avatar(0, 1).at, null);
assert.equal(t.avatar(0, 1).permanentInfection, 1, 'stays after defeat');
assert.equal(t.anomaly(0, 1).at, null);
assert.equal(t.anomaly(0, 1).permanentInfection, 1, 'stays after defeat');
});
card('Infinite Loop', () => {
@ -132,8 +132,8 @@ card('Stack Overflow', () => {
const t = scene({ north: { main: ['Stack Overflow', 'Resource Leech'] } });
t.program(1, 'C1', 'Stack Overflow');
t.program(1, 'C1', 'Resource Leech');
assert.equal(avatarCores(t.s, 1, 1, 'defend'), 6, '+1 per Program here');
assert.equal(avatarCores(t.s, 0, 1, 'defend'), 4);
assert.equal(anomalyCores(t.s, 1, 1, 'defend'), 6, '+1 per Program here');
assert.equal(anomalyCores(t.s, 0, 1, 'defend'), 4);
});
card('Race Condition', () => {
@ -150,9 +150,9 @@ card('Race Condition', () => {
}
});
card('Memory Leak', () => {
const t = scene({ south: { main: ['Additional Core', 'Overclocked CPU'] }, north: { main: ['Memory Leak'] } });
t.program(1, 'C1', 'Memory Leak');
card('Bloatware', () => {
const t = scene({ south: { main: ['Additional Core', 'Overclocked CPU'] }, north: { main: ['Bloatware'] } });
t.program(1, 'C1', 'Bloatware');
t.hardware(0, 1, 'Additional Core');
t.hardware(0, 1, 'Overclocked CPU');
attackC1(t);
@ -165,7 +165,7 @@ card('Null Pointer', () => {
t.program(1, 'C1', 'Null Pointer');
const so = t.program(1, 'C1', 'Stack Overflow');
t.hand(0, 'Execute: Kill Process', 'Execute: Kill Process');
t.ram(0, 10).play(0, 'Execute: Kill Process', 'C1', { card: so }).settle();
t.bandwidth(0, 10).play(0, 'Execute: Kill Process', 'C1', { card: so }).settle();
assert.equal(t.s.cards[so].disabledUntil, 0, 'the first enemy Execution has no effect');
t.play(0, 'Execute: Kill Process', 'C1', { card: so }).settle();
assert.ok(t.s.cards[so].disabledUntil > t.s.clock, 'once per turn');
@ -202,11 +202,11 @@ card('Undefined Behavior', () => {
const ub = t.program(1, 'C1', 'Undefined Behavior');
const so = t.program(0, 'B1', 'Stack Overflow');
t.use(ub, { card: so }).settle();
assert.equal(avatarCores(t.s, 1, 1, 'defend'), 5, 'copied Stack Overflow: +1 for the one Program here');
assert.equal(anomalyCores(t.s, 1, 1, 'defend'), 5, 'copied Stack Overflow: +1 for the one Program here');
assert.ok(t.s.cards[ub].disabledUntil > t.s.clock, 'Undefined Behavior shuts itself off');
t.to('playAgain').end();
assert.equal(t.s.active, 0);
assert.equal(avatarCores(t.s, 1, 1, 'defend'), 5, "the copy lasts through the opponent's turn");
assert.equal(anomalyCores(t.s, 1, 1, 'defend'), 5, "the copy lasts through the opponent's turn");
});
card('Packet Loss', () => {
@ -228,7 +228,7 @@ card('Desynchronization', () => {
t.hardware(0, 1, 'Hot-Swap Bay');
t.hardware(0, 1, 'Additional Core');
t.hand(0, 'RAM Expansion');
t.ram(0, 10);
t.bandwidth(0, 10);
attackC1(t);
t.act({ type: 'end' });
// Broken Bits' own Ability still works after the roll; only the Hardware ability is blocked.
@ -251,7 +251,7 @@ card('Ghost Process', () => {
const t = scene({ south: { main: ['Ghost Process', 'Execute: Kill Process'] }, north: { main: ['Stack Overflow'] } });
const so = t.program(1, 'C1', 'Stack Overflow');
t.hand(0, 'Execute: Kill Process');
t.ram(0, 5);
t.bandwidth(0, 5);
const reach = () => executionActions(t.s, 0, 'now').some((a) => a.type === 'play' && a.target === 'B1' && a.args.card === so);
assert.ok(!reach(), 'without Ghost Process, B1 only reaches B1');
t.program(0, 'B1', 'Ghost Process');
@ -268,14 +268,14 @@ card('False Positive', () => {
t.place(0, 1, 'B1');
t.place(0, 2, 'A2');
t.hand(0, 'Execute: Force Reboot');
t.ram(0, 5);
t.bandwidth(0, 5);
t.to('attack').go({ type: 'attack', slot: 1, to: 'B1' }).act({ type: 'end' });
assert.equal(t.decider, 0, 'South may respond before the roll');
t.play(0, 'Execute: Force Reboot', 'B1', { ref: { player: 1, slot: 1 } });
assert.equal(t.s.choice?.kind, 'False Positive:redirect');
t.choose('Pixelated Picture').settle();
assert.ok(!execBlocked(t.s, 'C1'), "North's attacker is untouched");
assert.ok(execBlocked(t.s, 'A2'), "South's own Avatar took it");
assert.ok(execBlocked(t.s, 'A2'), "South's own Anomaly took it");
});
card('Fragmentation', () => {
@ -291,7 +291,7 @@ card('Latency Spike', () => {
const t = scene({ south: { main: ['Execute: Ping Sweep'] }, north: { main: ['Latency Spike'] } });
if (spike) t.program(1, 'C1', 'Latency Spike');
t.hand(0, 'Execute: Ping Sweep');
t.ram(0, 4);
t.bandwidth(0, 4);
attackC1(t);
t.act({ type: 'end' });
assert.equal(openWindow(t.s)?.kind, spike ? 'postRoll' : 'preRoll');
@ -315,10 +315,10 @@ card('Error Correction', () => {
t.own(0, 'B1');
t.program(0, 'B1', 'Error Correction');
t.place(0, 1, 'B1');
t.avatar(0, 1).infection = 2;
t.anomaly(0, 1).infection = 2;
t.to('playAgain').end();
assert.equal(t.s.active, 0);
assert.equal(t.avatar(0, 1).infection, 1, 'one removed at the start of the turn');
assert.equal(t.anomaly(0, 1).infection, 1, 'one removed at the start of the turn');
});
card('Garbage Collection', () => {
@ -327,7 +327,7 @@ card('Garbage Collection', () => {
const gc = t.program(0, 'B1', 'Garbage Collection');
const so = t.program(0, 'B1', 'Stack Overflow');
t.use(gc, { card: so }).settle();
assert.equal(t.s.players[0].ram, 7);
assert.equal(t.s.players[0].bandwidth, 7);
assert.deepEqual(t.s.locations.B1.programs, [gc]);
});
@ -346,8 +346,8 @@ card('Version Control', () => {
});
card('Rollback Routine', () => {
const t = scene({ south: { main: ['Rollback Routine', 'Additional Core'] }, north: { main: ['Memory Leak'] } });
t.program(1, 'C1', 'Memory Leak');
const t = scene({ south: { main: ['Rollback Routine', 'Additional Core'] }, north: { main: ['Bloatware'] } });
t.program(1, 'C1', 'Bloatware');
const rr = t.program(0, 'B1', 'Rollback Routine');
t.hardware(0, 1, 'Additional Core');
attackC1(t);
@ -356,17 +356,17 @@ card('Rollback Routine', () => {
assert.equal(t.decider, 0);
t.rig(6, 6, 6, 6, 6, 1, 1, 1, 1);
t.use(rr, { ref: { player: 0, slot: 1 } }).settle();
assert.equal(attackerDice(t), 5, "Memory Leak's -1 is undone");
assert.equal(attackerDice(t), 5, "Bloatware's -1 is undone");
});
card('Compatibility Layer', () => {
const t = new Table({ south: { main: ['Compatibility Layer', 'Stack Overflow', 'Hotfix'] } });
t.own(0, 'B1');
const [cl, so, hf] = t.hand(0, 'Compatibility Layer', 'Stack Overflow', 'Hotfix');
t.ram(0, 6 + 7 + 5).to('play');
t.bandwidth(0, 6 + 7 + 5).to('play');
t.go({ type: 'installProgram', card: cl, at: 'B1' });
t.go({ type: 'installProgram', card: so, at: 'B1' });
t.go({ type: 'installProgram', card: hf, at: 'B1' });
assert.equal(t.s.locations.B1.programs.length, 3);
assert.equal(t.s.players[0].ram, 0, 'Hotfix, a Patch, cost 2 less');
assert.equal(t.s.players[0].bandwidth, 0, 'Hotfix, a Patch, cost 2 less');
});

View file

@ -1,9 +1,9 @@
import assert from 'node:assert/strict';
import { avatarCores } from '../src/engine.ts';
import { anomalyCores } from '../src/engine.ts';
import { card } from './card.ts';
import { Table } from './table.ts';
/** South advances its Avatar 1 from S1 into A2, drawing `server` for it. */
/** South advances its Anomaly 1 from S1 into A2, drawing `server` for it. */
function captureA2(server: string) {
const t = new Table({ south: { servers: [server] } });
t.nextServer(0, server);
@ -13,36 +13,36 @@ function captureA2(server: string) {
return t;
}
card('High Efficiency RAM Server', () => {
const t = captureA2('High Efficiency RAM Server');
assert.equal(t.s.players[0].ram, 4 + 4, 'the capture pays 4, the Server adds 4');
card('High Bandwidth Server', () => {
const t = captureA2('High Bandwidth Server');
assert.equal(t.s.players[0].bandwidth, 4 + 4, 'the capture pays 4, the Server adds 4');
});
card('Power Server', () => {
const t = captureA2('Power Server');
assert.equal(t.s.players[0].ram, 8);
assert.equal(t.s.players[0].bandwidth, 8);
});
card('Server Farm', () => {
const t = captureA2('Server Farm');
assert.equal(t.s.players[0].ram, 8);
assert.equal(avatarCores(t.s, 0, 1, 'defend'), 4 + 2);
assert.equal(t.s.players[0].bandwidth, 8);
assert.equal(anomalyCores(t.s, 0, 1, 'defend'), 4 + 2);
});
card('MultiCore Server', () => {
const t = new Table({ south: { servers: ['MultiCore Server'] } });
t.own(0, 'B1', 'MultiCore Server');
t.place(0, 1, 'B1');
assert.equal(avatarCores(t.s, 0, 1, 'defend'), 6);
assert.equal(avatarCores(t.s, 0, 1, 'attack'), 6, 'attacking from it counts too');
assert.equal(avatarCores(t.s, 0, 1, 'attack', 'S1'), 4, 'only on that location');
assert.equal(anomalyCores(t.s, 0, 1, 'defend'), 6);
assert.equal(anomalyCores(t.s, 0, 1, 'attack'), 6, 'attacking from it counts too');
assert.equal(anomalyCores(t.s, 0, 1, 'attack', 'S1'), 4, 'only on that location');
});
card('Cloud Compute', () => {
const t = new Table({ south: { servers: ['Cloud Compute'] } });
t.own(0, 'B1', 'Cloud Compute');
t.place(0, 1, 'B1');
assert.equal(avatarCores(t.s, 0, 1, 'defend'), 8);
assert.equal(anomalyCores(t.s, 0, 1, 'defend'), 8);
});
const twoDefenders = (name: string) => () => {
@ -57,8 +57,8 @@ const twoDefenders = (name: string) => () => {
t.rig(6, 6, 6, 6, 1, 1, 1, 1, 1, 1, 1).end();
assert.match(t.logText(), /vs Broken Bits \[1,1,1,1\] \+ Pixelated Picture \[1,1,1\]=7/, 'both defenders roll together');
assert.equal(t.s.locations.C1.owner, 0);
assert.equal(t.avatar(1, 1).at, null);
assert.equal(t.avatar(1, 2).at, null, 'both defenders are defeated');
assert.equal(t.anomaly(1, 1).at, null);
assert.equal(t.anomaly(1, 2).at, null, 'both defenders are defeated');
};
card('Cluster Server', twoDefenders('Cluster Server'));
card('Pingable Server', twoDefenders('Pingable Server'));
@ -71,13 +71,13 @@ card('Backup Server', () => {
t.place(0, 1, 'B1');
t.place(1, 1, 'C1');
t.use(backup, { ref: { player: 0, slot: 1 }, to: 'A2' }).settle();
assert.equal(t.avatar(0, 5).at, 'A2', 'the copy of Avatar 1 is in play');
assert.equal(avatarCores(t.s, 0, 5, 'defend'), 4);
assert.equal(t.anomaly(0, 5).at, 'A2', 'the copy of Anomaly 1 is in play');
assert.equal(anomalyCores(t.s, 0, 5, 'defend'), 4);
assert.ok(!t.legal().some((a) => a.type === 'activate'), 'once per turn');
t.to('attack').go({ type: 'attack', slot: 1, to: 'C1' });
t.rig(1, 1, 1, 1, 6, 6, 6, 6).end();
assert.equal(t.avatar(0, 1).at, null);
assert.equal(t.avatar(0, 5).at, null, 'the copy goes when the original is defeated');
assert.equal(t.anomaly(0, 1).at, null);
assert.equal(t.anomaly(0, 5).at, null, 'the copy goes when the original is defeated');
});
card('Upgraded Hardware', () => {
@ -86,32 +86,32 @@ card('Upgraded Hardware', () => {
t.place(0, 1, 'B1');
t.place(0, 2, 'S1');
const [hw] = t.hand(0, 'Additional Core');
t.ram(0, 3).to('play');
t.bandwidth(0, 3).to('play');
assert.ok(!t.can({ type: 'installHardware', card: hw, slot: 2 }), 'full price elsewhere');
t.go({ type: 'installHardware', card: hw, slot: 1 });
assert.equal(t.s.players[0].ram, 0);
assert.equal(t.s.players[0].bandwidth, 0);
});
card('Network Throttle', () => {
const t = new Table();
t.own(0, 'A2');
t.ram(0, 1).to('play');
t.bandwidth(0, 1).to('play');
t.go({ type: 'firewall', line: 'A1-A2', level: 1 });
assert.equal(t.s.players[0].ram, 0, 'Lv 1 costs 1 next to Network Throttle');
assert.equal(t.s.players[0].bandwidth, 0, 'Lv 1 costs 1 next to Network Throttle');
});
card('Duplicate Server', () => {
for (const [copy, check] of [['Cloud Compute', 'cores'], ['High Efficiency RAM Server', 'ram']] as const) {
const t = new Table({ south: { servers: ['Duplicate Server', 'Cloud Compute', 'High Efficiency RAM Server'] } });
for (const [copy, check] of [['Cloud Compute', 'cores'], ['High Bandwidth Server', 'bandwidth']] as const) {
const t = new Table({ south: { servers: ['Duplicate Server', 'Cloud Compute', 'High Bandwidth Server'] } });
t.own(0, 'B1', 'Cloud Compute');
t.own(0, 'B2', 'High Efficiency RAM Server');
t.own(0, 'B2', 'High Bandwidth Server');
t.nextServer(0, 'Duplicate Server');
t.place(0, 1, 'B1');
t.go({ type: 'advance', slot: 1, to: 'C2' }).to('attack').end();
assert.equal(t.s.choice?.kind, 'Duplicate Server:copy');
t.choose(copy);
if (check === 'cores') assert.equal(avatarCores(t.s, 0, 1, 'defend'), 8);
else assert.equal(t.s.players[0].ram, 4 + 4, 'the capture pays 4, the copied bonus 4');
if (check === 'cores') assert.equal(anomalyCores(t.s, 0, 1, 'defend'), 8);
else assert.equal(t.s.players[0].bandwidth, 4 + 4, 'the capture pays 4, the copied bonus 4');
}
});
@ -123,7 +123,7 @@ card('Protected Server', () => {
t.place(1, 1, 'C1');
t.to('attack').go({ type: 'attack', slot: 1, to: 'C1' });
t.rig(1, 1, 1, 1, 6, 6, 6, 6).end();
assert.equal(t.s.players[1].ram, 2);
assert.equal(t.s.players[1].bandwidth, 2);
});
card('Callable Server', () => {

View file

@ -3,25 +3,25 @@
* directly and drive decisions one at a time.
*/
import assert from 'node:assert/strict';
import { loadCards } from '../src/cards.ts';
import { loadCards } from '../src/load.ts';
import { actionKey, applyAction, createGame, decider, legalActions, openWindow } from '../src/engine.ts';
import { checkInvariants } from '../src/invariants.ts';
import type { LocId } from '../src/map.ts';
import { coresOf, fighterOf, sideCores } from '../src/query.ts';
import { DEFAULT_RULES, type RulesConfig } from '../src/rules.ts';
import { avatar, removeFrom } from '../src/state.ts';
import type { Action, Args, AvatarRef, GameState, PlayerId } from '../src/types.ts';
import { anomaly, logFor, removeFrom } from '../src/state.ts';
import type { Action, Args, AnomalyRef, GameState, PlayerId } from '../src/types.ts';
export const pool = loadCards();
/** Cards that do nothing in hand and can't be played in response, used to pad decks. */
const FILLER = 'Network Interface Upgrade';
const PLAIN_SERVER = 'Network Throttle';
/** Avatars whose Abilities only work in combat, so they don't open response windows. */
const DEFAULT_AVATARS = ['Broken Bits', 'Pixelated Picture', 'Corrupt Driver', 'Code Zero'];
/** Anomalies whose Abilities only work in combat, so they don't open response windows. */
const DEFAULT_ANOMALIES = ['Broken Bits', 'Pixelated Picture', 'Corrupt Driver', 'Code Zero'];
export interface Side {
avatars?: string[];
anomalies?: string[];
servers?: string[];
main?: string[];
}
@ -31,12 +31,12 @@ export class Table {
constructor(o: { south?: Side; north?: Side; first?: PlayerId; seed?: number; health?: boolean } = {}) {
const side = (x: Side = {}) => ({
avatars: x.avatars ?? DEFAULT_AVATARS,
anomalies: x.anomalies ?? DEFAULT_ANOMALIES,
servers: [...(x.servers ?? []), ...Array(12).fill(PLAIN_SERVER)],
main: [...(x.main ?? []), ...Array(12).fill(FILLER)],
});
const decks = [side(o.south), side(o.north)] as const;
// Classic turns (one turn each, every Avatar acts), no turn-1 draw for the first player, and
// Classic turns (one turn each, every Anomaly acts), no turn-1 draw for the first player, and
// one-roll combats, which the card tests are written for. The command rule has its own tests in
// engine.test.ts, the health rule in health.test.ts (`health: true`).
const rules: RulesConfig = {
@ -45,7 +45,7 @@ export class Table {
firstTurn: { ...DEFAULT_RULES.firstTurn, draw: false },
health: { ...DEFAULT_RULES.health, on: o.health ?? false },
openingHand: 0,
deck: { avatars: 4, servers: decks[0].servers.length, main: decks[0].main.length, maxCopies: 99 },
deck: { anomalies: 4, servers: decks[0].servers.length, main: decks[0].main.length, maxCopies: 99 },
};
// Both decks must be the same size under one rules object; pad the shorter one.
const n = Math.max(decks[0].main.length, decks[1].main.length);
@ -65,10 +65,10 @@ export class Table {
const L = this.s.locations[start];
this.s.players[p].serverPile.push(L.server!);
L.server = this.take(p, PLAIN_SERVER);
this.s.players[p].ram = 0;
// Avatars in the order given, slot 1 face up.
const want = (p === 0 ? o.south : o.north)?.avatars ?? DEFAULT_AVATARS;
const avs = this.s.players[p].avatars;
this.s.players[p].bandwidth = 0;
// Anomalies in the order given, slot 1 face up.
const want = (p === 0 ? o.south : o.north)?.anomalies ?? DEFAULT_ANOMALIES;
const avs = this.s.players[p].anomalies;
want.forEach((name, i) => {
const j = avs.findIndex((a, k) => k < 4 && k >= i && this.s.cards[a.card].name === name);
[avs[i].card, avs[j].card] = [avs[j].card, avs[i].card];
@ -116,8 +116,8 @@ export class Table {
return id;
}
ram(p: PlayerId, n: number): this {
this.s.players[p].ram = n;
bandwidth(p: PlayerId, n: number): this {
this.s.players[p].bandwidth = n;
return this;
}
@ -130,9 +130,9 @@ export class Table {
return L.server;
}
/** Puts Avatar `slot` of `p` in play on `at` (face up). */
place(p: PlayerId, slot: number, at: LocId): AvatarRef {
const av = this.s.players[p].avatars[slot - 1];
/** Puts Anomaly `slot` of `p` in play on `at` (face up). */
place(p: PlayerId, slot: number, at: LocId): AnomalyRef {
const av = this.s.players[p].anomalies[slot - 1];
av.faceUp = true;
av.at = at;
return { player: p, slot };
@ -146,7 +146,7 @@ export class Table {
hardware(p: PlayerId, slot: number, name: string): number {
const id = this.take(p, name);
this.s.players[p].avatars[slot - 1].hardware.push(id);
this.s.players[p].anomalies[slot - 1].hardware.push(id);
return id;
}
@ -203,7 +203,7 @@ export class Table {
return this.act({ type: 'play', card, target, args, from });
}
/** Activates the ability of the card `id` (an Avatar's card id, a Program or Hardware). */
/** Activates the ability of the card `id` (an Anomaly's card id, a Program or Hardware). */
use(id: number, args: Args = {}): this {
return this.act({ type: 'activate', card: id, name: this.s.cards[id].name, args });
}
@ -220,8 +220,8 @@ export class Table {
// -------------------------------------------------------------------------------------------
// Reading
avatar(p: PlayerId, slot: number) {
return avatar(this.s, { player: p, slot });
anomaly(p: PlayerId, slot: number) {
return anomaly(this.s, { player: p, slot });
}
cores(p: PlayerId, slot: number): number {
@ -239,6 +239,6 @@ export class Table {
}
logText(): string {
return (this.s.log ?? []).join('\n');
return logFor(this.s, null).join('\n');
}
}