From 937f44defe1aea3a5cdc20cb4c6787cbc44134f4 Mon Sep 17 00:00:00 2001 From: Forrest Date: Thu, 1 Oct 2026 17:20:33 -0400 Subject: [PATCH] updates --- QUICKSTART.md | 94 +- app-plan.md | 318 ++++ app/.gitignore | 2 + app/README.md | 115 ++ app/decks/glitch-tricks.json | 79 + app/decks/patch-wall.json | 79 + app/decks/virus-swarm.json | 79 + app/index.html | 12 + app/package-lock.json | 1306 ++++++++++++++++ app/package.json | 22 + app/src/cards.ts | 12 + app/src/decks.ts | 86 ++ app/src/describe.ts | 2 + app/src/layout.ts | 46 + app/src/main.tsx | 125 ++ app/src/match.ts | 419 ++++++ app/src/moves.ts | 122 ++ app/src/render-card.ts | 94 ++ app/src/replay.ts | 55 + app/src/storage.ts | 96 ++ app/src/styles.css | 1321 +++++++++++++++++ app/src/ui/board.tsx | 257 ++++ app/src/ui/cards.tsx | 132 ++ app/src/ui/game.tsx | 629 ++++++++ app/src/ui/panels.tsx | 139 ++ app/src/ui/replay.tsx | 143 ++ app/src/ui/side.tsx | 340 +++++ app/src/ui/start.tsx | 209 +++ app/test/match.test.ts | 148 ++ app/test/moves.test.ts | 59 + app/tsconfig.json | 19 + app/vite.config.ts | 9 + card-template.html | 10 +- cards.md | 210 +-- .../{avatar-front.css => anomaly-front.css} | 18 +- .../{avatar-front.html => anomaly-front.html} | 22 +- decks/files-deck-1/attributes.csv | 6 +- decks/files-deck-1/cards.csv | 262 ++-- .../files-deck-1/copy-of-server-front-alt.css | 6 +- .../copy-of-server-front-alt.html | 4 +- decks/files-deck-1/execution-front-alt.css | 225 +++ decks/files-deck-1/execution-front-alt.html | 48 + decks/files-deck-1/execution-front.css | 6 +- decks/files-deck-1/execution-front.html | 8 +- decks/files-deck-1/hardware-front-alt.css | 338 +++++ decks/files-deck-1/hardware-front-alt.html | 55 + decks/files-deck-1/hardware-front.css | 22 +- decks/files-deck-1/hardware-front.html | 16 +- decks/files-deck-1/program-front-alt.css | 251 ++++ decks/files-deck-1/program-front-alt.html | 48 + decks/files-deck-1/program-front.css | 12 +- decks/files-deck-1/program-front.html | 12 +- decks/files-deck-1/server-front-alt.css | 6 +- decks/files-deck-1/server-front-alt.html | 4 +- decks/files-deck-1/server-front.css | 7 +- decks/files-deck-1/server-front.html | 4 +- decks/files-deck-1/turn-order-front.html | 4 +- expansion-plan.md | 237 ++- new-cards.md | 240 +-- notes.md | 2 +- rules.md | 230 +-- sim/README.md | 35 +- sim/src/bots/eval.ts | 66 +- sim/src/bots/greedy.ts | 206 +-- sim/src/cards.ts | 33 +- sim/src/cards/{avatars.ts => anomalies.ts} | 80 +- sim/src/cards/executions.ts | 102 +- sim/src/cards/hardware.ts | 117 +- sim/src/cards/programs.ts | 127 +- sim/src/cards/servers.ts | 49 +- sim/src/cards/util.ts | 26 +- sim/src/cli.ts | 24 +- sim/src/deck.ts | 20 +- sim/src/describe.ts | 129 ++ sim/src/engine.ts | 280 ++-- sim/src/flow.ts | 191 +-- sim/src/invariants.ts | 36 +- sim/src/load.ts | 11 + sim/src/map.ts | 132 +- sim/src/odds.ts | 36 + sim/src/query.ts | 133 +- sim/src/rules.ts | 90 +- sim/src/scripts.ts | 66 +- sim/src/state.ts | 118 +- sim/src/stats.ts | 18 +- sim/src/trace.ts | 184 +++ sim/src/types.ts | 105 +- .../{avatars.test.ts => anomalies.test.ts} | 72 +- sim/test/app.test.ts | 103 ++ sim/test/cards.test.ts | 20 +- sim/test/engine.test.ts | 176 +-- sim/test/executions.test.ts | 90 +- sim/test/fuzz.test.ts | 22 +- sim/test/hardware.test.ts | 80 +- sim/test/health.test.ts | 108 +- sim/test/map.test.ts | 59 +- sim/test/odds.test.ts | 16 +- sim/test/programs.test.ts | 84 +- sim/test/servers.test.ts | 56 +- sim/test/table.ts | 46 +- 100 files changed, 10185 insertions(+), 2042 deletions(-) create mode 100644 app-plan.md create mode 100644 app/.gitignore create mode 100644 app/README.md create mode 100644 app/decks/glitch-tricks.json create mode 100644 app/decks/patch-wall.json create mode 100644 app/decks/virus-swarm.json create mode 100644 app/index.html create mode 100644 app/package-lock.json create mode 100644 app/package.json create mode 100644 app/src/cards.ts create mode 100644 app/src/decks.ts create mode 100644 app/src/describe.ts create mode 100644 app/src/layout.ts create mode 100644 app/src/main.tsx create mode 100644 app/src/match.ts create mode 100644 app/src/moves.ts create mode 100644 app/src/render-card.ts create mode 100644 app/src/replay.ts create mode 100644 app/src/storage.ts create mode 100644 app/src/styles.css create mode 100644 app/src/ui/board.tsx create mode 100644 app/src/ui/cards.tsx create mode 100644 app/src/ui/game.tsx create mode 100644 app/src/ui/panels.tsx create mode 100644 app/src/ui/replay.tsx create mode 100644 app/src/ui/side.tsx create mode 100644 app/src/ui/start.tsx create mode 100644 app/test/match.test.ts create mode 100644 app/test/moves.test.ts create mode 100644 app/tsconfig.json create mode 100644 app/vite.config.ts rename decks/files-deck-1/{avatar-front.css => anomaly-front.css} (96%) rename decks/files-deck-1/{avatar-front.html => anomaly-front.html} (78%) create mode 100644 decks/files-deck-1/execution-front-alt.css create mode 100644 decks/files-deck-1/execution-front-alt.html create mode 100644 decks/files-deck-1/hardware-front-alt.css create mode 100644 decks/files-deck-1/hardware-front-alt.html create mode 100644 decks/files-deck-1/program-front-alt.css create mode 100644 decks/files-deck-1/program-front-alt.html rename sim/src/cards/{avatars.ts => anomalies.ts} (65%) create mode 100644 sim/src/describe.ts create mode 100644 sim/src/load.ts create mode 100644 sim/src/trace.ts rename sim/test/{avatars.test.ts => anomalies.test.ts} (73%) create mode 100644 sim/test/app.test.ts diff --git a/QUICKSTART.md b/QUICKSTART.md index 358216e..34c24ab 100644 --- a/QUICKSTART.md +++ b/QUICKSTART.md @@ -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 diff --git a/app-plan.md b/app-plan.md new file mode 100644 index 0000000..e18d8e3 --- /dev/null +++ b/app-plan.md @@ -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. diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..f06235c --- /dev/null +++ b/app/.gitignore @@ -0,0 +1,2 @@ +node_modules +dist diff --git a/app/README.md b/app/README.md new file mode 100644 index 0000000..6fe7dd1 --- /dev/null +++ b/app/README.md @@ -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. diff --git a/app/decks/glitch-tricks.json b/app/decks/glitch-tricks.json new file mode 100644 index 0000000..b545ccb --- /dev/null +++ b/app/decks/glitch-tricks.json @@ -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" + ] +} \ No newline at end of file diff --git a/app/decks/patch-wall.json b/app/decks/patch-wall.json new file mode 100644 index 0000000..1cf163a --- /dev/null +++ b/app/decks/patch-wall.json @@ -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" + ] +} \ No newline at end of file diff --git a/app/decks/virus-swarm.json b/app/decks/virus-swarm.json new file mode 100644 index 0000000..f232bee --- /dev/null +++ b/app/decks/virus-swarm.json @@ -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" + ] +} \ No newline at end of file diff --git a/app/index.html b/app/index.html new file mode 100644 index 0000000..2d76134 --- /dev/null +++ b/app/index.html @@ -0,0 +1,12 @@ + + + + + + Files TCG + + +
+ + + diff --git a/app/package-lock.json b/app/package-lock.json new file mode 100644 index 0000000..debfe93 --- /dev/null +++ b/app/package-lock.json @@ -0,0 +1,1306 @@ +{ + "name": "files-tcg-app", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "files-tcg-app", + "dependencies": { + "handlebars": "^4.7.9", + "preact": "^11.0.0" + }, + "devDependencies": { + "@types/node": "^26.6.3", + "typescript": "^7.0.2", + "vite": "^8.3.1" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.152.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.152.0.tgz", + "integrity": "sha512-oM/5rLBm2tPkg0iBgkH/FOeR3PCDpY19GTgAZjMFM8h9WI9VW7cLgzp6nwtarYKmovavIQZ+Fe/RKX/8C8O/Rw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.12.tgz", + "integrity": "sha512-dB/a1214qKfHMXCpgqR4OZT+jS4kTyEXbQGJPqzobt5EwH5rX080pxE37alt3RzvR1bf1Yz/yGqRfrYAxuPw0A==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.12.tgz", + "integrity": "sha512-7KHFgQ5VJxIHcLlrwrc3Xbds7oTNQT7Pgi9gQCJKrd2VGab/UksIOYp6VD8MzCstGxOKMgNamPwUCfxPdP1OHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.12.tgz", + "integrity": "sha512-3YIhqHD96nA5SaYNRBR16HnGv4oavZvXfD/ayHM+oYZ0WD/8lBAtf6zQua4kEyAvpqrluKXl0lnOBoiNby7x9w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.12.tgz", + "integrity": "sha512-UuuJ35MFw4gmFOrE9pEqIV+K3syIKveph+Qc1/ljHZVdoDW4pz/JHR/eMVom+TZGl/5OOvGJOWaOCVt3ZfqhxA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.12.tgz", + "integrity": "sha512-uMvssit0a4W+/7D8CbHUvG719mH3R2jwXAlh/XcPvuHTE0g++LymF88DCGNX0HM2rBOn0xrzgXktIB6fLSJBTQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.12.tgz", + "integrity": "sha512-XcFu0R0xWnwzSf4IQgFH1rJIckPN1pLy2R+4r9IDB7Yfu/ys9cVqfa4pBrMHj7a3gl8mIR4nRNPg0e5IvEVs6g==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.12.tgz", + "integrity": "sha512-260UrKgn8tz39ak+SMDOirKzr7V04M9dWPw5llW00SwBivCZoWcRBKV1d8cXnRkUmSZA3BdiUmBHWk7734Ulpw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.12.tgz", + "integrity": "sha512-5YK1I9SqDkbPgc1IA8BgDl34suqUS2q0KWnBrirm0E51YjOs6eo6dV6jbQfNE/argHRSvd0QUGgtpIoYx+WWpw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.12.tgz", + "integrity": "sha512-Rkcrmp7eFRg74yL5fXEU91JEWbdEPLevWwGtXpmhbjlD1StScbWTmO94Bhly+Mo+ketKYkdmM1vNUKeWSlx8cQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.12.tgz", + "integrity": "sha512-qvK4DuAsQc2BSjlx+Xr+IzOIvvxbGZqxFwdWfG6F518Erj0GGISyQbJ6pIappnOxlNPzNHvo/L0BwB30GZ+zVw==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.12.tgz", + "integrity": "sha512-Q9uLBO53Xd4QIq1WOycVQyPP1O4HhraEV2qqb3uTrnVw6QZih9duY4vNXOivL1xoUS1/z+W8eF4NMfl2a8Sdjw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.12.tgz", + "integrity": "sha512-3IBxWFMjbOZskDPKv8Lf9BCnahlKuHthWkYnyIxOH/QcJrFcS4EmcenthApkwr/5+nEqZlLzeYbxeMaX7A5u4g==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.12.tgz", + "integrity": "sha512-xtX61xg4LKPkPWilZU1ynKClz5Gj4bf74LML4r3eVLWumKnGjoEr1OSHQhMdbBDoYTi+yjrujvpZe2pUnqCrrA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.12.tgz", + "integrity": "sha512-At7fPB6PCaIjzgIhEZFxuT+BBFqiQibJDT4d3PhiR3f4E7bbMZF4aKblbFfEM3sETRDd1YiQx/+U/g/B/ou5Ew==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.12.tgz", + "integrity": "sha512-WIw2haVKwjuYdXkHaoC0mF8Le71TuCBxjrdKqLbJGctbBABj+ClfmNvtbOnzpq3RokNo5+V1qhtSzJyXorsklQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "26.6.3", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.3.tgz", + "integrity": "sha512-dsqMQQoeTLqu9wynDD00q573mNzso3IdQOAfHRJqLCcmCFPoGo9A1bDpUcv/9tnKpErQWv9uKeGfl37EIS02Yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/handlebars": { + "version": "4.7.9", + "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.7.9.tgz", + "integrity": "sha512-4E71E0rpOaQuJR2A3xDZ+GM1HyWYv1clR58tC8emQNeQe3RH7MAzSbat+V0wG78LQBo6m6bzSG/L4pBuCsgnUQ==", + "license": "MIT", + "dependencies": { + "minimist": "^1.2.5", + "neo-async": "^2.6.2", + "source-map": "^0.6.1", + "wordwrap": "^1.0.0" + }, + "bin": { + "handlebars": "bin/handlebars" + }, + "engines": { + "node": ">=0.4.7" + }, + "optionalDependencies": { + "uglify-js": "^3.1.4" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/nanoid": { + "version": "3.3.19", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.19.tgz", + "integrity": "sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/neo-async": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", + "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==", + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.28", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", + "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.18", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/preact": { + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/preact/-/preact-11.0.0.tgz", + "integrity": "sha512-LRTLKuSe6VYPhvBDjwFaX+nuZnpsw6IN2GSboisAvhGsncylBmrbDCERhgKDn6yP2mAwbGvsB5OVyTe33M8gBg==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/preact" + }, + "peerDependencies": { + "preact-render-to-string": ">=6.7.0" + }, + "peerDependenciesMeta": { + "preact-render-to-string": { + "optional": true + } + } + }, + "node_modules/rolldown": { + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.12.tgz", + "integrity": "sha512-8wafseiaG80xmXSfqidUNqZcylTlhmPZZt+za2m+js2sFZ8dTNlhIOV2WcbIPx2hgwPBJpEUGFAMZ9bgBBLTSQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.152.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.12", + "@rolldown/binding-android-arm64": "1.2.12", + "@rolldown/binding-darwin-arm64": "1.2.12", + "@rolldown/binding-darwin-x64": "1.2.12", + "@rolldown/binding-freebsd-x64": "1.2.12", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.12", + "@rolldown/binding-linux-arm64-gnu": "1.2.12", + "@rolldown/binding-linux-arm64-musl": "1.2.12", + "@rolldown/binding-linux-ppc64-gnu": "1.2.12", + "@rolldown/binding-linux-s390x-gnu": "1.2.12", + "@rolldown/binding-linux-x64-gnu": "1.2.12", + "@rolldown/binding-linux-x64-musl": "1.2.12", + "@rolldown/binding-openharmony-arm64": "1.2.12", + "@rolldown/binding-win32-arm64-msvc": "1.2.12", + "@rolldown/binding-win32-x64-msvc": "1.2.12" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/typescript": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } + }, + "node_modules/uglify-js": { + "version": "3.19.3", + "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.19.3.tgz", + "integrity": "sha512-v3Xu+yuwBXisp6QYTcH4UbH+xYJXqnq2m/LtQVWKWzYc1iehYnLixoQDN9FH6/j9/oybfd6W9Ghwkl8+UMKTKQ==", + "license": "BSD-2-Clause", + "optional": true, + "bin": { + "uglifyjs": "bin/uglifyjs" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "dev": true, + "license": "MIT" + }, + "node_modules/vite": { + "version": "8.3.1", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.1.tgz", + "integrity": "sha512-/bvH9E9tmCXRGp2uXY3WbOldqpTwFkbha/8ANaEQ6VkxhH60KyqLwgZq6lG2y+4uT55x9+9eUHMpQ7uGnOCKjA==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.28", + "rolldown": "~1.2.9", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/wordwrap": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", + "integrity": "sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q==", + "license": "MIT" + } + } +} diff --git a/app/package.json b/app/package.json new file mode 100644 index 0000000..c1064b2 --- /dev/null +++ b/app/package.json @@ -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" + } +} diff --git a/app/src/cards.ts b/app/src/cards.ts new file mode 100644 index 0000000..fd03dfc --- /dev/null +++ b/app/src/cards.ts @@ -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> = new Map(parseCsvObjects(csv).map((r) => [r['Name'], r])); diff --git a/app/src/decks.ts b/app/src/decks.ts new file mode 100644 index 0000000..f1279a5 --- /dev/null +++ b/app/src/decks.ts @@ -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>; + +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; + 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(); + 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 }; +} diff --git a/app/src/describe.ts b/app/src/describe.ts new file mode 100644 index 0000000..4c75957 --- /dev/null +++ b/app/src/describe.ts @@ -0,0 +1,2 @@ +/** Action labels live in the sim, next to the engine they describe. */ +export * from '../../sim/src/describe.ts'; diff --git a/app/src/layout.ts b/app/src/layout.ts new file mode 100644 index 0000000..06d9918 --- /dev/null +++ b/app/src/layout.ts @@ -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; + 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 = {}; + 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 }; +} diff --git a/app/src/main.tsx b/app/src/main.tsx new file mode 100644 index 0000000..b7cb385 --- /dev/null +++ b/app/src/main.tsx @@ -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 => ({ + autoSkip: s.autoSkip, + stops: s.stops, + checkInvariants: s.checkInvariants, + undo: playtest, +}); + +function App() { + const [settings, setSettings] = useState(loadSettings); + const [screen, setScreen] = useState({ 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 ( + 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 ( + 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 ( + { + 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).__files = { + get match() { + return current; + }, + greedyBot: () => import('../../sim/src/bots/greedy.ts').then((m) => m.greedyBot()), + }; +} + +render(, document.getElementById('app')!); diff --git a/app/src/match.ts b/app/src/match.ts new file mode 100644 index 0000000..372de6d --- /dev/null +++ b/app/src/match.ts @@ -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 = { + 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 = {}) { + 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 = {}): 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): 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), + }; + } +} diff --git a/app/src/moves.ts b/app/src/moves.ts new file mode 100644 index 0000000..e34431a --- /dev/null +++ b/app/src/moves.ts @@ -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:` a card in your hand + * - `anomaly::` an Anomaly token (or its slot in the player panel when it isn't in play) + * - `loc:` a location + * - `gate:` 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(); + 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(); + 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; +} diff --git a/app/src/render-card.ts b/app/src/render-card.ts new file mode 100644 index 0000000..c062771 --- /dev/null +++ b/app/src/render-card.ts @@ -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; +const assetFiles = import.meta.glob('../../assets/*.{jpeg,jpg,png,svg,webp,gif}', { query: '?url', import: 'default', eager: true }) as Record; + +/** 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( + "" + + "" + + "" + + "NO ART YET", + ).replace(/[()']/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`); + +const assets: Record = { placeholder: PLACEHOLDER }; +for (const [path, url] of Object.entries(assetFiles)) assets[kebab(baseName(path))] = url; + +const hb = Handlebars.create(); +hb.registerHelper('index', (obj: Record | undefined, key: string | undefined) => { + if (!obj || !key) return ''; + const value = String(key).split('.').reduce((o, part) => (o as Record | 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; +const compiled = new Map(); +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(); + +/** 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 = {}; + 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 = `${html(ctx)}`; + } catch (e) { + console.warn(`Couldn't render ${name}:`, e); + } + } + } + cache.set(name, out); + return out; +} diff --git a/app/src/replay.ts b/app/src/replay.ts new file mode 100644 index 0000000..19bf1d7 --- /dev/null +++ b/app/src/replay.ts @@ -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) }; + } +} diff --git a/app/src/storage.ts b/app/src/storage.ts new file mode 100644 index 0000000..f16c126 --- /dev/null +++ b/app/src/storage.ts @@ -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(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(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); +} diff --git a/app/src/styles.css b/app/src/styles.css new file mode 100644 index 0000000..8d25ee6 --- /dev/null +++ b/app/src/styles.css @@ -0,0 +1,1321 @@ +/* Files TCG app. Dark, monospace, the cards' neon accents. Owner colors are Okabe–Ito sky blue and + orange, which stay apart for color-blind players; stripes (South) and dots (North) are a second cue. */ + +:root { + --bg: #06090d; + --panel: #0c1218; + --panel-2: #111a22; + --line: #1e2a36; + --text: #d7dee6; + --muted: #7d8a97; + --accent: #2de2c4; + --warn: #ffb454; + --bad: #ff6b6b; + --p0: #56b4e9; + --p0-dk: #16415c; + --p1: #e69f00; + --p1-dk: #5a3e00; + --attack: #ff5c7a; + --target: #2de2c4; + font-family: 'JetBrains Mono', 'Consolas', 'Menlo', monospace; + font-size: 13px; + color: var(--text); + background: var(--bg); + color-scheme: dark; +} + +* { + box-sizing: border-box; +} + +body { + margin: 0; + min-width: 1280px; + min-height: 720px; +} + +button, +select, +input, +textarea { + font: inherit; + color: inherit; +} + +button { + background: var(--panel-2); + border: 1px solid var(--line); + border-radius: 6px; + padding: 5px 10px; + cursor: pointer; +} +button:hover:not(:disabled) { + border-color: var(--accent); +} +button:disabled { + opacity: 0.45; + cursor: default; +} +button.primary { + background: #0f3b36; + border-color: var(--accent); + color: #e6fffa; +} +button.ghost { + background: transparent; +} +button.linkish { + background: none; + border: none; + padding: 0; + text-decoration: underline dotted; +} +kbd { + font-size: 10px; + border: 1px solid var(--line); + border-radius: 3px; + padding: 0 4px; + margin-left: 4px; + color: var(--muted); +} +input, +select, +textarea { + background: #080d12; + border: 1px solid var(--line); + border-radius: 5px; + padding: 4px 6px; +} +input.bad, +textarea.bad { + border-color: var(--bad); +} +textarea { + width: 100%; + resize: vertical; +} +.muted { + color: var(--muted); +} +.small { + font-size: 11px; +} +.error { + color: var(--bad); + margin: 4px 0; +} +ul.error { + padding-left: 18px; +} +.owner-0 { + --own: var(--p0); + --own-dk: var(--p0-dk); +} +.owner-1 { + --own: var(--p1); + --own-dk: var(--p1-dk); +} + +/* ------------------------------------------------------------------------------------------ */ +/* Game layout */ + +.game { + display: grid; + grid-template-columns: 240px minmax(0, 1fr) 320px; + grid-template-rows: 40px minmax(0, 1fr) clamp(184px, 22vh, 260px); + grid-template-areas: + 'top top top' + 'left center right' + 'bottom bottom bottom'; + height: 100vh; + min-height: 720px; + overflow: hidden; +} +.topbar { + grid-area: top; + display: flex; + align-items: center; + gap: 12px; + padding: 0 12px; + border-bottom: 1px solid var(--line); + background: var(--panel); + white-space: nowrap; + overflow: hidden; +} +.brand { + color: var(--accent); + font-weight: bold; + letter-spacing: 2px; +} +.status { + color: var(--text); +} +.stack { + color: var(--warn); + overflow: hidden; + text-overflow: ellipsis; +} +.spacer { + flex: 1; +} +.bot-controls { + display: flex; + gap: 6px; + align-items: center; +} +.bot-controls input[type='range'] { + width: 90px; + vertical-align: middle; +} +.left { + grid-area: left; + display: flex; + flex-direction: column; + justify-content: space-between; + gap: 6px; + padding: 6px; + overflow: hidden; + border-right: 1px solid var(--line); +} +.center { + grid-area: center; + position: relative; + display: flex; + flex-direction: column; + min-height: 0; +} +.right { + grid-area: right; + display: flex; + flex-direction: column; + border-left: 1px solid var(--line); + min-height: 0; +} +.bottom { + grid-area: bottom; + display: flex; + border-top: 1px solid var(--line); + background: var(--panel); + min-width: 0; +} + +/* ------------------------------------------------------------------------------------------ */ +/* Board */ + +.board { + flex: 1; + width: 100%; + min-height: 0; + user-select: none; +} +.link { + stroke: #2a3947; + stroke-width: 3; +} +.link.walled { + stroke: #7a2c3a; + stroke-dasharray: 6 5; +} +.loc { + cursor: pointer; +} +.loc-bg { + fill: #0d141b; +} +.loc.owner-0 .loc-bg { + fill: var(--p0-dk); +} +.loc.owner-1 .loc-bg { + fill: var(--p1-dk); +} +.loc-edge { + fill: none; + stroke: #2a3947; + stroke-width: 2; +} +.loc.owner-0 .loc-edge { + stroke: var(--p0); +} +.loc.owner-1 .loc-edge { + stroke: var(--p1); +} +.loc.start .loc-edge { + stroke-width: 3; + stroke-dasharray: 2 3; +} +.loc text { + fill: var(--text); + pointer-events: none; +} +.loc-id { + font-weight: bold; + font-size: 15px; +} +.loc-lv { + font-size: 11px; + text-anchor: end; + fill: var(--muted) !important; +} +.loc-server { + font-size: 12px; + text-anchor: middle; +} +.loc-room { + font-size: 11px; + font-weight: normal; + fill: var(--warn); +} +.prog { + fill: #d264ff; + stroke: #0008; +} +.prog.off { + fill: #444; +} +.loc.mark-source .loc-edge, +.loc.mark-respond .loc-edge { + stroke: var(--accent); + stroke-dasharray: 4 3; +} +.loc.mark-selected .loc-edge { + stroke: #fff; + stroke-width: 3; +} +.loc.mark-target .loc-edge { + stroke: var(--target); + stroke-width: 4; + filter: url(#glow); +} +.loc.mark-attack .loc-edge { + stroke: var(--attack); + stroke-width: 4; + filter: url(#glow); +} +.loc.mark-fight .loc-edge { + stroke: var(--warn); + stroke-width: 4; + animation: pulse 1s ease-in-out infinite alternate; +} +@keyframes pulse { + from { + opacity: 1; + } + to { + opacity: 0.45; + } +} + +.gate { + cursor: pointer; +} +.gate rect { + fill: #0d141b; + stroke: #3a4a59; + stroke-width: 2; +} +.gate.open rect { + fill: #0d141b; +} +.gate.fw rect { + fill: #5c1f2c; + stroke: #ff6b6b; +} +.gate.fw-2 rect { + fill: #7a2233; +} +.gate.fw-3 rect { + fill: #9e2539; +} +.gate text { + fill: #fff; + font-size: 13px; + font-weight: bold; + text-anchor: middle; + pointer-events: none; +} +.gate.mark-source rect, +.gate.mark-respond rect { + stroke: var(--accent); +} +.gate.mark-selected rect { + stroke: #fff; + stroke-width: 3; +} + +.token { + cursor: pointer; +} +.token-body { + fill: var(--own-dk); + stroke: var(--own); + stroke-width: 2; +} +.token.copy .token-body { + stroke-dasharray: 4 3; +} +.hp-track { + fill: none; + stroke: #0009; + stroke-width: 4; +} +.hp-ring { + fill: none; + stroke: #5fd35f; + stroke-width: 4; +} +.token-slot { + fill: #fff; + font-size: 16px; + font-weight: bold; + text-anchor: middle; + pointer-events: none; +} +.core-badge { + fill: #06090d; + stroke: var(--own); +} +.core-text { + fill: var(--own); + font-size: 11px; + font-weight: bold; + text-anchor: middle; + pointer-events: none; +} +.token-icons { + fill: var(--warn); + font-size: 12px; + text-anchor: middle; +} +.token.mark-source .token-body, +.token.mark-respond .token-body { + stroke: var(--accent); + stroke-width: 3; +} +.token.mark-selected .token-body { + stroke: #fff; + stroke-width: 4; + filter: url(#glow); +} +.token.mark-target .token-body { + stroke: var(--target); + stroke-width: 4; + filter: url(#glow); +} +.token.mark-attack .token-body { + stroke: var(--attack); + stroke-width: 4; + filter: url(#glow); +} + +.fx { + pointer-events: none; +} +.fx-capture { + fill: none; + stroke: var(--own); + stroke-width: 6; + animation: capture 1.4s ease-out forwards; + transform-box: fill-box; + transform-origin: center; +} +@keyframes capture { + from { + opacity: 1; + transform: scale(1); + } + to { + opacity: 0; + transform: scale(1.35); + } +} +.fx-damage { + fill: var(--bad); + font-size: 20px; + font-weight: bold; + text-anchor: middle; + animation: float 1.5s ease-out forwards; +} +.fx-damage.dead { + fill: #ff9e9e; +} +@keyframes float { + from { + opacity: 1; + transform: translateY(0); + } + to { + opacity: 0; + transform: translateY(-30px); + } +} +.fx-firewall { + fill: none; + stroke: #ff6b6b; + stroke-width: 4; + animation: capture 1.2s ease-out forwards; + transform-box: fill-box; + transform-origin: center; +} + +/* Overlays on the board */ + +.banner { + position: absolute; + top: 8px; + left: 8px; + max-width: min(calc(50% - 80px), 420px); + z-index: 2; + padding: 5px 9px; + font-size: 12px; + border-radius: 6px; + border: 1px solid var(--line); + background: #0c1218ee; + line-height: 1.4; +} +.banner.respond { + border-color: var(--warn); + background: #2a1e08; +} +.banner.mine { + border-color: #1d4a44; +} +.banner.theirs { + color: var(--muted); +} +.source-menu { + position: absolute; + right: 8px; + bottom: 8px; + max-width: calc(50% - 90px); + z-index: 2; + background: #0b1117f2; + border: 1px solid var(--accent); + border-radius: 8px; + padding: 8px 10px; + box-shadow: 0 6px 24px #000a; +} +.source-menu.responses { + max-width: 320px; +} +.source-menu.responses button { + font-size: 11px; + padding: 3px 7px; + text-align: left; +} +.sm-title { + font-weight: bold; + color: var(--accent); +} +.sm-hint, +.sm-odds { + color: var(--muted); + margin-top: 2px; +} +.sm-odds { + color: var(--warn); +} +.sm-moves { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin-top: 6px; +} +.popover { + position: fixed; + z-index: 20; + display: flex; + flex-direction: column; + gap: 4px; + min-width: 220px; + max-width: 370px; + background: #0b1117; + border: 1px solid var(--accent); + border-radius: 8px; + padding: 6px; + box-shadow: 0 6px 24px #000c; +} +.popover button { + text-align: left; +} +.errors { + position: absolute; + top: 44px; + right: 8px; + max-width: 60%; + background: #3a0d12; + border: 1px solid var(--bad); + border-radius: 6px; + padding: 6px 8px; +} + +/* ------------------------------------------------------------------------------------------ */ +/* Panels */ + +.panel { + background: var(--panel); + border: 1px solid var(--line); + border-radius: 8px; + padding: 6px 8px; +} +.panel.player { + border-left: 4px solid var(--own); + flex: 0 1 auto; + min-height: 0; + overflow-y: auto; +} +.panel.player.active { + box-shadow: 0 0 0 1px var(--own) inset; +} +.panel header { + display: flex; + align-items: baseline; + gap: 6px; +} +.seat { + font-weight: bold; + color: var(--own); +} +.who { + color: var(--muted); +} +.gb { + margin-left: auto; + font-size: 16px; + font-weight: bold; + color: #e6c15a; +} +.held { + display: flex; + align-items: center; + gap: 8px; + margin: 3px 0; + font-size: 12px; +} +.held-bar { + flex: 1; + height: 6px; + background: #1a2530; + border-radius: 3px; + overflow: hidden; +} +.held-fill { + height: 100%; + background: var(--own); +} +.piles { + display: flex; + gap: 10px; + color: var(--muted); +} +.slots { + list-style: none; + padding: 0; + margin: 4px 0 0; + display: flex; + flex-direction: column; + gap: 2px; +} +.slot { + display: grid; + grid-template-columns: 14px 1fr auto; + grid-template-areas: 'n name where' 'n stats stats' 'n hw hw'; + column-gap: 6px; + padding: 2px 5px; + font-size: 12px; + border-radius: 5px; + background: #0a0f14; + border: 1px solid transparent; + cursor: pointer; +} +.slot.face-down { + color: var(--muted); +} +.slot.in-play { + background: #0f171f; +} +.slot-n { + grid-area: n; + color: var(--own); + font-weight: bold; +} +.slot-name { + grid-area: name; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.slot-where { + grid-area: where; + color: var(--muted); +} +.slot-stats { + grid-area: stats; + color: var(--muted); + font-size: 11px; +} +.slot-hw { + grid-area: hw; + display: flex; + gap: 3px; + overflow: hidden; + white-space: nowrap; +} +.hw { + flex: 0 1 auto; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + font-size: 10px; + background: #1a2530; + border-radius: 3px; + padding: 0 4px; +} +.slot.mark-source, +.slot.mark-respond { + border-color: var(--accent); + border-style: dashed; +} +.slot.mark-selected { + border-color: #fff; +} +.slot.mark-target { + border-color: var(--target); + box-shadow: 0 0 8px var(--target); +} + +/* Hand */ + +.hand { + flex: 1; + display: flex; + align-items: flex-start; + gap: 6px; + padding: 7px 8px 0; + overflow-x: auto; + overflow-y: hidden; + min-width: 0; +} +.hand-card { + flex: none; + cursor: pointer; + border-radius: 7px; + outline: 2px solid transparent; + transition: transform 0.08s; +} +.hand-card:hover { + transform: translateY(-3px); +} +.hand-card .text-card { + aspect-ratio: 750 / 1050; + overflow: hidden; + font-size: 10px; +} +.hand-card.mark-source, +.hand-card.mark-respond { + outline-color: var(--accent); +} +.hand-card.mark-respond { + outline-color: var(--warn); +} +.hand-card.mark-selected { + outline: 3px solid #fff; + transform: translateY(-6px); +} +.hand-label { + display: flex; + justify-content: space-between; + gap: 4px; + font-size: 10px; + margin-top: 2px; +} +.hand-label span { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.hand-label b { + color: #e6c15a; + flex: none; +} +.hand-empty { + color: var(--muted); + padding: 20px; +} +.card-view { + border-radius: 6px; + overflow: hidden; +} + +.actions { + flex: none; + width: 330px; + display: flex; + flex-direction: column; + gap: 6px; + padding: 8px; + border-left: 1px solid var(--line); +} +.actions button { + padding: 7px 10px; +} +.steps { + display: flex; + gap: 3px; +} +.step { + flex: 1; + text-align: center; + font-size: 11px; + padding: 3px 0; + border-radius: 4px; + background: #0a0f14; + color: var(--muted); +} +.step.on { + background: #0f3b36; + color: #e6fffa; +} +.step.other { + color: var(--own, var(--muted)); +} + +/* ------------------------------------------------------------------------------------------ */ +/* Side column */ + +.tabs { + display: flex; + border-bottom: 1px solid var(--line); +} +.tabs button { + flex: 1; + border: none; + border-radius: 0; + background: none; + padding: 8px 2px; + white-space: nowrap; + color: var(--muted); +} +.tabs button.on { + color: var(--text); + box-shadow: 0 -2px 0 var(--accent) inset; +} +.tab-body { + flex: 1; + overflow-y: auto; + padding: 8px; + min-height: 0; + display: flex; + flex-direction: column; +} +.mini-info { + max-height: 34%; + overflow-y: auto; + border-top: 1px solid var(--line); + padding: 6px 8px; + background: var(--panel); +} +.empty-note { + color: var(--muted); + padding: 8px 2px; +} +.log-panel { + display: flex; + flex-direction: column; + min-height: 0; + flex: 1; +} +.chips { + display: flex; + gap: 4px; + margin-bottom: 6px; +} +.chips button { + padding: 2px 7px; + font-size: 11px; +} +.chips button.on { + border-color: var(--accent); +} +.log { + flex: 1; + overflow-y: auto; + font-size: 12px; + line-height: 1.4; +} +.line { + padding: 1px 0; + border-left: 2px solid transparent; + padding-left: 5px; +} +.line.owner-0, +.line.owner-1 { + border-left-color: var(--own); +} +.line.tag-turn { + margin-top: 8px; + color: var(--own, var(--accent)); + font-weight: bold; +} +.line.tag-combat { + color: #f0c8c8; +} +.line.tag-capture { + color: #cdeccd; +} +.line.tag-effect { + color: #d7c8f0; +} + +.combat-head { + font-size: 14px; + margin-bottom: 6px; +} +.fighter { + border-left: 3px solid var(--own); + background: var(--panel); + border-radius: 6px; + padding: 6px 8px; +} +.fighter-head { + display: flex; + gap: 6px; + align-items: baseline; +} +.role { + color: var(--muted); + font-size: 11px; +} +.fname { + color: var(--own); + font-weight: bold; + flex: 1; +} +.fcores { + font-weight: bold; +} +.parts { + list-style: none; + padding: 0; + margin: 4px 0; + font-size: 11px; +} +.parts li { + display: flex; + gap: 6px; +} +.part-kind { + color: var(--muted); + width: 62px; +} +.part-src { + flex: 1; +} +.parts b.neg { + color: var(--bad); +} +.roll { + display: flex; + align-items: center; + gap: 6px; +} +.dice { + display: flex; + flex-wrap: wrap; + gap: 3px; +} +.die { + width: 22px; + height: 22px; + display: grid; + place-items: center; + background: #e8eef4; + color: #0b1017; + border-radius: 4px; + font-weight: bold; +} +.dice.rolling .die { + animation: shake 0.14s linear infinite; +} +@keyframes shake { + 0% { + transform: rotate(-12deg); + } + 50% { + transform: rotate(12deg); + } + 100% { + transform: rotate(-12deg); + } +} +.total { + font-size: 16px; +} +.fhealth { + font-size: 11px; + color: var(--muted); + margin-top: 3px; +} +.took { + color: var(--bad); +} +.vs { + text-align: center; + color: var(--muted); + margin: 3px 0; +} +.odds { + margin-top: 8px; + padding: 6px 8px; + border: 1px dashed var(--warn); + border-radius: 6px; +} +.result { + margin: 8px 0 0; + padding-left: 16px; +} +.result li.owner-0, +.result li.owner-1 { + color: var(--own); +} + +.info h3 { + margin: 0 0 4px; + font-size: 14px; +} +.info p { + margin: 2px 0 6px; +} +.info.compact { + border-top: 1px solid var(--line); + padding-top: 4px; +} +.info-card { + background: var(--panel); + border: 1px solid var(--line); + border-radius: 6px; + padding: 4px 6px; + margin-bottom: 4px; +} +.info-card.program { + border-left: 3px solid #d264ff; +} +.info-card.program.off { + opacity: 0.55; +} +.info-card.hardware { + border-left: 3px solid #e6c15a; +} +.info-card p { + margin: 2px 0 0; + font-size: 11px; + color: #b8c3ce; +} +.statuses { + margin: 4px 0; + padding-left: 16px; + color: var(--warn); +} + +.moves .search { + width: 100%; + margin-bottom: 6px; +} +.moves details { + margin-bottom: 4px; +} +.moves summary { + cursor: pointer; + color: var(--accent); +} +.move { + display: block; + width: 100%; + text-align: left; + margin: 2px 0; + font-size: 12px; +} + +/* ------------------------------------------------------------------------------------------ */ +/* Cards */ + +.zoom { + position: fixed; + z-index: 50; + pointer-events: none; + filter: drop-shadow(0 8px 24px #000c); +} +.zoom.pinned { + pointer-events: auto; +} +.zoom-close { + position: absolute; + top: -10px; + right: -10px; + border-radius: 50%; + width: 28px; + height: 28px; + padding: 0; + font-size: 16px; +} +.text-card { + background: #0d141b; + border: 1px solid var(--line); + border-radius: 7px; + padding: 6px; + font-size: 11px; + --accent-c: #8b949e; + border-top: 3px solid var(--accent-c); +} +.text-card.large { + font-size: 14px; + padding: 12px; + min-height: 300px; +} +.text-card.kind-execution { + --accent-c: #ffb454; +} +.text-card.kind-hardware { + --accent-c: #e6c15a; +} +.text-card.kind-server { + --accent-c: #2de2c4; +} +.text-card.type-v { + --accent-c: #3fb950; +} +.text-card.type-b { + --accent-c: #ff5c5c; +} +.text-card.type-g { + --accent-c: #d264ff; +} +.text-card.type-p { + --accent-c: #4aa3ff; +} +.tc-head { + display: flex; + justify-content: space-between; + gap: 4px; + font-weight: bold; +} +.tc-gb { + color: #e6c15a; + flex: none; +} +.tc-kind { + color: var(--accent-c); + margin: 2px 0 4px; + font-size: 0.9em; +} +.tc-text, +.tc-ability { + color: #b8c3ce; + line-height: 1.35; +} + +/* ------------------------------------------------------------------------------------------ */ +/* Dialogs */ + +.modal-back { + position: fixed; + inset: 0; + z-index: 30; + background: #000a; + display: grid; + place-items: center; +} +.modal-back.see-through { + background: transparent; + place-items: start center; + padding-top: 56px; + pointer-events: none; +} +.modal-back.see-through .modal { + pointer-events: auto; +} +.modal { + background: var(--panel); + border: 1px solid var(--accent); + border-radius: 10px; + padding: 16px 20px; + max-width: 640px; + max-height: 90vh; + overflow-y: auto; + box-shadow: 0 10px 40px #000; +} +.modal h2 { + margin: 0 0 10px; + font-size: 17px; +} +.modal .buttons, +.start .buttons { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 12px; + align-items: center; +} +.choice-options { + display: flex; + flex-direction: column; + gap: 6px; +} +.choice-options button { + text-align: left; + padding: 8px 10px; +} +.choice-salvage { + display: flex; + flex-wrap: wrap; + gap: 4px; +} +.stats { + border-collapse: collapse; + width: 100%; +} +.stats th, +.stats td { + padding: 2px 8px; + text-align: right; + border-bottom: 1px solid var(--line); +} +.stats td:first-child { + text-align: left; +} +.stats th.owner-0, +.stats th.owner-1 { + color: var(--own); +} +.settings fieldset { + border: 1px solid var(--line); + border-radius: 6px; + margin: 10px 0; +} +.settings legend { + color: var(--accent); +} +.radio, +.check { + display: block; + margin: 4px 0; + cursor: pointer; +} +.range { + display: flex; + flex-direction: column; + gap: 4px; + margin: 8px 0; +} +.error-list { + color: var(--bad); + font-size: 11px; + max-height: 160px; + overflow-y: auto; +} +.pile-cards { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 6px; +} + +/* ------------------------------------------------------------------------------------------ */ +/* Start screen */ + +.start { + min-height: 100vh; + display: grid; + place-items: center; + padding: 20px; + background: radial-gradient(60% 60% at 50% 0%, #0f2a2a 0%, transparent 70%), var(--bg); +} +.start-box { + width: 820px; + background: var(--panel); + border: 1px solid var(--line); + border-radius: 12px; + padding: 20px 26px; +} +.start h1 { + margin: 0 0 14px; + color: var(--accent); + letter-spacing: 3px; + font-size: 22px; +} +.start .form { + display: grid; + grid-template-columns: 150px 1fr; + gap: 10px 14px; + align-items: start; +} +.start .form > label { + padding-top: 5px; + color: var(--muted); +} +.seg { + display: flex; + gap: 4px; + align-items: center; +} +.seg button.on { + border-color: var(--accent); + background: #0f3b36; +} +.saved { + border: 1px solid var(--warn); + border-radius: 8px; + padding: 10px; + margin-bottom: 14px; + background: #1f1707; +} +button.big { + font-size: 15px; + padding: 9px 20px; +} +.file-button { + border: 1px dashed var(--line); + border-radius: 6px; + padding: 6px 10px; + cursor: pointer; +} +.file-button input { + display: none; +} + +/* ------------------------------------------------------------------------------------------ */ +/* Replay */ + +.replay-controls { + flex-direction: column; + padding: 8px; + gap: 8px; +} +.hands { + flex: 1; + overflow-y: auto; + display: flex; + flex-direction: column; + gap: 4px; + font-size: 12px; +} +.replay-hand b { + color: var(--own); +} +.hand-name { + display: inline-block; + background: #1a2530; + border-radius: 3px; + padding: 0 5px; + margin: 1px 2px; +} +.hidden-card { + color: var(--muted); + margin: 0 1px; +} +.scrub { + display: flex; + gap: 6px; + align-items: center; +} +.scrub input[type='range'] { + flex: 1; +} diff --git a/app/src/ui/board.tsx b/app/src/ui/board.tsx new file mode 100644 index 0000000..2a622c8 --- /dev/null +++ b/app/src/ui/board.tsx @@ -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; + 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 { + const out = new Map(); + for (const p of [0, 1] as const) { + const byLoc = new Map(); + 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 ( + onPick('none', e)}> + + + + + + + + + + + + + + + + + {layout.lines.map((line) => { + const a = layout.at[line.a]; + const b = layout.at[line.b]; + const level = view.firewalls[line.id] ?? 0; + return ; + })} + + {Object.keys(layout.at).map((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 ( + + {level ? `Lv ${level} Firewall on ${line.a}–${line.b}` : `Gateway ${line.a}–${line.b}: no Firewall`} + + {level > 0 && {level}} + + ); + })} + + {[0, 1].flatMap((p) => + refsInPlay(view, p as PlayerId).map((r) => { + const key = anomalyKey(r); + return ; + }), + )} + + {effects.map((e) => )} + + ); +} + +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 ( + + + {L.owner !== null && } + + + {loc} + {room > 1 && ( + + ×{room} + Holds {room} of its owner’s Anomalies + + )} + + + {start ? (loc === START_LOC[me] ? 'YOUR START' : 'START') : `Lv ${level}`} + + {server ? shorten(server, 19) : L.owner === null ? 'open' : 'no Server'} + {L.programs.length > 0 && ( + + {L.programs.map((id, i) => ( + + {view.cards[id].name}{programActive(view, id) ? '' : ' (disabled)'} + + ))} + + )} + + ); +} + +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 ( + + {title} + + + + {copy ? `${r.slot - 4}′` : r.slot} + + + {cores} + + {icons.length > 0 && ( + + {icons.map(([glyph, tip], i) => ( + + {glyph} + {tip} + + ))} + + )} + + ); +} + +function EffectView({ e, layout, spots }: { e: Effect; layout: BoardLayout; spots: Map }) { + 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 ; + } + 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 ; + if (e.kind === 'damage' || e.kind === 'destroyed') { + return ( + + {e.kind === 'destroyed' ? `−${e.amount} ✖` : `−${e.amount}`} + + ); + } + return null; +} diff --git a/app/src/ui/cards.tsx b/app/src/ui/cards.tsx new file mode 100644 index 0000000..dcdabb0 --- /dev/null +++ b/app/src/ui/cards.tsx @@ -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) => { + 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 | 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 ( +
+ {real ? : } + {zoom.pinned && ( + + )} +
+ ); +} + +// --------------------------------------------------------------------------------------------- + +/** A card drawn from its Cider template, scaled to `width` pixels. */ +export function CardView({ name, width }: { name: string; width: number }) { + const host = useRef(null); + useLayoutEffect(() => { + const el = host.current; + if (!el) return; + const root = el.shadowRoot ?? el.attachShadow({ mode: 'open' }); + const markup = cardMarkup(name); + root.innerHTML = markup + ? `
${markup}
` + : `
${name}
`; + }, [name, width]); + return
; +} + +const KIND_LABEL = { anomaly: 'Anomaly', server: 'Server', program: 'Program', hardware: 'Hardware', execution: 'Execution' } as const; +const TYPE_LABEL: Record = { 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
{name}
; + const type = TYPE_LABEL[def.type]; + return ( +
+
+ {def.name} + {def.bandwidth > 0 && {def.bandwidth} Gb} +
+
+ {KIND_LABEL[def.kind]} + {type ? ` · ${type}` : ''} + {def.kind === 'anomaly' ? ` · ${def.cores} Cores · ${def.health} Health · ${def.slots} Slots` : ''} +
+ {def.ability && ( +
+ {def.ability.name} + {def.ability.cost ? ` (${def.ability.cost} Gb)` : ''}: {def.ability.text} +
+ )} + {def.kind !== 'anomaly' &&
{def.text}
} +
+ ); +} diff --git a/app/src/ui/game.tsx b/app/src/ui/game.tsx new file mode 100644 index 0000000..a9b0876 --- /dev/null +++ b/app/src/ui/game.tsx @@ -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(null); + const [hover, setHover] = useState(null); + const [focus, setFocus] = useState(null); + const [popover, setPopover] = useState<{ x: number; y: number; moves: Move[] } | null>(null); + const [tab, setTab] = useState('log'); + const [paused, setPaused] = useState(false); + const [dialog, setDialog] = useState<'settings' | { pile: PlayerId } | null>(null); + const [effects, setEffects] = useState([]); + 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(); + 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 ( +
+
+ FILES TCG + {status} + {stackItems.length > 0 && ( + + Waiting: {stackItems.map((it) => `${it.name.replace(/^Execute: /, '')} (${PLAYER_NAMES[it.player]}${it.target ? ` → ${it.target}` : ''})`).join(' ← ')} + + )} + + + + + + + + +
+ + + +
+ + + {selected && !myChoice && ( +
+
{sourceTitle(view, selected, me)}
+ {targeted.length > 0 &&
Click a highlighted {targetWords(targeted)}.
} + {preview &&
Attack odds: {preview.text}
} +
+ {untargeted.map((m) => ( + + ))} + +
+
+ )} + {inWindow && !selected && ( +
+
Your responses
+
+ {responseSources.map(([source, list]) => + list.length === 1 ? ( + + ) : ( + + ), + )} + {primary && ( + + )} +
+
+ )} + {popover && ( +
+ {popover.moves.map((m) => ( + + ))} + +
+ )} + {match.errors.length > 0 && ( +
+ Rule invariants broke ({match.errors.length}). Export the game record from Settings and attach it to a bug report. +
{match.errors.at(-1)}
+
+ )} +
+ + + +
+ +
+
+ {view.active === me ? ( + STEPS.map(([id, label]) => ( + + {label} + + )) + ) : ( + {PLAYER_NAMES[bot]}’s command + )} +
+ + + {playtest && ( + + )} +
+
+ + {myChoice && view.choice && } + {match.over && !overClosed && setOverClosed(true)} onNewGame={onNewGame} onRematch={onRematch} onReplay={onReplay} />} + {dialog === 'settings' && setDialog(null)} />} + {dialog && typeof dialog === 'object' && setDialog(null)} />} + +
+ ); +} + +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 ( + + ); + } + 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 ( + + ); + } + if (!myTurn) { + return ( + + ); + } + 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 ( + + ); +} + +const STAT_LABELS: Record = { + 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 ( + + ); +} + +function SettingsDialog({ match, settings, playtest, onSettings, onClose }: { match: Match; settings: Settings; playtest: boolean; onSettings(s: Settings): void; onClose(): void }) { + const set = (patch: Partial) => onSettings({ ...settings, ...patch }); + const [copied, setCopied] = useState(''); + return ( + + ); +} + +function PileDialog({ view, p, me, onClose }: { view: GameState; p: PlayerId; me: PlayerId; onClose(): void }) { + const pile = view.players[p].discard; + return ( + + ); +} diff --git a/app/src/ui/panels.tsx b/app/src/ui/panels.tsx new file mode 100644 index 0000000..c6b9905 --- /dev/null +++ b/app/src/ui/panels.tsx @@ -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; + 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 ( +
+
+ {PLAYER_NAMES[p]} + {mine ? 'you' : 'bot'} + {pl.bandwidth} Gb +
+
+
+
+
+ + {held}/{need} locations + +
+
+ ✋ {pl.hand.length} + ▤ {pl.deck.length} + + ⛁ {pl.serverPile.length} +
+
    + {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 ( +
  • onPick(key, e)} {...zoomable(name)}> + {copy ? `${slot - 4}′` : slot} + {name ?? (view.rules.recruit.on && av.card < 0 && !copy ? 'empty' : 'face down')} + {inPlay ? av.at : name ? 'in slot' : ''} + {name && ( + + {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(' ')}`} + + )} + {av.hardware.length > 0 && ( + + {av.hardware.map((h) => ( + + {view.cards[h].name} + + ))} + + )} +
  • + ); + })} +
