diff --git a/decks/files-deck-1/cards.csv b/decks/files-deck-1/cards.csv index 1e2577b..b3ac4d3 100644 --- a/decks/files-deck-1/cards.csv +++ b/decks/files-deck-1/cards.csv @@ -2,55 +2,55 @@ "Carbon NanoBots","1","Avatar Front","Card Back",,"2","Nasty little bugs...","B","nano-bots","4","5","Replicate","Avatar may create a copy of itself. Only one copy is allowed at a time. If the copy is defeated the original does not lose any hardware upgrades. If the original is defeated the replicate is as well." "Corrupt Driver","1","Avatar Front","Card Back",,"3",,"V","driver-ascii-art","3","4","Driver Fault","Choose one Hardware on an enemy Avatar in combat with this Avatar. It is disabled until the end of your next turn." "Pixelated Picture","1","Avatar Front","Card Back",,"3",,"G","pix","3","3","Low Resolution","Attacking Avatars have -1 cores against this Avatar." -"Beta Version 1.0","1","Avatar Front","Card Back",,"4",,"P","beta-version","2","4","Push Update","While in combat an additional piece of hardware can be placed on this avatar until the end of your turn. If there no ports available this can still be attached." -"Code Zero","1","Avatar Front","Card Back",,"2",,"V","code-zero","4","4","Patient Zero","Place an Infection counter on every enemy Avatar in combat at this Server. While this Avatar is in play, an Avatar with 2+ Infection counters has -1 Core." +"Beta Version 1.0","1","Avatar Front","Card Back",,"4",,"P","broken-bits","2","4","Push Update","While in combat an additional piece of hardware can be placed on this avatar until the end of your turn. If there no ports available this can still be attached." +"Code Zero","1","Avatar Front","Card Back",,"3",,"V","code-zero","4","4","Patient Zero","Place an Infection counter on every enemy Avatar in combat at this Server. While this Avatar is in play, an Avatar with 1+ Infection counters has -1 Core." "Data Leaker","1","Avatar Front","Card Back",,"3",,"G","data-leaker","3","3","Exfiltrate","Look at your opponent's hand and choose one card in it. They must discard that card without gaining RAM. If this Avatar breached a Server this turn, draw a card." "Backup Machine","1","Avatar Front","Card Back",,"3",,"P","backup","3","5","Restore Point","Return one Hardware or Program from your discard pile to your hand. If it is a Hardware and this Avatar has an open port, you may install it immediately for 2 less RAM." -"Broken Bits","1","Avatar Front","Card Back",,"4",,"B","broken-bits","2","4","Bit Flip","During a combat at this Server, reroll any number of this Avatar's Core dice." -"Recursive Infection","1","Program Front","Card Back","6",,"Whenever an enemy Avatar attacks or breaches this Server, place an Infection counter on it. An Avatar with 3+ Infection counters has -1 Core.","V",,,,, -"Memory Parasite","1","Program Front","Card Back","5",,"Enemy Avatars attacking this Server have -1 RAM available for Executions.","V",,,,, -"Replication Routine","1","Program Front","Card Back","6",,"When you install a Virus Program on this Server, you may install a second Virus Program from your hand here for 1 less RAM.","V",,,,, -"Resource Leech","1","Program Front","Card Back","5",,"Whenever an enemy Avatar is destroyed while attacking this Server, gain 2 RAM.","V",,,,, +"Broken Bits","1","Avatar Front","Card Back",,"4",,"B","broken-bits-2","2","4","Bit Flip","During a combat at this Server, reroll any number of this Avatar's Core dice." +"Recursive Infection","1","Program Front","Card Back","6",,"Whenever an enemy Avatar attacks or breaches this Server, place an Infection counter on it. An Avatar with 3+ Infection counters has -2 Core.","V",,,,, +"Memory Parasite","1","Program Front","Card Back","5",,"Enemy Avatars attacking this Server have 1 hardware component disabled of the owners choosing.","V",,,,, +"Replication Routine","1","Program Front","Card Back","6",,"When you install a Virus Program on this Server, you may install a second Virus Program from your hand here for no RAM cost.","V",,,,, +"Resource Leech","1","Program Front","Card Back","5",,"Whenever an enemy Avatar is destroyed while attacking this Server, gain 5 RAM.","V",,,,, "Worm Protocol","1","Program Front","Card Back","4",,"The localized effects of your other Programs on this Server also apply at one adjacent Server you choose when this is installed.","V",,,,, -"Payload Injector","1","Program Front","Card Back","6",,"The first Execution you play targeting this Server each turn costs 1 less RAM.","V",,,,, -"Persistent Infection","1","Program Front","Card Back","6",,"If this Server stops being under your control, keep this Program installed here; its effect now applies to every Avatar at that Server regardless of controller.","V",,,,, -"Infinite Loop","1","Program Front","Card Back","5",,"The first enemy Avatar to attack this Server each turn is caught in a loop: if it survives the battle, it must immediately repeat its attack once. Gain 1 RAM.","B",,,,, +"Payload Injector","1","Program Front","Card Back","6",,"The first Execution you play targeting this Server each turn costs 2 less RAM.","V",,,,, +"Persistent Infection","1","Program Front","Card Back","6",,"If an Avatar is defeated at this Server, place an Infection Counter on it permanently.","V",,,,, +"Infinite Loop","1","Program Front","Card Back","5",,"If the attacking Avatar is controlled by the owner of this Program, it may attack a second adjacent Server in the same turn.","B",,,,, "Stack Overflow","1","Program Front","Card Back","7",,"Avatars you control defending this Server gain +1 Core for each Program installed on this Server (including this one).","B",,,,, -"Race Condition","1","Program Front","Card Back","4",,"During any combat at this Server, both players secretly choose Attack or Defend. If the choices differ, the defender gains a combat bonus.","B",,,,, -"Memory Leak","1","Program Front","Card Back","6",,"At the start of any combat at this Server, the attacking Avatar loses 1 RAM for each Hardware installed on it.","B",,,,, -"Null Pointer","1","Program Front","Card Back","5",,"Once per turn, when an enemy Execution would resolve at this Server, resolve the game's uncertainty mechanic. On success, it does nothing.","B",,,,, -"Deadlock","1","Program Front","Card Back","4",,"Neither Avatar in a combat that takes place at this Server may retreat until that combat resolves.","B",,,,, -"Overflow Error","1","Program Front","Card Back","5",,"When an enemy Avatar is destroyed while attacking this Server, destroy or disable one Hardware or Program that Avatar's controller has in play.","B",,,,, -"Undefined Behavior","1","Program Front","Card Back","8",,"Once per turn, copy the localized effect of another Program on this Server. Then disable this Program until your next turn.","B",,,,, +"Race Condition","1","Program Front","Card Back","4",,"During any combat at this Server, both players secretly choose Attack or Defend. If the choices differ, the defender gains a combat bonus of +2 Cores.","B",,,,, +"Memory Leak","1","Program Front","Card Back","6",,"At the start of any combat at this Server, the attacking Avatar loses 1 Core for each Hardware installed on it.","B",,,,, +"Null Pointer","1","Program Front","Card Back","5",,"Once per turn, when an enemy Execution would resolve at this Server, it's effect does not occur.","B",,,,, +"Stock Rice","1","Program Front","Card Back","4",,"Neither Avatar in a combat that takes place at this Server may use any Hardware bonuses.","B",,,,, +"Overflow Error","1","Program Front","Card Back","5",,"When an enemy Avatar is destroyed while attacking this Server, destroy or disable one Program that Avatar's controller has in play.","B",,,,, +"Undefined Behavior","1","Program Front","Card Back","8",,"Once per turn, copy the localized effect of another Program on another Server. Then disable this Program until your next turn.","B",,,,, "Packet Loss","1","Program Front","Card Back","6",,"When an enemy successfully breaches this Server, its controller discards a card at random.","G",,,,, "Desynchronization","1","Program Front","Card Back","5",,"Enemy Avatars attacking this Server cannot use their Hardware's ""once per turn"" abilities during that combat.","G",,,,, -"Visual Artifact","1","Program Front","Card Back","5",,"The first attack made against an Avatar you control at this Server each turn suffers -1 Core.","G",,,,, +"Visual Artifact","1","Program Front","Card Back","5",,"The first attack made against an Avatar you control at this Server suffers -1 Core.","G",,,,, "Ghost Process","1","Program Front","Card Back","6",,"Your Executions played targeting this Server may also affect Avatars, Programs, and Hardware at one adjacent Server.","G",,,,, -"False Positive","1","Program Front","Card Back","7",,"When an enemy Execution targets an Avatar you control at this Server, you may redirect it to another legal Avatar at this Server.","G",,,,, -"Fragmentation","1","Program Front","Card Back","6",,"Executions your opponents play targeting this Server cost +1 RAM.","G",,,,, +"False Positive","1","Program Front","Card Back","7",,"When an enemy Execution targets an Avatar you control at this Server, you may redirect it to another legal Avatar at another Server.","G",,,,, +"Fragmentation","1","Program Front","Card Back","6",,"Executions your opponents play targeting this Server cost +2 RAM.","G",,,,, "Latency Spike","1","Program Front","Card Back","5",,"The attacking player cannot play Executions during the first step of any combat at this Server.","G",,,,, "Hotfix","1","Program Front","Card Back","7",,"The first Program on this Server that would be destroyed each turn is instead disabled until your next turn.","P",,,,, "Error Correction","1","Program Front","Card Back","5",,"At the beginning of your turn, remove one negative counter or status from each Avatar you control at this Server.","P",,,,, "Garbage Collection","1","Program Front","Card Back","6",,"Once per turn, sacrifice one Program installed on this Server to recover its printed RAM value.","P",,,,, "Version Control","1","Program Front","Card Back","5",,"When a Program on this Server would be destroyed, or when this Server is captured, return one Program from this Server to your hand instead of discarding it.","P",,,,, "Rollback Routine","1","Program Front","Card Back","4",,"Once per turn, undo the most recent temporary stat reduction applied to an Avatar you control at this Server.","P",,,,, -"Compatibility Layer","1","Program Front","Card Back","6",,"This Server may hold one additional Program beyond the normal limit, and Patch Programs installed here cost 1 less RAM.","P",,,,, -"RAM Expansion","1","Hardware Front","Card Back","5",,"Avatar gains +2 RAM capacity.",,,,,, +"Compatibility Layer","1","Program Front","Card Back","6",,"This Server may hold one additional Program beyond the normal limit, and Patch Programs installed here cost 2 less RAM.","P",,,,, +"RAM Expansion","1","Hardware Front","Card Back","5",,"Avatar gains +2 Core capacity.",,,,,, "Additional Core","1","Hardware Front","Card Back","5",,"Avatar gains +1 Core.",,,,,, -"Overclocked CPU","1","Hardware Front","Card Back","6",,"Avatar gains +2 Cores during combat, but one installed Program becomes disabled afterward.",,,,,, -"Solid-State Cache","1","Hardware Front","Card Back","6",,"The first Program installed on this Avatar each turn costs 1 less RAM.",,,,,, -"Redundant Power Supply","1","Hardware Front","Card Back","8",,"The first time this Avatar would be destroyed, destroy this Hardware instead and leave the Avatar active.",,,,,, -"Network Interface Upgrade","1","Hardware Front","Card Back","4",,"Moving between adjacent Servers costs 1 less resource or may occur once per turn for free.",,,,,, +"Overclocked CPU","1","Hardware Front","Card Back","6",,"Avatar gains +2 Cores during combat, but one installed Program at the current server becomes disabled afterward for 2 turns.",,,,,, +"Solid-State Cache","1","Hardware Front","Card Back","6",,"The first Program installed on the occupied Server each turn costs 3 less RAM.",,,,,, +"Redundant Power Supply","1","Hardware Front","Card Back","8",,"The first time this Avatar would be destroyed, do not destroy the Hardware.",,,,,, +"Network Interface Upgrade","1","Hardware Front","Card Back","4",,"This Hardware can be played without taking an upgrade port on the Avatar.",,,,,, "Dedicated GPU","1","Hardware Front","Card Back","6",,"Executions performed by this Avatar receive +1 effectiveness or combat strength.",,,,,, "ECC Memory","1","Hardware Front","Card Back","5",,"Opponents cannot place Bug counters or Bug status effects on this Avatar.",,,,,, -"Cooling System","1","Hardware Front","Card Back","6",,"Prevent penalties caused by Overclocking Hardware or allow one Hardware to activate twice per turn.",,,,,, -"RAID Array","1","Hardware Front","Card Back","5",,"When a Program on this Avatar is destroyed, resolve the game's uncertainty mechanic. On success, return it to your hand.",,,,,, -"Packet Accelerator","1","Hardware Front","Card Back","4",,"This Avatar acts first when it initiates combat.",,,,,, -"Firewall Appliance","1","Hardware Front","Card Back","6",,"The first hostile Program or Execution targeting this Avatar each turn costs the opponent +1 RAM.",,,,,, -"Hardware Sandbox","1","Hardware Front","Card Back","7",,"Choose one Program installed on this Avatar. It cannot be targeted by opponents.",,,,,, -"Diagnostic Module","1","Hardware Front","Card Back","4",,"Look at one facedown or hidden card associated with an opposing Avatar or Server once per turn.",,,,,, +"Cooling System","1","Hardware Front","Card Back","6",,"Allow one Hardware to activate twice per turn.",,,,,, +"RAID Array","1","Hardware Front","Card Back","5",,"When this Avatar is destroyed, all hardware can be kept by paying half the RAM cost.",,,,,, +"Packet Accelerator","1","Hardware Front","Card Back","4",,"This Avatar gains +1 Core hen attacking.",,,,,, +"Firewall Appliance","1","Hardware Front","Card Back","6",,"The first hostile Program or Execution targeting this Avatar each turn costs the opponent +3 RAM.",,,,,, +"Hardware Sandbox","1","Hardware Front","Card Back","7",,"Choose one Program installed on the occupied Server. It cannot be targeted by opponents.",,,,,, +"Diagnostic Module","1","Hardware Front","Card Back","4",,"Look at one face down card in your draw pile. You may place it at the bottom and draw another to start your turn.",,,,,, "Hot-Swap Bay","1","Hardware Front","Card Back","6",,"Once per turn, return one Hardware to your hand and install another Hardware from your hand, paying the difference in cost.",,,,,, -"Quantum Coprocessor","1","Hardware Front","Card Back","9",,"Once per turn when this Avatar uses an Execution, you may copy that Execution's effect with a different legal target, then disable this Hardware until your next turn.",,,,,, +"Quantum Coprocessor","1","Hardware Front","Card Back","9",,"Once per turn when this Avatar uses an Execution, you may copy that Execution's effect with a different legal target, then disable this Hardware.",,,,,, "High Efficiency RAM Server","1","Server Front","Card Back",,,"Add additional 4 RAM to resource total",,,,,, "MultiCore Server","1","Server Front","Card Back",,,"Add 2 Cores to any Avatars",,,,,, "Cluster Server","1","Server Front","Card Back",,,"Up to 2 Avatars can defend this Server",,,,,, @@ -69,7 +69,7 @@ "Execute: Kill Process","1","Execution Front","Card Back","5",,"Disable one Program installed on the target Server until its controller's next turn.",,,,,, "Execute: Force Reboot","1","Execution Front","Card Back","5",,"Remove all temporary bonuses and penalties from one Avatar you control at the target Server, or one Avatar attacking it. That Avatar cannot play another Execution this turn.",,,,,, "Execute: Fork","1","Execution Front","Card Back","7",,"Copy the localized effect of one Program installed on the target Server until end of turn.",,,,,, -"Execute: Ping Sweep","1","Execution Front","Card Back","4",,"Look at all Programs and Hardware attached to the target Server and to every Avatar based at or attacking it, then draw a card.",,,,,, +"Execute: Ping Sweep","1","Execution Front","Card Back","4",,"You may draw 2 cards from the top of your deck.",,,,,, "Execute: Trace Route","1","Execution Front","Card Back","5",,"Move one Avatar you control from an adjacent Server to the target Server. If the target Server is enemy-controlled, your Avatar attacks it with +1 Core for the resulting combat.",,,,,, "Execute: Override","1","Execution Front","Card Back","5",,"Choose one enemy Program installed on the target Server. Ignore its text until the end of turn.",,,,,, "Execute: Memory Dump","1","Execution Front","Card Back","4",,"Draw 2 cards, then discard 1. If you control the target Server, draw 1 extra card instead of discarding.",,,,,, diff --git a/rules.md b/rules.md new file mode 100644 index 0000000..3c7f5a0 --- /dev/null +++ b/rules.md @@ -0,0 +1,413 @@ +# Files TCG Rules + +*Draft v0.8 — 2026-09-28.* The basic game rules are complete. v0.8 replaces whole turns with +[rounds of alternating commands](#rounds-and-commands). Card text and stats come from +`decks/files-deck-1/cards.csv` (`cards.md` is out of date). [Card Rules](#card-rules) says how card +text is read; readings marked ⚠ are the simulator's guesses and are listed in +[Open Questions](#open-questions). + +## Winning + +The first player to control **10 Server locations** wins. Starting Servers don't count, so that's +10 of the 13 grid locations. The win is checked as soon as a capture resolves. + +## Deck Construction + +Each player brings: + +- **4 Avatars** +- **20 Servers** +- **45 cards**: any mix of Executions, Hardware and Programs + +A deck can hold at most **2 copies** of any one card. + +## Setup + +1. Shuffle your 4 Avatars and place them face down in your 4 Avatar slots (the ✚ icons), numbered 1–4. +2. Shuffle your Servers face down into your Server pile. +3. Shuffle your 45 cards face down into your Deck. +4. Place 1 Server from your pile face down on your starting Server (the ■ icon). Reveal it when the + game starts; its ability applies. +5. Draw 7 cards. +6. Start with **4 RAM**. This is the capture payout for your starting Server, not an extra 4. +7. Flip Avatar 1 face up. It is available from the start. + +The first player is chosen at random. They take the first command of round 1 and skip their draw in +round 1. + +## The Playmat + +Each player's starting Server (`S1` for the South player, `S2` for the North player) connects to a +13-location grid. Two locations are **adjacent** if a single line connects them directly and that +line isn't blocked by a [Firewall](#firewalls). + +``` + S2 North start + | +E1 -----o------ E2 -----o----- E3 + \ / \ / + o o o o + \ / \ / + D1 D2 + / \ / \ + o o o o + / \ / \ +C1 C2 C3 + \ / \ / + o o o o + \ / \ / + B1 B2 + / \ / \ + o o o o + / \ / \ +A1 -----o------ A2 -----o----- A3 + | + S1 South start +``` + +`o` = gateway (20 in total), where Firewalls are placed. The two lines out of the starts (`S1–A2` +and `E2–S2`) have no gateways, so they can never be firewalled. A2 and E2 don't connect to C2. + +### Adjacency + +| Location | Adjacent to | +|---|---| +| S1 | A2 | +| A1 | A2, B1 | +| A2 | S1, A1, A3, B1, B2 | +| A3 | A2, B2 | +| B1 | A1, A2, C1, C2 | +| B2 | A2, A3, C2, C3 | +| C1 | B1, D1 | +| C2 | B1, B2, D1, D2 | +| C3 | B2, D2 | +| D1 | C1, C2, E1, E2 | +| D2 | C2, C3, E2, E3 | +| E1 | E2, D1 | +| E2 | S2, E1, E3, D1, D2 | +| E3 | E2, D2 | +| S2 | E2 | + +### Levels + +A location's level depends on **who captures it**: deeper into enemy territory means a higher level. +Your starting Server and your first row are Lv 1, and each row after that is one level higher. +Levels decide which Avatars unlock. Every capture pays the same **4 RAM**, whatever the level. + +| Row | South player's level | North player's level | +|---|---|---| +| S1 | Lv 1 (start) | — | +| A1–A3 | Lv 1 | Lv 5 | +| B1–B2 | Lv 2 | Lv 4 | +| C1–C3 | Lv 3 | Lv 3 | +| D1–D2 | Lv 4 | Lv 2 | +| E1–E3 | Lv 5 | Lv 1 | +| S2 | — | Lv 1 (start) | + +### Avatar unlocks + +The first time you capture a Lv N location, flip Avatar N face up, plus any lower-numbered Avatar +that's still face down. Your first row (Lv 1) unlocks nothing; Avatar 2 unlocks in your second row. +Capturing Lv 3 before Lv 2 unlocks Avatars 2 and 3. Unlocks are permanent, even if you later lose +the location. An Avatar unlocked during a round can enter play from the next round. + +## Rounds and Commands + +The game is played in **rounds**. In each round, each player gets **2 commands**, taken one at a +time in a snake order: + +| Round | Order of commands | +|---|---| +| 1, 3, 5… | first player, second player, second player, first player | +| 2, 4, 6… | second player, first player, first player, second player | + +Each player gets one pair of back-to-back commands per round, and the pair swaps sides every round. +Nobody acts twice in a row across the end of a round. + +**Your first command of a round** starts with: + +1. **Draw** a card. If your Deck is empty, skip this. There's no maximum hand size. +2. **Refresh:** each of your Avatars can act and be placed again this round. Effects that happen + "at the start of your turn" happen now. + +**A command:** + +1. **Deploy & Move.** + - First, place any of your face-up Avatars onto locations you control. This includes Avatars + entering play from a slot and Avatars repositioning. Placement is free and doesn't count as a + move. Each Avatar can be placed once per round. + - Then you may **advance** one Avatar: move it to an unowned location, or an undefended enemy + location, that is adjacent to any location you control. + - Each location holds 1 of your Avatars. Cluster Server and Pingable Server raise this to 2. +2. **Play cards** from your hand. +3. **Attack.** If you didn't advance, one Avatar may attack one **defended** enemy location adjacent + to **the location it's on**. It gets the Core bonus of the Server it attacks from. +4. **Resolve** the advance or attack right away, with the capture or combat and Server placement. +5. **Play additional cards**, including with RAM gained in step 4. + +A command is **one advance or one attack**, or neither (a pass). Each Avatar can advance or attack +only **once per round**, so with one Avatar in play your second command of a round can play cards but +can't act. Copies are Avatars: each can act once per round, but they don't add commands. + +There's no limit on how many cards you can play, other than the RAM you have. + +### "Turn" on cards + +Card text is written for turns. With commands it reads like this: + +- **Your turn** is your commands in the current round. "At the start of your turn" happens at your + first command of the round. +- **Limits counted per turn** (once per turn, the first … each turn) count **per round**, for both + players together. +- **"This turn"** and **"until end of turn"** last until the end of the current command. +- **"Until your next turn"** and **"the end of your next turn"** mean your next command. + +## Capturing Locations + +- **Unowned location:** your Avatar moves in. Draw the top Server from your pile, place it face up + there, and gain RAM. +- **Undefended enemy location:** your Avatar moves in. The enemy puts their Server card on the bottom + of their pile, and Programs there go to their discard pile. Then place your own Server and gain + RAM, as above. +- **Defended enemy location:** combat. If you win, capture it as an undefended location. If you + lose, the location isn't captured. +- **Starting Servers** can't be attacked or captured. + +## Combat + +1. Both players roll 1d6 per Core, counting Cores from the Avatar, Hardware, Programs, effects, and + the Server each Avatar is on: the attacker's origin, and the location being defended. Each side + always rolls at least 1 die. +2. The higher total wins. **On a tie, both sides reroll all their dice** until one wins. +3. The **loser** returns to its Avatar slot, face up. Its Hardware goes to its owner's discard pile + and all counters and effects on it are removed, debuffs included. It can be placed again from its + owner's next command, if it hasn't been placed yet this round. +4. The **winner** keeps everything. A winning attacker moves into the captured location. + +## RAM + +- RAM carries over between commands and rounds, and there's no cap. +- Avatars cost 0 RAM. Other cards cost their printed RAM value. +- **Capture:** gain **4 RAM**, paid once when you capture a location, whatever its level. You get + paid again every time you recapture a location. A Server card's RAM bonus (for example "+4 RAM") is + also paid once, when the card is placed, on top of the capture RAM. A Server's Core bonus applies to your Avatar + at that location. +- **Salvage:** discard a card from your hand to gain its printed RAM value. You can salvage any time + you need to pay a cost. Installed cards can't be salvaged. +- **Firewalls:** you spend RAM to place, upgrade and clear them. + +## Firewalls + +Firewalls are bought with RAM and placed on a gateway (`o`). They aren't cards. A Firewall blocks +**all** movement and attacks along its line: for both players, and for card effects that move +Avatars (such as Trace Route and Disconnect). + +| Firewall | Cost | +|---|---| +| Lv 1 | 2 RAM | +| Lv 2 | 4 RAM | +| Lv 3 | 8 RAM | + +- **Placing:** in your command (steps 2 and 5), on an empty gateway whose line touches a location you + control. Pay the cost of the level you place. Each gateway holds 1 Firewall, and there's no limit on + how many you can place. +- **Upgrading:** same timing and placement rules as placing. Pay the **full cost** of the new level; + for example, Lv 1 → Lv 2 costs 4 RAM. +- **Clearing:** in your command, in steps 1 and 3, before you advance or attack, on a line touching a + location you control. Pay the Firewall's **current level cost**. This applies to everyone, including + the player who placed it; there's no free removal. Clearing doesn't use an Avatar's action. +- **Permanent:** a Firewall stays until someone pays to clear it, even if the locations at either end + change hands. Once placed, it doesn't belong to either player. + +## Playing Cards + +- **Programs:** in your command (steps 2 and 5), on a location you control. Maximum 2 per location. +- **Hardware:** in your command (steps 2 and 5), on one of your Avatars that's in play (not in its + slot), up to its Expansion Slots. +- **Executions:** at any time, by either player (see [Timing](#timing)). +- **Avatar abilities:** Execution timing, once per turn (per round), only while the Avatar is in + play. +- **Other activated abilities** (Garbage Collection, Rollback Routine, Undefined Behavior, Hot-Swap + Bay, Backup Server): the same, Execution timing and once per turn (per round). Using one isn't + playing a card. + +## Timing + +"Any time" means at these response windows: + +- **After any declaration:** when a player declares an advance or attack, or plays a card, the other + player may respond. +- **During combat:** there's one window before the dice are rolled, and one after the roll but before + the result. +- **Chains:** an Execution or ability can respond to another one. The most recent one resolves first. + Each time a player adds to the chain, the other player may respond. When a player passes instead, + the whole chain resolves. +- The player whose command it isn't can only act in these windows. The player taking the command + can also play Executions and use abilities during its steps. + +## Card Rules + +### Terms + +- **"This Server"** on a Program or Server is the location it's on. Avatars **"at"** a location are + the ones standing on it, plus an enemy attacking it in the current combat. Enemy Avatars never + stand on your locations. +- **"A combat at this Server"** on an Avatar Ability means any combat that Avatar is fighting in, + attacking or defending. +- **Destroyed / defeated** (Avatars) means losing a combat. A Program or Hardware is destroyed when an + effect sends it to the discard pile (Overflow Error, Sabotage). Programs on a captured location + are discarded, not destroyed. +- **Breach:** capture an enemy-owned location, by advancing into it or winning an attack on it. +- **Disabled Hardware or Program:** its effect stops. With no duration on the card, it stays + disabled until something re-enables it (Execute: Defragment) or it leaves play. +- **Disabled Avatar** (Emergency Shutdown): can't advance, attack, move or use its Ability. It still + defends. ⚠ +- **Infection counters** come off when the Avatar is defeated, except the ones Persistent Infection + places. Code Zero (1+ counters: −1 Core) and Recursive Infection (3+: −2 Cores) apply everywhere + while the card is in play, once each no matter how many copies are in play. +- **Bug counters** work like Infection counters, for Bug cards. They come off when the Avatar is + defeated, and Error Correction can remove one. No card places them yet; that needs new cards. + ECC Memory stops opponents from placing them. Purge removes only Virus/Infection counters. +- **Temporary bonuses and penalties** are Core changes from Abilities, Executions and Program + triggers that last one combat or one turn: Memory Leak, Visual Artifact, Race Condition, Low + Resolution, Trace Route. Force Reboot removes them; Rollback Routine undoes the most recent penalty. +- **Copies** (Carbon NanoBots, Backup Server): a copy is an extra Avatar with the original's printed + Cores and the original's Hardware bonuses, but no Hardware or Ability of its own. Each Avatar can + have one copy at a time. It enters play on any location you control with room, can advance, attack + and defend, and is removed if it's defeated or its original is. ⚠ +- **Mid-combat:** no Avatar can enter a location while a combat is going on there, whether it's a + new copy or an Avatar moved by Disconnect. It wouldn't be in the combat, and the location could be + captured with it still standing there. ⚠ +- **Executions are performed by Servers**, never by Avatars. When you play one, one of your Servers + performs it (you pick which). Three cards were written for Avatars performing Executions, and read + it through the Server the Avatar stands on: Dedicated GPU and Quantum Coprocessor work for + Executions that Server performs, and Force Reboot stops that Server from performing Executions for + the rest of the turn. +- **Protected** (Execute: Root Access) means the Program Hardware Sandbox protects. No card protects + Hardware yet. +- **Two defenders** (Cluster Server, Pingable Server): both roll together as one side. If they lose, + both are defeated. +- **Cores that change after the roll** change the dice: each Core gained rolls one more die, and each + Core lost removes one of that Avatar's rolled dice, the one showing the highest number. +- **Once per turn** means once per round, counting uses in both players' commands (see + ["Turn" on cards](#turn-on-cards)). + +### Readings + +Cards not listed here work exactly as printed. + +| Card | How the simulator reads it | +|---|---| +| **Servers** | | +| Cluster Server, Pingable Server | Two of your Avatars fit; both defend together (see Terms). | +| Backup Server | Once per turn, at any time, make a copy of your Avatar standing here (see Copies). | +| Upgraded Hardware | −2 RAM for Hardware installed on your Avatar standing here. | +| Network Throttle | −1 RAM for Firewalls you place or upgrade on a line touching it. Clearing costs full price. | +| Duplicate Server | When placed, pick one adjacent Server (either player's) and gain its ability while this card stays. A copied RAM bonus is paid at once. ⚠ | +| Protected Server | +2 RAM each time a combat starts here with your Avatar defending. ⚠ | +| Callable Server | Every draw after the opening hand, once per card drawn. A second Callable Server doesn't add more. | +| **Programs** | | +| Recursive Infection | One counter per attack declared on this location, or per capture of it without an attack. ⚠ | +| Memory Parasite | "The owner" is the attacking Avatar's owner, who picks which of its Hardware is off for that combat. | +| Replication Routine | Installing this card counts, so it can bring a second Virus with it. Program slots still apply. | +| Worm Protocol | Its other Programs' effects also apply at the adjacent location chosen on install (any owner's). | +| Persistent Infection | Enemy Avatars only; Virus Programs hit attackers. ⚠ | +| Infinite Loop | Your Avatar attacking from here may declare a second attack on another adjacent location. Both attacks come from here, even if the first one moved it. If it loses the first, the second is off. ⚠ | +| Stack Overflow | Counts Programs installed here, including Process Clone and Remote Access copies. | +| Race Condition | The attacker picks first, hidden from the defender. The +2 goes to the defending side. | +| Null Pointer | Automatic: the first enemy Execution targeting this location each turn does nothing. The card is still spent. | +| Stock Rice | "Hardware bonuses" are the Cores Hardware adds. ⚠ | +| Overflow Error | "Disable" lasts until re-enabled. | +| Undefined Behavior | The copy is yours, works on this location, and lasts until your next turn. ⚠ | +| Desynchronization | The once-per-turn Hardware abilities are Hot-Swap Bay and Quantum Coprocessor. | +| Visual Artifact | Once per installation, since "each turn" was removed from the card. ⚠ | +| Ghost Process | An Execution you play on this location may pick its Avatar, Program or Hardware at one adjacent location. | +| False Positive | Redirect to any other Avatar the Execution could legally hit at another location. | +| Latency Spike | "The first step" is the window before the roll. Abilities still work. | +| Hotfix | Only effects destroy Programs (Overflow Error); capture doesn't. | +| Error Correction | Removes one of: an Infection counter, a permanent counter, disabled Hardware, the latest penalty, Packet Flood, Disabled. | +| Garbage Collection | It can sacrifice itself. | +| Version Control | On capture, one Program goes back to your hand; on destruction, the destroyed Program does. | +| Compatibility Layer | +1 Program slot here; −2 RAM for Patch Programs installed here after it. | +| **Hardware** | | +| RAM Expansion | +2 Cores. | +| Overclocked CPU | After each combat, one of your Programs on the location it fought from is disabled through the end of the next turn. ⚠ | +| Solid-State Cache | −3 RAM for the first Program you install each turn on the location the wearer stands on. | +| Redundant Power Supply | The first time the wearer is defeated, all its Hardware stays on it, in its slot. ⚠ | +| Network Interface Upgrade | Takes no port and adds one, so the wearer nets +1 Expansion Slot. The card text should say so. If it leaves (Sabotage, Rollback), the wearer discards Hardware until it fits, newest first. ⚠ | +| Dedicated GPU | +1 to the number an Execution uses (cards drawn, Cores, RAM) when the Server the wearer stands on performs it. | +| ECC Memory | Opponents can't give the wearer Bug counters. "Bug status effects" are opponents' Bug Program effects on it (Memory Leak, Stock Rice). ⚠ | +| Cooling System | One other Hardware on the same Avatar gets two uses a turn of its once-per-turn or first-each-turn effect. | +| RAID Array | Half the combined printed RAM of its Hardware, rounded up. ⚠ | +| Firewall Appliance | Programs never target Avatars, so this taxes the first enemy Execution each turn that targets the wearer or its Hardware. | +| Hardware Sandbox | Pick the Program on install, and again at the start of your turn if the wearer has moved. It's protected only while the wearer stands with it. ⚠ | +| Diagnostic Module | At the start of your turn, look at your top card and you may put it on the bottom; then draw normally. ⚠ | +| Hot-Swap Bay | Swap Hardware on this Avatar, at any time, paying the difference in printed RAM (no refund). The result must fit the ports. ⚠ | +| Quantum Coprocessor | Works for Executions performed by the Server the wearer stands on. "Disable this Hardware" lasts until your next turn, as the card used to say. | +| **Executions** | | +| Execute: Disconnect | Moves to a location you control with room. An attacker can retreat to where it stands. If the last defender leaves, the attacker takes the location. ⚠ | +| Execute: Sabotage | "Disable" lasts until re-enabled. | +| Execute: Force Reboot | Clears every temporary effect on the Avatar. The Server it stands on can't perform Executions for the rest of the turn. | +| Execute: Fork | The copy is yours, works on the target location until end of turn, and doesn't count as installed. | +| Execute: Trace Route | Resolves right away, only while no combat is going on. Into your own location it's a move, into an unowned or undefended one a capture, into a defended one an attack with +1 Core from the location it left. It works in either player's command. | +| Execute: Rollback | Programs installed on the target this turn, or Hardware installed this turn on an Avatar there. | +| Execute: Packet Flood | Affected Avatars can't advance, attack, reposition or be moved, and moves they already declared fail. ⚠ | +| Execute: Emergency Shutdown | Nobody moves; Disabled Avatars still defend (see Terms). ⚠ | +| Execute: Process Clone | The second copy counts as installed. | +| Execute: Remote Access | The Program keeps its owner and works at both locations until end of turn. ⚠ | +| Execute: Purge | Removes Infection (permanent too), opponents' penalties, Packet Flood, Disabled, and disabled Hardware. | +| **Avatar Abilities** | | +| Carbon NanoBots (Replicate) | See Copies. Two NanoBots in a deck can have two copies. ⚠ | +| Pixelated Picture (Low Resolution) | Only while it defends: −1 Core for the attacker, that combat. ⚠ | +| Beta Version 1.0 (Push Update) | During a combat it's in, install a Hardware from hand (paying for it), ignoring ports. That Hardware is discarded at the end of your turn. | +| Data Leaker (Exfiltrate) | "Breached a Server this turn" = captured an enemy location this turn. | +| Broken Bits (Bit Flip) | Rerolls its dice showing a chosen number or less, which is always the best set to reroll. | + +--- + +## Open Questions + +None for the basic game. For the cards: + +1. **Bug counters** need cards that place them, and cards that punish having them (like Code Zero + and Recursive Infection do for Infection). +2. Card text to update for rulings already made: Network Interface Upgrade (+1 port), and the + typos Packet Accelerator "hen attacking" (when), Null Pointer "it's effect" (its), Push Update "If + there no ports" (there are), Memory Parasite "owners choosing" (owner's). +3. The other ⚠ readings above are smaller guesses. Say if any look wrong. + +## Simulation Watch List + +Things the first sim runs should measure: + +- **Salvage efficiency.** Salvage pays full printed value, so any card can pay for another card of + equal or lower cost. Does capture RAM matter? +- **Fight rate.** Undefended locations are free to take. With at most 4 Avatars and 10 locations + needed, is the game a land race with few fights? +- **Recapture farming.** Can players profit by trading the same location back and forth? +- **Firewall stalling.** Can a leading player wall off their side with Lv 3 Firewalls and stall the + game? Firewalls block everyone, and every line between the B and C rows (and C and D) has a + gateway, so four Lv 3 Firewalls can seal one half off. +- **Game length.** Deck is 45 cards, 7 of them in the opening hand, so 38 draws. Do games end before + decks run out? +- **First-player advantage.** With whole turns the first player won about 70% of sim games (with + bots that rush Avatar unlocks). Rounds of alternating commands in the snake order bring it to about + 50%. A plain alternating lead gave 49%, the first player always leading 51%. +- **Game length.** Commands make games longer: a median of 13 rounds (26 commands each), 90% within + 35 rounds. + +## Appendix: Combat Odds + +Exact chance that the attacker wins, by Core count, with ties rerolled. Rows are the attacker's +Cores, columns the defender's. + +| Atk \ Def | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | +|---|---|---|---|---|---|---|---|---| +| **1** | 50% | 10% | 1% | 0% | 0% | 0% | 0% | 0% | +| **2** | 90% | 50% | 16% | 4% | 1% | 0% | 0% | 0% | +| **3** | 99% | 84% | 50% | 21% | 6% | 2% | 0% | 0% | +| **4** | 100% | 96% | 79% | 50% | 23% | 9% | 3% | 1% | +| **5** | 100% | 99% | 94% | 77% | 50% | 26% | 11% | 4% | +| **6** | 100% | 100% | 98% | 91% | 74% | 50% | 28% | 13% | +| **7** | 100% | 100% | 100% | 97% | 89% | 72% | 50% | 29% | +| **8** | 100% | 100% | 100% | 99% | 96% | 87% | 71% | 50% | diff --git a/sim/README.md b/sim/README.md index 251a2aa..b33e10a 100644 --- a/sim/README.md +++ b/sim/README.md @@ -26,7 +26,8 @@ of how much a card helps. ## What's simulated -- **Rules:** everything in `rules.md`: setup, the turn steps, placement and advancing, attacks, +- **Rules:** everything in `rules.md`: setup, rounds of alternating commands (or whole turns, with + `--rule commands.on=false`), placement and advancing, attacks, combat with tie rerolls, captures, levels and RAM, Avatar unlocks, Firewalls, Salvage, response windows and chains, and the win condition. - **Every card:** all 83 cards in `../decks/files-deck-1/cards.csv` have a script, including Avatar @@ -60,9 +61,10 @@ fixed hooks: Core totals, costs, combat start, defeat, capture, draws, installs, ## Bots -- **greedy** plans each turn: grabs open locations, attacks at 60%+ odds, guards threatened - locations, installs Hardware and Programs where they help, walls off undefended locations, and - keeps RAM for tricks. On the opponent's turn it answers after the dice are rolled with whichever +- **greedy** plans each command: takes the best single advance or attack (open locations first, + rushing the ones that unlock Avatars; attacks at 60%+ odds), guards threatened locations, installs + Hardware and Programs where they help, walls off undefended locations, and keeps RAM for tricks. + With whole turns it plans every Avatar's move at once. On the opponent's commands it answers after the dice are rolled with whichever Execution or Ability most improves the combat, and tries to stop advances into its locations. - **nocards** is greedy but only uses Core Hardware, like the first version of the sim. - **bold / cautious / nowall / wall3** change one greedy setting each; **random** picks any legal diff --git a/sim/src/bots/eval.ts b/sim/src/bots/eval.ts index 04e8cd1..687f432 100644 --- a/sim/src/bots/eval.ts +++ b/sim/src/bots/eval.ts @@ -20,6 +20,14 @@ export function locationValue(v: GameState, p: PlayerId, loc: LocId): number { return LOCATION_POINTS + taken + v.rules.levelRam[levelFor(p, loc)] * RAM_POINTS; } +/** How many Avatars capturing `loc` would unlock for `p` (level unlocks only). */ +export function unlocksAt(v: GameState, p: PlayerId, loc: LocId): number { + if (v.rules.recruit.on || v.rules.buyAvatars.on || isStart(loc)) return 0; + const level = levelFor(p, loc); + if (level <= v.players[p].unlockedLevel) return 0; + return v.players[p].avatars.slice(0, Math.min(level, 4)).filter((a) => !a.faceUp).length; +} + /** What losing an Avatar costs: the tempo, plus its Hardware. */ export function avatarStake(v: GameState, r: AvatarRef): number { return LOSS_POINTS + hardwareOf(v, r).reduce((t, h) => t + (h < 0 ? 0 : defOf(v, h).ram), 0) * RAM_POINTS; diff --git a/sim/src/bots/greedy.ts b/sim/src/bots/greedy.ts index 931426e..ab7a830 100644 --- a/sim/src/bots/greedy.ts +++ b/sim/src/bots/greedy.ts @@ -8,10 +8,12 @@ import { firewallCost, hardwareCost, openWindow, + avatarForSale, programCost, + recruitSlots, } from '../engine.ts'; import { GRID, LINES_AT, LOCATIONS, otherEnd, type LocId } from '../map.ts'; -import { coresOf, hardwareActive, hasRoom, portsFree, programSlots, sources } from '../query.ts'; +import { avatarRoom, coresOf, hardwareActive, hasRoom, portsFree, programSlots, sources } from '../query.ts'; import { scriptOf } from '../scripts.ts'; import { avatar, @@ -19,6 +21,7 @@ import { controls, defendersAt, defOf, + freshCopy, hardwareOf, isCopy, isOpen, @@ -41,6 +44,7 @@ import { locationValue, printedRam, stakes, + unlocksAt, } from './eval.ts'; export interface GreedyParams { @@ -53,6 +57,8 @@ export interface GreedyParams { ramReserve: number; /** Play Programs, Executions and Abilities. Off plays like the Phase 2 bot: Core Hardware only. */ useCards: boolean; + /** Extra value of a capture per Avatar it unlocks (a location is worth about 12). 0 ignores unlocks. */ + unlockPoints: number; } export const DEFAULT_GREEDY: GreedyParams = { @@ -61,6 +67,7 @@ export const DEFAULT_GREEDY: GreedyParams = { maxFirewallsPerTurn: 2, ramReserve: 6, useCards: true, + unlockPoints: 15, }; /** @@ -108,6 +115,7 @@ const COMBAT_TRICKS = new Set([ /** How much the bot wants to keep a card rather than salvage it. Below 3 is fodder. */ function keepScore(v: GameState, id: number): number { const def = defOf(v, id); + if (def.kind === 'avatar') return recruitSlot(v, v.cards[id].owner, id) === null ? 1 : 7; if (def.kind === 'hardware') { if (hardwareCores(v, id) > 0) return 6; return (UTILITY_HARDWARE[def.name] ?? 0) * 2; @@ -139,7 +147,47 @@ function salvageFor(v: GameState, me: PlayerId, cost: number, except: number | n /** The card an action spends from hand, so Salvage doesn't use it. */ const spentCard = (a: Action): number | null => - a.type === 'play' || a.type === 'installHardware' || a.type === 'installProgram' ? a.card : null; + a.type === 'play' || a.type === 'installHardware' || a.type === 'installProgram' || a.type === 'recruit' ? a.card : null; + +// --------------------------------------------------------------------------------------------- +// Recruiting (recruit rule) + +/** + * Where the bot would recruit Avatar `id`: an empty slot while there's room, otherwise over a + * weaker Avatar (fewer Cores) that carries no Hardware, preferring one sitting in its slot. + * `taken` are slots already planned this step. + */ +function recruitSlot(v: GameState, me: PlayerId, id: number, taken: number[] = []): number | null { + if (!v.rules.recruit.on) return null; + const avs = v.players[me].avatars; + const cores = (card: number) => defOf(v, card).cores; + const empty = avs.findIndex((a, i) => i < 4 && a.card < 0 && !taken.includes(i + 1)); + const planned = taken.filter((slot) => avs[slot - 1].card < 0).length; + const inUse = avs.filter((a, i) => (i < 4 ? a.card >= 0 : a.at !== null)).length; + if (empty >= 0 && avatarRoom(v, me) && inUse + planned < 4) return empty + 1; + const weaker = recruitSlots(v, me) + .filter((slot) => !taken.includes(slot) && avs[slot - 1].card >= 0 && avs[slot - 1].hardware.length === 0) + .filter((slot) => cores(avs[slot - 1].card) < cores(id)) + .sort((a, b) => Number(avs[a - 1].at !== null) - Number(avs[b - 1].at !== null) || cores(avs[a - 1].card) - cores(avs[b - 1].card)); + return weaker[0] ?? null; +} + +/** Recruit the strongest Avatars in hand that fit, within `budget`. */ +function recruitPlan(v: GameState, me: PlayerId, budget: number): Action[] { + if (!v.rules.recruit.on) return []; + const hand = v.players[me].hand + .filter((id) => id >= 0 && defOf(v, id).kind === 'avatar') + .sort((a, b) => defOf(v, b).cores - defOf(v, a).cores); + const out: Extract[] = []; + for (const card of hand) { + const price = printedRam(v, card); + const slot = price <= budget ? recruitSlot(v, me, card, out.map((a) => a.slot)) : null; + if (slot === null) continue; + out.push({ type: 'recruit', card, slot }); + budget -= price; + } + return out; +} const reach = (v: GameState, me: PlayerId) => v.players[me].ram + v.players[me].hand.reduce((t, id) => t + printedRam(v, id), 0); @@ -210,7 +258,7 @@ function planTurn(v: GameState, me: PlayerId, params: GreedyParams): TurnPlan { for (const to of gridFrom(me)) { if (controls(v, me, to)) continue; const defended = defendersAt(v, to).length > 0; - const value = locationValue(v, me, to); + const value = locationValue(v, me, to) + params.unlockPoints * unlocksAt(v, me, to); for (const line of LINES_AT.get(to)!) { const from = otherEnd(line, to); if (!controls(v, me, from)) continue; @@ -220,6 +268,7 @@ function planTurn(v: GameState, me: PlayerId, params: GreedyParams): TurnPlan { const clear = level ? line.id : undefined; for (const { slot } of ready) { const ref = { player: me, slot }; + if (freshCopy(v, ref)) continue; if (!defended) { // Advancing needs no dice, so prefer weak Avatars and save strong ones for attacks. const weakness = 0.01 * coresOf(v, { ref, role: 'attack', at: null, loc: null, combat: null }); @@ -244,6 +293,7 @@ function planTurn(v: GameState, me: PlayerId, params: GreedyParams): TurnPlan { const clears = new Set(); for (const o of options) { if (o.score <= 0) break; + if (v.rules.commands.on && chosen.length > 0) break; // one advance or attack per command if (usedTargets.has(o.to)) continue; const n = uses.get(o.slot) ?? 0; if (n > 0) { @@ -606,19 +656,21 @@ const totalCost = (v: GameState, list: Action[]) => list.reduce((t, a) => t + ac function planPlay(v: GameState, me: PlayerId, params: GreedyParams, plan: TurnPlan | null): Action[] { const budget = spendable(v, me); const attackers = v.step === 'play' && plan?.turn === v.turn ? plan.attackers : new Set(); + const sale = avatarForSale(v, me); + const recruits = [...recruitPlan(v, me, budget), ...(sale && sale.price <= budget ? [{ type: 'buyAvatar', slot: sale.slot } as const] : [])]; if (v.step === 'play') { const early = params.useCards ? [...clearTheWay(v, me, plan), ...preAttackPlays(v, me, plan)] : []; - return [...early, ...hardwarePlan(v, me, attackers, budget - totalCost(v, early), params.useCards)]; + return [...recruits, ...early, ...hardwarePlan(v, me, attackers, budget - totalCost(v, [...recruits, ...early]), params.useCards)]; } const keep = heldReserve(v, me, params); - const hw = hardwarePlan(v, me, attackers, budget - keep, params.useCards); - let left = budget - keep - totalCost(v, hw); + const hw = hardwarePlan(v, me, attackers, budget - keep - totalCost(v, recruits), params.useCards); + let left = budget - keep - totalCost(v, [...recruits, ...hw]); const progs = params.useCards ? programPlan(v, me, left - params.ramReserve) : []; left -= totalCost(v, progs); const walls = firewallPlan(v, me, params, left); left -= totalCost(v, walls); const extra = params.useCards ? utilityPlays(v, me, left - params.ramReserve) : []; - return [...hw, ...progs, ...walls, ...extra]; + return [...recruits, ...hw, ...progs, ...walls, ...extra]; } // --------------------------------------------------------------------------------------------- diff --git a/sim/src/cards/avatars.ts b/sim/src/cards/avatars.ts index 02146fe..9084a18 100644 --- a/sim/src/cards/avatars.ts +++ b/sim/src/cards/avatars.ts @@ -5,7 +5,7 @@ */ import { createCopy, drawCards } from '../flow.ts'; import { LOCATIONS } from '../map.ts'; -import { costOf, hardwareActive, hasRoom, portsFree } from '../query.ts'; +import { canCopy, costOf, hardwareActive, hasRoom, portsFree } from '../query.ts'; import type { Script } from '../scripts.ts'; import { addMod, @@ -46,12 +46,12 @@ export const AVATARS: Record = { text: 'Avatar may create a copy of itself. Only one copy is allowed at a time. If the copy is defeated the original does not lose any hardware upgrades. If the original is defeated the replicate is as well.', ability: { uses(s, src) { - if (avatar(s, copyOf(src.ref!)).at !== null) return []; + if (avatar(s, copyOf(src.ref!)).at !== null || !canCopy(s, src.controller)) return []; return LOCATIONS.filter((l) => hasRoom(s, src.controller, l)).map((to) => ({ to })); }, resolve(s, item, src) { const to = item.args.to!; - if (avatar(s, copyOf(src.ref!)).at !== null || !hasRoom(s, src.controller, to)) return; + if (avatar(s, copyOf(src.ref!)).at !== null || !canCopy(s, src.controller) || !hasRoom(s, src.controller, to)) return; fired(s, 'Carbon NanoBots', src.controller); createCopy(s, src.ref!, to); }, @@ -111,8 +111,8 @@ export const AVATARS: Record = { }, 'Code Zero': { - text: 'Place an Infection counter on every enemy Avatar in combat at this Server. While this Avatar is in play, an Avatar with 2+ Infection counters has -1 Core.', - globalCores: (s, f) => (infectionOf(avatar(s, f.ref)) >= 2 ? -1 : 0), + text: 'Place an Infection counter on every enemy Avatar in combat at this Server. While this Avatar is in play, an Avatar with 1+ Infection counters has -1 Core.', + globalCores: (s, f) => (infectionOf(avatar(s, f.ref)) >= 1 ? -1 : 0), ability: { uses: (s, src) => (opponentsInCombat(s, src.ref!).length ? [{}] : []), resolve(s, _item, src) { diff --git a/sim/src/cards/servers.ts b/sim/src/cards/servers.ts index 00769da..2677b47 100644 --- a/sim/src/cards/servers.ts +++ b/sim/src/cards/servers.ts @@ -4,7 +4,7 @@ */ import { createCopy, drawNow } from '../flow.ts'; import { LINE_BY_ID } from '../map.ts'; -import { hasRoom, sameSource, sourcesNamed } from '../query.ts'; +import { canCopy, hasRoom, sameSource, sourcesNamed } from '../query.ts'; import type { Fighter, Script } from '../scripts.ts'; import { ask, @@ -48,6 +48,7 @@ export const SERVERS: Record = { ability: { uses(s, src) { const p = src.controller; + if (!canCopy(s, p)) return []; const spots = LOCATIONS.filter((l) => hasRoom(s, p, l)); return refsInPlay(s, p) .filter((r) => !isCopy(r) && avatar(s, r).at === src.at && avatar(s, copyOf(r)).at === null) @@ -56,7 +57,7 @@ export const SERVERS: Record = { resolve(s, item) { const r = item.args.ref!; const to = item.args.to!; - if (avatar(s, r).at === null || avatar(s, copyOf(r)).at !== null || !hasRoom(s, r.player, to)) return; + if (avatar(s, r).at === null || avatar(s, copyOf(r)).at !== null || !canCopy(s, r.player) || !hasRoom(s, r.player, to)) return; fired(s, 'Backup Server', r.player); createCopy(s, r, to); }, diff --git a/sim/src/cli.ts b/sim/src/cli.ts index 696e5ec..630a5b6 100644 --- a/sim/src/cli.ts +++ b/sim/src/cli.ts @@ -29,12 +29,17 @@ const USAGE = `Files TCG simulator --seed N first game's seed; game i uses seed + i (default 1) --south BOT South's bot (default greedy) --north BOT North's bot (default greedy) - --max-turns N player turns before a draw (default ${DEFAULT_RULES.maxTurns}) + --max-turns N rounds × 2 before a draw (default ${DEFAULT_RULES.maxTurns}, i.e. ${DEFAULT_RULES.maxTurns / 2} rounds) --rule K=V change a rule in src/rules.ts; repeatable. Examples: winLocations=9, - levelRam=4,4,6,8,10, startingAvatars=4, firstTurn.advance=false, + levelRam=4,4,6,8,10, startingAvatars=4, firstTurn.draw=true, firstTurn.advance=false, firstTurn.captureRam=false, firstTurn.unlock=false, firstTurn.cards=false, - secondPlayer.ram=4, secondPlayer.avatars=1, secondPlayer.cards=2, - secondPlayer.locations=1 + secondPlayer.ram=4, secondPlayer.avatars=1, secondPlayer.cards=2, secondPlayer.firstDraw=1, + secondPlayer.locations=1, drawPerTurn=2, deck.main=60, + recruit.on=true (Avatars in the deck; also recruit.avatarsInDeck=5, recruit.price=8), + buyAvatars.on=true (buy Avatars 2-4 instead of unlocking; buyAvatars.prices=8,12,16), + copies.waitATurn=true, copies.needAvatar2=true, copies.allowed=false, + commands.on=false (whole turns instead of rounds of commands), + commands.perPlayer=3, commands.leads=F|FS|FFSS|thue, commands.snake=false --log play one game and print the play-by-play --check check rule invariants after every action (slow) --json FILE also write the summary and every game's result as JSON diff --git a/sim/src/deck.ts b/sim/src/deck.ts index d0bc697..c36c88b 100644 --- a/sim/src/deck.ts +++ b/sim/src/deck.ts @@ -1,11 +1,11 @@ import type { CardDef, CardKind, CardPool } from './cards.ts'; import { shuffle, type Rng } from './rng.ts'; -import type { RulesConfig } from './rules.ts'; +import { avatarsOutside, type RulesConfig } from './rules.ts'; export interface DeckList { avatars: string[]; servers: string[]; - /** Executions, Hardware and Programs. */ + /** Executions, Hardware and Programs (and Avatars, when recruiting). */ main: string[]; } @@ -22,9 +22,9 @@ export function validateDeck(pool: CardPool, deck: DeckList, rules: RulesConfig) else if (!kinds.includes(card.kind)) errors.push(`${label}: "${name}" is a ${card.kind}`); } }; - part('Avatars', deck.avatars, ['avatar'], rules.deck.avatars); + part('Avatars', deck.avatars, ['avatar'], avatarsOutside(rules)); part('Servers', deck.servers, ['server'], rules.deck.servers); - part('Deck', deck.main, MAIN_KINDS, rules.deck.main); + part('Deck', deck.main, rules.recruit.on ? [...MAIN_KINDS, 'avatar'] : MAIN_KINDS, rules.deck.main); const copies = new Map(); for (const name of [...deck.avatars, ...deck.servers, ...deck.main]) { copies.set(name, (copies.get(name) ?? 0) + 1); @@ -49,6 +49,12 @@ export function randomDeck( if (names.length < size) throw new Error(`Not enough ${kinds.join('/')} cards for a deck`); return shuffle(rng, names).slice(0, size); }; + if (rules.recruit.on) { + const k = rules.recruit.avatarsInDeck; + const avatars = sample(['avatar'], 1 + k); + const servers = sample(['server'], rules.deck.servers); + return { avatars: avatars.slice(0, 1), servers, main: shuffle(rng, [...avatars.slice(1), ...sample(MAIN_KINDS, rules.deck.main - k)]) }; + } return { avatars: sample(['avatar'], rules.deck.avatars), servers: sample(['server'], rules.deck.servers), diff --git a/sim/src/engine.ts b/sim/src/engine.ts index c2d7446..3071ab0 100644 --- a/sim/src/engine.ts +++ b/sim/src/engine.ts @@ -6,6 +6,7 @@ */ import type { CardPool } from './cards.ts'; import { validateDeck, type DeckList } from './deck.ts'; +import type { CardDef } from './cards.ts'; import { captureHooks, captureMain, @@ -14,9 +15,11 @@ import { drawNow, drawTask, resolveDeclaration, + retireAvatar, } from './flow.ts'; import { GRID, LINES, LINES_AT, LINE_BY_ID, LOCATIONS, START_LOC, isStart, otherEnd, type LocId } from './map.ts'; import { + avatarRoom, costOf, coresOf, desynced, @@ -44,10 +47,14 @@ import { endOf, firewallCost, gridCount, + commanderOf, + firstCommand, + freshCopy, isCopy, isOpen, markUsed, nameOf, + originalOf, other, fired, played, @@ -55,6 +62,7 @@ import { pushTasks, refsInPlay, removeFrom, + roundOf, running, say, startOf, @@ -114,6 +122,32 @@ function newStats(): GameStats { return Object.fromEntries(STAT_KEYS.map((k) => [k, [0, 0]])) as GameStats; } +/** Recruit rule: an Avatar's printed RAM is its price, which is also what it salvages for. */ +function withPrice(def: CardDef, rules: RulesConfig): CardDef { + if (!rules.recruit.on || def.kind !== 'avatar') return def; + return { ...def, ram: rules.recruit.price + rules.recruit.pricePerCore * def.cores }; +} + +/** Recruit rule: slots `p` can recruit into. The first empty one while there's room, or any Avatar to retire. */ +export function recruitSlots(s: GameState, p: PlayerId): number[] { + const avs = s.players[p].avatars.slice(0, 4); + const out: number[] = []; + const empty = avs.findIndex((a) => a.card < 0); + if (empty >= 0 && avatarRoom(s, p)) out.push(empty + 1); + avs.forEach((a, i) => { + const declared = s.declarations.some((d) => d.ref.player === p && originalOf(d.ref).slot === i + 1); + if (a.card >= 0 && !declared) out.push(i + 1); + }); + return out; +} + +/** Buy-Avatars rule: the next Avatar `p` can buy (its slot) and its price, or null. */ +export function avatarForSale(s: GameState, p: PlayerId): { slot: number; price: number } | null { + if (!s.rules.buyAvatars.on) return null; + const i = s.players[p].avatars.slice(0, 4).findIndex((a) => !a.faceUp); + return i < 1 ? null : { slot: i + 1, price: s.rules.buyAvatars.prices[i - 1] }; +} + function newAvatar(card: number, faceUp: boolean, copyOf: number | null): AvatarState { return { card, @@ -131,6 +165,8 @@ function newAvatar(card: number, faceUp: boolean, copyOf: number | null): Avatar rootedUntil: 0, breachedTurn: 0, copyOf, + createdTurn: 0, + unlockedTurn: 0, }; } @@ -171,13 +207,15 @@ export function createGame({ pool, decks, seed, rules = DEFAULT_RULES, log = fal log: log ? [] : null, }; const add = (name: string, owner: PlayerId): number => { - s.defs[name] = pool.byName.get(name)!; + s.defs[name] = withPrice(pool.byName.get(name)!, rules); s.cards.push({ id: s.cards.length, name, owner, disabledUntil: 0, ignoredUntil: 0, installedTurn: 0 }); return s.cards.length - 1; }; for (const p of [0, 1] as const) { const deck = decks[p]; + // Recruit rule: slots after the starting Avatar begin empty (-1). const avatars = shuffle(rng, deck.avatars.map((n) => add(n, p))); + const slots = [0, 1, 2, 3].map((i) => avatars[i] ?? -1); s.players.push({ ram: 0, hand: [], @@ -185,8 +223,8 @@ export function createGame({ pool, decks, seed, rules = DEFAULT_RULES, log = fal discard: [], serverPile: shuffle(rng, deck.servers.map((n) => add(n, p))), avatars: [ - ...avatars.map((card, i) => newAvatar(card, i < rules.startingAvatars, null)), - ...avatars.map((card, i) => newAvatar(card, false, i + 1)), + ...slots.map((card, i) => newAvatar(card, card >= 0 && i < rules.startingAvatars, null)), + ...slots.map((card, i) => newAvatar(card, false, i + 1)), ], unlockedLevel: 1, }); @@ -207,7 +245,7 @@ export function createGame({ pool, decks, seed, rules = DEFAULT_RULES, log = fal const p2 = other(s.firstPlayer); const second = s.players[p2]; second.ram += rules.secondPlayer.ram; - second.avatars.slice(0, rules.startingAvatars + rules.secondPlayer.avatars).forEach((av) => (av.faceUp = true)); + second.avatars.slice(0, rules.startingAvatars + rules.secondPlayer.avatars).forEach((av) => (av.faceUp = av.card >= 0)); for (let i = 0; i < rules.secondPlayer.cards; i++) drawNow(s, p2); if (rules.secondPlayer.locations > 0) { // The location next to the starting Server, with a Server from the pile: no RAM, no unlock. @@ -219,13 +257,14 @@ export function createGame({ pool, decks, seed, rules = DEFAULT_RULES, log = fal } s.stats.cardsDrawn = [0, 0]; say(s, `${playerName(s.firstPlayer)} goes first.`); - beginTurn(s, true); + beginTurn(s, !rules.firstTurn.draw); run(s); return s; } function beginTurn(s: GameState, skipDraw: boolean): void { - if (s.turn >= s.rules.maxTurns) { + const cmd = s.rules.commands.on; + if (s.turn >= s.rules.maxTurns * (cmd ? s.rules.commands.perPlayer : 1)) { s.over = true; s.endReason = 'turnLimit'; say(s, `Turn limit reached: draw (South ${gridCount(s, 0)}, North ${gridCount(s, 1)} locations).`); @@ -233,21 +272,34 @@ function beginTurn(s: GameState, skipDraw: boolean): void { } s.turn++; s.clock = startOf(s.turn); - s.used = {}; + // Command rule: a player's turn is their commands in a round, so its refreshes come at the first. + const fresh = !cmd || firstCommand(s, s.turn); + if (!cmd || roundOf(s, s.turn) !== roundOf(s, s.turn - 1)) s.used = {}; tidy(s); const me = s.players[s.active]; - for (const av of me.avatars) { - av.placed = false; - av.advanced = false; - av.attacks = 0; + if (fresh) { + for (const av of me.avatars) { + av.placed = false; + av.advanced = false; + av.attacks = 0; + } } s.declarations = []; s.step = 'deploy'; - say(s, `\n— Turn ${s.turn}: ${playerName(s.active)} (${me.ram} RAM, ${me.hand.length} cards, ${gridCount(s, s.active)} locations) —`); - if (!skipDraw) pushTasks(s, { t: 'draw', player: s.active }); - emit(s, 'onTurnStart', null); + const title = cmd ? `Round ${roundOf(s, s.turn)}, command ${s.turn}` : `Turn ${s.turn}`; + say(s, `\n— ${title}: ${playerName(s.active)} (${me.ram} RAM, ${me.hand.length} cards, ${gridCount(s, s.active)} locations) —`); + const draws = s.rules.drawPerTurn + (s.turn === 2 ? s.rules.secondPlayer.firstDraw : 0); + if (fresh && !skipDraw) pushTasks(s, ...Array.from({ length: draws }, (): Task => ({ t: 'draw', player: s.active }))); + if (fresh) emit(s, 'onTurnStart', null); } +/** Command rule: this game turn's command is spent (an advance or attack is declared). */ +const commandSpent = (s: GameState): boolean => s.rules.commands.on && s.declarations.length > 0; + +/** Command rule: an Avatar unlocked this round waits in its slot until the next round. */ +const waitsForRound = (s: GameState, av: AvatarState): boolean => + s.rules.commands.on && av.at === null && av.unlockedTurn > 0 && roundOf(s, av.unlockedTurn) === roundOf(s, s.turn); + function endTurn(s: GameState): void { s.clock = endOf(s.turn); // Push Update: the extra Hardware leaves at the end of its controller's turn. @@ -264,7 +316,7 @@ function endTurn(s: GameState): void { } } tidy(s); - s.active = other(s.active); + s.active = s.rules.commands.on ? commanderOf(s, s.turn + 1) : other(s.active); beginTurn(s, false); } @@ -321,7 +373,7 @@ export function maxAttacks(s: GameState, ref: AvatarRef): number { export function attackTargets(s: GameState, ref: AvatarRef): LocId[] { const av = avatar(s, ref); - if (!av.faceUp || av.at === null || av.advanced || av.attacks >= maxAttacks(s, ref) || !canAct(s, ref)) return []; + if (!av.faceUp || av.at === null || av.advanced || av.attacks >= maxAttacks(s, ref) || !canAct(s, ref) || freshCopy(s, ref)) return []; const opp = other(ref.player); return LINES_AT.get(av.at)! .filter((line) => isOpen(s, line)) @@ -507,14 +559,15 @@ export function legalActions(s: GameState): Action[] { const ref = { player: p, slot: i + 1 }; if (!av.faceUp || av.advanced || av.attacks > 0) return; if (av.at !== null && !canAct(s, ref)) return; - if (placementOpen && !av.placed) { + if (placementOpen && !av.placed && !waitsForRound(s, av)) { for (const to of LOCATIONS) if (to !== av.at && hasRoom(s, p, to)) out.push({ type: 'place', slot: i + 1, to }); } - if (av.at !== null) for (const to of targets) out.push({ type: 'advance', slot: i + 1, to }); + if (av.at !== null && !freshCopy(s, ref) && !commandSpent(s)) for (const to of targets) out.push({ type: 'advance', slot: i + 1, to }); }); pushClears(s, p, out); } else if (s.step === 'attack') { me.avatars.forEach((_, i) => { + if (commandSpent(s)) return; for (const to of attackTargets(s, { player: p, slot: i + 1 })) out.push({ type: 'attack', slot: i + 1, to }); }); pushClears(s, p, out); @@ -531,6 +584,8 @@ export function legalActions(s: GameState): Action[] { out.push({ type: 'installHardware', card, slot: ref.slot }); } } + } else if (def.kind === 'avatar' && s.rules.recruit.on) { + if (def.ram <= me.ram) for (const slot of recruitSlots(s, p)) out.push({ type: 'recruit', card, slot }); } else if (def.kind === 'program') { for (const at of LOCATIONS) { if (controls(s, p, at) && s.locations[at].programs.length < programSlots(s, at) && programCost(s, p, card, at, all) <= me.ram) { @@ -539,6 +594,8 @@ export function legalActions(s: GameState): Action[] { } } } + const sale = avatarForSale(s, p); + if (sale && sale.price <= me.ram) out.push({ type: 'buyAvatar', slot: sale.slot }); for (const line of LINES) { if (!line.gateway || !(controls(s, p, line.a) || controls(s, p, line.b))) continue; for (let level = (s.firewalls[line.id] ?? 0) + 1; level <= s.rules.firewallCost.length; level++) { @@ -560,6 +617,10 @@ export function actionCost(s: GameState, a: Action): number { return firewallCost(s, s.firewalls[a.line] ?? 0); case 'installHardware': return hardwareCost(s, a.card, { player: p, slot: a.slot }); + case 'recruit': + return defOf(s, a.card).ram; + case 'buyAvatar': + return avatarForSale(s, p)?.price ?? 0; case 'installProgram': return programCost(s, p, a.card, a.at); case 'play': @@ -598,6 +659,10 @@ export function actionKey(a: Action): string { return `salvage:${a.card}`; case 'installHardware': return `hw:${a.card}:${a.slot}`; + case 'recruit': + return `recruit:${a.card}:${a.slot}`; + case 'buyAvatar': + return `buy:${a.slot}`; case 'installProgram': return `prog:${a.card}:${a.at}`; case 'play': @@ -653,6 +718,30 @@ export function applyAction(s: GameState, a: Action, legal: Action[] = legalActi fn(s, ch.resume.data, option.value); break; } + case 'buyAvatar': { + const { price } = avatarForSale(s, p)!; + const av = me.avatars[a.slot - 1]; + me.ram -= price; + stat(s, 'ramOnAvatars', p, price); + stat(s, 'avatarsBought', p); + av.faceUp = true; + say(s, `${who} buys Avatar ${a.slot}: ${nameOf(s, av.card)} (-${price} RAM, now ${me.ram}).`); + break; + } + case 'recruit': { + const cost = defOf(s, a.card).ram; + const av = me.avatars[a.slot - 1]; + if (av.card >= 0) retireAvatar(s, ref(a.slot)); + removeFrom(me.hand, a.card); + me.ram -= cost; + stat(s, 'ramOnCards', p, cost); + stat(s, 'avatarsRecruited', p); + played(s, nameOf(s, a.card), p); + Object.assign(av, newAvatar(a.card, true, null)); + me.avatars[a.slot + 3].card = a.card; + say(s, `${who} recruits ${nameOf(s, a.card)} as Avatar ${a.slot} (-${cost} RAM, now ${me.ram}).`); + break; + } case 'salvage': { const gain = defOf(s, a.card).ram; removeFrom(me.hand, a.card); diff --git a/sim/src/flow.ts b/sim/src/flow.ts index c4d4899..619b233 100644 --- a/sim/src/flow.ts +++ b/sim/src/flow.ts @@ -82,6 +82,18 @@ export function removeCopy(s: GameState, ref: AvatarRef): void { dropFromCombat(s, ref); } +/** Recruit rule: an Avatar recruited over leaves for the discard pile with its Hardware, and its copy leaves play. */ +export function retireAvatar(s: GameState, ref: AvatarRef): void { + const av = avatar(s, ref); + removeCopy(s, copyOf(ref)); + if (av.hardware.length) stat(s, 'hardwareLost', ref.player, av.hardware.length); + for (const hw of av.hardware) toDiscard(s, hw); + say(s, `${playerName(ref.player)} retires ${avatarName(s, ref)}${av.at ? ` from ${av.at}` : ''}.`); + dropFromCombat(s, ref); + toDiscard(s, av.card); + stat(s, 'avatarsRetired', ref.player); +} + /** * The loser of a combat goes back to its slot. Its Hardware is discarded unless `keepHardware`, * and its counters and effects are removed (Persistent Infection's counters stay). @@ -125,6 +137,7 @@ export function createCopy(s: GameState, original: AvatarRef, to: LocId): void { disabledUntil: 0, rootedUntil: 0, breachedTurn: 0, + createdTurn: s.turn, } satisfies Partial); say(s, `${playerName(ref.player)} creates ${avatarName(s, ref)} on ${to}.`); } @@ -382,11 +395,13 @@ export function captureMain(s: GameState, ref: AvatarRef, loc: LocId, how: Captu const from = previous === null ? '' : ` from ${playerName(previous)}`; say(s, `${playerName(p)} captures ${loc}${from} (Lv ${level}) with ${L.server === null ? 'no Server' : nameOf(s, L.server)}: +${ram} RAM (now ${me.ram}).`); - if (level > me.unlockedLevel && turn1?.unlock !== false) { + const unlocks = !s.rules.recruit.on && !s.rules.buyAvatars.on; + if (unlocks && level > me.unlockedLevel && turn1?.unlock !== false) { me.unlockedLevel = level; me.avatars.slice(0, 4).forEach((av, i) => { if (i < level && !av.faceUp) { av.faceUp = true; + av.unlockedTurn = s.turn; say(s, `${playerName(p)} unlocks Avatar ${i + 1}: ${nameOf(s, av.card)}.`); } }); diff --git a/sim/src/invariants.ts b/sim/src/invariants.ts index 7780eb6..a6df6e1 100644 --- a/sim/src/invariants.ts +++ b/sim/src/invariants.ts @@ -31,10 +31,11 @@ export function checkInvariants(s: GameState): string[] { const slot = i + 1; const copy = slot > 4; if (!copy) { - own([av.card], `avatar${slot}`); + if (av.card >= 0 || !s.rules.recruit.on) own([av.card], `avatar${slot}`); + else if (av.at !== null || av.hardware.length) errors.push(`p${p} empty slot ${slot} is in use`); own(av.hardware, `avatar${slot}.hardware`); const ported = av.hardware.filter((h) => !scriptOf(s.cards[h].name)?.noPort && s.cards[h].pushedUntil === undefined); - if (ported.length > portsTotal(s, { player: p as 0 | 1, slot })) errors.push(`p${p} Avatar ${slot} is over its slots`); + if (av.card >= 0 && ported.length > portsTotal(s, { player: p as 0 | 1, slot })) errors.push(`p${p} Avatar ${slot} is over its slots`); } else { if (av.hardware.length) errors.push(`p${p} copy ${slot - 4} has Hardware of its own`); if (av.at !== null && pl.avatars[i - 4].at === null) errors.push(`p${p} copy ${slot - 4} is in play without its original`); @@ -46,6 +47,8 @@ export function checkInvariants(s: GameState): string[] { count.set(av.at, (count.get(av.at) ?? 0) + 1); }); for (const [loc, n] of count) if (n > capacity(s, loc)) errors.push(`p${p} has ${n} Avatars on ${loc}`); + const total = pl.avatars.filter((av, i) => (i < 4 ? av.card >= 0 : av.at !== null)).length; + if (s.rules.recruit.on && total > 4) errors.push(`p${p} has ${total} Avatars, counting copies`); }); for (const loc of LOCATIONS) { diff --git a/sim/src/query.ts b/sim/src/query.ts index b3fab07..5472092 100644 --- a/sim/src/query.ts +++ b/sim/src/query.ts @@ -24,6 +24,19 @@ export const programActive = (s: GameState, id: number): boolean => !running(s, s.cards[id].disabledUntil) && !running(s, s.cards[id].ignoredUntil); export const hardwareActive = (s: GameState, id: number): boolean => !running(s, s.cards[id].disabledUntil); +/** Recruit rule: `p` has fewer than 4 Avatars, counting copies. Always true without the rule. */ +export function avatarRoom(s: GameState, p: PlayerId): boolean { + if (!s.rules.recruit.on) return true; + const avs = s.players[p].avatars; + return avs.slice(0, 4).filter((a) => a.card >= 0).length + avs.slice(4).filter((a) => a.at !== null).length < 4; +} + +/** Whether `p` may make a copy now: the copy-rule switches, and room under the recruit rule. */ +export function canCopy(s: GameState, p: PlayerId): boolean { + const c = s.rules.copies; + return c.allowed && (!c.needAvatar2 || s.players[p].avatars[1].faceUp) && avatarRoom(s, p); +} + /** Everything with an effect in play right now. */ export function sources(s: GameState): Source[] { const out: Source[] = []; diff --git a/sim/src/rules.ts b/sim/src/rules.ts index 499e701..9e3a45f 100644 --- a/sim/src/rules.ts +++ b/sim/src/rules.ts @@ -5,6 +5,8 @@ export interface RulesConfig { startingRam: number; openingHand: number; + /** Cards drawn in each turn's draw step. */ + drawPerTurn: number; /** Grid locations needed to win (starting Servers don't count). */ winLocations: number; /** Player turns before the game is called a draw. */ @@ -17,8 +19,9 @@ export interface RulesConfig { deck: { avatars: number; servers: number; main: number; maxCopies: number }; /** Avatars face up at the start (rules: Avatar 1 only). */ startingAvatars: number; - /** What the first player may do on turn 1 (the rules allow everything). */ + /** What the first player may do on turn 1 (the rules skip the draw and allow the rest). */ firstTurn: { + draw: boolean; advance: boolean; /** Captures pay capture RAM. A Server card's own RAM bonus is still paid. */ captureRam: boolean; @@ -29,25 +32,65 @@ export interface RulesConfig { }; /** * Catch-up for whoever goes second: extra starting RAM, extra Avatars face up, extra cards in the - * opening hand, and (0 or 1) owning the location next to their starting Server at the start. + * opening hand, extra cards in their first draw step, and (0 or 1) owning the location next to + * their starting Server at the start. */ - secondPlayer: { ram: number; avatars: number; cards: number; locations: number }; + secondPlayer: { ram: number; avatars: number; cards: number; firstDraw: number; locations: number }; + /** + * Prototype: Avatars in the deck instead of level unlocks. You start with one Avatar; another + * `avatarsInDeck` are shuffled into the main deck (inside its size). On your turn (steps 3 and 6) + * pay an Avatar's price to recruit it from hand into an empty slot, or retire one of yours + * (discarding it and its Hardware) to recruit into its slot. At most 4 Avatars, copies included. + * Price = `price` + `pricePerCore` × Cores; it's also the card's salvage value. + */ + recruit: { on: boolean; avatarsInDeck: number; price: number; pricePerCore: number }; + /** + * Prototype: buy Avatars instead of level unlocks. On your turn (steps 3 and 6) pay RAM to flip + * your next face-down Avatar; `prices` are for Avatars 2, 3 and 4. + */ + buyAvatars: { on: boolean; prices: number[] }; + /** + * Copies (Carbon NanoBots' Replicate, Backup Server), for testing: whether they can be made at + * all; whether a new copy must wait for its owner's next turn to advance or attack (it can + * defend); whether making one needs Avatar 2 unlocked. + */ + copies: { allowed: boolean; waitATurn: boolean; needAvatar2: boolean }; + /** + * Rounds of alternating commands (the rules since v0.8; off = the old one-turn-each structure). + * Each round both players get `perPlayer` commands, taken in turn. A command is one advance or one attack (or a pass), + * with placement and cards before it and cards after it. A player's "turn" is their commands in + * a round: the draw, turn-start effects and each Avatar's one action a round refresh at their + * first command; once-per-turn effects become once per round. Avatars unlocked during a round + * enter play from the next round. + * `leads` says who takes a round's first command, round after round (F = first player, S = + * second; the pattern repeats; "thue" is the Thue–Morse order F S S F S F F S…). `snake` orders + * a round's commands A B B A instead of A B A B. + */ + commands: { on: boolean; perPlayer: number; leads: string; snake: boolean }; } export const DEFAULT_RULES: RulesConfig = { startingRam: 4, openingHand: 7, + drawPerTurn: 1, winLocations: 10, maxTurns: 200, levelRam: { 1: 4, 2: 4, 3: 4, 4: 4, 5: 4 }, firewallCost: [2, 4, 8], maxProgramsPerLocation: 2, - deck: { avatars: 4, servers: 20, main: 30, maxCopies: 2 }, + deck: { avatars: 4, servers: 20, main: 45, maxCopies: 2 }, startingAvatars: 1, - firstTurn: { advance: true, captureRam: true, unlock: true, cards: true }, - secondPlayer: { ram: 0, avatars: 0, cards: 0, locations: 0 }, + firstTurn: { draw: false, advance: true, captureRam: true, unlock: true, cards: true }, + secondPlayer: { ram: 0, avatars: 0, cards: 0, firstDraw: 0, locations: 0 }, + recruit: { on: false, avatarsInDeck: 3, price: 6, pricePerCore: 0 }, + buyAvatars: { on: false, prices: [8, 12, 16] }, + copies: { allowed: true, waitATurn: false, needAvatar2: false }, + commands: { on: true, perPlayer: 2, leads: 'FS', snake: true }, }; +/** Avatars kept outside the main deck: all of them, or just the starting one when recruiting. */ +export const avatarsOutside = (rules: RulesConfig): number => (rules.recruit.on ? 1 : rules.deck.avatars); + /** * A copy of `rules` with one setting changed, from text like "winLocations=9", * "secondPlayer.ram=4", "firstTurn.advance=false" or "levelRam=4,4,4,4,4" (Lv 1 to 5). @@ -71,6 +114,7 @@ export function withRule(rules: RulesConfig, spec: string): RulesConfig { return n; }; if (typeof old === 'number') obj[last] = num(raw); + else if (typeof old === 'string') obj[last] = raw; else if (typeof old === 'boolean') { if (raw !== 'true' && raw !== 'false') throw new Error(`Rule "${key}" needs true or false`); obj[last] = raw === 'true'; diff --git a/sim/src/state.ts b/sim/src/state.ts index c181801..1935911 100644 --- a/sim/src/state.ts +++ b/sim/src/state.ts @@ -56,8 +56,39 @@ export const fired = (s: GameState, name: string, p: PlayerId): void => void use export const endOfTurn = (s: GameState): Clock => 2 * s.turn + 1; export const startOf = (turn: number): Clock => 2 * turn; export const endOf = (turn: number): Clock => 2 * turn + 1; -/** The turn number of `p`'s next turn (not the current one). */ -export const nextTurnOf = (s: GameState, p: PlayerId): number => (s.active === p ? s.turn + 2 : s.turn + 1); +/** The turn number of `p`'s next turn (not the current one). Under the command rule, their next command. */ +export function nextTurnOf(s: GameState, p: PlayerId): number { + if (!s.rules.commands.on) return s.active === p ? s.turn + 2 : s.turn + 1; + let t = s.turn + 1; + while (commanderOf(s, t) !== p) t++; + return t; +} + +// Command rule: game turns are commands. A round is 2 × perPlayer of them, alternating players, +// and the lead alternates by round. +const commandsPerRound = (s: GameState): number => 2 * s.rules.commands.perPlayer; + +/** Command rule: who takes game turn `turn`. */ +export function commanderOf(s: GameState, turn: number): PlayerId { + const { leads, snake } = s.rules.commands; + const round = Math.floor((turn - 1) / commandsPerRound(s)); + const i = (turn - 1) % commandsPerRound(s); + const ones = round.toString(2).split('1').length - 1; + const mark = leads === 'thue' ? 'FS'[ones % 2] : leads[round % leads.length]; + if (mark !== 'F' && mark !== 'S') throw new Error(`commands.leads should use F and S, or be "thue": "${leads}"`); + const lead = mark === 'F' ? s.firstPlayer : other(s.firstPlayer); + const leadsThis = snake ? i % 4 === 0 || i % 4 === 3 : i % 2 === 0; + return leadsThis ? lead : other(lead); +} + +/** Command rule: the round game turn `turn` belongs to, from 1. */ +export const roundOf = (s: GameState, turn: number): number => Math.floor((turn - 1) / commandsPerRound(s)) + 1; + +/** Command rule: whether `turn` is its commander's first command of the round. */ +export const firstCommand = (s: GameState, turn: number): boolean => (turn - 1) % commandsPerRound(s) < 2; + +/** Rounds played so far: both players taking a turn (or all their commands). */ +export const roundsPlayed = (s: GameState): number => (s.rules.commands.on ? roundOf(s, s.turn) : Math.ceil(s.turn / 2)); export const running = (s: GameState, until: Clock): boolean => until > s.clock; /** Once-per-turn bookkeeping. Returns how many times `key` was used this turn. */ @@ -116,6 +147,10 @@ export function wearerOf(s: GameState, hw: number): AvatarRef | null { export const isRooted = (s: GameState, r: AvatarRef): boolean => running(s, avatar(s, r).rootedUntil); export const isDisabledAvatar = (s: GameState, r: AvatarRef): boolean => running(s, avatar(s, r).disabledUntil); /** Can act: advance, attack, move, use its Ability. */ +/** Copy-rule variant: a copy made this player-turn can't advance or attack yet. It can still defend. */ +export const freshCopy = (s: GameState, r: AvatarRef): boolean => + isCopy(r) && s.rules.copies.waitATurn && avatar(s, r).createdTurn === s.turn; + export const canAct = (s: GameState, r: AvatarRef): boolean => inPlay(s, r) && !isRooted(s, r) && !isDisabledAvatar(s, r); diff --git a/sim/src/stats.ts b/sim/src/stats.ts index 9678eb0..cb1de6d 100644 --- a/sim/src/stats.ts +++ b/sim/src/stats.ts @@ -1,5 +1,6 @@ import type { CardPool } from './cards.ts'; import { gridCount } from './engine.ts'; +import { roundsPlayed } from './state.ts'; import { STAT_KEYS, type CardUse, type GameState, type StatKey } from './types.ts'; export interface GameRecord { @@ -7,6 +8,7 @@ export interface GameRecord { winner: 0 | 1 | null; firstPlayer: 0 | 1; turns: number; + rounds: number; locations: [number, number]; stats: Record; cardUse: Record; @@ -31,6 +33,7 @@ export function recordOf(seed: number, s: GameState): GameRecord { winner: s.winner, firstPlayer: s.firstPlayer, turns: s.turn, + rounds: roundsPlayed(s), locations: [gridCount(s, 0), gridCount(s, 1)], stats: s.stats, cardUse: s.cardUse, @@ -38,8 +41,7 @@ export function recordOf(seed: number, s: GameState): GameRecord { }; } -/** Rounds: both players taking one turn each. */ -const roundsOf = (r: GameRecord) => Math.ceil(r.turns / 2); +const roundsOf = (r: GameRecord) => r.rounds; export function summarize(records: GameRecord[]): BatchSummary { const n = records.length; @@ -79,7 +81,7 @@ export function formatSummary(sum: BatchSummary, labels: [string, string]): stri ' Draws (turn limit)'.padEnd(36) + pct(sum.draws, sum.games), ' First player wins'.padEnd(36) + `${pct(sum.firstPlayerWins, decided)} of decided games`, '', - 'Game length, in rounds (both players take a turn)', + 'Game length, in rounds (every player takes all their commands, or a turn)', ` mean ${fmt(sum.rounds.mean)} · median ${sum.rounds.median} · 10% of games ≤ ${sum.rounds.p10} · 90% ≤ ${sum.rounds.p90}`, '', row('Average per player, per game', labels[0], labels[1]), diff --git a/sim/src/types.ts b/sim/src/types.ts index 5e39dca..386c8f8 100644 --- a/sim/src/types.ts +++ b/sim/src/types.ts @@ -83,6 +83,10 @@ export interface AvatarState { breachedTurn: number; /** For copies: the original's slot. */ copyOf: number | null; + /** For copies: the player-turn it was made. */ + createdTurn: number; + /** The game turn its level unlock happened (0 if it started face up). */ + unlockedTurn: number; } export interface PlayerState { @@ -252,6 +256,10 @@ export type Action = | { type: 'firewall'; line: string; level: number } | { type: 'salvage'; card: number } | { type: 'installHardware'; card: number; slot: number } + /** Recruit rule: an Avatar from hand into `slot`, retiring the Avatar there if there is one. */ + | { type: 'recruit'; card: number; slot: number } + /** Buy-Avatars rule: flip Avatar `slot`, the next face-down one, for its price. */ + | { type: 'buyAvatar'; slot: number } | { type: 'installProgram'; card: number; at: LocId } | { type: 'play'; card: number; target: LocId | null; args: Args; from: LocId | null } | { type: 'activate'; card: number; name: string; args: Args }; @@ -280,6 +288,10 @@ export const STAT_KEYS = [ 'programsLost', 'executionsPlayed', 'abilitiesUsed', + 'avatarsRecruited', + 'avatarsRetired', + 'avatarsBought', + 'ramOnAvatars', ] as const; export type StatKey = (typeof STAT_KEYS)[number]; diff --git a/sim/test/avatars.test.ts b/sim/test/avatars.test.ts index 8e8cf00..115ebf5 100644 --- a/sim/test/avatars.test.ts +++ b/sim/test/avatars.test.ts @@ -2,6 +2,7 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; import { avatarCores, openWindow } from '../src/engine.ts'; import { hasRoom } from '../src/query.ts'; +import { withRule } from '../src/rules.ts'; import { card } from './card.ts'; import { Table, type Side } from './table.ts'; @@ -39,6 +40,35 @@ card('Carbon NanoBots', () => { assert.equal(t.avatar(0, 1).hardware.length, 1); }); +test('copy rule variants: a new copy defends but only advances or attacks from its next turn', () => { + const t = scene('Carbon NanoBots', 'Broken Bits'); + t.s.rules = withRule(t.s.rules, 'copies.waitATurn=true'); + t.own(0, 'A2'); + t.ram(0, 5).use(avatarCard(t, 0, 1), { to: 'A2' }).settle(); + assert.equal(t.avatar(0, 5).at, 'A2', 'the copy is in play, defending A2'); + const acts = () => t.legal().filter((a) => (a.type === 'advance' || a.type === 'attack') && a.slot === 5); + assert.deepEqual(acts(), []); + assert.ok(t.legal().some((a) => a.type === 'advance' && a.slot === 1), 'the original still can'); + t.to('attack'); + assert.deepEqual(acts(), []); + t.to('playAgain').end().to('playAgain').end(); + assert.ok(acts().length > 0, 'next turn it can advance'); +}); + +test('copy rule variants: copies can need Avatar 2 unlocked, or be off', () => { + const t = scene('Carbon NanoBots', 'Broken Bits'); + t.own(0, 'A2'); + t.ram(0, 5); + const replicate = () => t.legal().some((a) => a.type === 'activate' && a.name === 'Carbon NanoBots'); + assert.ok(replicate()); + t.s.rules = withRule(t.s.rules, 'copies.needAvatar2=true'); + assert.ok(!replicate(), 'Avatar 2 is still face down'); + t.avatar(0, 2).faceUp = true; + assert.ok(replicate()); + t.s.rules = withRule(t.s.rules, 'copies.allowed=false'); + assert.ok(!replicate()); +}); + test('no copy can enter a location while a combat is going on there', () => { const t = scene('Broken Bits', 'Carbon NanoBots', { north: { servers: ['Cluster Server'] } }); t.own(1, 'C1', 'Cluster Server'); @@ -86,14 +116,14 @@ card('Beta Version 1.0', () => { card('Code Zero', () => { const t = scene('Broken Bits', 'Code Zero'); - t.avatar(0, 1).infection = 1; t.ram(1, 4); fight(t); assert.equal(t.decider, 1); - t.rig(6, 6, 6, 1, 1); + t.rig(6, 6, 6, 1, 1, 1); t.use(avatarCard(t, 1, 1)).settle(); - assert.equal(t.avatar(0, 1).infection >= 2 || t.avatar(0, 1).at === null, true); - assert.equal(dice(t, 'atk'), 3, '2 Infection counters: -1 Core while Code Zero is in play'); + assert.equal(t.avatar(0, 1).infection >= 1 || t.avatar(0, 1).at === null, true); + assert.equal(dice(t, 'atk'), 3, '1 Infection counter: -1 Core while Code Zero is in play'); + assert.equal(dice(t, 'def'), 3, 'Code Zero has 3 Cores'); }); card('Data Leaker', () => { diff --git a/sim/test/engine.test.ts b/sim/test/engine.test.ts index 604cd6e..c6fc5d5 100644 --- a/sim/test/engine.test.ts +++ b/sim/test/engine.test.ts @@ -5,7 +5,8 @@ import { randomDeck } from '../src/deck.ts'; import { advanceTargets, avatarCores, createGame, legalActions, viewFor } from '../src/engine.ts'; import { checkInvariants } from '../src/invariants.ts'; import { makeRng } from '../src/rng.ts'; -import { DEFAULT_RULES, withRule } from '../src/rules.ts'; +import { DEFAULT_RULES, withRule, type RulesConfig } from '../src/rules.ts'; +import { commanderOf, roundOf } from '../src/state.ts'; import { Table } from './table.ts'; const pool = loadCards(); @@ -36,6 +37,31 @@ test('the first player skips the draw; the second player draws', () => { assert.equal(t.s.players[1].hand.length, 1); }); +test('rule variants: the first player draws on turn 1', () => { + const pool = loadCards(); + const hand = (rules: RulesConfig) => { + const s = createGame({ pool, decks: [randomDeck(pool, makeRng(1), rules), randomDeck(pool, makeRng(2), rules)], seed: 5, rules }); + return s.players[s.firstPlayer].hand.length; + }; + assert.equal(hand(withRule(DEFAULT_RULES, 'firstTurn.draw=true')), hand(DEFAULT_RULES) + 1); +}); + +test('rule variants: the second player draws extra in their first draw step only', () => { + const t = new Table({ north: { main: ['Additional Core', 'Additional Core', 'Additional Core', 'Additional Core'] } }); + t.s.rules = withRule(t.s.rules, 'secondPlayer.firstDraw=1'); + t.to('playAgain').end(); + assert.equal(t.s.players[1].hand.length, 2); + t.to('playAgain').end().to('playAgain').end(); + assert.equal(t.s.players[1].hand.length, 3); +}); + +test('rule variants: more cards per draw step', () => { + const t = new Table({ north: { main: ['Additional Core', 'Additional Core'] } }); + t.s.rules = withRule(t.s.rules, 'drawPerTurn=2'); + t.to('playAgain').end(); + assert.equal(t.s.players[1].hand.length, 2); +}); + test('advancing captures an unowned location in step 5 and pays 4 RAM; Lv 1 unlocks nothing', () => { const t = new Table(); t.ram(0, 4); @@ -240,3 +266,200 @@ test('an opponent with a response gets a window after a declaration; without one t.act({ type: 'pass' }); assert.equal(t.decider, 0); }); + +// --------------------------------------------------------------------------------------------- +// Recruit rule (prototype): Avatars in the deck, bought with RAM + +/** A table under the recruit rule: Avatar 1 stays, Avatars 2–4 move to their owner's hand, priced at 6 RAM. */ +function recruitTable(o: ConstructorParameters[0] = {}): Table { + const t = new Table(o); + t.s.rules = withRule(t.s.rules, 'recruit.on=true'); + for (const p of [0, 1] as const) { + const avs = t.s.players[p].avatars; + for (let i = 1; i < 4; i++) { + const name = t.s.cards[avs[i].card].name; + t.s.defs[name] = { ...t.s.defs[name], ram: 6 }; + t.s.players[p].hand.push(avs[i].card); + avs[i].card = avs[i + 4].card = -1; + avs[i].faceUp = false; + } + } + return t; +} + +const recruits = (t: Table) => t.legal().filter((a) => a.type === 'recruit'); + +test('recruit rule: buy an Avatar from hand into an empty slot; it enters play on a later turn', () => { + const t = recruitTable(); + const card = t.s.players[0].hand[0]; + t.ram(0, 5).to('play'); + assert.equal(recruits(t).length, 0, "can't afford 6 RAM"); + t.ram(0, 6); + assert.deepEqual(recruits(t).map((a) => a.type === 'recruit' && a.slot), [2, 1, 2, 1, 2, 1], 'first empty slot, or over Avatar 1'); + t.go({ type: 'recruit', card, slot: 2 }); + assert.equal(t.s.players[0].ram, 0); + assert.equal(t.avatar(0, 2).card, card); + assert.equal(t.avatar(0, 2).faceUp, true); + assert.ok(!t.s.players[0].hand.includes(card)); + t.to('playAgain').end().to('playAgain').end(); + assert.ok(t.can({ type: 'place', slot: 2, to: 'S1' })); +}); + +test('recruit rule: captures unlock nothing, and a salvaged Avatar pays its price', () => { + const t = recruitTable(); + t.own(0, 'B1'); + t.place(0, 1, 'B1'); + t.go({ type: 'advance', slot: 1, to: 'C2' }).to('attack').end(); + assert.equal(t.s.locations.C2.owner, 0); + assert.equal(t.avatar(0, 2).card, -1); + const ram = t.s.players[0].ram; + t.go({ type: 'salvage', card: t.s.players[0].hand[0] }); + assert.equal(t.s.players[0].ram, ram + 6); +}); + +test('recruit rule: copies count toward the 4 Avatars', () => { + const t = recruitTable({ south: { avatars: ['Carbon NanoBots', 'Broken Bits', 'Pixelated Picture', 'Corrupt Driver'] } }); + t.own(0, 'A2'); + t.place(0, 1, 'A2'); + const [a, b] = t.s.players[0].hand; + t.ram(0, 30).to('play'); + t.go({ type: 'recruit', card: a, slot: 2 }).go({ type: 'recruit', card: b, slot: 3 }); + const replicate = t.legal().find((x) => x.type === 'activate' && x.name === 'Carbon NanoBots' && x.args.to === 'S1'); + assert.ok(replicate, '3 Avatars, so a copy fits'); + t.go(replicate).settle(); + assert.equal(t.avatar(0, 5).at, 'S1'); + assert.ok(!recruits(t).some((r) => r.type === 'recruit' && r.slot === 4), 'no room for a fourth with the copy out'); +}); + +test('recruit rule: recruiting over an Avatar retires it and its Hardware', () => { + const t = recruitTable({ south: { main: ['Additional Core'] } }); + t.own(0, 'A2'); + const ref = t.place(0, 1, 'A2'); + const old = t.avatar(0, 1).card; + const hw = t.hardware(ref.player, ref.slot, 'Additional Core'); + const card = t.s.players[0].hand.find((id) => t.s.defs[t.s.cards[id].name].kind === 'avatar')!; + t.ram(0, 6).to('play').go({ type: 'recruit', card, slot: 1 }); + assert.equal(t.avatar(0, 1).card, card); + assert.equal(t.avatar(0, 1).at, null); + assert.deepEqual(t.avatar(0, 1).hardware, []); + assert.ok(t.s.players[0].discard.includes(old) && t.s.players[0].discard.includes(hw)); + assert.equal(t.s.locations.A2.owner, 0, 'the location stays yours'); +}); + +test('recruit rule: decks keep one Avatar outside and shuffle the rest into the main deck', () => { + const pool = loadCards(); + const rules = withRule(withRule(DEFAULT_RULES, 'recruit.on=true'), 'recruit.avatarsInDeck=5'); + const deck = randomDeck(pool, makeRng(3), rules); + assert.equal(deck.avatars.length, 1); + assert.equal(deck.main.length, 45); + assert.equal(deck.main.filter((n) => pool.byName.get(n)!.kind === 'avatar').length, 5); + const s = createGame({ pool, decks: [deck, randomDeck(pool, makeRng(4), rules)], seed: 1, rules }); + assert.deepEqual(s.players[0].avatars.slice(0, 4).map((a) => a.card >= 0), [true, false, false, false]); + assert.equal(checkInvariants(s).length, 0); +}); + +// --------------------------------------------------------------------------------------------- +// Buy-Avatars rule (prototype): pay RAM to flip the next Avatar instead of unlocking by level + +test('buy rule: pay to flip the next face-down Avatar; it enters play on a later turn', () => { + const t = new Table(); + t.s.rules = withRule(withRule(t.s.rules, 'buyAvatars.on=true'), 'buyAvatars.prices=8,12,16'); + t.ram(0, 7).to('play'); + assert.ok(!t.can({ type: 'buyAvatar', slot: 2 }), "can't afford 8 RAM"); + t.ram(0, 20).go({ type: 'buyAvatar', slot: 2 }); + assert.equal(t.avatar(0, 2).faceUp, true); + assert.equal(t.s.players[0].ram, 12); + assert.ok(t.can({ type: 'buyAvatar', slot: 3 }), 'Avatar 3 is next, at 12'); + t.go({ type: 'buyAvatar', slot: 3 }); + assert.equal(t.s.players[0].ram, 0); + t.to('playAgain').end().to('playAgain').end(); + assert.ok(t.can({ type: 'place', slot: 2, to: 'S1' })); +}); + +test('buy rule: captures unlock nothing', () => { + const t = new Table(); + t.s.rules = withRule(t.s.rules, 'buyAvatars.on=true'); + t.own(0, 'B1'); + t.place(0, 1, 'B1'); + t.go({ type: 'advance', slot: 1, to: 'C2' }).to('attack').end(); + assert.equal(t.s.locations.C2.owner, 0); + assert.deepEqual([t.avatar(0, 2).faceUp, t.avatar(0, 3).faceUp], [false, false]); +}); + +// --------------------------------------------------------------------------------------------- +// Command rule (prototype): alternating commands, 2 per player per round + +/** Command rule with plain A B A B rounds, so tests can predict whose command it is. */ +function commandTable(): Table { + const t = new Table(); + t.s.rules = withRule(withRule(t.s.rules, 'commands.on=true'), 'commands.snake=false'); + return t; +} + +test('command rule: players alternate commands, and the lead alternates by round', () => { + const t = commandTable(); + assert.deepEqual([1, 2, 3, 4, 5, 6, 7, 8, 9].map((turn) => commanderOf(t.s, turn)), [0, 1, 0, 1, 1, 0, 1, 0, 0]); + assert.deepEqual([1, 4, 5, 8, 9].map((turn) => roundOf(t.s, turn)), [1, 1, 2, 2, 3]); + t.to('playAgain').end(); + assert.equal(t.s.active, 1); + t.to('playAgain').end().to('playAgain').end().to('playAgain').end(); + assert.equal(t.s.turn, 5); + assert.equal(t.s.active, 1, 'North leads round 2'); +}); + +test('command rule: the order of commands can follow a pattern of round leads, or snake', () => { + const order = (...specs: string[]) => { + const t = commandTable(); + for (const sp of specs) t.s.rules = withRule(t.s.rules, sp); + return Array.from({ length: 16 }, (_, i) => 'FS'[commanderOf(t.s, i + 1)]).join(''); + }; + assert.equal(order(), 'FSFS' + 'SFSF' + 'FSFS' + 'SFSF'); + assert.equal(order('commands.leads=F'), 'FSFS'.repeat(4)); + assert.equal(order('commands.leads=FFSS'), 'FSFS' + 'FSFS' + 'SFSF' + 'SFSF'); + assert.equal(order('commands.leads=thue'), 'FSFS' + 'SFSF' + 'SFSF' + 'FSFS'); + assert.equal(order('commands.snake=true', 'commands.leads=F'), 'FSSF'.repeat(4)); + assert.equal(order('commands.snake=true'), 'FSSF' + 'SFFS' + 'FSSF' + 'SFFS', 'the default order'); + assert.equal(DEFAULT_RULES.commands.snake, true); +}); + +test('command rule: one advance or attack per command, each Avatar once a round', () => { + const t = commandTable(); + t.own(0, 'A2'); + t.own(0, 'A1'); + t.place(0, 1, 'A2'); + t.place(0, 2, 'A1'); + t.go({ type: 'advance', slot: 1, to: 'A3' }); + assert.ok(!t.legal().some((a) => a.type === 'advance'), 'the command is spent'); + t.to('attack'); + assert.ok(!t.legal().some((a) => a.type === 'attack')); + t.to('playAgain').end().to('playAgain').end(); + assert.equal(t.s.turn, 3); + const movers = new Set(t.legal().filter((a) => a.type === 'advance').map((a) => a.type === 'advance' && a.slot)); + assert.deepEqual([...movers], [2], 'Avatar 1 already acted this round'); +}); + +test('command rule: an Avatar unlocked this round enters play next round', () => { + const t = commandTable(); + t.own(0, 'A2'); + t.place(0, 1, 'A2'); + t.go({ type: 'advance', slot: 1, to: 'B1' }).to('attack').end(); + assert.equal(t.avatar(0, 2).faceUp, true); + t.to('playAgain').end().to('playAgain').end(); + assert.equal(t.s.turn, 3); + assert.ok(!t.legal().some((a) => a.type === 'place' && a.slot === 2)); + t.to('playAgain').end().to('playAgain').end().to('playAgain').end(); + assert.equal(t.s.turn, 6); + assert.ok(t.legal().some((a) => a.type === 'place' && a.slot === 2)); +}); + +test('command rule: each player draws at their first command of a round only', () => { + const t = commandTable(); + const hand = () => t.s.players[1].hand.length; + t.to('playAgain').end(); + assert.equal(hand(), 1, "North's first command of round 1"); + t.to('playAgain').end().to('playAgain').end(); + assert.equal(hand(), 1, 'no draw on the second command'); + t.to('playAgain').end(); + assert.equal(t.s.turn, 5); + assert.equal(hand(), 2, 'round 2'); +}); diff --git a/sim/test/fuzz.test.ts b/sim/test/fuzz.test.ts index 5403574..c95a6d5 100644 --- a/sim/test/fuzz.test.ts +++ b/sim/test/fuzz.test.ts @@ -4,6 +4,7 @@ import { DEFAULT_GREEDY, greedyBot } from '../src/bots/greedy.ts'; import { randomBot } from '../src/bots/random.ts'; import { loadCards } from '../src/cards.ts'; import { playGame } from '../src/play.ts'; +import { DEFAULT_RULES, withRule } from '../src/rules.ts'; const pool = loadCards(); @@ -26,6 +27,42 @@ test('greedy bots play 200 games without breaking a rule', () => { assert.ok(wins >= 196, `only ${wins}/200 games ended in a win`); }); +test('bots play the recruit rule without breaking a rule', () => { + for (const k of [3, 7]) { + const rules = withRule(withRule(DEFAULT_RULES, 'recruit.on=true'), `recruit.avatarsInDeck=${k}`); + for (let seed = 1; seed <= 25; seed++) { + assert.ok(playGame({ pool, bots: [randomBot, randomBot], seed, rules, check: true }).over); + assert.ok(playGame({ pool, bots: [() => greedyBot(), () => greedyBot()], seed, rules, check: true }).over); + } + } +}); + +test('bots play the buy-Avatars rule without breaking a rule', () => { + const rules = withRule(DEFAULT_RULES, 'buyAvatars.on=true'); + for (let seed = 1; seed <= 25; seed++) { + assert.ok(playGame({ pool, bots: [randomBot, randomBot], seed, rules, check: true }).over); + assert.ok(playGame({ pool, bots: [() => greedyBot(), () => greedyBot()], seed, rules, check: true }).over); + } +}); + +test('bots play the copy-rule variants without breaking a rule', () => { + for (const spec of ['copies.waitATurn=true', 'copies.needAvatar2=true', 'copies.allowed=false']) { + const rules = withRule(DEFAULT_RULES, spec); + for (let seed = 1; seed <= 15; seed++) { + assert.ok(playGame({ pool, bots: [randomBot, randomBot], seed, rules, check: true }).over); + assert.ok(playGame({ pool, bots: [() => greedyBot(), () => greedyBot()], seed, rules, check: true }).over); + } + } +}); + +test('bots play the command rule without breaking a rule', () => { + const rules = withRule(DEFAULT_RULES, 'commands.on=true'); + for (let seed = 1; seed <= 25; seed++) { + assert.ok(playGame({ pool, bots: [randomBot, randomBot], seed, rules, check: true }).over); + assert.ok(playGame({ pool, bots: [() => greedyBot(), () => greedyBot()], seed, rules, check: true }).over); + } +}); + test('greedy beats random', () => { let wins = 0; for (let seed = 1; seed <= 100; seed++) { diff --git a/sim/test/table.ts b/sim/test/table.ts index d4b5d6f..49a76e1 100644 --- a/sim/test/table.ts +++ b/sim/test/table.ts @@ -36,8 +36,11 @@ export class Table { main: [...(x.main ?? []), ...Array(12).fill(FILLER)], }); const decks = [side(o.south), side(o.north)] as const; + // Classic turns (one turn each, every Avatar acts), which the card tests are written for. The + // command rule has its own tests in engine.test.ts. const rules: RulesConfig = { ...DEFAULT_RULES, + commands: { ...DEFAULT_RULES.commands, on: false }, openingHand: 0, deck: { avatars: 4, servers: decks[0].servers.length, main: decks[0].main.length, maxCopies: 99 }, };