Versus mode: attack vs defend (sim, bots, server, client)

One player defends, the other plays the Internet: earns credits over time and
spends them on packets, upgrades and sabotage. Two rounds with swapped roles,
timed (the faster fall wins). Built end to end, NOT yet QA'd or balanced.

Sim (public/js/sim.js, TD.VS table): attacker economy (income, lifetime bonus,
leak payback), spawn / stage / launch convoys, 7 tech tracks, abilities (EMP,
decoy, surge, DDoS), defender tools (scan, patch, repair, quarantine), role-checked
commands, round result, role-private state. Co-op/solo unchanged (24 scripted
games replay identically).

Bots (public/js/bot.js, tools/versus.js): defender (maze + turrets) and attacker
(budgeted spender reading the tower mix); headless bot-vs-bot runner.

Server (server/versus.js, protocol doc): versus rooms with lobby / countdown /
playing / roundover / matchover, role stamping, cross-role refusal, role-private
priv messages at 4 Hz, computer seat, freeze/forfeit rules, no pause/speed.

Client (public/js/versus.js): setup dialog (role, length, vs computer or online),
countdown, defender tools row, attacker unit shop with convoy + launch, tech and
abilities, gateway choice, round/match screens, sounds, phone-first dock rows.

Status and next steps (balance: the attacker currently wins ~100% of bot rounds;
QA with two browsers; layout matrix rerun) are in docs/NEXT.md and docs/VERSUS.md.
The full planned workflow incl. balance/QA prompts is in docs/workflows/versus-full.js.

253 unit tests pass; one smoke e2e run; no other e2e per the user's request.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
This commit is contained in:
Claude 2026-10-11 10:22:29 +00:00
parent b4ae6cb57d
commit 2098d59c1f
23 changed files with 6166 additions and 90 deletions

View file