+
+ ); +} + +interface HandProps { + view: GameState; + me: PlayerId; + marks: Map; + 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 ( +
+ {hand.map((id) => { + const name = view.cards[id].name; + const key = handKey(name); + const mark = marks.get(key); + const def = view.defs[name]; + return ( +
onPick(key, e as unknown as MouseEvent)} {...zoomable(name)}> + {real ? : } +
+ {name.replace(/^Execute: /, '')} + {def.bandwidth} Gb +
+
+ ); + })} + {hand.length === 0 &&
Your hand is empty.
} +
+ ); +} diff --git a/app/src/ui/replay.tsx b/app/src/ui/replay.tsx new file mode 100644 index 0000000..559bb02 --- /dev/null +++ b/app/src/ui/replay.tsx @@ -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 ( +
+
+ FILES TCG · REPLAY + + Seed {setup.seed} · you were {PLAYER_NAMES[human]} · {header} + + + + + +
+ +
+ {replay.error && } + {}} onHover={() => {}} /> +
+ +
+
+ {([0, 1] as const).map((p) => ( +
+ {PLAYER_NAMES[p]}’s hand{' '} + {view.players[p].hand.map((id, i) => + id < 0 ? ( + ▮ + ) : ( + + {view.cards[id].name} + + ), + )} +
+ ))} +
+
+ + + + + + + + setN(Number(e.currentTarget.value))} /> + + move {n}/{replay.length} + + + +
+
+ +
+ ); +} diff --git a/app/src/ui/side.tsx b/app/src/ui/side.tsx new file mode 100644 index 0000000..86a0464 --- /dev/null +++ b/app/src/ui/side.tsx @@ -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 ( + + {dice.map((d, i) => ( + + {rolling ? 1 + Math.floor(Math.random() * 6) : d} + + ))} + + ); +} + +function Parts({ parts }: { parts: CorePart[] }) { + return ( +
    + {parts.map((p, i) => ( +
  • + {KIND_NAMES[p.kind]} + {p.source} + {i === 0 ? p.cores : `${p.cores > 0 ? '+' : ''}${p.cores}`} +
  • + ))} +
+ ); +} + +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 ( +
+
+ {role} + = 0 ? view.cards[anomaly(view, f.ref).card].name : null)}> + {refName(view, f.ref, me)} + + {f.cores} Cores +
+ + {f.dice.length > 0 && ( +
+ + {!rolling && = {total}} +
+ )} +
+ {f.health > 0 && `${f.healthLeft}/${f.health} Health before the result`} + {damage.amount > 0 && !rolling && · took {damage.amount}{damage.dead ? ', destroyed' : ''}} +
+
+ ); +} + +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
No combat yet. Combats show here with each side’s Cores, dice and damage.
; + 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 ( +
+
+ Combat at {combat.loc} · {combat.kind === 'traceRoute' ? 'Trace Route' : combat.kind} · {stage} +
+ +
vs
+ {combat.defenders.map((d) => )} + {odds && !combat.rolled && !combat.done && ( +
+ {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)} +
+ Average damage: {o.damageDealt.toFixed(1)} to the defender, {o.damageTaken.toFixed(1)} to the attacker +
+
+ )} + {!rolling && result.length > 0 && ( +
    + {result.map((l, i) =>
  • {l.text}
  • )} +
+ )} +
+ ); +} + +/** 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
Point at a location or an Anomaly for its details. Right-click a card to pin it.
; + const ref = refOfKey(focus); + if (ref) return ; + const m = focus.match(/^loc:(.+)$/); + if (m) return ; + const g = focus.match(/^gate:(.+)$/); + if (g) { + const level = view.firewalls[g[1]] ?? 0; + return ( +
+

Gateway {g[1].replace('-', '–')}

+

{level ? `A Lv ${level} Firewall blocks this line. Clearing it costs ${view.rules.firewallCost[level - 1]} Gb.` : 'Open: no Firewall.'}

+
+ ); + } + 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 ( +
+

+ {loc} · {isStart(loc) ? 'start' : `Lv ${levelFor(me, loc)} for you`} · {owner} +

+ {server && def && ( +
+ {server} +

{def.text}

+
+ )} + {L.programs.map((id) => { + const name = view.cards[id].name; + return ( +
+ + {name} + {programActive(view, id) ? '' : ' (disabled)'} + +

{view.defs[name].text}

+
+ ); + })} + {anomaliesAt(view, loc).map((r) => )} + {walls.length > 0 && ( +

+ Firewalls: {walls.map((l) => `${otherEnd(l, loc)} (Lv ${view.firewalls[l.id]})`).join(', ')} +

+ )} +
+ ); +} + +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

Anomaly {r.slot}: face down

; + const name = view.cards[av.card].name; + const def = view.defs[name]; + const inPlay = av.at !== null; + const mods = activeMods(view, av); + return ( +
+

+ {refName(view, r, me)} + {inPlay && · on {av.at}} +

+

+ {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)}`} +

+ {!compact && def.ability && ( +

+ {def.ability.name} + {def.ability.cost ? ` (${def.ability.cost} Gb)` : ''}: {def.ability.text} +

+ )} + {av.hardware.map((h) => ( +
+ {view.cards[h].name} + {!compact &&

{view.defs[view.cards[h].name].text}

} +
+ ))} + {inPlay && ( +
    + {infectionOf(av) > 0 &&
  • ☣ {infectionOf(av)} Infection{av.permanentInfection ? ` (${av.permanentInfection} permanent)` : ''}
  • } + {av.bugs > 0 &&
  • ✱ {av.bugs} Bug counters
  • } + {isDisabledAnomaly(view, r) &&
  • ⏻ Disabled
  • } + {isRooted(view, r) &&
  • ⚓ Can’t move or retreat
  • } + {mods.map((m) => ( +
  • + {m.cores > 0 ? '+' : ''} + {m.cores} Cores from {m.source} + {m.combat !== undefined ? ' this combat' : ''} +
  • + ))} +
+ )} +
+ ); +} + +// --------------------------------------------------------------------------------------------- +// 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(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 ( +
+
+ {FILTERS.map((f) => ( + + ))} +
+
{ + const el = e.currentTarget; + stick.current = el.scrollTop + el.clientHeight >= el.scrollHeight - 8; + }} + > + {shown.map(([l, i]) => ( +
+ {l.text.trim()} +
+ ))} +
+
+ ); +} + +// --------------------------------------------------------------------------------------------- +// 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 ( +
+ setQ(e.currentTarget.value)} /> + {moves.length === 0 &&
{over ? 'The game is over.' : 'No moves: it’s the bot’s decision.'}
} + {groups.map(([group, list]) => ( +
+ + {group} ({list.length}) + + {list.map((m) => ( + + ))} +
+ ))} +
+ ); +} diff --git a/app/src/ui/start.tsx b/app/src/ui/start.tsx new file mode 100644 index 0000000..4731da3 --- /dev/null +++ b/app/src/ui/start.tsx @@ -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(initial); + const [importError, setImportError] = useState(null); + const set = (patch: Partial) => 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 ( +
+
+

+ FILES TCG · play the bot +

+ {saved && ( +
+
+ Game in progress: 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()}. +
+ {resumeError &&
{resumeError}
} +
+ + +
+
+ )} + +
+ +
+ {(['south', 'north', 'random'] as const).map((s) => ( + + ))} + Who goes first is random either way. +
+ + +
+ set({ seed: e.currentTarget.value })} /> + The same seed and decks always deal the same game. +
+ + {(['Your deck', 'The bot’s deck'] as const).map((label, i) => ( + set({ decks: (i === 0 ? [d, prefs.decks[1]] : [prefs.decks[0], d]) as [DeckChoice, DeckChoice] })} + /> + ))} + + +
+ + {BOT_STYLES[prefs.bot]?.about} +
+ + + + + +
+