@ -4,6 +4,8 @@ Two people play **the same map together**: one shared base, one shared credit po
The Node server runs the game (the same `public/js/sim.js` the browser uses for solo play) and is the
single source of truth. Clients send *commands*; the server steps the simulation and broadcasts *snapshots*.
Clients never simulate in multiplayer; they render (with interpolation) what the server says.
A room is either **co-op** (this document up to "Tick loop") or **versus** (attack vs defend, see "Versus" at the end: same transport, same
snapshots, plus lobby / role-private messages); `join.mode` picks.
Transport: one WebSocket per player at `ws(s)://<host>/ws`, JSON text frames, one object per frame, field `t`
= message type. Client -> server frames are capped at **2048 bytes** (`maxPayload`).
@ -78,20 +80,25 @@ at a domain root and under a path prefix the proxy strips.
Client's first message:
```
{ t:'join', pid, name, room?, map?, difficulty? }
{ t:'join', pid, name, room?, map?, difficulty?, mode?, limit?, rounds? }
```
* `pid` `^[A-Za-z0-9_-]{8,40}$` - random, generated by the client, kept in `sessionStorage` (stable across reloads).
* `name` any string; server trims, strips control chars, caps at 16 chars, default `"Player"`.
* `room` absent -> **create** a room. `map` must be a key of `TD.MAPS` (default `'open'`). `difficulty` must be a key of
`TD.DIFFICULTIES` (`'easy'`, `'normal'`, `'hard'`; default `'normal'`, `null` counts as absent), see "Difficulty" below.
Server generates a 4 character code from `ABCDEFGHJKLMNPQRSTUVWXYZ23456789`, unique among rooms.
* `room` present (`^[A-Za-z0-9]{4}$`, case-insensitive -> upper-cased) -> **join**. `map` and `difficulty` are ignored on a join (not even
validated): the joiner gets the room's, in `state.map` / `state.difficulty` of the `joined` message. A reconnect (same `pid`) is a join.
* `mode`, `limit`, `rounds` (creating join only): `mode` is `'coop'` (the default; `null` counts as absent) or `'versus'` (see "Versus" below).
For `'versus'`, `limit` is the round length in seconds, one of `TD.VS.LIMITS` (480, 720, 960; default 720) and `rounds` must be 2.
They are checked after `map` and `difficulty`. A co-op creating join ignores `limit` and `rounds`.
* `room` present (`^[A-Za-z0-9]{4}$`, case-insensitive -> upper-cased) -> **join**. `map`, `difficulty`, `mode`, `limit` and `rounds` are ignored on a join (not even
validated): the joiner gets the room's, in `state.map` / `state.difficulty` (and `state.mode` / `state.limit` in versus) of the `joined` message. A reconnect (same `pid`) is a join.
Failure: `{ t:'error', code, msg }` then the server closes the socket (code 4000+).
Codes: `bad_request`, `no_room`, `full` (two *other* pids already hold the slots), `too_many_rooms`, `bad_map`, `bad_difficulty`
Codes: `bad_request`, `no_room`, `full` (two *other* pids already hold the slots, or a computer holds the second seat of a running versus match),
`too_many_rooms`, `bad_map`, `bad_difficulty`
(a creating join whose `difficulty` is not one of the table's keys: wrong type, `'toString'`, `'__proto__'`, ... all refused, no room is
created, the socket closes with 4400; a bad `map` is checked first).
created, the socket closes with 4400; a bad `map` is checked first), `bad_mode` (`mode` is neither `'coop'` nor `'versus'`), `bad_limit` (versus `limit` not in
`TD.VS.LIMITS`, or not a number), `bad_rounds` (versus `rounds` is not 2). The three new codes also close with 4400 and create no room.
Success: reply to the joiner
@ -127,6 +134,7 @@ pid for the viewer's own entry and an opaque, stable per-room alias for the othe
| `{t:'sync'}` | ask for a full state resend |
| `{t:'newgame', map?, difficulty?}` | **host only**: replace the sim with a fresh `new Sim({map, difficulty})`; resets pause/speed. An absent (or `null`) `map` / `difficulty` keeps the room's current one, so a plain `{t:'newgame'}` is "play again" |
| `{t:'leave'}` | leave now |
| `{t:'vs', c, v?}` | **versus rooms only** (malformed in a co-op room): `role`, `ready`, `bot`, `start`, `next`, `rematch`; see "Versus" |
**Idempotent `upgrade` and `wave`.** Two players who press Upgrade (or Next wave) at the same moment both send the command; without
a guard the tower would be upgraded twice and the second player charged for a level they never asked for, or two waves would start.
@ -208,6 +216,7 @@ it when creating the room (`join.difficulty`) or when starting a new game (`newg
## Tick loop
(Co-op. A versus room has its own phases and only ticks while `playing` with every human online, at speed 1: see "Versus".)
Fixed step `TD.STEP` (1/60 s) with an accumulator driven by `process.hrtime.bigint()`; real time elapsed is
multiplied by `speed` (1-3) and ignored while `paused`; clamp elapsed per iteration to 250 ms so a stalled event
loop does not fast-forward the game. Drive it with a `setInterval` of ~8 ms (or setTimeout chain) per room, or one
@ -217,3 +226,120 @@ global loop for all rooms. Must keep working with several rooms at once.
`place`, `sell`, `up`, `shot`, `arc`, `boom`, `kill`, `leak`, `wave`, `clear`, `win`, `lose` (see `sim.js`).
Treat them as opaque JSON.
## Versus (attack vs defend)
Design: `docs/VERSUS.md`. A versus room is created with `join.mode = 'versus'`. One player **defends** (builds the maze and turrets with the credits of
`snap.g`), the other **attacks** (buys packets with credits only they can see); a match is two rounds with the roles swapped. The server is the
only simulation (`new TD.Sim({ map, mode: 'versus', limit })`, a fresh one per round) and the only referee. Everything below is additive: a co-op room
never sends or accepts any of it (a `vs` message or a versus command sent to a co-op room is malformed, exactly as before), the `joined` / `state`
messages of a co-op room are byte-identical to what they were.
### Seats and roles
* Two **seats** (the same slots 0 and 1). A seat is held by a human (as in co-op: grace period, reconnect by `pid`, host migration) or, in the
lobby, by a **computer** (below). `roles` maps each seat to `'attacker'` or `'defender'` and is always one of each.
* Round 1 roles: whatever the lobby says when the host starts (a coin flip until somebody chooses). Round 2 swaps them.
* **The server decides the role of every command from the seat, for the current round**; a `role` or `by` field in a client message is ignored.
A command for the other role is answered `{ t:'reject', c, reason:'role' }` and changes nothing.
### Phases
```
lobby --start--> countdown --> playing --> roundover --next--> countdown --> playing --> matchover --rematch--> countdown ...
```
| phase | what happens |
|---|---|
| `lobby` | roles, ready flags and the computer seat are agreed. The room's sim exists (so a joiner has a board) but **never ticks**; game commands are refused with `reason:'phase'`. Snapshots keep flowing (the client's watchdog needs them). |
| `countdown` | a fresh sim for the round was built and sent as `{ t:'state', newgame:true, ... }`; `countdown` seconds left are in the `vs` message; nothing ticks, **no command is accepted** (`'phase'`). |
| `playing` | the sim ticks (speed 1 only) while **every human seat is online**; commands are accepted. |
| `roundover` | the round's `result` is shown; the next round starts when every human sent `next`, or after `vsNextMs` (30 s by default) whichever is first. |
| `matchover` | after round 2 (or a forfeit): `scores` and `winner`. `rematch` starts a new match. |
Commands in `roundover` / `matchover` get `reason:'over'`; while a human seat is offline `reason:'frozen'`.
### Messages, client -> server
Lobby and match control, all `{ t:'vs', c, ... }`. A malformed one (wrong type, unknown `c`) counts towards the 20-malformed limit; a well-formed one that is
not allowed right now gets `{ t:'reject', c:<the vs command>, reason }`.
| message | who / when | meaning | reasons |
|---|---|---|---|
| `{ t:'vs', c:'role', v:'attacker'\|'defender'\|'random' }` | any human, lobby | choose your role; the other seat gets the opposite. `'random'` flips a coin (`random:true` in the `vs` message). The last choice wins. Clears every ready flag. | `phase` |
| `{ t:'vs', c:'ready', v:boolean }` | any human, lobby | ready flag (the host does not need one; a computer is always ready) | `phase` |
| `{ t:'vs', c:'bot', v:'attacker'\|'defender'\|null, skill?:0..1 }` | host, lobby | put a computer with that role in the **empty** seat (the human gets the opposite role); `null` removes it. `skill` defaults to 1. A human who joins in the lobby takes the seat over (the computer goes away). | `not_host`, `phase`, `full` (both seats already hold humans) |
| `{ t:'vs', c:'start' }` | host, lobby | begin the match: every human except the host must be ready and online, two seats must be filled | `not_host`, `phase`, `no_opponent`, `offline`, `not_ready` |
| `{ t:'vs', c:'next' }` | any human, roundover | go on to the next round; it starts when every human has sent it (a computer needs no vote) | `phase` |
| `{ t:'vs', c:'rematch' }` | any human, matchover | vote for a new match with the **first round's roles swapped**, straight into the countdown; needs every human (and an opponent) | `phase`, `no_opponent` |
Game commands are `{ t:'cmd', c, ... }` as in co-op, with a per-mode whitelist (the sim checks the values and answers `{ ok:false, reason }`, which becomes
a `reject` to the sender):
| role | `c` | fields |
|---|---|---|
| defender | `place` `sell` `upgrade` `target` | as in co-op (`type,x,y` / `id` / `id,lv?` / `id,mode`) |
| defender | `tool` | `id:'scan'\|'patch'\|'repair'\|'quarantine'`, `x,y` (scan), `tid` (patch) |
| attacker | `spawn` `stage` | `kind` (an enemy kind), `n?` (1..250, default 1), `gate?` (spawn index) |
| attacker | `launch` | `gate?` |
| attacker | `tech` | `id` (`armor`, `speed`, `health`, `regen`, `shield`, `stealth`, `crypt`) |
| attacker | `ability` | `id:'emp'\|'decoy'\|'surge'\|'ddos'`, `tid?` (emp, decoy), `gate?` (decoy) |
| nobody | `wave` `auto` `continue` | valid messages, always refused with `reason:'versus'` |
Types are checked before the sim sees anything: `kind` a string (at most 24 chars), `n` / `lv` / `gate` / `tid` integers (or null), `id` a string for
`tool` / `ability` / `tech` and a number for `sell` / `upgrade` / `target`; anything else is malformed. Reasons: `role`, `credits` (`gold` for `place`),
`cooldown`, `cap`, `max`, `bad_target`, `bad_kind`, `bad_cmd`, `empty` (nothing staged), `over`, `phase`, `frozen`, `versus`, plus the co-op ones.
A reject echoes `x`, `y`, `id` (now also a string id) and `tid`. `ctl` `pause` / `speed` are **refused** in versus with `{ t:'reject', c:'pause'|'speed', reason:'versus' }`
(a malformed `ctl` is still malformed), and `newgame` with `reason:'versus'` (replay with `rematch`).
### Messages, server -> client
```
{ t:'vs', phase, round, rounds, roles:{ '0':role, '1':role }, random, bot:{ slot, role, skill, name }|null, limit, ready:{ '0':bool, '1':bool }, frozen,
countdown?, // countdown: whole seconds left
next?:{ '0':bool, '1':bool }, nextIn?, // roundover: who has pressed next, seconds until the next round starts anyway
result?, // roundover, matchover: the round that just ended
history?, // as soon as a round has finished (also in round 2's countdown / playing, and after a reconnect)
scores?, winner?, forfeit?, rematch? } // matchover
{ t:'priv', role, ...sim.privateState(role) } // role-private data, see below
```
* `vs` is sent to everybody on **every change** (a role, a ready flag, the computer, a phase, each countdown second, a vote, a player joining, leaving, dropping or
returning) and is part of `joined` as `joined.vs`. `frozen` is true while the round (or countdown, or result timer) waits for an offline human. `random` is
true while the roles are still the coin flip. `bot.name` is `'Computer'`; its seat shows `ready: true`.
* `result` = `{ winner:'attacker'|'defender', t, integrityLost, attacker:slot, defender:slot, forfeit? }`: the sim's own `vs.result` plus who sat where.
`history` lists every finished round of the match as `{ round, roles, result }` (absent until the first round has finished, and in a new match), so the end screen can show both rounds side by side and a client that reconnects in round 2 can still show round 1. After round 2 the phase goes
straight to `matchover` (it carries that round's `result`).
* `scores` = `[{ slot, name, fellAt|null, integrityLost }]` per **attacking** performance: `fellAt` is the sim time the server fell in the round that seat attacked (null if it
did not, or if the round was a forfeit); `integrityLost` is the integrity taken off in total (repairs do not give it back). `winner` is a slot, or `null` for a **draw**.
Rule: the earlier fall wins; if only one seat felled the server it wins; if neither did, the one who took off more integrity; equal is a draw.
* `forfeit` (matchover) is the seat that left (or whose grace period ran out); the other seat wins the match and, if a round was being played, that round.
* **Private data** `priv`: `{ t:'priv', role, credits, income, tech, staged, cd, active }` for the attacker, `{ t:'priv', role, cd }` for the defender, to **each human only
for its own current role**, at 4 Hz during `countdown` and `playing`, once when a round ends, on `sync`, and when a player (re)joins. The attacker's purse, tech, convoy
composition and cooldowns are never sent to the defender, the defender's cooldowns never to the attacker (the test suite scans every frame both sockets receive).
After a role swap the first `priv` of the new round replaces the old; clients should compare `priv.role` with their current role.
* **No cursors, no map pings.** `cursor` and `mark` are valid messages in a versus room but are ignored: `snap.cur` is always `[]` and no `mark` is ever broadcast (an opponent must not see what you are
about to build or target).
* Snapshots are the co-op ones plus the shared block `vs: { t, lim, st }` (round clock, round limit, size of the staged convoy) and a 4th field `[id, tgt, kills, emp]`
on the `tt` rows (seconds of EMP left). `state` / `joined.state` carry `mode:'versus'` and `limit`. `snap.s` is `'playing'` until the round ends, then `'over'`
(`snap.pa` is always 0 and `snap.sp` always 1). The sim's `round` event arrives in `ev` as `{ e:'round', winner, t }`; the other new events are `emp`, `decoy`,
`surge`, `ddos`, `quarantine`, `scan`, `repair`. Every round starts with a `{ t:'state', newgame:true }` (new sim, new tower list).
* Size: the worst case is the alive cap (250 units) plus a built-up defence, about 38 bytes per unit row, roughly 10 KB per snapshot, 200 KB/s per client at 20 Hz
(a test pins it below 16 KB). The `vs` and `priv` messages are under 500 bytes each.
### The computer seat
`{ t:'vs', c:'bot', v:<role> }` (host, lobby) puts `NWBot` (`public/js/bot.js`) in the empty seat, with that role and `skill` 0..1. It runs **on the server**, inside the room loop,
and plays through exactly the same door as a human: its commands are stamped with the seat's role and `by`, refused outside `playing` and while frozen, and it only sees the
sim through the public API (`privateState` of its own role). Limits so that a computer seat cannot be used to burn CPU: it is asked to think at most 4 times per second of game
time, only while `playing`; all the computers of the server together may start thinking only while less than 15 ms were spent on them in this 8 ms loop iteration, and a decision that
took `d` buys a quiet period of `3d` for its room (so a heavy decision costs at most about a quarter of the loop); a bot that throws is switched off for the round. The computer seat is **not**
a connection: a room with only a computer left is deleted, and in a running match a stranger who joins gets `full`. A solo player can also play a computer without the server:
`NW.LocalController` with `mode:'versus'` (same `vs` / `priv` shapes, see `controllers.js`).
### Disconnects, forfeits and hosts
* **Freeze.** While *any* human seat is offline the countdown, the round and the result timer stand still (co-op ticks while anyone is online; versus must not let one side keep
building or spawning against an absent opponent) and commands get `reason:'frozen'`. The player can come back with the same `pid` within `graceMs` (60 s): `joined` carries the
current `vs`, a `priv` follows, `frozen` becomes false for everybody.
* **Forfeit.** When the grace period runs out, or a player sends `leave`, the one who stays wins: in `playing` the current round is awarded to them (the sim ends it with
the `round` event, `result.forfeit:true`), between rounds the match is over with the finished rounds in `history`; either way the phase becomes `matchover` with
`forfeit:<leaver's seat>` and `winner:<the other seat>`. A forfeit never counts as "the server fell". After that the remaining player is host (migration as in co-op) and
the room stays in `matchover`: a new human can take the empty seat (`rematch` then needs both votes); the computer seat can only be set in the lobby, so a player who wants a
computer instead creates a new room.
* A leave or a timed-out grace period in the **lobby** just changes the seats (ready flags are cleared); in the **countdown of round 1** it sends the room back to the lobby (no match
had started); in the countdown of round 2 it is a forfeit.
* The host migrates exactly as in co-op; the host's powers are `bot` and `start`. A guest can pick roles and ready up.
* Server options for tests: `vsCountdownMs` (3000) and `vsNextMs` (30000) in `createServer`.