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

@ -176,6 +176,19 @@ the trailing slash). A dedicated sub-domain is simpler.
| **Credits** | From kills and cleared waves. Upgrade turrets (3 levels, 4 for the Uplink); selling returns 70% (walls 100%). | | **Credits** | From kills and cleared waves. Upgrade turrets (3 levels, 4 for the Uplink); selling returns 70% (walls 100%). |
| **Difficulty** | **Easy / Normal / Hard**, picked in the menu (solo) or by the host when creating a co-op room, and shown next to the next-wave list and on the end screen. It scales the starting credits and integrity, the hit points of every packet and what a kill pays (the table is `DIFFICULTIES` in `public/js/sim.js`). Normal uses the base tables of the game with every multiplier at 1. Your best wave is kept per map **and** difficulty. | | **Difficulty** | **Easy / Normal / Hard**, picked in the menu (solo) or by the host when creating a co-op room, and shown next to the next-wave list and on the end screen. It scales the starting credits and integrity, the hit points of every packet and what a kill pays (the table is `DIFFICULTIES` in `public/js/sim.js`). Normal uses the base tables of the game with every multiplier at 1. Your best wave is kept per map **and** difficulty. |
### Versus: play the Internet (new, lightly tested)
One player **defends** (builds the maze and turrets as usual), the other **attacks**: you earn credits over time and spend them
on packets, upgrades and sabotage. A match is two rounds with the roles swapped; the round ends when the server falls or the
timer runs out, and the faster fall wins the match.
* **Attacker:** a unit shop (every packet type), buy now or **stage** a convoy and **launch** it all at once, pick the gateway,
seven tech upgrades (armor, speed, health, regeneration, shield, stealth, encryption), and abilities (EMP a turret, decoy,
surge, DDoS). Units that survive longer pay you a lifetime bonus; a leak pays back its price.
* **Defender:** the normal build palette plus counter-tools: Scan, Patch, Repair, Quarantine.
* Play **against the computer** (no server needed) or in an online room with a friend; a computer can also fill the empty seat of a room.
* Status: built end to end but **not yet balanced or QA'd**: the attacker has the edge for now. See `docs/VERSUS.md` and `docs/NEXT.md`.
Controls, desktop: click to build, drag to paint walls, right-click cancels, `1`-`9` pick a tower, `Space` next wave, Controls, desktop: click to build, drag to paint walls, right-click cancels, `1`-`9` pick a tower, `Space` next wave,
`U` upgrade, `X` sell, `T` change targeting, `P` pause, `F` speed, `A` auto-waves, `M` mute, wheel zoom, Alt+click pings. `U` upgrade, `X` sell, `T` change targeting, `P` pause, `F` speed, `A` auto-waves, `M` mute, wheel zoom, Alt+click pings.

View file

@ -104,6 +104,15 @@ not `join` within 10 s is closed. When all 50 rooms exist, a room in which nobod
its `GRACE_MS`) is deleted to make room for a new one, longest-abandoned first, so on a full server the grace period is its `GRACE_MS`) is deleted to make room for a new one, longest-abandoned first, so on a full server the grace period is
not guaranteed; rooms with somebody online are never evicted (the newcomer gets `too_many_rooms`). not guaranteed; rooms with somebody online are never evicted (the newcomer gets `too_many_rooms`).
**Versus rooms** (attack vs defend, `docs/PROTOCOL.md` "Versus") count against the same 50 rooms and need nothing extra: no new port, no new environment variable,
the same WebSocket. Two things differ from co-op that an operator may notice. A disconnected player freezes the round for everybody until they are back or `GRACE_MS`
has passed (then the other player wins the match), so a long `GRACE_MS` means a long wait for the player who stayed. And a room may hold a computer opponent that runs
inside the server process: it thinks about 4 times per game second and costs well under 1 ms of CPU per game second on average. A single decision of a computer defender
(its opening purchases) takes 10-20 ms, up to ~80 ms on a cold process. A decision cannot be interrupted, so the server gates *when* the computers 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 its room a quiet period of `3d`. Many computer rooms starting at
the same moment are therefore spread over a few hundred milliseconds instead of stalling the other rooms.
The log has one line per versus round (start, result, forfeit).
What the server does, relevant to a proxy setup: What the server does, relevant to a proxy setup:
* **Real client IP** is used only for the log and the per-IP cap. With `TRUST_PROXY=auto` and a private/loopback peer * **Real client IP** is used only for the log and the per-IP cap. With `TRUST_PROXY=auto` and a private/loopback peer

View file

@ -33,7 +33,7 @@ and a check that the layout holds on **tablets and foldables**.
| 2 | Co-op robustness (stalled-render tower loss, half-open sockets, idempotent upgrade/wave, restart message), audio + keyboard + a11y | **done 2026-10-10** (QA passed) | | 2 | Co-op robustness (stalled-render tower loss, half-open sockets, idempotent upgrade/wave, restart message), audio + keyboard + a11y | **done 2026-10-10** (QA passed) |
| 3 | New enemies (Daemon healer, Proxy shielded, Botnet swarm) and towers (Sandbox stun, Load Balancer buff), glyphs/shapes, gallery e2e; Orbital Uplink (4 levels, priced 1500 + 25% per owned, upgrades scale equally; ); 4 new maps | **done 2026-10-10** (QA passed) | | 3 | New enemies (Daemon healer, Proxy shielded, Botnet swarm) and towers (Sandbox stun, Load Balancer buff), glyphs/shapes, gallery e2e; Orbital Uplink (4 levels, priced 1500 + 25% per owned, upgrades scale equally; ); 4 new maps | **done 2026-10-10** (QA passed) |
| 4 | Difficulty picker (Easy/Normal/Hard) + ONE time-boxed balance pass (IDS no longer sufficient, credit snowball tamed, Mortar/Arc/Filter buffed, flyers slower); Uplink price step set to 30% per owned | **done 2026-10-11** (QA passed) | | 4 | Difficulty picker (Easy/Normal/Hard) + ONE time-boxed balance pass (IDS no longer sufficient, credit snowball tamed, Mortar/Arc/Filter buffed, flyers slower); Uplink price step set to 30% per owned | **done 2026-10-11** (QA passed) |
| 5 | Attack-vs-defend versus mode, bots for both sides | design in `docs/VERSUS.md`, workflow drafted | | 5 | Attack-vs-defend versus mode, bots for both sides | **built 2026-10-11, NOT QA'd, NOT balanced** (sim, bots, server, client; see below) |
| 6 | Server leaderboard (needs `StateDirectory=netwall` + `DATA_DIR`; solo scores are client-reported) and an opt-in public room list | after 5 | | 6 | Server leaderboard (needs `StateDirectory=netwall` + `DATA_DIR`; solo scores are client-reported) and an opt-in public room list | after 5 |
| any | Fold/tablet real-device check; open items below | | | any | Fold/tablet real-device check; open items below | |
@ -48,6 +48,24 @@ and a check that the layout holds on **tablets and foldables**.
* If room codes ever get longer than 4 characters, boot's regex and the `inCode` maxlength must change together. * If room codes ever get longer than 4 characters, boot's regex and the `inCode` maxlength must change together.
### Versus mode: where it stands and what is left
Built: sim rules + economy + tech + abilities + defender tools (`TD.VS` table), `public/js/bot.js` (defender and attacker bots), `tools/versus.js`
(bot-vs-bot runner), server rooms/phases/roles/forfeit/private data/computer seat (`server/versus.js`), protocol (`docs/PROTOCOL.md` "Versus"),
client (`public/js/versus.js`: setup dialog, countdown, role-aware HUD, shop, convoy/launch, tech, abilities, tools, round/match screens). 253 unit tests
pass; the client was played by hand (local match vs the computer through both rounds, online rooms on the real server). **No e2e, no layout-matrix
run, no independent QA, no balance pass** (the user asked to skip them for now).
Left to do, in order:
1. **Balance** with `node tools/versus.js --maps all --limit 720 --seeds 6`: the attacker wins ~100% today. Cheapest lever: raise the buyCost of botnet
and spam (3 credits each; botnet 8 / spam 6 flips it to ~0%); target 40-60% for equal bots on every map. The `buyCost` lives in `ENEMIES`, the rest in `TD.VS`.
2. **QA** with two real browsers (prompt in `docs/workflows/versus-full.js`) plus the usual suites: `npm run e2e` (rerun the layout matrix: the menu foot now holds
three buttons, the palette becomes the unit shop in versus, new dock rows in the side panel).
3. Known limits from the client agent: a local computer match cannot be paused (opening the menu leaves the round running); no one-tap convoy presets (Rush, Swarm,
Siege...); the defender sees no stealth/shield cue (by design); on very small phones the setup dialog's Online block needs a scroll; remote rematch, frozen/reconnect
and reload-resume into a versus room were not exercised.
4. Ideas not built: spectators, handicap sliders in the lobby, a leaderboard of attack times, an invite link that opens the versus lobby directly.
## Suggested order of work ## Suggested order of work
1. **The wall bug above**, then the other confirmed high/medium client bugs: 1. **The wall bug above**, then the other confirmed high/medium client bugs:

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 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*. 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. 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` 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`). = 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: 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). * `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"`. * `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 * `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. `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. 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 * `mode`, `limit`, `rounds` (creating join only): `mode` is `'coop'` (the default; `null` counts as absent) or `'versus'` (see "Versus" below).
validated): the joiner gets the room's, in `state.map` / `state.difficulty` of the `joined` message. A reconnect (same `pid`) is a join. 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+). 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 (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 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:'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:'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:'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 **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. 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 ## 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 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 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 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`). `place`, `sell`, `up`, `shot`, `arc`, `boom`, `kill`, `leak`, `wave`, `clear`, `win`, `lose` (see `sim.js`).
Treat them as opaque JSON. 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`.

View file

@ -1,5 +1,10 @@
# Versus mode: attack vs defend ("play as the Internet") # Versus mode: attack vs defend ("play as the Internet")
> **Status 2026-10-11:** implemented end to end (sim + bots, server + protocol, client UI) but **not QA'd and not balanced**. With the shipped numbers
> the attacker bot wins ~100% of rounds on every map; the cheap 3-credit swarm units (botnet, spam) are the dominant lever (botnet 8 and spam 6
> flips it to ~0%; botnet 6 / spam 4 / worm 8 lands near 75%). The remaining planned steps (balance pass with `tools/versus.js`, independent QA with
> two real browsers) are in `docs/workflows/versus-full.js` (the BALANCE and QA prompts at its end).
Requested 2026-10-10. One player **defends** (builds the maze and turrets, as today); the other **attacks** (earns credits over Requested 2026-10-10. One player **defends** (builds the maze and turrets, as today); the other **attacks** (earns credits over
time, spends them on spawning packets, upgrades and sabotage). Same board, same rules, one authoritative simulation per room. time, spends them on spawning packets, upgrades and sabotage). Same board, same rules, one authoritative simulation per room.
Decisions made with the user: timed rounds then swap roles; attacker abilities *and* defender counter-tools; a computer Decisions made with the user: timed rounds then swap roles; attacker abilities *and* defender counter-tools; a computer
@ -72,3 +77,31 @@ prioritises for 5 s; *Surge* all units +40% speed for 6 s; *DDoS* all turrets fi
6. **e2e**: two browsers play a round each way; one bot match. 6. **e2e**: two browsers play a round each way; one bot match.
Depends on the content wave (new enemy kinds become shop items) and on the difficulty/economy constants, so it comes after them. Depends on the content wave (new enemy kinds become shop items) and on the difficulty/economy constants, so it comes after them.
## Client as built (2026-10-11)
All of it lives in `public/js/versus.js` (`NW.Versus`, created by `main.js`; with no versus game running it does nothing, so solo and co-op are untouched) plus the
`#vsSetup`, `#vsRoom` and `#vsEnd` dialogs in `index.html`, a block at the end of `style.css`, versus cues in `render.js` and the new sounds in `audio.js`.
* **Entering.** Menu -> *Versus* -> setup dialog: your role (Attack / Defend / Random), round length (8 / 12 / 16 min, from `TD.VS.LIMITS`), computer skill (Easy 0.35 /
Normal 0.7 / Hard 1). *Play the computer* starts a `LocalController` match (no server, no lobby: it starts in its 3 s countdown). *Create room* / *Join* (code) go to the
server; an invite link (`?room=`) still opens the co-op lobby dialog and works for a versus room too (the room says what it is).
* **Room (online lobby).** Seats with role badge and ready flag, your role (Attack / Defend / Random), host-only *Opponent: A friend / Computer*, host *Start match* (disabled with the
reason until the opponent is online and ready), guest *I'm ready*. Then a countdown card on the stage ("Round 1 of 2: YOU ATTACK"), round over (`#vsEnd`, both rounds side by side,
*Next round*), match over (the server's verdict from `vs.winner` / `vs.forfeit`, never recomputed; *Rematch (roles swap)*). A frozen room (opponent offline) shows a PAUSED card.
* **Defender HUD.** Today's tower palette, plus a tools row under it: Scan (tap, then tap the map; radius ring follows the pointer), Patch (re-enables the selected disabled tower, else
the one with most EMP left), Repair, Quarantine (second tap to confirm, like every action of 150+ credits). Each has a cooldown ring + seconds and greys out when it cannot be afforded.
* **Attacker HUD.** The palette becomes the unit shop (every `TD.ENEMY_ORDER` kind with `buyCost`, price shown for the chosen quantity; a tap buys; fewer is bought when credits fall short),
then a row `[x1|x5|x10] [Send|Stage] [Any gate|Gate n] [LAUNCH n + convoy composition]`, the four abilities with cooldown rings (EMP: tap it, then a tower; or select a tower and use the
button in its action bar), and the tech row (7 upgrades, level pips, price doubling per level). Credits (smoothly run forward from the 4 Hz `priv` data) and income are in the top bar,
units alive and the defender's credits in a pill on the stage. Tapping a gateway (or the gate button) chooses where packets enter; units appearing at a gateway pulse it for both sides.
Keys: 1-9 buy that unit, Space launches. Optimistic local bookkeeping (credits, cooldown start) is overwritten by the next `priv`.
* **Layout.** Stacked layouts: the dock (convoy row + abilities / tools) is pinned to the bottom of the side panel and the board gets less height (`V.minSide`); the tech row scrolls like the
shop. Short landscape: the shop and tech are scrolling grids in the 200 px column, the abilities keep four columns as icon + cost.
* **Rendering.** EMP'd towers are dimmed with hazard stripes, sparks and a draining arc; armed EMP outlines every target; decoys are dashed-ringed and half transparent (from the `decoy`
event on the wire, `m.decoy` locally); the attacker sees its own stealth (cloak shimmer for the first seconds) and shield (ring) because the wire carries neither (inferred from its tech
levels when the unit first appears, exact in a local match); Surge (orange edge), DDoS (violet scan lines), Quarantine (icy tint) and Scan zones are drawn for both sides. The defender
deliberately sees no stealth or shield cue (it does not know the attacker's tech).
* **Known limits.** A local match cannot be paused (versus has no pause; `LocalController.ctl` ignores it), so opening the menu in a computer match leaves the round running behind it.
Presets (Rush, Swarm, ...) from the design are not in the UI yet; the x1/x5/x10 selector covers most of it.

View file

@ -0,0 +1,109 @@
export const meta = {
name: 'netwall-wave4-versus-mode',
description: 'Wave 4: attack-vs-defend multiplayer: sim rules + bots, then server/protocol, then client UI, then bot-vs-bot balance, then independent QA (strictly sequential, one owner at a time)',
phases: [
{ title: 'Sim', detail: 'versus rules, economy, abilities, bots (pure, tested)' },
{ title: 'Server', detail: 'rooms, roles, rounds, protocol, bot seat' },
{ title: 'Client', detail: 'lobby, role-aware HUD, attacker shop, tools, phone-first' },
{ title: 'Balance', detail: 'bot-vs-bot matches, time-boxed' },
{ title: 'QA', detail: 'two real browsers play a full match' },
],
}
const SP = '/tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad'
const ROOT = '/home/jav/git/towerdefence'
const COMMON = `
PROJECT: "Netwall", an HTML5 maze-building tower defence game: solo in the browser, two-player co-op through a Node server (ws). Repo: ${ROOT} (git repo; do NOT run git commit/push or checkout/reset/stash: the lead commits).
Read ${ROOT}/README.md, ${ROOT}/docs/NEXT.md, ${ROOT}/docs/PROTOCOL.md and ESPECIALLY ${ROOT}/docs/VERSUS.md (the design the user approved: attack-vs-defend, timed rounds then swap roles, attacker abilities AND defender counter-tools, a computer opponent for either side).
Layout: public/ (index.html, css/style.css, js/sim.js shared PURE rules (browser solo + Node server), js/controllers.js Local+Remote, js/render.js, js/main.js UI/input/lobby, js/audio.js, sw.js), server/ (Node + ws), test/ (node:test; ONLY real test files), e2e/ (Playwright scenarios, "npm run e2e [-- filter]"), tools/bot.js (headless defender bot used for balancing).
ENVIRONMENT: no system Node. First: source ${SP}/pwenv.sh. playwright-core is in ${ROOT}/node_modules. Launch with chromium.launch({args:['--no-sandbox']}). Examples: ${ROOT}/e2e/scenarios/*.js. Look at screenshots with the Read tool. Real server: cd ${ROOT} && PORT=<yours> HOST=127.0.0.1 node server/index.js (serves public/ too). Use ONLY your port range; KILL every server/browser you start by port (ss -ltnp | grep :PORT), never a broad pkill. Scratch work in ${SP}/wave4/<key>/, never in the repo.
Compatibility rules: (1) sim.js stays PURE and DOM-free; (2) the existing co-op/solo behaviour and wire format must keep working unchanged (versus is an additional mode); (3) never assume 3 tower levels, a fixed tower/enemy count or exactly 2 maps; (4) no new dependencies, vanilla JS, classic scripts (no ES modules) in public/; (5) every new rule has a unit test, every new UI behaviour an e2e assertion that FAILS without it; (6) phones first: all new controls must be reachable by thumb on 320x568, 390x844 and 667x375, in the same compact/bar patterns the UI already uses (read public/css/style.css and main.js layoutBars/towerbar code first, and extend the 22-layout matrix e2e/scenarios/05-layout-matrix.js for new controls).
CURRENT STATE you build on (all of this exists and is tested): 7 maps, 9 towers (wall, filter, ids, mortar, throttle, arc, sandbox, balancer, uplink; the Uplink has 4 levels and gets dearer per owned unit via TD.priceFor/upgradePrice and a per-tower price multiplier 'pm' carried as the 9th field of tower rows), 9 enemy kinds in TD.ENEMY_ORDER (ping, worm, trojan, spam, ghost, rootkit, daemon healer, proxy shielded, botnet swarm) each with a buyCost, an Easy/Normal/Hard difficulty option for solo and co-op (versus IGNORES difficulty: units use base stats x attacker tech, no wave hp scaling), idempotent upgrade/wave commands ('stale'), a shared priceOf in the UI, 17 e2e scenarios and 156 unit tests, and phone UI patterns (layoutBars, #confirm and tower bars, compact overlays with pinned footers, role=dialog handling). Read the code before extending it; do not undo any of it.
MACHINE NOTE: the box is shared and slow under load; e2e timing checks can flake: rerun a failing scenario alone before concluding anything; the full layout matrix takes ~8 minutes.
Aim for about 75 minutes of focused work per agent; do not gold-plate; "node --test" and "npm run e2e" must be green when you finish.
BINDING CONTRACT between the agents (names are exact; extend, do not rename):
SIM
- new TD.Sim({ map, mode: 'versus', limit: 720 }). In versus: no automatic waves, startWave refused, no clear bonus, no win-wave; hp scaling by wave is off (units use base stats x attacker tech); state stays 'playing' until the round ends; then sim.state = 'over' and sim.vs.result = { winner: 'attacker'|'defender', t: <seconds>, integrityLost: n }.
- sim.cmd({ c, role, by, ...fields }) where role is 'defender' | 'attacker' (the server fills role from the seat; the sim REFUSES cross-role commands with reason 'role'). Solo/co-op commands (no role) behave exactly as before.
- defender commands: place, sell, upgrade, target (as today) and { c:'tool', id:'scan'|'patch'|'repair'|'quarantine', x?, y?, tid? }.
- attacker commands: { c:'spawn', kind, n?, gate? } buy and release now; { c:'stage', kind, n? } pay now, hold in the convoy; { c:'launch', gate? } release the convoy as a ~3 s stream; { c:'tech', id } buy the next level; { c:'ability', id:'emp'|'decoy'|'surge'|'ddos', tid?, gate? }. 'gate' is a spawn index (default: round robin).
- Every command returns { ok, reason? }. Reasons used: 'role','credits','cooldown','cap','max','bad_target','over'.
- sim.snapshot() gains a SHARED block 'vs': { t, lim, st /*staged count*/ } only. Role-private data comes from sim.privateState(role) -> attacker: { credits, income, tech:{armor,speed,health,regen,shield,stealth,crypt}, staged:[[kind,n]], cd:{emp,decoy,surge,ddos}, active:{surge,ddos} } ; defender: { cd:{scan,patch,repair,quarantine} }. fullState() carries mode, limit and map as today.
- ENEMIES entries have 'buyCost' (already added to every enemy kind by an earlier agent; verify).
- events: 'spawn' not needed; add { e:'emp', id }, { e:'surge' }, { e:'ddos' }, { e:'quarantine' }, { e:'scan', x, y }, { e:'repair' }, { e:'round', winner, t } as needed (small objects).
BOTS (public/js/bot.js, UMD like sim.js: window.NWBot / module.exports): NWBot.create(sim, role, { seed, skill }) -> { think(dt) } driven ONLY through sim.cmd/sim.preview/sim.privateState (the same API humans use). Defender bot: a productionised, lighter version of the maze+turret logic in tools/bot.js (reuse its ideas, keep it < ~400 lines, no heavy analytic model needed). Attacker bot: a budgeted spender that watches the tower mix (flyers when there is no anti-air, armoured units against filters/arcs, healers behind trojans), saves credits for convoys, buys tech, uses abilities sensibly.
PROTOCOL (see docs/PROTOCOL.md; add a "Versus" section)
- join/create takes { mode:'coop'|'versus' (default coop), limit?:480|720|960, rounds?: 2 }.
- versus lobby messages (client -> server): { t:'vs', c:'role', v:'attacker'|'defender'|'random' }, { t:'vs', c:'ready', v:boolean }, { t:'vs', c:'bot', v:'attacker'|'defender'|null } (host: put a computer in the empty seat with that role), { t:'vs', c:'start' } (host, when everyone is ready), { t:'vs', c:'next' } (continue after a round), { t:'vs', c:'rematch' }.
- server -> client: { t:'vs', phase:'lobby'|'countdown'|'playing'|'roundover'|'matchover', round:1|2, rounds, roles:{ '<slot>': 'attacker'|'defender' }, bot:{ slot?, role }|null, countdown?:seconds, limit, result?:{...}, scores?:[{slot, name, fellAt|null, integrityLost}] } on every change; role-private data { t:'priv', role, ...sim.privateState(role) } to each human at 4 Hz while playing; snapshots as today with the shared 'vs' block.
- commands arrive as { t:'cmd', c:..., ...} exactly as today; the server adds role from the seat. ctl pause/speed are rejected in versus ({t:'reject', reason:'versus'}).
- disconnect: the round freezes for the 60 s grace, then the remaining player wins the round.
MATCH RULES: two rounds, roles swapped after round 1 (host's first role choice, or random); a round ends when integrity reaches 0 (attacker wins, time recorded) or the timer hits the limit (defender wins). Match winner = the player whose attacking round ended earlier; if neither felled the server, the player who took off more integrity; else a draw.
ECONOMY (starting numbers, tuned later by the balance agent through constants in one VS table at the top of sim.js): attacker start 150, income 4/s + 0.02/s per second elapsed, lifetime bonus buyCost*0.004 per second alive capped at 50% of buyCost per unit, leak pays back the unit's buyCost; caps 250 units alive / 200 staged; defender start 250, trickle 2/s, kill reward round(buyCost*0.4); tech levels: armor +1 (5 levels), speed +8% (5), health +15% (5), regen +1% max hp/s (3), shield +40 per level (3), stealth: towers cannot target a unit for its first 1/1.5/2 s on the map (3 levels), crypt: resists slows 20/40/60% (3); costs 100*2^level. Abilities (credits, cooldown): emp (disable one tower 6 s; 80cr, 20 s), decoy (a harmless unit every tower prioritises 5 s; 60cr, 25 s), surge (all units +40% speed 6 s; 120cr, 40 s), ddos (all towers fire 40% slower 4 s; 200cr, 70 s). Defender tools: scan (clear emp + reveal stealth in radius 4 for 3 s; 40cr, 15 s), patch (instantly re-enable one tower; 30cr, 8 s), repair (+3 integrity up to max; 120cr, 30 s), quarantine (all units frozen 2 s; 150cr, 60 s).`
const RESULT = {
type: 'object',
properties: {
summary: { type: 'string' },
implemented: { type: 'array', items: { type: 'object', properties: { what: { type: 'string' }, details: { type: 'string' } }, required: ['what', 'details'] } },
contractChanges: { type: 'array', items: { type: 'string' } },
filesChanged: { type: 'array', items: { type: 'string' } },
testsAdded: { type: 'array', items: { type: 'string' } },
unitTests: { type: 'string' },
e2e: { type: 'string' },
notes: { type: 'string' },
},
required: ['summary', 'implemented', 'unitTests', 'e2e'],
}
const SIM = `${COMMON}
YOUR BRIEF (agent "vs-sim", ports 8610-8619). You OWN public/js/sim.js, public/js/bot.js (new), test/sim-versus.test.js (new), tools/ additions. Implement the SIM and BOTS part of the contract: versus mode in the Sim (economy, spawn/stage/launch, tech, abilities, defender tools, role checks, round timer and result, private state, snapshot vs block, events), the shared VS constants table at the top, and public/js/bot.js with a defender bot and an attacker bot. Also add a headless runner tools/versus.js: "node tools/versus.js --maps open,twin --limit 600 --seeds 6 [--attacker-skill 1 --defender-skill 1]" that plays bot-vs-bot rounds and prints a table (who won, time to fall, integrity lost, credits spent, units spawned) so the balance agent can tune later; keep it fast (all CPU cores via worker threads or child processes like tools/bot.js).
Unit tests (test/sim-versus.test.js) must cover: role refusal both ways, credits and caps, spawn vs stage vs launch, lifetime bonus and its cap, leak payback, every tech level effect on a spawned unit (armor, speed, health, regen, shield, stealth: towers skip a stealthed unit; crypt), each ability and tool incl. cooldowns and costs (emp disables a tower for its duration, decoy is prioritised and harmless, surge, ddos slows fire, scan reveals/clears, patch, repair never exceeds max, quarantine freezes), round end both ways and the result object, privateState shape, snapshot JSON round trip with the vs block, no regression of solo/co-op (existing tests keep passing), and bot smoke tests (a bot round runs to completion without throwing and without illegal commands on all maps).
Keep co-op/solo behaviour byte-identical when mode is not 'versus'.`
const SERVER = (prev) => `${COMMON}
YOUR BRIEF (agent "vs-server", ports 8620-8629). The sim agent finished (report: ${JSON.stringify(prev)}). You OWN server/*, test/server.test.js (and new test files for versus), docs/PROTOCOL.md, docs/DEPLOY.md only if needed, and public/js/controllers.js ONLY for the RemoteController message handling of the new messages (vs / priv) and exposing them (ctrl.vs, ctrl.priv, events 'vs' and 'priv'), plus LocalController support for a local versus game against a bot (ctrl.kind 'local', the human has a role and NWBot plays the other seat; no pause/speed). Implement the SERVER and PROTOCOL part of the contract: room mode versus, the lobby/ready/countdown/round/roundover/matchover state machine, seats and roles (random/choose/swap), the optional bot seat (server-side NWBot ticking with the room loop, think() at about 4 Hz, commands go through the same validated path as humans), role added to commands from the seat and cross-role refusal surfaced as reject, ctl pause/speed rejected, private data messages at 4 Hz, grace/forfeit rules, host migration, rematch, disconnect during countdown/roundover, snapshot size sanity, and docs/PROTOCOL.md "Versus" section. Security: a client can never see the other role's private data, never send commands for the other role, malformed vs messages count as malformed, and a bot seat cannot be used to run unbounded work (cap thinking time per tick).
INTERRUPTED EARLIER ATTEMPT: a previous run of this agent was cut off by an account spend limit in the middle of its work. The working tree already contains its UNVERIFIED partial work: server/versus.js, test/server-versus.test.js, test/controllers-versus.test.js, edits to server/room.js, server/index.js, public/js/controllers.js and docs/PROTOCOL.md; "node --test" currently shows about 4 failing tests because of it. Start by reading "git status" and "git diff", understand what is there, review it critically against the contract (do not trust it), keep what is good, fix what is wrong, finish what is missing, and make everything green. Do not duplicate files.
Tests: protocol tests with raw ws clients for the full match (two humans, and human + bot), role leaks, forged role, reconnect mid-round, forfeit, rematch, and that co-op rooms behave exactly as before.`
const CLIENT = (prev) => `${COMMON}
YOUR BRIEF (agent "vs-client", ports 8630-8639). The sim and server agents finished (reports: sim ${JSON.stringify(prev.sim)}; server ${JSON.stringify(prev.server)}). You OWN public/index.html, public/css/style.css, public/js/main.js, public/js/render.js, public/js/audio.js (new sfx) and e2e/. Implement the CLIENT part: (1) lobby: mode choice Co-op vs Versus, role choice (attacker / defender / random), round time limit, 'play against computer' (a bot in the other seat; also a SOLO versus game that needs no server using LocalController), ready/start/countdown, round-over and match-over screens (both rounds side by side, who won, rematch); the lobby/menu slots #menuOpts and #roomList exist (reserved earlier) but are not required for this; (2) ROLE-AWARE HUD: the defender keeps today's build palette plus a counter-tools bar (scan, patch, repair, quarantine with cooldown rings and costs) and the round timer; the attacker gets: the palette becomes the UNIT SHOP (all enemy kinds with buyCost, tap = buy 1, a x1/x5/x10 quantity selector, a Send-now/Stage toggle), a Convoy readout with a big LAUNCH button, a tech panel (7 upgrades with level pips and cost), an abilities bar (emp: tap then tap a tower; decoy; surge; ddos) with cooldown rings, the credits + income/s readout, units alive, round timer; the attacker cannot place towers; the attacker sees the defender's board live; (3) rendering for versus: units already render; add shield/stealth/decoy/emp visuals (a disabled tower looks disabled), surge/ddos/quarantine screen cues, spawn pulses at gates the attacker chooses (an attacker can tap a gateway to choose it); (4) phone-first layouts using the existing bar patterns (attacker shop must scale to 9+ unit kinds, convoy/launch always reachable), add the new controls to the 22-layout matrix (e2e/scenarios/05-layout-matrix.js) with the same objective reachability assertions; (5) sounds for the new actions; (6) help text for versus; (7) e2e: a scenario with TWO browsers (one attacker, one defender, real server) that plays a full short round (limit 60 s via a test option or server option), checks role-private data does not leak into the other client, the swap, the match result, plus a solo-vs-bot scenario; (8) keep co-op and solo untouched.`
const BALANCE = (prev) => `${COMMON}
YOUR BRIEF (agent "vs-balance", ports 8640-8649). All parts exist now (reports: ${JSON.stringify(prev)}). TIME-BOX HARD: at most 12 runs of tools/versus.js (each run in the background with a wait; do not babysit), then stop. You OWN only the VS constants table at the top of public/js/sim.js, the enemy buyCost values, and public/js/bot.js tuning. Goal: neither side wins more than about 60% of rounds on any of the 7 maps when two equally skilled bots play (limit 720 s); the defender must be able to survive a sensible attacker for a good while on easy maps; the attacker's lifetime bonus must matter but not snowball; abilities and tools must be used by the bots and matter. Report a before/after table and every constant you changed. Keep all tests green.`
const QA = (all) => `${COMMON}
YOUR BRIEF (independent QA, ports 8650-8659). Versus mode was built in 4 steps: ${JSON.stringify(all)}.
1. Run "cd ${ROOT} && node --test" and "cd ${ROOT} && npm run e2e" yourself (the layout matrix takes ~6 minutes); report exact results.
2. PLAY a full match with TWO real browsers (a desktop and a 390x844 phone with CDP touch) on the real server: humans in both roles, then human + bot in both roles, then solo versus bot with no server. Look at screenshots (Read tool) of every state: lobby, countdown, attacker shop (all unit kinds), staging and launch, tech, abilities, defender tools, round over, match over. Judge thumb reach, clarity, clutter, and whether a first-time attacker would understand what to do.
3. ATTACK the implementation: attacker sends defender commands and vice versa (raw ws), forged role, spamming spawn to hit caps, negative/huge n, NaN, staging 10^6 units, launching an empty convoy, using an ability on a dead tower, disconnect mid-round (both sides), reconnect, host leaves, rematch spam, three clients in a versus room, a coop client joining a versus room. Check the defender can never read attacker credits/composition from any message, the server stays responsive with a bot seat and 250 units, and snapshot size stays sane.
4. Review "git diff"/"git status" for sloppy code, protocol/doc/code mismatches, leftover debug.
Fix trivial regressions yourself (say what); report bigger issues with exact repro. No new features.`
phase('Sim')
const sim = await agent(SIM, { label: 'vs-sim', phase: 'Sim', schema: RESULT })
phase('Server')
const server = await agent(SERVER(sim), { label: 'vs-server', phase: 'Server', schema: RESULT })
phase('Client')
const client = await agent(CLIENT({ sim, server }), { label: 'vs-client', phase: 'Client', schema: RESULT })
phase('Balance')
const balance = await agent(BALANCE({ sim, server, client }), { label: 'vs-balance', phase: 'Balance', schema: RESULT })
phase('QA')
const qa = await agent(QA({ sim, server, client, balance }), {
label: 'qa', phase: 'QA',
schema: {
type: 'object',
properties: {
unitTests: { type: 'string' }, e2e: { type: 'string' },
regressions: { type: 'array', items: { type: 'string' } },
changedByQa: { type: 'array', items: { type: 'string' } },
securityFindings: { type: 'array', items: { type: 'string' } },
uxProblems: { type: 'array', items: { type: 'string' } },
verdict: { type: 'string' },
},
required: ['unitTests', 'e2e', 'verdict'],
},
})
return { sim, server, client, balance, qa }

View file

@ -445,3 +445,134 @@ input.code { text-align: center; letter-spacing: .5em; font-family: var(--mono);
.overlay { background: Canvas; } .overlay { background: Canvas; }
#side { border-color: CanvasText; } #side { border-color: CanvasText; }
} }
/* ================================================================ versus (attack vs defend), see js/versus.js
* #app[data-mode="versus"] is set while a versus game runs, data-role="attacker|defender" for the current round. Nothing below applies to solo or co-op. */
.vs-only { display: none; }
#app[data-mode="versus"] #statTime { display: flex; }
#app[data-mode="versus"] #vIncome { display: inline; }
#app[data-mode="versus"] #statWave, #app[data-mode="versus"] #btnWave, #app[data-mode="versus"] #btnAuto, #app[data-mode="versus"] #btnSpeed,
#app[data-mode="versus"] #btnPause, #app[data-mode="versus"] #netChip { display: none !important; } /* no waves, no pause, no speed in versus; nobody to invite mid-match */
#statTime { font-variant-numeric: tabular-nums; }
#statTime.low { border-color: var(--red); color: var(--red); background: #2a0e18; animation: pulse 0.8s infinite; }
#vIncome { color: var(--green); font-size: 11px; margin-left: 2px; }
@media (max-width: 420px) { #app[data-mode="versus"] #vIncome { display: none; } }
#app[data-mode="versus"] #nextwave { display: none; }
/* stage overlays */
.vshud { position: absolute; left: 8px; bottom: 8px; max-width: calc(100% - 64px); padding: 3px 10px; border-radius: 999px; background: rgba(8, 13, 26, .82); border: 1px solid var(--line); font: 11.5px/1.4 var(--mono); color: var(--dim); pointer-events: none; z-index: 1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.vsfx { position: absolute; right: 8px; top: 8px; display: flex; flex-direction: column; align-items: flex-end; gap: 4px; pointer-events: none; z-index: 2; }
.fxchip { padding: 3px 10px; border-radius: 999px; font: 700 11px/1.4 var(--mono); background: rgba(8, 13, 26, .92); border: 1px solid; }
.fxchip.surge { color: var(--amber); border-color: #8a6a1a; } .fxchip.ddos { color: #c9a2ff; border-color: #5b3a8a; } .fxchip.freeze { color: #bfeaff; border-color: #3a7a9a; }
.vscount { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; gap: 2px; padding: 10px 14px; background: rgba(4, 7, 14, .6); pointer-events: none; z-index: 3; }
.vsc-top { font-size: 12px; letter-spacing: .22em; color: var(--dim); }
.vsc-role { font-size: clamp(22px, 6vw, 38px); font-weight: 800; letter-spacing: .12em; }
.vsc-role.att { color: var(--red); text-shadow: 0 0 22px rgba(255, 92, 122, .6); } .vsc-role.def { color: var(--cyan); text-shadow: 0 0 22px rgba(77, 227, 255, .6); }
.vsc-sub { max-width: 30em; font-size: 13px; color: #bcd3f5; margin: 2px 0 4px; }
.vsc-num { font: 800 clamp(40px, 12vw, 72px)/1 var(--mono); color: #fff; }
.vsc-big { font-size: clamp(22px, 6vw, 34px); font-weight: 800; letter-spacing: .2em; color: var(--amber); }
#vsNote { z-index: 4; }
/* the dock under the board: unit shop (the palette), convoy row, abilities / tools, tech */
.vsbar { display: flex; flex-direction: column; gap: 6px; }
.vsrow { display: flex; gap: 6px; align-items: stretch; }
.vsctlrow { flex-wrap: wrap; }
.vsctl { flex: 0 0 auto; min-height: 46px; padding: 0 7px; font: 700 13px var(--mono); white-space: nowrap; }
.vsctl.on { background: #0f3550; border-color: var(--cyan); color: var(--cyan); }
.vslaunch { flex: 1 1 112px; min-width: 0; min-height: 46px; padding: 0 10px; gap: 8px; font-size: 14px; justify-content: flex-start; }
.vslaunch .lt { display: flex; flex-direction: column; align-items: flex-start; min-width: 0; line-height: 1.15; }
.vslaunch small { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 10.5px; font-weight: 500; opacity: .9; }
.vslaunch:not(:disabled) { animation: glow 1.6s infinite; }
.vslaunch:disabled, #vsSetup button.primary:disabled, #vsRoom button.primary:disabled, #vsEnd button.primary:disabled { background: #0c1426; border-color: #172540; color: #8da3c8; animation: none; }
.vsabil { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 6px; }
.vsbtn { position: relative; flex-direction: column; gap: 1px; padding: 4px 2px 3px; min-height: 48px; line-height: 1.1; overflow: hidden; }
.vsbtn .ic { width: 18px; height: 18px; }
.vsbtn .nm { font-size: 11px; max-width: 100%; overflow: hidden; text-overflow: ellipsis; }
.vsbtn .cost { font: 11.5px var(--mono); color: var(--amber); }
.vsbtn::after { content: ""; position: absolute; inset: 0; background: conic-gradient(rgba(4, 8, 16, .74) calc(var(--p, 0) * 1turn), transparent 0); pointer-events: none; }
.vsbtn .cd { position: absolute; inset: 0; z-index: 1; display: flex; align-items: center; justify-content: center; font: 700 15px var(--mono); color: #fff; text-shadow: 0 0 4px #000, 0 0 2px #000; pointer-events: none; }
.vsbtn.poor { color: #9fb2d4; } .vsbtn.poor .cost { color: #ff8fa3; } .vsbtn.idle { opacity: .55; }
.vsbtn.live { border-color: var(--amber); box-shadow: 0 0 0 2px rgba(255, 210, 77, .3); }
.vsbtn.armed { border-color: var(--cyan); background: #0f3550; box-shadow: inset 0 0 0 1px var(--cyan); }
.vsbtn.ready { border-color: var(--green); }
.vsbtn.confirm { border-color: var(--amber); background: #3a2c08; animation: glow 0.7s infinite; }
.vstech { display: block; }
.vshead { display: flex; align-items: baseline; gap: 8px; margin-bottom: 4px; font-size: 11px; letter-spacing: .14em; color: var(--dim); text-transform: uppercase; font-weight: 600; }
.vshead small { text-transform: none; letter-spacing: 0; font-weight: 400; font-size: 11px; opacity: .85; }
.vstiles { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 6px; }
.techbtn { flex-direction: column; gap: 0; padding: 4px 2px 3px; min-height: 56px; }
.techbtn .ic { width: 18px; height: 18px; color: var(--cyan); }
.techbtn .nm { font-size: 11.5px; } .techbtn .pips { font-size: 9px; letter-spacing: 1px; color: var(--cyan); line-height: 1; min-height: 9px; }
.techbtn.maxed { border-color: #1c6a55; } .techbtn.maxed .cost { color: var(--green); }
.techbtn.poor .cost { color: #ff8fa3; } .techbtn.poor .ic { opacity: .6; }
.ubtn.hit { background: #0f3550; border-color: var(--cyan); }
#info .actions [data-act="emp"].poor .cost { color: #ff8fa3; }
/* a tower's panel for the attacker: just EMP and close */
#app[data-role="attacker"] #info .actions [data-act="emp"] { flex-grow: 2; }
/* stacked layouts: the dock is pinned to the bottom of the side panel (thumb reach), the tech row scrolls like the shop */
@media (orientation: portrait), (max-width: 760px) and (min-height: 521px) {
#vsbar { position: sticky; bottom: 0; z-index: 2; margin: 0 -10px; padding: 6px 10px 8px; background: #0a101f; border-top: 1px solid var(--line); }
.vstiles { display: flex; overflow-x: auto; scrollbar-width: none; scroll-snap-type: x proximity; margin: 0 -10px; padding: 0 10px; }
.vstiles::-webkit-scrollbar { display: none; }
.techbtn { flex: 0 0 76px; scroll-snap-align: start; }
#palette.shop .tbtn { flex: 0 0 72px; min-height: 66px; }
#palette.shop { padding-top: 6px; padding-bottom: 4px; }
#palette.shop .tbtn canvas { width: 30px; height: 30px; }
}
@media (min-width: 640px) and (orientation: portrait), (min-width: 640px) and (max-width: 760px) and (min-height: 521px) {
.vstiles { display: grid; overflow: visible; margin: 0; padding: 0; grid-template-columns: repeat(auto-fill, minmax(84px, 1fr)); }
.techbtn { flex: none; }
}
/* short landscape: a 200 px column. Convoy controls wrap (Launch on its own row), abilities keep their four columns as icons + cost, the shop scrolls */
@media (orientation: landscape) and (max-height: 520px) {
#vsbar { position: sticky; bottom: 0; z-index: 2; margin: 0 -6px; padding: 5px 6px 6px; background: #0a101f; border-top: 1px solid var(--line); gap: 4px; }
.vsctlrow { flex-wrap: wrap; } .vsctl { min-height: 44px; flex: 1 1 0; padding: 0 4px; font-size: 12px; } .vslaunch { flex: 1 1 100%; min-height: 44px; }
.vsbtn { min-height: 44px; padding: 3px 1px; } .vsbtn .nm { display: none; } .vsbtn .cost { font-size: 11px; }
#palette.shop { max-height: calc(var(--tile-h) * 2.6 + 10px); }
.techbtn { min-height: 52px; padding: 3px 1px; } .techbtn .nm { font-size: 10px; } .vshead small { display: none; }
.vsfx { top: 4px; right: 4px; } .vshud { font-size: 10.5px; }
.vsc-sub { font-size: 12px; } .vsc-top { font-size: 10.5px; }
}
@media (max-width: 340px) { .vsctl { padding: 0 6px; font-size: 12px; } .vslaunch { padding: 0 8px; } }
/* dialogs */
.vsfield { display: flex; align-items: center; gap: 10px; margin: 10px 0; }
.vsfield .seg { flex: 1 1 auto; max-width: none; }
.flabel { flex: 0 0 104px; font-size: 12px; letter-spacing: .06em; color: var(--dim); }
@media (max-width: 480px) { .vsfield { flex-direction: column; align-items: stretch; gap: 3px; margin: 8px 0; } .flabel { flex: none; } }
.vsonline { margin-top: 12px; padding: 4px 12px 12px; border: 1px solid var(--line); border-radius: 12px; background: rgba(255, 255, 255, .02); }
.vsonline h3 { margin-top: 10px; }
@media (max-height: 640px) { .vsonline .field { margin: 6px 0; } #vsMapName { display: none; } .vsfield { margin: 6px 0; } } /* small phones: the map is the one picked in the menu (and visible behind) */
.vsroomhead { display: flex; align-items: center; gap: 10px; margin: 0 0 8px; flex-wrap: wrap; }
.vsroomhead .rc { font: 800 22px var(--mono); letter-spacing: .2em; color: var(--cyan); }
.vsroomhead .link { margin-left: auto; }
.vsseat { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; padding: 8px 10px; margin-bottom: 6px; border: 1px solid var(--line); border-radius: 10px; background: var(--panel); }
.vsseat.empty { border-style: dashed; color: var(--dim); }
.vsseat .sn { flex: 1 1 80px; min-width: 0; font-weight: 700; overflow: hidden; text-overflow: ellipsis; }
.vsseat .you, #players .pl .you { color: var(--dim); font-size: 12px; } .vsseat .off { color: var(--red); font-size: 12px; }
.vsseat .rdy { font-size: 12px; color: var(--dim); } .vsseat .rdy.ok { color: var(--green); }
.rolebadge { font: 700 10.5px/1.5 var(--mono); letter-spacing: .1em; padding: 1px 7px; border-radius: 6px; border: 1px solid; margin-left: auto; }
.rolebadge.attacker { color: var(--red); border-color: #6a2336; } .rolebadge.defender { color: var(--cyan); border-color: #1c5a70; }
#players .pl .rolebadge { margin-left: auto; }
#btnVsReady.on { background: #0f3550; border-color: var(--cyan); color: var(--cyan); }
.vscols { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 10px; margin-top: 8px; }
.vsround { padding: 10px 12px; border: 1px solid var(--line); border-radius: 12px; background: var(--panel); }
.vsround.pending { border-style: dashed; opacity: .75; }
.vsround h4, .vsscore h4 { margin: 0 0 6px; font-size: 11px; letter-spacing: .14em; color: var(--dim); text-transform: uppercase; font-weight: 600; }
.vsrow2 { display: flex; justify-content: space-between; align-items: baseline; gap: 10px; padding: 3px 0; border-bottom: 1px solid var(--line); font-size: 13px; }
.vsrow2:last-child { border-bottom: 0; }
.vsrow2 > span { color: var(--dim); flex: none; } .vsrow2 > b { font-family: var(--mono); text-align: right; font-size: 12.5px; }
.vsrow2 .good { color: var(--green); } .vsrow2 .bad { color: var(--red); }
.vsrow2 .rolebadge { margin-left: 0; }
.vsscore { margin-top: 12px; padding: 10px 12px; border: 1px solid var(--line); border-radius: 12px; }
@media (orientation: landscape) and (max-height: 520px) { .vsfield { margin: 4px 0; } .vsonline { margin-top: 6px; padding: 2px 10px 8px; } .vsroomhead .rc { font-size: 18px; } .vsseat { padding: 5px 8px; margin-bottom: 4px; } }
@media (prefers-reduced-motion: reduce) { .vslaunch:not(:disabled), .vsbtn.confirm, #statTime.low { animation: none; } }
/* the menu's three modes: one row where it fits; on a phone Play solo has the row to itself and Co-op / Versus share the next one (the foot stays two rows tall) */
.row.modes > .big { flex: 1 1 150px; padding: 0 10px; white-space: nowrap; }
@media (max-width: 560px) {
.row.modes > #btnSolo { flex-basis: 100%; }
.row.modes > #btnCoop, .row.modes > #btnVersus { flex: 1 1 120px; font-size: 15px; }
.row.modes > #btnCoop .ic, .row.modes > #btnVersus .ic { display: none; }
}

View file

@ -8,7 +8,7 @@
<meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-title" content="Netwall"> <meta name="apple-mobile-web-app-title" content="Netwall">
<meta name="description" content="Netwall: build firewalls, stretch the route, protect the server. A maze tower defence game with two-player co-op."> <meta name="description" content="Netwall: build firewalls, stretch the route, protect the server. A maze tower defence game with two-player co-op and attack-vs-defend versus.">
<title>Netwall</title> <title>Netwall</title>
<link rel="manifest" href="manifest.webmanifest"> <link rel="manifest" href="manifest.webmanifest">
<link rel="icon" href="icons/icon.svg" type="image/svg+xml"> <link rel="icon" href="icons/icon.svg" type="image/svg+xml">
@ -36,6 +36,23 @@
<symbol id="i-trash" viewBox="0 0 24 24"><path d="M5 7h14M10 7V4.5h4V7M7 7l1 12.5h8L17 7M10.5 11v5M13.5 11v5" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"/></symbol> <symbol id="i-trash" viewBox="0 0 24 24"><path d="M5 7h14M10 7V4.5h4V7M7 7l1 12.5h8L17 7M10.5 11v5M13.5 11v5" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-users" viewBox="0 0 24 24"><circle cx="9" cy="8.5" r="3.3" fill="currentColor"/><path d="M2.5 19.5c0-3.6 2.9-5.6 6.5-5.6s6.5 2 6.5 5.6z" fill="currentColor"/><circle cx="17" cy="9.5" r="2.5" fill="currentColor" opacity=".7"/><path d="M16.5 14.2c3 0 5 1.6 5 4.6h-4.2" fill="currentColor" opacity=".7"/></symbol> <symbol id="i-users" viewBox="0 0 24 24"><circle cx="9" cy="8.5" r="3.3" fill="currentColor"/><path d="M2.5 19.5c0-3.6 2.9-5.6 6.5-5.6s6.5 2 6.5 5.6z" fill="currentColor"/><circle cx="17" cy="9.5" r="2.5" fill="currentColor" opacity=".7"/><path d="M16.5 14.2c3 0 5 1.6 5 4.6h-4.2" fill="currentColor" opacity=".7"/></symbol>
<symbol id="i-target" viewBox="0 0 24 24"><circle cx="12" cy="12" r="7.5" fill="none" stroke="currentColor" stroke-width="2"/><circle cx="12" cy="12" r="2.2" fill="currentColor"/><path d="M12 2.5v4M12 17.5v4M2.5 12h4M17.5 12h4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></symbol> <symbol id="i-target" viewBox="0 0 24 24"><circle cx="12" cy="12" r="7.5" fill="none" stroke="currentColor" stroke-width="2"/><circle cx="12" cy="12" r="2.2" fill="currentColor"/><path d="M12 2.5v4M12 17.5v4M2.5 12h4M17.5 12h4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></symbol>
<symbol id="i-clock" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5" fill="none" stroke="currentColor" stroke-width="2.2"/><path d="M12 7v5.2l3.4 2" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-launch" viewBox="0 0 24 24"><path d="M6 18L18 6M9 6h9v9" fill="none" stroke="currentColor" stroke-width="2.8" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-ab-emp" viewBox="0 0 24 24"><path d="M13.5 3L5.5 13.5h5.5L10 21l8.5-11h-5.5z" fill="currentColor"/></symbol>
<symbol id="i-ab-decoy" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8" fill="none" stroke="currentColor" stroke-width="2" stroke-dasharray="3.2 3"/><circle cx="12" cy="12" r="3" fill="currentColor"/></symbol>
<symbol id="i-ab-surge" viewBox="0 0 24 24"><path d="M5 18l7-7 7 7M5 11.5l7-7 7 7" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-ab-ddos" viewBox="0 0 24 24"><path d="M4.5 15a7.5 7.5 0 0115 0M8 15a4 4 0 018 0" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/><circle cx="12" cy="17.5" r="1.8" fill="currentColor"/><path d="M4 21h16" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-dasharray="1 3.2"/></symbol>
<symbol id="i-tl-scan" viewBox="0 0 24 24"><circle cx="10.5" cy="10.5" r="5.8" fill="none" stroke="currentColor" stroke-width="2.2"/><path d="M15 15l5 5" stroke="currentColor" stroke-width="2.6" stroke-linecap="round"/></symbol>
<symbol id="i-tl-patch" viewBox="0 0 24 24"><rect x="4" y="4" width="16" height="16" rx="4" fill="none" stroke="currentColor" stroke-width="2.2"/><path d="M12 8v8M8 12h8" stroke="currentColor" stroke-width="2.4" stroke-linecap="round"/></symbol>
<symbol id="i-tl-repair" viewBox="0 0 24 24"><path d="M4.5 19.5L13 11" stroke="currentColor" stroke-width="3" stroke-linecap="round"/><circle cx="16.2" cy="7.8" r="4" fill="none" stroke="currentColor" stroke-width="2.2"/></symbol>
<symbol id="i-tl-quarantine" viewBox="0 0 24 24"><rect x="5.5" y="11" width="13" height="9.5" rx="2.2" fill="currentColor"/><path d="M8.5 11V8a3.5 3.5 0 017 0v3" fill="none" stroke="currentColor" stroke-width="2.2"/></symbol>
<symbol id="i-te-armor" viewBox="0 0 24 24"><path d="M12 3l7 3v5.5c0 4.6-3 7.6-7 9.5-4-1.9-7-4.9-7-9.5V6z" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linejoin="round"/></symbol>
<symbol id="i-te-speed" viewBox="0 0 24 24"><path d="M5.5 6l6 6-6 6M12.5 6l6 6-6 6" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-te-health" viewBox="0 0 24 24"><path d="M12 5v14M5 12h14" stroke="currentColor" stroke-width="3.4" stroke-linecap="round"/></symbol>
<symbol id="i-te-regen" viewBox="0 0 24 24"><path d="M19 12a7 7 0 11-2.2-5.1M19 4.5v4.3h-4.3" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-te-shield" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8" fill="none" stroke="currentColor" stroke-width="2.2"/><path d="M7.8 12a4.2 4.2 0 014.2-4.2" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/></symbol>
<symbol id="i-te-stealth" viewBox="0 0 24 24"><path d="M2.5 12s3.6-6 9.5-6 9.5 6 9.5 6-3.6 6-9.5 6-9.5-6-9.5-6z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/><circle cx="12" cy="12" r="2.6" fill="currentColor"/><path d="M4.5 20L19.5 4" stroke="currentColor" stroke-width="2.4" stroke-linecap="round"/></symbol>
<symbol id="i-te-crypt" viewBox="0 0 24 24"><circle cx="8" cy="12" r="3.6" fill="none" stroke="currentColor" stroke-width="2.2"/><path d="M11.6 12H21M17.5 12v3.2M20.5 12v2.2" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/></symbol>
<symbol id="i-fs" viewBox="0 0 24 24"><path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></symbol> <symbol id="i-fs" viewBox="0 0 24 24"><path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></symbol>
</defs> </defs>
</svg> </svg>
@ -44,9 +61,10 @@
<header id="topbar"> <header id="topbar">
<button id="btnMenu" class="icon" aria-label="Menu"><svg class="ic"><use href="#i-menu"/></svg></button> <button id="btnMenu" class="icon" aria-label="Menu"><svg class="ic"><use href="#i-menu"/></svg></button>
<div class="stat vs-only" id="statTime" title="Round time left"><svg class="ic"><use href="#i-clock"/></svg><b id="vTime">0:00</b></div>
<div class="stat" id="statWave" title="Wave"><span class="lbl">WAVE</span><b id="vWave">0</b><small id="vWaveMax"></small></div> <div class="stat" id="statWave" title="Wave"><span class="lbl">WAVE</span><b id="vWave">0</b><small id="vWaveMax"></small></div>
<div class="stat" id="statLives" title="Server integrity"><svg class="ic"><use href="#i-heart"/></svg><b id="vLives">20</b></div> <div class="stat" id="statLives" title="Server integrity"><svg class="ic"><use href="#i-heart"/></svg><b id="vLives">20</b></div>
<div class="stat" id="statGold" title="Credits"><svg class="ic"><use href="#i-coin"/></svg><b id="vGold">0</b></div> <div class="stat" id="statGold" title="Credits"><svg class="ic"><use href="#i-coin"/></svg><b id="vGold">0</b><small id="vIncome" class="vs-only"></small></div>
<button id="netChip" class="chip" type="button" hidden title="Co-op room: tap to invite your partner" aria-label="Co-op room. Tap to invite your partner"><svg class="ic"><use href="#i-users"/></svg><span id="netRoom"></span><span id="netPing"></span><svg class="ic share"><use href="#i-share"/></svg></button> <button id="netChip" class="chip" type="button" hidden title="Co-op room: tap to invite your partner" aria-label="Co-op room. Tap to invite your partner"><svg class="ic"><use href="#i-users"/></svg><span id="netRoom"></span><span id="netPing"></span><svg class="ic share"><use href="#i-share"/></svg></button>
<div class="spacer"></div> <div class="spacer"></div>
<button id="btnWave" class="primary" aria-label="Start next wave"><svg class="ic"><use href="#i-play"/></svg><span id="btnWaveText">Wave 1</span></button> <button id="btnWave" class="primary" aria-label="Start next wave"><svg class="ic"><use href="#i-play"/></svg><span id="btnWaveText">Wave 1</span></button>
@ -61,6 +79,10 @@
<div id="hint" class="hint" hidden></div> <div id="hint" class="hint" hidden></div>
<div id="banner" class="banner" aria-live="polite"></div> <div id="banner" class="banner" aria-live="polite"></div>
<button id="pausedTag" class="paused-tag" type="button" hidden><svg class="ic"><use href="#i-play"/></svg><span>PAUSED<small>tap to resume</small></span></button> <button id="pausedTag" class="paused-tag" type="button" hidden><svg class="ic"><use href="#i-play"/></svg><span>PAUSED<small>tap to resume</small></span></button>
<div id="vsHud" class="vshud" hidden></div>
<div id="vsNote" class="hint info" hidden></div>
<div id="vsFx" class="vsfx" aria-live="polite"></div>
<div id="vsCount" class="vscount" hidden></div>
<div id="toasts" aria-live="polite"></div> <div id="toasts" aria-live="polite"></div>
<button id="btnFit" class="icon floating" aria-label="Reset zoom" hidden><svg class="ic"><use href="#i-fit"/></svg></button> <button id="btnFit" class="icon floating" aria-label="Reset zoom" hidden><svg class="ic"><use href="#i-fit"/></svg></button>
<div id="confirm" class="confirm" hidden> <div id="confirm" class="confirm" hidden>
@ -79,6 +101,8 @@
<aside id="side"> <aside id="side">
<section id="palette" aria-label="Build"></section> <section id="palette" aria-label="Build"></section>
<section id="vsbar" class="vsbar" aria-label="Versus controls" hidden></section>
<section id="vstech" class="vstech" aria-label="Tech upgrades" hidden></section>
<section id="info" aria-live="polite"></section> <section id="info" aria-live="polite"></section>
<section id="nextwave"></section> <section id="nextwave"></section>
<section id="players" hidden></section> <section id="players" hidden></section>
@ -98,9 +122,10 @@
<div id="diffPick" class="seg" role="radiogroup" aria-label="Difficulty"></div><!-- Easy / Normal / Hard, built by main.js from TD.DIFFICULTIES --> <div id="diffPick" class="seg" role="radiogroup" aria-label="Difficulty"></div><!-- Easy / Normal / Hard, built by main.js from TD.DIFFICULTIES -->
<p id="diffNote" class="diffnote"></p> <p id="diffNote" class="diffnote"></p>
</div> </div>
<div class="row"> <div class="row modes">
<button id="btnSolo" class="primary big"><svg class="ic"><use href="#i-play"/></svg>Play solo</button> <button id="btnSolo" class="primary big"><svg class="ic"><use href="#i-play"/></svg>Play solo</button>
<button id="btnCoop" class="big"><svg class="ic"><use href="#i-users"/></svg>Co-op online</button> <button id="btnCoop" class="big"><svg class="ic"><use href="#i-users"/></svg>Co-op online</button>
<button id="btnVersus" class="big"><svg class="ic"><use href="#i-ab-emp"/></svg>Versus</button>
</div> </div>
<button id="btnResume" class="big resume" hidden></button> <button id="btnResume" class="big resume" hidden></button>
<div class="row small"> <div class="row small">
@ -144,6 +169,77 @@
</div> </div>
</div> </div>
<!-- ===== versus setup (solo against the computer, or create / join an online room) ===== -->
<div id="vsSetup" class="overlay" hidden role="dialog" aria-modal="true" aria-labelledby="vsSetupTitle">
<div class="card">
<div class="card-body">
<h2 id="vsSetupTitle">Versus</h2>
<p class="muted lead">One of you builds the maze, the other sends the packets. Two rounds, the roles swap. Whoever breaks the server fastest wins.</p>
<p class="muted small" id="vsMapName"></p>
<div class="vsfield"><span class="flabel">You play</span><div id="vsRolePick" class="seg" role="radiogroup" aria-label="Your role"></div></div>
<div class="vsfield"><span class="flabel">Round length</span><div id="vsLimitPick" class="seg" role="radiogroup" aria-label="Round length"></div></div>
<div class="vsfield"><span class="flabel">Computer skill</span><div id="vsSkillPick" class="seg" role="radiogroup" aria-label="Computer skill"></div></div>
<div class="vsonline">
<h3>Online</h3>
<label class="field"><span>Your name</span><input id="vsName" maxlength="16" autocomplete="nickname" autocapitalize="words" spellcheck="false" placeholder="Player"></label>
<div class="joinrow">
<input id="vsCode" class="code" maxlength="4" autocomplete="off" autocapitalize="characters" spellcheck="false" inputmode="text" placeholder="ABCD" aria-label="Room code">
<button id="btnVsJoin" class="big">Join</button>
</div>
</div>
</div>
<div class="card-foot">
<p id="vsMsg" class="msg" role="status"></p>
<div class="row">
<button id="btnVsComputer" class="primary big">Play the computer</button>
<button id="btnVsCreate" class="big"><svg class="ic"><use href="#i-users"/></svg>Create room</button>
</div>
<div class="row small"><button id="btnVsBack" class="link">&larr; Back</button></div>
</div>
</div>
</div>
<!-- ===== versus room: roles, ready, computer seat, start ===== -->
<div id="vsRoom" class="overlay" hidden role="dialog" aria-modal="true" aria-labelledby="vsRoomTitle">
<div class="card">
<div class="card-body">
<h2 id="vsRoomTitle">Versus room</h2>
<div class="vsroomhead"><span class="rc" id="vsRoomCode"></span><span id="vsRoomLimit" class="muted small"></span><button id="btnVsInvite" type="button" class="link">Invite</button></div>
<div id="vsSeats" class="vsseats"></div>
<div class="vsfield"><span class="flabel">Your role</span><div id="vsRoomRole" class="seg" role="radiogroup" aria-label="Your role"></div></div>
<div class="vsfield" id="vsOppField"><span class="flabel">Opponent</span><div id="vsRoomOpp" class="seg" role="radiogroup" aria-label="Opponent"></div></div>
<p id="vsRoomNote" class="muted small"></p>
</div>
<div class="card-foot">
<p id="vsRoomMsg" class="msg" role="status"></p>
<div class="row">
<button id="btnVsReady" class="big">I'm ready</button>
<button id="btnVsStart" class="primary big">Start match</button>
</div>
<div class="row small"><button id="btnVsLeave" class="link">Leave room</button></div>
</div>
</div>
</div>
<!-- ===== versus: round over / match over ===== -->
<div id="vsEnd" class="overlay" hidden role="dialog" aria-modal="true" aria-labelledby="vsEndTitle" aria-describedby="vsEndText">
<div class="card wide">
<div class="card-body">
<h2 id="vsEndTitle"></h2>
<p id="vsEndText" class="muted"></p>
<div id="vsEndRounds" class="vsrounds"></div>
</div>
<div class="card-foot">
<p id="vsEndWait" class="msg" role="status" hidden></p>
<div class="row">
<button id="btnVsNext" class="primary big">Next round</button>
<button id="btnVsRematch" class="primary big">Rematch</button>
<button id="btnVsEndMenu" class="big">Menu</button>
</div>
</div>
</div>
</div>
<!-- ===== help ===== --> <!-- ===== help ===== -->
<div id="help" class="overlay" hidden role="dialog" aria-modal="true" aria-labelledby="helpTitle"> <div id="help" class="overlay" hidden role="dialog" aria-modal="true" aria-labelledby="helpTitle">
<div class="card wide"> <div class="card wide">
@ -156,6 +252,7 @@
<li><b>Credits.</b> Earned from kills and every cleared wave. Upgrade turrets up to level 3. Sell for 70% back (walls refund in full).</li> <li><b>Credits.</b> Earned from kills and every cleared wave. Upgrade turrets up to level 3. Sell for 70% back (walls refund in full).</li>
<li><b>Controls.</b> <span class="kbd-only">Click to build, drag to paint walls, right-click to cancel. Keys <span id="helpKeys">1&ndash;6</span> pick a tower, Space starts a wave, U upgrades, X sells, T changes targeting, P pauses, F changes speed, M mutes, wheel zooms.</span> <li><b>Controls.</b> <span class="kbd-only">Click to build, drag to paint walls, right-click to cancel. Keys <span id="helpKeys">1&ndash;6</span> pick a tower, Space starts a wave, U upgrades, X sells, T changes targeting, P pauses, F changes speed, M mutes, wheel zooms.</span>
<span class="touch-only">Tap a tower type, then tap the map to preview; nudge the cell with the arrows and tap &#10003; to build. Walls paint as you drag. Pinch to zoom, two fingers to pan, long-press to ping your partner.</span></li> <span class="touch-only">Tap a tower type, then tap the map to preview; nudge the cell with the arrows and tap &#10003; to build. Walls paint as you drag. Pinch to zoom, two fingers to pan, long-press to ping your partner.</span></li>
<li><b>Versus.</b> One player <b>defends</b> (builds the maze and turrets as usual, with counter-tools: Scan, Patch, Repair, Quarantine) and the other <b>attacks</b>: spend credits on packets (tap a unit to buy; <i>Stage</i> pays now and holds them for one <b>Launch</b>), buy tech upgrades, and sabotage the defence (EMP a turret, Decoy, Surge, DDoS). Tap a gateway to choose where packets enter. A round ends when the server falls or the clock runs out; then the roles swap. Whoever breaks the server fastest wins the match. No pause, no speed control. Play a friend online or the computer.</li>
<li><b>Co-op.</b> Both players share everything and can build, sell and upgrade at the same time. You see each other's cursors; long-press / Alt-click pings the map.</li> <li><b>Co-op.</b> Both players share everything and can build, sell and upgrade at the same time. You see each other's cursors; long-press / Alt-click pings the map.</li>
</ul> </ul>
</div> </div>
@ -186,9 +283,11 @@
</div> </div>
<script src="js/sim.js"></script> <script src="js/sim.js"></script>
<script src="js/bot.js"></script>
<script src="js/audio.js"></script> <script src="js/audio.js"></script>
<script src="js/controllers.js"></script> <script src="js/controllers.js"></script>
<script src="js/render.js"></script> <script src="js/render.js"></script>
<script src="js/versus.js"></script>
<script src="js/main.js"></script> <script src="js/main.js"></script>
</body> </body>
</html> </html>

View file

@ -95,8 +95,24 @@
clear: () => { tone(660, 0.09, 'triangle', 0.2); tone(880, 0.09, 'triangle', 0.2, 0, 0.09); tone(1320, 0.2, 'triangle', 0.2, 0, 0.18); }, clear: () => { tone(660, 0.09, 'triangle', 0.2); tone(880, 0.09, 'triangle', 0.2, 0, 0.09); tone(1320, 0.2, 'triangle', 0.2, 0, 0.18); },
ping: () => { tone(1320, 0.18, 'sine', 0.25, 1760); tone(1760, 0.3, 'sine', 0.12, 0, 0.12); }, ping: () => { tone(1320, 0.18, 'sine', 0.25, 1760); tone(1760, 0.3, 'sine', 0.12, 0, 0.12); },
join: () => { tone(660, 0.1, 'triangle', 0.2); tone(990, 0.16, 'triangle', 0.2, 0, 0.1); }, join: () => { tone(660, 0.1, 'triangle', 0.2); tone(990, 0.16, 'triangle', 0.2, 0, 0.1); },
// versus: attacker purchases, abilities, defender tools, the round countdown
buy: () => { tone(500, 0.06, 'square', 0.16, 760); noise(0.04, 0.08, 'highpass', 4000); },
stage: () => { tone(380, 0.07, 'triangle', 0.2, 300); tone(300, 0.08, 'triangle', 0.18, 0, 0.06); },
launch: () => { tone(220, 0.5, 'sawtooth', 0.2, 880); noise(0.4, 0.2, 'bandpass', 600, 3000); tone(880, 0.2, 'square', 0.12, 1320, 0.4); },
tech: () => { tone(440, 0.07, 'triangle', 0.2); tone(660, 0.07, 'triangle', 0.2, 0, 0.07); tone(880, 0.07, 'triangle', 0.2, 0, 0.14); tone(1320, 0.18, 'triangle', 0.18, 0, 0.21); },
emp: () => { noise(0.35, 0.3, 'bandpass', 4000, 200); tone(1800, 0.3, 'sawtooth', 0.14, 90); },
decoy: () => { tone(900, 0.08, 'sine', 0.22, 1400); tone(1400, 0.1, 'sine', 0.18, 900, 0.09); },
surge: () => { tone(200, 0.5, 'sawtooth', 0.2, 700); tone(300, 0.5, 'square', 0.1, 1000, 0.05); },
ddos: () => { noise(0.6, 0.28, 'lowpass', 2500, 120); tone(90, 0.6, 'sawtooth', 0.3, 40); },
scan: () => { tone(1500, 0.16, 'sine', 0.2, 900); tone(1500, 0.16, 'sine', 0.15, 900, 0.18); },
patch: () => { tone(520, 0.08, 'triangle', 0.22); tone(780, 0.12, 'triangle', 0.22, 0, 0.08); },
repair: () => { tone(440, 0.12, 'triangle', 0.2, 660); tone(660, 0.2, 'triangle', 0.2, 990, 0.1); },
quarantine: () => { tone(1200, 0.5, 'sine', 0.2, 200); noise(0.5, 0.15, 'highpass', 5000, 1500); },
breach: () => { tone(600, 0.08, 'triangle', 0.18, 900); tone(150, 0.2, 'sine', 0.35, 70); }, // what a leak sounds like to the attacker: the server took a hit
tick: () => tone(880, 0.06, 'square', 0.12),
go: () => { tone(660, 0.1, 'square', 0.18); tone(990, 0.25, 'square', 0.2, 0, 0.1); },
}; };
const MIN_GAP = { shot_uplink: 0.12, shot_filter: 0.06, kill: 0.05, arc: 0.07, boom: 0.08, shot_mortar: 0.1, shot_ids: 0.08, wall: 0.03 }; const MIN_GAP = { buy: 0.03, breach: 0.08, shot_uplink: 0.12, shot_filter: 0.06, kill: 0.05, arc: 0.07, boom: 0.08, shot_mortar: 0.1, shot_ids: 0.08, wall: 0.03 };
function sfx(name) { function sfx(name) {
if (muted || !unlocked || !ctx || !SFX[name]) return; if (muted || !unlocked || !ctx || !SFX[name]) return;

520
public/js/bot.js Normal file
View file

@ -0,0 +1,520 @@
/*
* NETWALL versus bots: a computer opponent for either side (docs/VERSUS.md).
*
* const bot = NWBot.create(sim, 'defender' | 'attacker', { seed, skill, by });
* bot.think(dt); // call it with the sim seconds that passed (every tick is fine); it decides about once per sim second
*
* Loaded as a classic <script> in the browser (window.NWBot, needs window.TD from sim.js first) and with require() in Node (the server and
* tools/versus.js). It drives the game ONLY the way a human does: sim.cmd({ role, by, ... }) for every action, sim.preview / the public
* board and tower list to look, and sim.privateState(its own role) for what only its own side may see. The defender never looks at the
* attacker's convoy, tech or credits; the attacker never looks at the defender's cooldowns. All randomness is a seeded PRNG (no
* Math.random: the same seed plays the same game). `skill` 0..1 (default 1) slows its decisions, adds noise and drops the clever parts
* (maze, tools, tech, abilities) for the weakest settings. Every command is checked against affordability and cooldowns first, so a bot
* never sends a command the sim would refuse for a reason a human's UI would have prevented (it can still meet 'monster' / 'blocks' /
* 'occupied' when the board changes under a wall or turret placement, exactly like a human).
*/
(function (root, factory) {
if (typeof module === 'object' && module.exports) module.exports = factory(require('./sim.js'));
else root.NWBot = factory(root.TD);
})(typeof self !== 'undefined' ? self : this, function (TD) {
'use strict';
const { VS, TOWERS, ENEMIES, ENEMY_ORDER } = TD;
const clamp = (v, lo, hi) => (v < lo ? lo : v > hi ? hi : v);
const perHit = (d, armor) => Math.max(d - armor, d * 0.25);
function prng(seed) { // mulberry32
let a = seed >>> 0;
return function () {
a = (a + 0x6D2B79F5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
class Base {
constructor(sim, role, o) {
o = o || {};
this.sim = sim; this.role = role;
this.by = o.by | 0;
this.skill = clamp(o.skill === undefined || o.skill === null ? 1 : +o.skill, 0, 1);
this.rng = prng((o.seed === undefined ? 1 : o.seed) * 7919 + (role === 'defender' ? 13 : 29));
this.interval = 1 + (1 - this.skill) * 3; // sim seconds between decisions
this.clock = this.rng() * this.interval; // two bots do not wake on the same tick
this.refused = []; // the last few refusals (for the tools that watch the bots)
}
// the one door to the sim: carries the role and the seat
cmd(c) {
const r = this.sim.cmd(Object.assign({ role: this.role, by: this.by }, c));
if (!r.ok && this.refused.length < 20) this.refused.push({ c: c.c, id: c.id || c.type || c.kind, reason: r.reason });
return r;
}
think(dt) {
if (this.sim.state !== 'playing') return;
this.clock += dt;
if (this.clock < this.interval) return;
this.clock = 0;
this.act();
}
}
// ====================================================================================================================
// The defender: turrets where the route is, a maze of wall lines, upgrades, and the counter-tools.
// ====================================================================================================================
const TURRETS = TD.TOWER_ORDER.filter((t) => TOWERS[t].role !== 'wall'); // whatever the table holds (a new tower type is simply another candidate)
const DIRS = [[1, 0], [-1, 0], [0, 1], [0, -1]];
// Until it has a few turrets the defender does not know what is coming; a crowd (ground or air) at the very start is what loses a round
// fastest, and cheap rapid fire stops that best per credit. After the opening the scores below follow what it has actually seen.
const OPENING = { filter: 3, arc: 1.2, throttle: 0.6, mortar: 0.5, ids: 0.4, sandbox: 0.3, balancer: 0.1, uplink: 0.1 };
class Defender extends Base {
constructor(sim, o) {
super(sim, 'defender', o);
const r = this.rng, s = this.skill;
this.share = (0.12 + 0.2 * r()) * (s < 0.3 ? 0 : s); // the share of all the credits it has seen that may go into walls
this.openN = 7 + Math.floor(r() * 4); // turrets that count as the opening (and come before the first wall)
this.jitter = 0.1 + (1 - s) * 0.5; // relative noise on every score
this.fav = {}; // every player has favourites
for (const t of TURRETS) this.fav[t] = 0.85 + 0.3 * r();
this.types = TURRETS.filter((t) => s > 0.5 || (TOWERS[t].role !== 'control' && TOWERS[t].role !== 'support')); // the fiddly ones are for the better players
this.plan = []; // wall cells still to place
this.spentWalls = 0; this.spentOther = 0;
this.nextSeg = 0; this.noSegRev = -1;
this.th = { air: 0.15, armor: 0.1, swarm: 0.5 }; // what it has been seeing (moving averages); the start is a guess: expect a crowd, mostly on the ground
this.clock = this.interval; // the defender builds at once: a round starts with the attacker's credits in hand
this.geo = null; this.tables = {};
this.badUntil = new Map(); // cells where a turret just failed to go up (a packet in the way): not again for a while
}
act() {
this.observe();
if (this.skill >= 0.3) this.tools();
for (let n = 0; n < 10; n++) if (!this.step()) break; // (the opening spends the whole start purse in one go)
}
// ---- what is coming: the share of flyers / armoured / tiny units among what is on the board (judged by kind and hit points, as the screen shows them)
observe() {
const ms = this.sim.monsters.filter((m) => !m.dead);
if (!ms.length) return;
let air = 0, armor = 0, small = 0;
for (const m of ms) {
const d = ENEMIES[m.kind];
if (d.air) air++;
if (d.armor >= 3 || d.shield || m.maxhp >= 300) armor++;
if (m.maxhp <= 20) small++;
}
const a = 0.25, n = ms.length;
this.th.air += a * (air / n - this.th.air);
this.th.armor += a * (armor / n - this.th.armor);
this.th.swarm += a * (Math.min(1, (small + Math.max(0, n - 12)) / n) - this.th.swarm);
}
// ---- counter-tools: patch / scan EMPed towers, scan stealth, repair, quarantine
tools() {
const sim = this.sim, T = VS.TOOLS, cd = sim.privateState('defender').cd, rng = this.rng;
const can = (id) => cd[id] <= 0 && sim.gold >= T[id].cost;
const awake = rng() < 0.45 + 0.55 * this.skill; // a slower player reacts a decision later
const emped = sim.towers.filter((t) => t.empT > 0);
if (emped.length && awake) {
const r2 = T.scan.radius * T.scan.radius, near = (a, b) => (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y) <= r2 * 0.5;
const group = emped.filter((t) => near(t, emped[0]));
if (group.length >= 2 && can('scan')) {
const cx = group.reduce((s, t) => s + t.x + 0.5, 0) / group.length, cy = group.reduce((s, t) => s + t.y + 0.5, 0) / group.length;
this.cmd({ c: 'tool', id: 'scan', x: cx, y: cy });
} else if (can('patch') && sim.gold >= T.patch.cost + 20) this.cmd({ c: 'tool', id: 'patch', tid: emped[0].id });
}
const hidden = this.silent();
if (hidden.length >= 2 && awake && can('scan') && sim.gold >= T.scan.cost + 60) {
const core = sim.board.core, h = hidden.reduce((a, b) => (Math.hypot(a.x - core.x, a.y - core.y) < Math.hypot(b.x - core.x, b.y - core.y) ? a : b));
this.cmd({ c: 'tool', id: 'scan', x: h.x, y: h.y });
}
if (can('repair') && sim.lives <= sim.maxLives - T.repair.amount && sim.gold >= T.repair.cost + 40) this.cmd({ c: 'tool', id: 'repair' });
if (can('quarantine') && awake && sim.gold >= T.quarantine.cost) {
const core = sim.board.core; // units about to reach the server, by the integrity they would cost
let danger = 0;
for (const m of sim.monsters) if (!m.dead && Math.hypot(m.x - core.x - 0.5, m.y - core.y - 0.5) <= 5) danger += ENEMIES[m.kind].leak;
if (danger >= Math.max(4, sim.lives * 0.35)) this.cmd({ c: 'tool', id: 'quarantine' });
}
}
// Units standing inside the reach of an attack tower that is working and could hit them, while that tower has no target: something is hiding
// them (stealth). Only what a screen shows: the tower list, whether a tower is out (EMP) and what it is aiming at.
silent() {
const out = [];
for (const m of this.sim.monsters) {
if (m.dead) continue;
for (const t of this.sim.towers) {
const d = TOWERS[t.type];
if (d.role !== 'attack' || t.empT > 0 || t.tgt !== 0 || (m.air ? !d.air : !d.ground)) continue;
const r = d.levels[t.level - 1].range, dx = m.x - t.x - 0.5, dy = m.y - t.y - 0.5;
if (dx * dx + dy * dy <= r * r) { out.push(m); break; }
}
}
return out;
}
turretCount() { let n = 0; for (const t of this.sim.towers) if (TOWERS[t.type].role !== 'wall') n++; return n; }
step() {
if (this.turretCount() >= this.openN && this.mazeStep()) return true;
return this.buyBest();
}
// ---- the maze: wall lines that lengthen the route, under a budget that is a share of everything it has been paid
wallBudget() {
const sim = this.sim, total = this.spentWalls + this.spentOther + sim.gold;
const ramp = clamp((sim.time - 15) / 45, 0, 1); // the first minute belongs to the turrets
return this.share * ramp * total + (ramp > 0 ? 10 : 0) - this.spentWalls;
}
mazeStep() {
const sim = this.sim, wc = TOWERS.wall.levels[0].cost;
if (!this.plan.length) {
if (this.share <= 0 || sim.time < this.nextSeg || this.noSegRev === sim.rev) return false;
if (this.wallBudget() < 2 * wc || sim.gold < 2 * wc) return false;
this.nextSeg = sim.time + 4;
const seg = this.bestSegment();
if (!seg) { this.noSegRev = sim.rev; return false; }
this.plan = seg;
}
let placed = 0;
while (this.plan.length && sim.gold >= wc && this.wallBudget() >= wc) {
const c = this.plan[0], r = this.cmd({ c: 'place', type: 'wall', x: c[0], y: c[1] });
if (r.ok) { placed++; this.spentWalls += wc; this.plan.shift(); }
else if (r.reason === 'monster') break; // a packet is in the way: try again next time
else if (r.reason === 'occupied') this.plan.shift();
else { this.plan = []; break; }
}
return placed > 0;
}
// The wall line (from a border / a solid cell, straight, up to 14 cells) that adds the most route length per credit. A sample of
// the possible lines, a path field per candidate: the cost is bounded (about 700 fields).
bestSegment() {
const sim = this.sim, b = sim.board, cols = b.cols, rows = b.rows, rng = this.rng, wc = TOWERS.wall.levels[0].cost;
const mc = sim.monsterCells(), solid = Uint8Array.from(b.solid), base = b.routeLen, geo = this.geometry();
const starts = [];
for (let y = 0; y < rows; y++) for (let x = 0; x < cols; x++) {
const i = y * cols + x;
if (solid[i] || b.isSpecial(x, y) || mc.reserved.has(i)) continue;
for (const d of DIRS) {
const px = x - d[0], py = y - d[1];
if (px < 0 || py < 0 || px >= cols || py >= rows || solid[py * cols + px]) starts.push([x, y, d]);
}
}
for (let i = starts.length - 1; i > 0; i--) { const j = Math.floor(rng() * (i + 1)), t = starts[i]; starts[i] = starts[j]; starts[j] = t; }
let best = null;
for (const [x0, y0, d] of starts.slice(0, 120)) {
let cx = x0, cy = y0, touched = false;
const added = [];
for (let l = 1; l <= 14; l++) {
if (cx < 0 || cy < 0 || cx >= cols || cy >= rows) break;
const ci = cy * cols + cx;
if (solid[ci] || b.isSpecial(cx, cy) || mc.reserved.has(ci)) break;
solid[ci] = 1; added.push(ci);
if (geo.onRoute[ci]) touched = true;
if (touched && l >= 3 && l % 2 === 1) {
const f = TD.buildField(cols, rows, solid, b.coreIdx);
let after = 0, blocked = false;
for (const sp of b.spawns) { const v = f[sp.y * cols + sp.x]; if (!isFinite(v)) { blocked = true; break; } after += v; }
if (!blocked) for (const m of mc.must) if (!isFinite(f[m])) { blocked = true; break; }
if (blocked) break;
const gain = after - base, near = 1 - clamp(Math.hypot(cx - b.core.x, cy - b.core.y) / 18, 0, 1);
const ratio = gain / (wc * l) * (1 + 0.8 * near);
if (gain >= 3 && (!best || ratio > best.ratio)) best = { ratio, x: x0, y: y0, d, l };
}
cx += d[0]; cy += d[1];
}
for (const ci of added) solid[ci] = 0;
}
if (!best) return null;
const cells = [];
for (let k = 0; k < best.l; k++) cells.push([best.x + best.d[0] * k, best.y + best.d[1] * k]);
return cells;
}
// ---- turrets and upgrades, scored by (damage x what the route lets the turret reach x what is coming) per credit
geometry() {
const sim = this.sim, b = sim.board;
if (this.geo && this.geo.rev === sim.rev) return this.geo;
const gx = [], gy = [], onRoute = new Uint8Array(b.cols * b.rows);
for (const route of b.routes) for (const c of route) { gx.push(c[0] + 0.5); gy.push(c[1] + 0.5); onRoute[c[1] * b.cols + c[0]] = 1; }
const ax = [], ay = []; // flyers go straight from each gateway to the server
for (const sp of b.spawns) {
const x0 = sp.x + 0.5, y0 = sp.y + 0.5, x1 = b.core.x + 0.5, y1 = b.core.y + 0.5, n = Math.max(2, Math.ceil(Math.hypot(x1 - x0, y1 - y0)));
for (let i = 0; i <= n; i++) { ax.push(x0 + (x1 - x0) * i / n); ay.push(y0 + (y1 - y0) * i / n); }
}
this.geo = { rev: sim.rev, gx, gy, ax, ay, onRoute };
this.tables = {};
return this.geo;
}
cover(x, y, r, air) { // how much route (and flight line) is within r of the point
const g = this.geometry(), r2 = r * r, wa = 0.3 + 1.5 * this.th.air;
let s = 0;
for (let i = 0; i < g.gx.length; i++) { const dx = g.gx[i] - x, dy = g.gy[i] - y; if (dx * dx + dy * dy <= r2) s++; }
if (air) for (let i = 0; i < g.ax.length; i++) { const dx = g.ax[i] - x, dy = g.ay[i] - y; if (dx * dx + dy * dy <= r2) s += wa * 0.5; }
return s;
}
// the best free cells for a tower of range r (cached until the board changes)
sites(r, air) {
const key = r + (air ? 'a' : 'g'), g = this.geometry(); // (the geometry drops the cached tables when the board has changed)
if (this.tables[key]) return this.tables[key];
const sim = this.sim, b = sim.board, res = sim.monsterCells().reserved, list = [];
for (let y = 0; y < b.rows; y++) for (let x = 0; x < b.cols; x++) {
const i = y * b.cols + x;
if (b.solid[i] || b.obst[i] || g.onRoute[i] || res.has(i) || b.isSpecial(x, y) || (this.badUntil.get(i) || 0) > sim.time) continue;
const c = this.cover(x + 0.5, y + 0.5, r, air);
if (c > 0) list.push({ x, y, c });
}
list.sort((p, q) => q.c - p.c);
return (this.tables[key] = list.slice(0, 8));
}
// a turret's worth in "damage per second against what is coming"
power(type, st) {
const def = TOWERS[type], th = this.th, arm = 1 + 3 * th.armor;
if (def.role === 'attack') {
let p = (type === 'uplink' ? st.dmg : perHit(st.dmg, arm)) * st.rate;
if (type === 'mortar') p *= 1.2 * (1 + th.swarm) * (1 - 0.9 * th.air);
else if (type === 'arc') { let c = 0, m = 1; for (let i = 0; i < st.chains; i++) { m *= st.falloff; c += m; } p *= 1 + c * (0.3 + th.swarm); }
else if (type === 'uplink') p *= 2.5;
else if (type === 'ids') p *= (1 + 0.5 * th.armor) * (1 - 0.6 * th.swarm); // one big shot at a time: poor against a crowd
return p;
}
if (def.role === 'aura') return st.slow * 60;
if (def.role === 'control') return (st.stun / st.pulse) * 70;
return 0;
}
options() {
const sim = this.sim, opts = [], count = {};
for (const t of sim.towers) count[t.type] = (count[t.type] || 0) + 1;
const jit = (v) => v * (1 + this.jitter * (this.rng() - 0.5) * 2);
const opening = this.turretCount() < this.openN;
const diversity = (type) => (opening && OPENING[type] !== undefined ? OPENING[type] : 1) / (1 + 0.2 * (count[type] || 0));
for (const type of this.types) {
const def = TOWERS[type], st = def.levels[0], price = TD.priceFor(type, sim.towers);
if (price > sim.gold * 3) continue;
if (def.role === 'support') { // a booster: next to several attackers
const att = sim.towers.filter((t) => TOWERS[t.type].role === 'attack');
if (att.length < 3) continue;
const b = sim.board, res = sim.monsterCells().reserved;
let bestN = 0, bestC = null;
for (let y = 0; y < b.rows; y++) for (let x = 0; x < b.cols; x++) {
const i = y * b.cols + x;
if (b.solid[i] || b.obst[i] || res.has(i) || b.isSpecial(x, y) || this.geometry().onRoute[i]) continue;
let n = 0;
for (const t of att) if ((t.x - x) * (t.x - x) + (t.y - y) * (t.y - y) <= st.range * st.range) n += this.power(t.type, TOWERS[t.type].levels[t.level - 1]);
if (n > bestN) { bestN = n; bestC = { x, y }; }
}
if (bestC) opts.push({ kind: 'new', type, x: bestC.x, y: bestC.y, cost: price, ratio: jit(st.boost * bestN * 0.6 / price * this.fav[type]) });
continue;
}
const air = !!def.air, sites = this.sites(st.range, air);
for (const site of sites.slice(0, 4)) {
const v = this.power(type, st) * site.c / price * this.fav[type] * diversity(type);
opts.push({ kind: 'new', type, x: site.x, y: site.y, cost: price, ratio: jit(v) });
}
}
for (const t of sim.towers) {
const def = TOWERS[t.type], nx = def.levels[t.level];
if (!nx || def.role === 'wall' || def.role === 'support' || !this.types.includes(t.type)) continue;
const cost = sim.upgradeCost(t);
if (cost === null || cost > sim.gold * 3) continue;
const cur = def.levels[t.level - 1], c = this.cover(t.x + 0.5, t.y + 0.5, nx.range, !!def.air);
const v = (this.power(t.type, nx) * c - this.power(t.type, cur) * this.cover(t.x + 0.5, t.y + 0.5, cur.range, !!def.air)) / cost * this.fav[t.type];
if (v > 0) opts.push({ kind: 'up', id: t.id, type: t.type, cost, ratio: jit(v) * (opening ? 0.5 : 1.1) });
}
return opts;
}
buyBest() {
const sim = this.sim;
if (sim.gold < 25) return false;
const opts = this.options().filter((o) => o.ratio > 0).sort((p, q) => q.ratio - p.ratio);
if (!opts.length) return false;
const best = opts[0], aff = opts.find((o) => o.cost <= sim.gold);
if (!aff) return false;
if (aff !== best && best.cost <= sim.gold * 3 && aff.ratio < 0.6 * best.ratio) return false; // rather save for the clearly better one
const r = aff.kind === 'up' ? this.cmd({ c: 'upgrade', id: aff.id }) : this.cmd({ c: 'place', type: aff.type, x: aff.x, y: aff.y });
if (r.ok) this.spentOther += aff.cost;
else if (aff.kind === 'new') { this.badUntil.set(aff.y * sim.board.cols + aff.x, sim.time + 6); this.tables = {}; }
return r.ok;
}
}
// ====================================================================================================================
// The attacker: reads the tower mix, buys what the defence is worst at per credit, saves a convoy, buys tech, plays the abilities.
// ====================================================================================================================
const TECH_WEIGHT = { armor: 1.0, health: 1.0, speed: 0.8, regen: 0.45, shield: 0.7, stealth: 0.7, crypt: 0.5 };
class Attacker extends Base {
constructor(sim, o) {
super(sim, 'attacker', o);
const r = this.rng, s = this.skill;
this.interval = 1 + (1 - s) * 2.5;
this.aggr = 0.75 + 0.6 * r(); // how big a convoy it wants before it launches
this.techShare = (0.15 + 0.2 * r()) * (s < 0.3 ? 0 : s); // the share of everything it has seen that may go into tech
this.spent = { tech: 0, units: 0, abilities: 0 };
this.lastLaunch = 0;
this.want = null; this.wantAt = 0; // the kind it is saving for
this.p = null;
}
act() {
const sim = this.sim, p = this.p = sim.privateState('attacker');
const def = this.assess();
this.def = def;
if (this.skill >= 0.3) { this.abilities(p, def); this.tech(this.p = sim.privateState('attacker'), def); }
this.units(this.p = sim.privateState('attacker'), def); // (what it has left after what it just bought)
}
// ---- the defence, in numbers
assess() {
const sim = this.sim, towers = [], hits = [];
let dps = 0, airDps = 0, splash = 0, slowers = 0, best = null;
for (const t of sim.towers) {
const def = TOWERS[t.type], st = def.levels[t.level - 1];
if (t.empT > 0) continue;
if (def.role === 'aura' || def.role === 'control') { slowers++; continue; }
if (def.role !== 'attack') continue;
const d = st.dmg * st.rate;
towers.push(t);
dps += d; if (def.air) airDps += d;
if (t.type === 'mortar' || t.type === 'arc' || t.type === 'uplink') splash += d;
hits.push({ dmg: st.dmg, w: d, ignore: t.type === 'uplink', air: !!def.air });
if (!best || d > best.d) best = { t, d };
}
return { n: towers.length, dps, airDps, splashShare: dps ? splash / dps : 0, slowers, hits, best: best && best.t };
}
// the part of the defence's damage that gets through to a unit with this much armour (and that can reach it at all)
bite(def, armor, air) {
let tot = 0, got = 0;
for (const h of def.hits) {
if (air && !h.air) continue;
tot += h.w; got += h.w * (h.ignore ? 1 : perHit(h.dmg, armor) / h.dmg);
}
return got;
}
// value per credit of a unit kind against this defence: leak damage x the chance to get through / price
kindValue(kind, def) {
const d = ENEMIES[kind], T = this.p.tech, X = VS.TECH;
const hp = d.hp * (1 + X.health.per * T.health) + (d.shield || 0) + X.shield.per * T.shield;
const dps = Math.max(1, this.bite(def, d.armor + X.armor.per * T.armor, d.air));
let dur = hp / dps; // seconds of the whole defence's fire to kill one
if (d.hp <= 20 && !d.air) dur *= 1 - 0.5 * def.splashShare; // little ones die in groups to splash
if (d.heal) dur *= 1.4; // a healer keeps the others alive
const speed = d.speed * (1 + X.speed.per * T.speed);
const escape = 1 - Math.exp(-dur * speed / 3);
return d.leak * escape / d.buyCost;
}
// ---- units: rush a weak defence, otherwise save a convoy and launch it
units(p, def) {
const sim = this.sim, rng = this.rng, left = sim.vs.limit - sim.time;
const price = (k) => ENEMIES[k].buyCost;
const weak = def.dps < 40; // (almost) nothing shoots yet: units that leak pay themselves back, so go now
const endgame = left < 50; // the clock is about to decide it: nothing is worth saving any more
const direct = weak || endgame;
const mix = this.mix(def);
// the money it can spend on units now: a share is kept for tech while that is still worth it
let budget = p.credits - this.techReserve(p);
if (direct && budget < price(mix[0].k)) budget = p.credits;
let room = direct ? VS.MAX_ALIVE - sim.vsAlive() : VS.MAX_STAGED - p.staged.reduce((s, e) => s + e[1], 0);
// a shopping list of one: draw a kind by its share, SAVE until it is affordable (not "spend on whatever is cheap meanwhile": a
// trojan would never get bought), then buy a chunk of it
for (let guard = 0; guard < 6 && room > 0; guard++) {
if (!this.want || sim.time - this.wantAt > 20 || !mix.some((m) => m.k === this.want)) { this.want = this.draw(mix); this.wantAt = sim.time; }
const cost = price(this.want);
if (budget < cost) break;
const n = Math.min(Math.max(1, Math.floor(Math.min(budget, 40 + 60 * rng()) / cost)), room);
const r = this.cmd({ c: direct ? 'spawn' : 'stage', kind: this.want, n });
if (!r.ok) break;
this.spent.units += n * cost; budget -= n * cost; room -= n; this.want = null;
}
// launch the convoy when it is big enough for this defence, when waiting has gone on long enough, or when the round is nearly over
const staged = sim.privateState('attacker').staged, value = staged.reduce((s, e) => s + e[1] * price(e[0]), 0);
if (!value) return;
const need = this.aggr * (60 + 22 * def.n + 0.5 * def.dps) * (0.8 + 0.4 * rng());
const waited = sim.time - this.lastLaunch;
if (value >= need || (waited > 90 && value >= 80) || (endgame && waited > 5)) {
if (this.cmd({ c: 'launch' }).ok) this.lastLaunch = sim.time;
}
}
draw(mix) { // a kind, with the probability of its share
let x = this.rng();
for (const m of mix) { x -= m.share; if (x <= 0) return m.k; }
return mix[0].k;
}
// the kinds worth buying, best first, with the share of the money each gets
mix(def) {
const rng = this.rng, noise = 0.1 + (1 - this.skill) * 0.6;
const kinds = ENEMY_ORDER.map((k) => ({ k, v: this.kindValue(k, def) * (1 + noise * (rng() - 0.5) * 2) })).sort((a, b) => b.v - a.v);
const top = kinds.slice(0, 3).filter((e, i) => i === 0 || e.v > 0.45 * kinds[0].v);
const sum = top.reduce((s, e) => s + e.v * e.v, 0) || 1;
const out = top.map((e) => ({ k: e.k, share: e.v * e.v / sum }));
if (out[0].k === 'trojan' && !out.some((e) => e.k === 'daemon')) { out[0].share *= 0.85; out.push({ k: 'daemon', share: 0.15 }); } // a healer behind the armour
return out;
}
// ---- tech: a share of everything seen, on whatever the defence is worst at stopping
techReserve(p) {
if (this.skill < 0.3) return 0;
const seen = p.credits + this.spent.tech + this.spent.units + this.spent.abilities;
const owed = this.techShare * seen - this.spent.tech;
return owed > 0 ? Math.min(owed, 400) : 0;
}
tech(p, def) {
const sim = this.sim, T = p.tech, reserve = this.techReserve(p);
if (reserve <= 0) return;
const wArmor = def.dps ? 1 - this.bite(def, 3, false) / def.dps : 0.3; // how much a few points of armour would cut the defence
const want = {
armor: TECH_WEIGHT.armor * (0.3 + wArmor), health: TECH_WEIGHT.health, speed: TECH_WEIGHT.speed, regen: TECH_WEIGHT.regen,
shield: TECH_WEIGHT.shield * (def.dps > 150 ? 1 : 0.6), stealth: TECH_WEIGHT.stealth * Math.min(1.5, 0.3 + def.n / 8),
crypt: TECH_WEIGHT.crypt * (def.slowers ? 1.6 : 0.2),
};
let bestId = null, bestV = 0, bestCost = 0;
for (const id of VS.TECH_ORDER) {
const cost = sim.techCost(id);
if (cost === null || cost > p.credits || cost > reserve * 1.6 + 1) continue; // (only when its share of the money has built up)
const v = want[id] / Math.pow(1.5, T[id]) * (1 + 0.2 * (this.rng() - 0.5)) / cost;
if (v > bestV) { bestV = v; bestId = id; bestCost = cost; }
}
if (bestId && this.cmd({ c: 'tech', id: bestId }).ok) this.spent.tech += bestCost;
}
// ---- abilities: only when there is a convoy on the map worth the money
abilities(p, def) {
const sim = this.sim, A = VS.ABILITIES, rng = this.rng;
const mine = sim.monsters.filter((m) => !m.dead && !m.decoy);
if (mine.length < 3 || !def.n) return;
const value = mine.reduce((s, m) => s + m.buyCost, 0);
const ready = (id) => p.cd[id] <= 0 && p.credits >= A[id].cost && value >= 2.2 * A[id].cost;
const inReach = (m) => def.best && (m.x - def.best.x - 0.5) * (m.x - def.best.x - 0.5) + (m.y - def.best.y - 0.5) * (m.y - def.best.y - 0.5) <= 100;
const pay = (id, extra) => { if (this.cmd(Object.assign({ c: 'ability', id }, extra)).ok) this.spent.abilities += A[id].cost; };
const underFire = mine.filter((m) => this.inRange(m)).length;
if (ready('emp') && def.best && mine.some(inReach) && rng() < 0.7) pay('emp', { tid: def.best.id });
else if (ready('ddos') && underFire >= Math.max(5, mine.length * 0.4) && value >= 400) pay('ddos');
else if (ready('surge') && mine.length >= 8 && underFire >= 2) pay('surge');
else if (ready('decoy') && def.best && underFire >= 3 && rng() < 0.5) pay('decoy', { tid: def.best.id });
}
inRange(m) { // is any attack tower reaching this unit now?
for (const t of this.sim.towers) {
const d = TOWERS[t.type];
if (d.role !== 'attack' || t.empT > 0) continue;
const r = d.levels[t.level - 1].range;
if ((m.x - t.x - 0.5) * (m.x - t.x - 0.5) + (m.y - t.y - 0.5) * (m.y - t.y - 0.5) <= r * r) return true;
}
return false;
}
}
function create(sim, role, opts) {
if (!sim || !sim.vs) throw new Error('NWBot needs a versus sim');
if (role === 'defender') return new Defender(sim, opts);
if (role === 'attacker') return new Attacker(sim, opts);
throw new Error('NWBot role must be "defender" or "attacker"');
}
return { create, Defender, Attacker, prng };
});

View file

@ -15,6 +15,24 @@
* ctrl.difficulty the game's difficulty id (TD.DIFFICULTIES); `newGame(map, difficulty)` keeps the current one when none is given * ctrl.difficulty the game's difficulty id (TD.DIFFICULTIES); `newGame(map, difficulty)` keeps the current one when none is given
* ctrl.preview(x,y,routes) would a block there be legal, and what does it do to the route? * ctrl.preview(x,y,routes) would a block there be legal, and what does it do to the route?
* events ctrl.on('events', list) | 'reject' | 'mark' | 'players' | 'status' | 'joined' | 'newgame' | 'fatal' | 'rtt' * events ctrl.on('events', list) | 'reject' | 'mark' | 'players' | 'status' | 'joined' | 'newgame' | 'fatal' | 'rtt'
*
* VERSUS (attack vs defend, docs/VERSUS.md and docs/PROTOCOL.md "Versus"). Both controllers speak the same language to the UI, so the UI code
* does not care whether the other seat is a person on the server or the computer in this tab:
* ctrl.mode 'solo' (LocalController), 'coop' or 'versus' (what the room was created as; RemoteController learns it from the server's state)
* ctrl.vs the newest match message { phase, round, rounds, roles:{slot:'attacker'|'defender'}, random, bot, limit, ready, frozen, countdown?, next?,
* result?, history?, scores?, winner?, forfeit?, rematch? }, or null (not versus); event 'vs' fires on every change.
* phase: lobby | countdown | playing | roundover | matchover (a LocalController starts in the countdown: there is no lobby)
* ctrl.priv the newest role-private data { role, ...privateState }: attacker { credits, income, tech, staged, cd, active }, defender { cd };
* event 'priv'. Compare priv.role with ctrl.role after a role swap (the first priv of a round replaces the old one).
* ctrl.role my role in the current round ('attacker' | 'defender') or null
* ctrl.view.vs the SHARED round block { t, lim, st } (round clock, limit, staged convoy size) or null; ctrl.view.mode as ctrl.mode
* view.towers[].empT seconds of EMP left on a tower (0 when none), versus only
* ctrl.send(cmd) also the versus commands: spawn | stage | launch | tech | ability | tool (see the protocol); the role is the controller's, never the caller's
* ctrl.vsSend(c, v, extra) lobby / match control: 'role' | 'ready' | 'bot' | 'start' | 'next' | 'rematch'; wrappers vsRole(v) vsReady(v) vsBot(v, skill)
* vsStart() vsNext() vsRematch(). A LocalController has no lobby: role / ready / bot / start are refused ('phase'),
* `next` starts round 2 and `rematch` a new match with the first roles swapped.
* ctrl.ctl(c, v) does nothing in versus (no pause, no speed); `new LocalController({ map, mode:'versus', role:'attacker'|'defender'|'random', limit, skill })`
* plays against NWBot (js/bot.js must be loaded), `new RemoteController({ ..., mode:'versus', limit })` creates a versus room.
*/ */
(function (root) { (function (root) {
'use strict'; 'use strict';
@ -42,6 +60,32 @@
return c; return c;
} }
// ---- match rules (the same rules as server/versus.js: test/controllers.test.js feeds both the same rounds) ----
const vsOpposite = (r) => (r === 'attacker' ? 'defender' : 'attacker');
const vsSwap = (roles) => ({ 0: vsOpposite(roles[0]), 1: vsOpposite(roles[1]) });
// history entry: { round, roles:{0,1}, result:{ winner, t, integrityLost, attacker:slot, defender:slot, forfeit? } }
function matchScores(history, names) {
return [0, 1].map((slot) => {
let fellAt = null, lost = 0;
for (const h of history) {
if (h.roles[slot] !== 'attacker') continue;
lost += h.result.integrityLost || 0;
if (h.result.winner === 'attacker' && !h.result.forfeit && (fellAt === null || h.result.t < fellAt)) fellAt = h.result.t;
}
return { slot, name: names[slot], fellAt, integrityLost: lost };
});
}
function matchWinner(scores) {
const a = scores[0], b = scores[1];
if (a.fellAt !== null && b.fellAt !== null) return a.fellAt === b.fellAt ? null : a.fellAt < b.fellAt ? a.slot : b.slot;
if (a.fellAt !== null) return a.slot;
if (b.fellAt !== null) return b.slot;
return a.integrityLost === b.integrityLost ? null : a.integrityLost > b.integrityLost ? a.slot : b.slot;
}
const VS_COUNTDOWN_MS = 3000; // a local match: the pause before each round (the server's default too)
const VS_BOT_STEP = 0.25; // the computer is asked to think at about 4 Hz of game time
const VS_PRIV_MS = 250; // role-private data at 4 Hz
// ws(s)://<same host>/ws, relative to the page so it also works under a proxy path prefix // ws(s)://<same host>/ws, relative to the page so it also works under a proxy path prefix
function wsUrl() { function wsUrl() {
const u = new URL('ws', root.location.href); const u = new URL('ws', root.location.href);
@ -60,19 +104,132 @@
this.speed = 1; this.paused = false; this.speed = 1; this.paused = false;
this.players = [{ slot: 0, name: 'You', online: true, host: true }]; this.players = [{ slot: 0, name: 'You', online: true, host: true }];
this.you = { slot: 0, host: true }; this.you = { slot: 0, host: true };
this._fresh(); this.versus = !!(opts && opts.mode === 'versus');
this.mode = this.versus ? 'versus' : 'solo';
this.vs = null; this.priv = null; this.bot = null;
if (this.versus) { this._vsInit(opts); this._vsRound(); } else this._fresh();
} }
get role() { return this.vs ? this.vs.roles[0] : null; }
_fresh() { _fresh() {
this.sim = new TD.Sim({ map: this.mapId, difficulty: this.difficulty }); this.sim = this.versus ? new TD.Sim({ map: this.mapId, mode: 'versus', limit: this.limit }) : new TD.Sim({ map: this.mapId, difficulty: this.difficulty });
this.board = this.sim.board; this.board = this.sim.board;
this.acc = 0; this.last = 0; this.acc = 0; this.last = 0;
this.view = { this.view = {
gold: 0, lives: 0, maxLives: 0, wave: 0, state: 'playing', auto: false, nextWaveIn: -1, kills: 0, winWave: 0, rev: 0, queued: 0, gold: 0, lives: 0, maxLives: 0, wave: 0, state: 'playing', auto: false, nextWaveIn: -1, kills: 0, winWave: 0, rev: 0, queued: 0,
speed: this.speed, paused: this.paused, time: 0, difficulty: this.difficulty, speed: this.speed, paused: this.paused, time: 0, difficulty: this.difficulty, mode: this.mode, vs: null,
towers: this.sim.towers, monsters: this.sim.monsters, bullets: this.sim.bullets, cursors: [], towers: this.sim.towers, monsters: this.sim.monsters, bullets: this.sim.bullets, cursors: [],
}; };
this._sync(); this._sync();
} }
// ---- versus against the computer (the human is seat 0, NWBot seat 1) ----
_vsInit(opts) {
if (!root.NWBot) throw new Error('A versus game against the computer needs js/bot.js (NWBot) to be loaded before it is created.');
const V = TD.VS;
this.limit = Number.isFinite(opts.limit) && opts.limit > 0 ? opts.limit : V.DEFAULT_LIMIT;
this.skill = Number.isFinite(opts.skill) ? clamp(opts.skill, 0, 1) : 1;
this.rounds = V.ROUNDS;
this.countdownMs = Number.isFinite(opts.countdownMs) ? opts.countdownMs : VS_COUNTDOWN_MS;
this.seed = Number.isInteger(opts.seed) ? opts.seed : Math.floor(Math.random() * 0x7fffffff);
const mine = opts.role === 'attacker' || opts.role === 'defender' ? opts.role : (Math.random() < 0.5 ? 'attacker' : 'defender');
this.firstRoles = { 0: mine, 1: vsOpposite(mine) };
this.players = [{ slot: 0, name: 'You', online: true, host: true }];
this._privAt = -Infinity;
this._vsStartMatch(this.firstRoles);
}
_vsStartMatch(roles) {
this.firstRoles = { 0: roles[0], 1: roles[1] };
this.vsm = { phase: 'countdown', round: 1, roles: { 0: roles[0], 1: roles[1] }, history: [], result: null, scores: null, winner: null, cdMs: 0, cdSent: -1, botAcc: 0 };
}
// The sim and the computer of the current round (called when a round's countdown starts).
_vsRound() {
const m = this.vsm;
this._fresh();
m.phase = 'countdown'; m.cdMs = this.countdownMs; m.cdSent = Math.ceil(m.cdMs / 1000); m.botAcc = 0; m.result = null;
this.bot = root.NWBot.create(this.sim, m.roles[1], { seed: this.seed + m.round * 101, skill: this.skill, by: 1 });
this._vsEmit();
this._vsPriv();
}
_vsNames() { return [this.players[0].name, 'Computer']; }
_vsMsg() {
const m = this.vsm;
const out = {
t: 'vs', phase: m.phase, round: m.round, rounds: this.rounds, roles: { 0: m.roles[0], 1: m.roles[1] }, random: false,
bot: { slot: 1, role: m.roles[1], skill: this.skill, name: 'Computer' }, limit: this.limit, ready: { 0: true, 1: true }, frozen: false,
};
if (m.phase === 'countdown') out.countdown = Math.max(0, Math.ceil(m.cdMs / 1000));
if (m.phase === 'roundover') out.next = { 0: false, 1: true };
if (m.phase === 'roundover' || m.phase === 'matchover') out.result = m.result;
if (m.history.length) out.history = m.history;
if (m.phase === 'matchover') { out.scores = m.scores; out.winner = m.winner; out.forfeit = null; out.rematch = { 0: false, 1: true }; }
return out;
}
_vsEmit() { this.vs = this._vsMsg(); this.emit('vs', this.vs); }
_vsPriv() {
const role = this.vsm.roles[0], ps = this.sim.privateState(role);
if (!ps) return;
this.priv = Object.assign({ t: 'priv', role }, ps);
this.emit('priv', this.priv);
}
_vsRoundEnd() {
const m = this.vsm, res = this.sim.vs.result;
const attacker = m.roles[0] === 'attacker' ? 0 : 1;
const entry = { round: m.round, roles: { 0: m.roles[0], 1: m.roles[1] }, result: { winner: res.winner, t: res.t, integrityLost: res.integrityLost, attacker, defender: 1 - attacker } };
m.history.push(entry); m.result = entry.result;
this.bot = null;
if (m.round < this.rounds) m.phase = 'roundover';
else { m.phase = 'matchover'; m.scores = matchScores(m.history, this._vsNames()); m.winner = matchWinner(m.scores); }
this._vsEmit();
this._vsPriv();
}
_vsUpdate(now) {
const m = this.vsm;
if (!this.last) this.last = now;
const dt = Math.min(0.25, Math.max(0, (now - this.last) / 1000));
this.last = now;
if (m.phase === 'countdown') {
m.cdMs -= dt * 1000;
if (m.cdMs <= 0) { m.phase = 'playing'; this.acc = 0; this._vsEmit(); this._vsPriv(); }
else if (Math.ceil(m.cdMs / 1000) !== m.cdSent) { m.cdSent = Math.ceil(m.cdMs / 1000); this._vsEmit(); }
} else if (m.phase === 'playing') {
this.acc = Math.min(0.6, this.acc + dt);
let ticked = 0;
while (this.acc >= TD.STEP && this.sim.state === 'playing') { this.sim.tick(TD.STEP); this.acc -= TD.STEP; ticked += TD.STEP; }
m.botAcc += ticked;
if (this.bot && m.botAcc >= VS_BOT_STEP) { const d = m.botAcc; m.botAcc = 0; try { this.bot.think(d); } catch (e) { console.error(e); this.bot = null; } }
if (this.sim.state !== 'playing') this._vsRoundEnd();
}
const ev = this.sim.drainEvents();
this._sync();
if (ev.length) this.emit('events', ev);
if ((m.phase === 'countdown' || m.phase === 'playing') && now - this._privAt >= VS_PRIV_MS) { this._privAt = now; this._vsPriv(); }
}
_vsSend(cmd) {
const m = this.vsm;
let res;
if (m.phase !== 'playing') res = { ok: false, reason: m.phase === 'roundover' || m.phase === 'matchover' ? 'over' : 'phase' };
else {
const c = Object.assign({}, cmd, { by: 0, role: m.roles[0] });
res = this.sim.cmd(stampCmd(c, this.view));
}
if (!res.ok) this.emit('reject', { c: cmd.c, reason: res.reason, x: cmd.x, y: cmd.y, id: cmd.id, tid: cmd.tid });
else { this._vsPriv(); this._sync(); }
return res;
}
// lobby / match control; a local game has no lobby, so only `next` and `rematch` do anything
vsSend(c, v) {
const m = this.vsm;
if (!this.versus) return { ok: false, reason: 'versus' };
if (c === 'next' && m.phase === 'roundover') { m.round++; m.roles = vsSwap(m.roles); this._vsRound(); return { ok: true }; }
if (c === 'rematch' && m.phase === 'matchover') { this._vsStartMatch(vsSwap(this.firstRoles)); this._vsRound(); return { ok: true }; }
this.emit('reject', { c, reason: 'phase' });
return { ok: false, reason: 'phase' };
}
vsRole(v) { return this.vsSend('role', v); }
vsReady(v) { return this.vsSend('ready', v); }
vsBot(v, skill) { return this.vsSend('bot', v, { skill }); }
vsStart() { return this.vsSend('start'); }
vsNext() { return this.vsSend('next'); }
vsRematch() { return this.vsSend('rematch'); }
_sync() { _sync() {
const s = this.sim, v = this.view; const s = this.sim, v = this.view;
v.gold = s.gold; v.lives = s.lives; v.maxLives = s.maxLives; v.wave = s.wave; v.state = s.state; v.gold = s.gold; v.lives = s.lives; v.maxLives = s.maxLives; v.wave = s.wave; v.state = s.state;
@ -80,8 +237,10 @@
v.winWave = isFinite(s.winWave) ? s.winWave : 0; v.rev = s.rev; v.queued = s.spawnQ.length; v.winWave = isFinite(s.winWave) ? s.winWave : 0; v.rev = s.rev; v.queued = s.spawnQ.length;
v.speed = this.speed; v.paused = this.paused; v.time = s.time; v.difficulty = s.difficulty; v.speed = this.speed; v.paused = this.paused; v.time = s.time; v.difficulty = s.difficulty;
v.towers = s.towers; v.monsters = s.monsters; v.bullets = s.bullets; v.towers = s.towers; v.monsters = s.monsters; v.bullets = s.bullets;
if (s.vs) v.vs = { t: TD.round2(s.time), lim: s.vs.limit, st: s.vsStaged() };
} }
update(now) { update(now) {
if (this.versus) { this._vsUpdate(now); return; }
if (!this.last) this.last = now; if (!this.last) this.last = now;
const dt = Math.min(0.25, Math.max(0, (now - this.last) / 1000)); const dt = Math.min(0.25, Math.max(0, (now - this.last) / 1000));
this.last = now; this.last = now;
@ -94,11 +253,13 @@
if (ev.length) this.emit('events', ev); if (ev.length) this.emit('events', ev);
} }
send(cmd) { send(cmd) {
if (this.versus) return this._vsSend(cmd);
const res = this.sim.cmd(stampCmd(Object.assign({}, cmd, { by: 0 }), this.view)); const res = this.sim.cmd(stampCmd(Object.assign({}, cmd, { by: 0 }), this.view));
if (!res.ok) this.emit('reject', { c: cmd.c, reason: res.reason, x: cmd.x, y: cmd.y, id: cmd.id }); if (!res.ok) this.emit('reject', { c: cmd.c, reason: res.reason, x: cmd.x, y: cmd.y, id: cmd.id });
return res; return res;
} }
ctl(c, v) { ctl(c, v) {
if (this.versus) return; // no pause, no speed in versus
if (c === 'pause') this.paused = !!v; if (c === 'pause') this.paused = !!v;
else if (c === 'speed') this.speed = clamp(v | 0, 1, 3); else if (c === 'speed') this.speed = clamp(v | 0, 1, 3);
this._sync(); this._sync();
@ -106,6 +267,11 @@
preview(x, y, routes) { return this.sim.preview(x, y, routes); } preview(x, y, routes) { return this.sim.preview(x, y, routes); }
// `difficulty` absent: the same one again ("Play again"); an unknown one is normal (the sim's rule) // `difficulty` absent: the same one again ("Play again"); an unknown one is normal (the sim's rule)
newGame(map, difficulty) { newGame(map, difficulty) {
if (this.versus) { // a new match (the first roles swapped), at once, whatever the phase
if (map) this.mapId = map;
this._vsStartMatch(vsSwap(this.firstRoles)); this._vsRound(); this.emit('newgame');
return;
}
if (map) this.mapId = map; if (map) this.mapId = map;
if (difficulty !== undefined && difficulty !== null) this.difficulty = TD.difficultyId(difficulty); if (difficulty !== undefined && difficulty !== null) this.difficulty = TD.difficultyId(difficulty);
this._fresh(); this.emit('newgame'); this._fresh(); this.emit('newgame');
@ -125,6 +291,9 @@
this.pid = opts.pid; this.name = opts.name || 'Player'; this.pid = opts.pid; this.name = opts.name || 'Player';
this.room = opts.room || null; // null => create a room on first connect this.room = opts.room || null; // null => create a room on first connect
this.mapId = opts.map || 'open'; this.mapId = opts.map || 'open';
this.mode = opts.mode === 'versus' ? 'versus' : 'coop'; // what a CREATING join asks for; afterwards whatever the server's state says
this.limit = opts.limit; // versus round limit (seconds) of a creating join
this.vs = null; this.priv = null; // the newest 'vs' / 'priv' messages (see the header)
this.difficulty = TD.difficultyId(opts.difficulty); // what a CREATING join asks for; afterwards whatever the server's state says this.difficulty = TD.difficultyId(opts.difficulty); // what a CREATING join asks for; afterwards whatever the server's state says
this.status = 'idle'; // idle | connecting | joined | reconnecting | closed this.status = 'idle'; // idle | connecting | joined | reconnecting | closed
this.ws = null; this.players = []; this.you = null; this.board = null; this.ws = null; this.players = []; this.you = null; this.board = null;
@ -140,13 +309,14 @@
this.speed = 1; this.paused = false; this.speed = 1; this.paused = false;
this.view = { this.view = {
gold: 0, lives: 0, maxLives: 0, wave: 0, state: 'playing', auto: false, nextWaveIn: -1, kills: 0, winWave: 0, rev: 0, queued: 0, gold: 0, lives: 0, maxLives: 0, wave: 0, state: 'playing', auto: false, nextWaveIn: -1, kills: 0, winWave: 0, rev: 0, queued: 0,
speed: 1, paused: false, time: 0, difficulty: this.difficulty, towers: [], monsters: [], bullets: [], cursors: [], speed: 1, paused: false, time: 0, difficulty: this.difficulty, mode: this.mode, vs: null, towers: [], monsters: [], bullets: [], cursors: [],
}; };
this._onVis = () => { if (!document.hidden) this._wake(); }; this._onVis = () => { if (!document.hidden) this._wake(); };
document.addEventListener('visibilitychange', this._onVis); document.addEventListener('visibilitychange', this._onVis);
root.addEventListener('online', this._onVis); root.addEventListener('online', this._onVis);
this._timers = []; this._timers = [];
} }
get role() { return this.vs && this.you ? this.vs.roles[this.you.slot] || null : null; }
// The document / window listeners must not outlive the controller (code-19): called when it dies and when it is closed. // The document / window listeners must not outlive the controller (code-19): called when it dies and when it is closed.
_dispose() { _dispose() {
document.removeEventListener('visibilitychange', this._onVis); document.removeEventListener('visibilitychange', this._onVis);
@ -162,7 +332,11 @@
this.ws = ws; this.ws = ws;
ws.onopen = () => { ws.onopen = () => {
const j = { t: 'join', pid: this.pid, name: this.name }; const j = { t: 'join', pid: this.pid, name: this.name };
if (this.room) j.room = this.room; else { j.map = this.mapId; j.difficulty = this.difficulty; } // only a creating join carries them: a joiner takes the room's if (this.room) j.room = this.room;
else { // only a creating join carries these: a joiner takes the room's
j.map = this.mapId; j.difficulty = this.difficulty;
if (this.mode === 'versus') { j.mode = 'versus'; if (this.limit) j.limit = this.limit; }
}
this._send(j); this._send(j);
}; };
ws.onmessage = (e) => { this.lastMsg = performance.now(); this._onMsg(e.data); }; ws.onmessage = (e) => { this.lastMsg = performance.now(); this._onMsg(e.data); };
@ -242,10 +416,12 @@
this.everJoined = true; this.everJoined = true;
this.retry = 0; this.speed = m.speed || 1; this.paused = !!m.paused; this.retry = 0; this.speed = m.speed || 1; this.paused = !!m.paused;
this._applyState(m.state, m.snap); this._applyState(m.state, m.snap);
if (m.vs) this.vs = m.vs;
this._setStatus('joined'); this._setStatus('joined');
this._startRtt(); this._startRtt();
this.emit('joined', m); this.emit('joined', m);
this.emit('players', this.players); this.emit('players', this.players);
if (m.vs) this.emit('vs', m.vs);
break; break;
case 'state': case 'state':
this.speed = m.speed || 1; this.paused = !!m.paused; this.speed = m.speed || 1; this.paused = !!m.paused;
@ -257,6 +433,8 @@
{ const me = this.players.find((p) => this.you && p.pid === this.you.pid); if (me) this.you = Object.assign({}, this.you, { host: me.host, slot: me.slot }); } { const me = this.players.find((p) => this.you && p.pid === this.you.pid); if (me) this.you = Object.assign({}, this.you, { host: me.host, slot: me.slot }); }
this.emit('players', this.players); this.emit('players', this.players);
break; break;
case 'vs': this.vs = m; this.emit('vs', m); break;
case 'priv': this.priv = m; this.emit('priv', m); break;
case 'reject': this.emit('reject', m); break; case 'reject': this.emit('reject', m); break;
case 'mark': this.emit('mark', m); break; case 'mark': this.emit('mark', m); break;
case 'rtt': case 'rtt':
@ -268,7 +446,7 @@
this._die('restarted', this.everJoined ? 'The server restarted, your game was lost.' : 'That co-op game is gone: the server restarted or the room timed out.'); this._die('restarted', this.everJoined ? 'The server restarted, your game was lost.' : 'That co-op game is gone: the server restarted or the room timed out.');
break; break;
} }
const msgs = { no_room: 'That room does not exist (any more).', full: 'That room already has two players.', bad_request: 'The server did not understand the request.', too_many_rooms: 'The server is full right now. Try again in a minute.', bad_map: 'Unknown map.', bad_difficulty: 'Unknown difficulty.' }; const msgs = { no_room: 'That room does not exist (any more).', full: 'That room already has two players.', bad_mode: 'Unknown game mode.', bad_limit: 'Unknown round length.', bad_rounds: 'Unsupported number of rounds.', bad_request: 'The server did not understand the request.', too_many_rooms: 'The server is full right now. Try again in a minute.', bad_map: 'Unknown map.', bad_difficulty: 'Unknown difficulty.' };
this._die(m.code || 'error', msgs[m.code] || m.msg || 'Server error.'); this._die(m.code || 'error', msgs[m.code] || m.msg || 'Server error.');
break; break;
} }
@ -292,6 +470,8 @@
this.maxLives = state.maxLives; this.winWave = state.winWave; this.maxLives = state.maxLives; this.winWave = state.winWave;
this.difficulty = TD.isDifficulty(state.difficulty) ? state.difficulty : 'normal'; // (a server from before difficulties sends none) this.difficulty = TD.isDifficulty(state.difficulty) ? state.difficulty : 'normal'; // (a server from before difficulties sends none)
this.view.difficulty = this.difficulty; this.view.difficulty = this.difficulty;
this.mode = state.mode === 'versus' ? 'versus' : 'coop'; this.limit = state.limit || this.limit;
this.view.mode = this.mode;
this.buf.length = 0; this._carryTw = null; this.monCache.clear(); this.bulCache.clear(); this.buf.length = 0; this._carryTw = null; this.monCache.clear(); this.bulCache.clear();
if (snap) this._push(snap, true); if (snap) this._push(snap, true);
} }
@ -345,6 +525,7 @@
v.rev = s.rev; v.queued = s.q || 0; v.time = s.time; v.rev = s.rev; v.queued = s.q || 0; v.time = s.time;
v.maxLives = this.maxLives; v.winWave = this.winWave; v.maxLives = this.maxLives; v.winWave = this.winWave;
v.speed = s.sp || 1; v.paused = !!s.pa; v.speed = s.sp || 1; v.paused = !!s.pa;
v.vs = s.vs || null; // versus: the shared round block { t, lim, st }
const gen = ++this._gen; const gen = ++this._gen;
const kinds = TD.ENEMY_ORDER; const kinds = TD.ENEMY_ORDER;
@ -375,6 +556,7 @@
for (const t of this.towers) { for (const t of this.towers) {
const r = a.tt.get(t.id); const r = a.tt.get(t.id);
t.tgt = r ? r[1] : 0; t.kills = r ? r[2] : 0; t.tgt = r ? r[1] : 0; t.kills = r ? r[2] : 0;
if (this.mode === 'versus') t.empT = r && r[3] ? r[3] : 0; // versus rows carry a 4th field: seconds of EMP left
} }
v.towers = this.towers; v.towers = this.towers;
const mySlot = this.you ? this.you.slot : -1; const mySlot = this.you ? this.you.slot : -1;
@ -382,12 +564,19 @@
} }
send(cmd) { send(cmd) {
const c = Object.assign({}, cmd); delete c.by; const c = Object.assign({}, cmd); delete c.by; delete c.role; // the server knows the seat and its role
stampCmd(c, this.view); stampCmd(c, this.view);
this._send(Object.assign({ t: 'cmd' }, c)); this._send(Object.assign({ t: 'cmd' }, c));
return { ok: true, pending: true }; return { ok: true, pending: true };
} }
ctl(c, v) { this._send({ t: 'ctl', c, v }); } ctl(c, v) { if (this.mode !== 'versus') this._send({ t: 'ctl', c, v }); } // versus has no pause and no speed (the server refuses them)
vsSend(c, v, extra) { this._send(Object.assign({ t: 'vs', c, v }, extra)); return { ok: true, pending: true }; }
vsRole(v) { return this.vsSend('role', v); }
vsReady(v) { return this.vsSend('ready', v); }
vsBot(v, skill) { return this.vsSend('bot', v, skill === undefined ? undefined : { skill }); }
vsStart() { return this.vsSend('start'); }
vsNext() { return this.vsSend('next'); }
vsRematch() { return this.vsSend('rematch'); }
preview(x, y, routes) { preview(x, y, routes) {
if (!this.board) return { ok: false, reason: 'bounds' }; if (!this.board) return { ok: false, reason: 'bounds' };
const reserved = new Set(); const reserved = new Set();
@ -423,5 +612,7 @@
NW.LocalController = LocalController; NW.LocalController = LocalController;
NW.RemoteController = RemoteController; NW.RemoteController = RemoteController;
NW.matchScores = matchScores; // the match rules (shared with the server by a parity test): also handy for the end screen
NW.matchWinner = matchWinner;
NW.wsUrl = wsUrl; NW.wsUrl = wsUrl;
})(typeof self !== 'undefined' ? self : this); })(typeof self !== 'undefined' ? self : this);

View file

@ -97,6 +97,14 @@
syncModal(); syncModal();
} }
// ------------------------------------------------------------------ versus (js/versus.js): the mode's dialogs, HUD and sounds. With no versus game running (V.active false) it does nothing.
const V = NW.Versus.create({
$, app, renderer, Audio, store, esc, toast, banner, showOverlay, slotColor,
buildPalette, selectType, renderInfo, updatePaletteHint, setScreen, renderPlayers, adoptBoard, resetSelection,
resize: () => scheduleResize(), startLocal: startVersusLocal, connect: connectRemote, cancelPending, invite, exitToMenu, openMenu, closeOverlayToGame,
});
for (const k in V.REASONS) if (!(k in REASONS)) REASONS[k] = V.REASONS[k]; // the versus refusals get words (existing ones keep theirs)
// ------------------------------------------------------------------ dialogs (menu, lobby, help, end are role=dialog) // ------------------------------------------------------------------ dialogs (menu, lobby, help, end are role=dialog)
// While one is open the page behind it is inert (not focusable, not clickable, hidden from screen readers), focus moves into the // While one is open the page behind it is inert (not focusable, not clickable, hidden from screen readers), focus moves into the
// dialog onto its primary button, Tab stays inside it, and focus goes back to where it was when the dialog closes (code-8). // dialog onto its primary button, Tab stays inside it, and focus goes back to where it was when the dialog closes (code-8).
@ -113,7 +121,7 @@
if (ov) { if (ov) {
const btns = [...ov.querySelectorAll('button')].filter(isShown); const btns = [...ov.querySelectorAll('button')].filter(isShown);
const first = btns.find((b) => b.classList.contains('primary')) || btns[0]; // never a text field: on a phone that would raise the keyboard const first = btns.find((b) => b.classList.contains('primary')) || btns[0]; // never a text field: on a phone that would raise the keyboard
if (ov.id === 'end') modal.guard = performance.now() + 600; // (see the click guard below) if (ov.id === 'end' || ov.id === 'vsEnd') modal.guard = performance.now() + 600; // (see the click guard below)
if (first) first.focus({ preventScroll: true }); if (first) first.focus({ preventScroll: true });
} else if (was) { } else if (was) {
const o = modal.opener; modal.opener = null; const o = modal.opener; modal.opener = null;
@ -132,7 +140,7 @@
{ const mo = new MutationObserver(syncModal); for (const o of document.querySelectorAll('.overlay')) mo.observe(o, { attributes: true, attributeFilter: ['hidden'] }); } { const mo = new MutationObserver(syncModal); for (const o of document.querySelectorAll('.overlay')) mo.observe(o, { attributes: true, attributeFilter: ['hidden'] }); }
// The game-over dialog takes focus the moment the game ends, and a player who was tapping Space / Enter to start waves would // The game-over dialog takes focus the moment the game ends, and a player who was tapping Space / Enter to start waves would
// press its focused "Play again" with the next key and never see the result. For the first 0.6 s only a pointer can press its buttons. // press its focused "Play again" with the next key and never see the result. For the first 0.6 s only a pointer can press its buttons.
$('end').addEventListener('click', (e) => { if (e.detail === 0 && performance.now() < modal.guard) { e.stopPropagation(); e.preventDefault(); } }, true); for (const id of ['end', 'vsEnd']) $(id).addEventListener('click', (e) => { if (e.detail === 0 && performance.now() < modal.guard) { e.stopPropagation(); e.preventDefault(); } }, true);
function setScreen(name) { function setScreen(name) {
app.screen = name; app.screen = name;
$('app').dataset.screen = name; $('app').dataset.screen = name;
@ -148,11 +156,13 @@
ctrl.on('reject', onReject); ctrl.on('reject', onReject);
ctrl.on('mark', (m) => { renderer.addMark(m.x, m.y, m.slot); Audio.sfx('ping'); }); ctrl.on('mark', (m) => { renderer.addMark(m.x, m.y, m.slot); Audio.sfx('ping'); });
ctrl.on('players', onPlayers); ctrl.on('players', onPlayers);
ctrl.on('vs', () => { if (ctrl === app.ctrl && ctrl.kind === 'remote') renderPlayers(); }); // the roles are part of the players panel
ctrl.on('newgame', () => { ctrl.on('newgame', () => {
resetSelection(); app.endShown = false; app.last.state = 'playing'; adoptBoard(); $('end').hidden = true; resetSelection(); app.endShown = false; app.last.state = 'playing'; adoptBoard(); $('end').hidden = true;
app.bossMusic = false; if (app.inGame) Audio.music('battle'); // a new game starts its music on every client, not only on the one that pressed Play again (code-5) app.bossMusic = false; if (app.inGame) Audio.music('battle'); // a new game starts its music on every client, not only on the one that pressed Play again (code-5)
if (ctrl.kind === 'remote') renderPlayers(); // (the room header names the difficulty, which a new game may have changed) if (ctrl.kind === 'remote') renderPlayers(); // (the room header names the difficulty, which a new game may have changed)
}); });
V.attach(ctrl); // a versus controller switches the HUD to versus, any other one switches it back
adoptBoard(true); adoptBoard(true);
} }
function adoptBoard(force) { function adoptBoard(force) {
@ -184,6 +194,21 @@
requestWakeLock(); requestWakeLock();
firstRunHelp(); firstRunHelp();
} }
// A versus match against the computer: no server, no lobby (the controller starts in its countdown). opts: { role, limit, skill, countdownMs?, seed? }
function startVersusLocal(opts) {
cancelPending();
leaveRemote(true);
store.set('nw.map', app.mapId);
const c = new NW.LocalController({ map: app.mapId, mode: 'versus', role: opts.role, limit: opts.limit, skill: opts.skill, countdownMs: opts.countdownMs, seed: opts.seed });
useController(c);
app.inGame = true; app.started = true; app.endShown = false; app.last = {};
resetSelection(); setScreen('playing'); showOverlay(null);
$('players').hidden = true; $('netChip').hidden = true; $('reconnect').hidden = true;
renderInfo(true);
app.bossMusic = false; Audio.music('battle');
requestWakeLock();
return c;
}
// The first-run help opens once per install (storage) and at most once per page load, so a browser whose storage throws does not get it on every start (code-26). // The first-run help opens once per install (storage) and at most once per page load, so a browser whose storage throws does not get it on every start (code-26).
function firstRunHelp() { function firstRunHelp() {
if (app.helpSeen) return; if (app.helpSeen) return;
@ -221,10 +246,10 @@
case 'arc': Audio.sfx('arc'); break; case 'arc': Audio.sfx('arc'); break;
case 'boom': Audio.sfx('boom'); break; case 'boom': Audio.sfx('boom'); break;
case 'kill': Audio.sfx('kill'); break; case 'kill': Audio.sfx('kill'); break;
case 'leak': Audio.sfx('leak'); break; case 'leak': Audio.sfx(V.leakSfx()); break;
case 'wave': banner(e.boss ? 'BOSS WAVE ' + e.n : 'WAVE ' + e.n, e.boss); Audio.sfx(e.boss ? 'boss' : 'wave'); break; case 'wave': banner(e.boss ? 'BOSS WAVE ' + e.n : 'WAVE ' + e.n, e.boss); Audio.sfx(e.boss ? 'boss' : 'wave'); break;
case 'clear': toast('Wave ' + e.n + ' cleared +' + e.bonus + ' credits', 'good'); Audio.sfx('clear'); break; case 'clear': toast('Wave ' + e.n + ' cleared +' + e.bonus + ' credits', 'good'); Audio.sfx('clear'); break;
default: break; default: if (V.active) V.onEvent(e); break; // versus: emp, decoy, surge, ddos, quarantine, scan, repair
} }
} }
} }
@ -243,7 +268,7 @@
function priceOf(type) { return TD.priceFor(type, app.ctrl && app.ctrl.view ? app.ctrl.view.towers : 0); } function priceOf(type) { return TD.priceFor(type, app.ctrl && app.ctrl.view ? app.ctrl.view.towers : 0); }
function buildPalette() { function buildPalette() {
const pal = $('palette'); const pal = $('palette');
pal.textContent = ''; pal.textContent = ''; pal.classList.remove('shop');
pal.classList.toggle('many', TD.TOWER_ORDER.length > 6); pal.classList.toggle('many', TD.TOWER_ORDER.length > 6);
for (const type of TD.TOWER_ORDER) { for (const type of TD.TOWER_ORDER) {
const def = TD.TOWERS[type]; const def = TD.TOWERS[type];
@ -279,9 +304,11 @@
} }
$('palette').addEventListener('scroll', updatePaletteHint, { passive: true }); $('palette').addEventListener('scroll', updatePaletteHint, { passive: true });
function drawPaletteIcons() { function drawPaletteIcons() {
if (V.shopOn) { V.drawShopIcons(); return; } // the attacker's palette is the unit shop
for (const b of $('palette').children) NW.drawIcon(b.querySelector('canvas'), b.dataset.type, 1); for (const b of $('palette').children) NW.drawIcon(b.querySelector('canvas'), b.dataset.type, 1);
} }
function syncPalette() { function syncPalette() {
if (V.shopOn) return; // (the attacker's unit shop has nothing to select)
for (const b of $('palette').children) { for (const b of $('palette').children) {
const sel = b.dataset.type === app.selType; const sel = b.dataset.type === app.selType;
b.classList.toggle('sel', sel); b.classList.toggle('sel', sel);
@ -290,6 +317,7 @@
} }
} }
function selectType(type) { function selectType(type) {
if (type && V.active) V.disarm();
app.selType = type; app.selTower = 0; app.pending = null; app.previewDirty = true; app.selType = type; app.selTower = 0; app.pending = null; app.previewDirty = true;
syncPalette(); renderInfo(true); updateConfirm(); syncPalette(); renderInfo(true); updateConfirm();
if (!type) { ui.preview = null; hint(null); } if (!type) { ui.preview = null; hint(null); }
@ -329,7 +357,7 @@
if (!tower) app.selTower = 0; if (!tower) app.selTower = 0;
} }
if (tower) { if (tower) {
if (ctrl.kind === 'remote' && ctrl.players.length > 1) ownerP = ctrl.players.find((p) => p.slot === tower.owner) || null; if (ctrl.kind === 'remote' && ctrl.players.length > 1 && !V.active) ownerP = ctrl.players.find((p) => p.slot === tower.owner) || null;
shape = 't' + tower.id + tower.type + ':' + (ownerP ? ownerP.slot + ownerP.name : ''); shape = 't' + tower.id + tower.type + ':' + (ownerP ? ownerP.slot + ownerP.name : '');
} else if (app.selType) shape = 'b' + app.selType + ':' + priceOf(app.selType); // the price can change while armed (Orbital Uplink) } else if (app.selType) shape = 'b' + app.selType + ':' + priceOf(app.selType); // the price can change while armed (Orbital Uplink)
if (!force && shape === info.shape) { if (tower) syncInfo(); return; } if (!force && shape === info.shape) { if (tower) syncInfo(); return; }
@ -337,12 +365,13 @@
info.shape = shape; info.sig = ''; info.lv = 0; info.dirty = false; info.shape = shape; info.sig = ''; info.lv = 0; info.dirty = false;
if (!shape) { box.textContent = ''; return; } if (!shape) { box.textContent = ''; return; }
if (tower) { if (tower) {
const def = TD.TOWERS[tower.type], wall = tower.type === 'wall', aim = aimsAtTargets(def); const def = TD.TOWERS[tower.type], wall = tower.type === 'wall', att = V.active && V.role === 'attacker', aim = aimsAtTargets(def) && !att;
const empBtn = att && !wall ? '<button type="button" data-act="emp" title="Disable this tower for a few seconds"><svg class="ic"><use href="#i-ab-emp"/></svg><span class="w">EMP</span><span class="cost"></span></button>' : '';
box.innerHTML = box.innerHTML =
'<div class="panel info"><div class="info-head"><canvas></canvas><div><div class="nm"></div><div class="lv"></div></div></div>' + '<div class="panel info"><div class="info-head"><canvas></canvas><div><div class="nm"></div><div class="lv"></div></div></div>' +
'<div class="desc"></div><div class="kv"></div><div class="actions">' + '<div class="desc"></div><div class="kv"></div><div class="actions">' +
(wall ? '' : '<button type="button" data-act="up"><svg class="ic"><use href="#i-up"/></svg><span class="w"></span><span class="cost" id="upCost"></span></button>') + (wall || att ? '' : '<button type="button" data-act="up"><svg class="ic"><use href="#i-up"/></svg><span class="w"></span><span class="cost" id="upCost"></span></button>') +
'<button type="button" data-act="sell" class="danger"><svg class="ic"><use href="#i-trash"/></svg><span class="w">Sell</span><span class="cost"></span></button>' + (att ? empBtn : '<button type="button" data-act="sell" class="danger"><svg class="ic"><use href="#i-trash"/></svg><span class="w">Sell</span><span class="cost"></span></button>') +
(aim ? '<button type="button" data-act="mode" title="Which packet to shoot"><svg class="ic"><use href="#i-target"/></svg><span class="w">Target:</span><span class="mv"></span></button>' : '') + (aim ? '<button type="button" data-act="mode" title="Which packet to shoot"><svg class="ic"><use href="#i-target"/></svg><span class="w">Target:</span><span class="mv"></span></button>' : '') +
'<button type="button" data-act="close" class="icon" aria-label="Close" title="Close"><svg class="ic"><use href="#i-x"/></svg></button></div>' + '<button type="button" data-act="close" class="icon" aria-label="Close" title="Close"><svg class="ic"><use href="#i-x"/></svg></button></div>' +
'<div class="byline">' + (aim ? '<span id="infoKills"></span>' : '') + (ownerP ? '<span class="dot" style="background:' + slotColor(ownerP.slot) + '"></span><span id="infoOwner"></span>' : '') + '</div></div>'; '<div class="byline">' + (aim ? '<span id="infoKills"></span>' : '') + (ownerP ? '<span class="dot" style="background:' + slotColor(ownerP.slot) + '"></span><span id="infoOwner"></span>' : '') + '</div></div>';
@ -396,8 +425,7 @@
up.setAttribute('aria-label', canUp ? 'Upgrade for ' + upCost + ' credits' : 'Max level'); up.setAttribute('aria-label', canUp ? 'Upgrade for ' + upCost + ' credits' : 'Max level');
} }
const sell = box.querySelector('[data-act="sell"]'); const sell = box.querySelector('[data-act="sell"]');
setText(sell.querySelector('.cost'), String(sellVal)); if (sell) { setText(sell.querySelector('.cost'), String(sellVal)); sell.setAttribute('aria-label', 'Sell for ' + sellVal + ' credits'); } // (the attacker's panel has no Sell)
sell.setAttribute('aria-label', 'Sell for ' + sellVal + ' credits');
const mode = box.querySelector('[data-act="mode"]'); const mode = box.querySelector('[data-act="mode"]');
if (mode) { setText(mode.querySelector('.mv'), MODE_NAMES[t.mode]); mode.setAttribute('aria-label', 'Target: ' + MODE_NAMES[t.mode] + '. Tap to change'); } if (mode) { setText(mode.querySelector('.mv'), MODE_NAMES[t.mode]); mode.setAttribute('aria-label', 'Target: ' + MODE_NAMES[t.mode] + '. Tap to change'); }
setText(box.querySelector('#infoKills'), t.kills + (t.kills === 1 ? ' kill' : ' kills')); setText(box.querySelector('#infoKills'), t.kills + (t.kills === 1 ? ' kill' : ' kills'));
@ -421,6 +449,7 @@
case 'up': ctrl.send({ c: 'upgrade', id: tower.id }); break; case 'up': ctrl.send({ c: 'upgrade', id: tower.id }); break;
case 'sell': ctrl.send({ c: 'sell', id: tower.id }); app.selTower = 0; renderInfo(true); app.previewDirty = true; break; case 'sell': ctrl.send({ c: 'sell', id: tower.id }); app.selTower = 0; renderInfo(true); app.previewDirty = true; break;
case 'close': selectTower(0); break; case 'close': selectTower(0); break;
case 'emp': V.castEmp(tower.id); break;
case 'mode': { case 'mode': {
const modes = TD.TARGET_MODES; ctrl.send({ c: 'target', id: tower.id, mode: modes[(modes.indexOf(tower.mode) + 1) % modes.length] }); const modes = TD.TARGET_MODES; ctrl.send({ c: 'target', id: tower.id, mode: modes[(modes.indexOf(tower.mode) + 1) % modes.length] });
break; break;
@ -430,6 +459,7 @@
}); });
function renderWavePanel(view) { function renderWavePanel(view) {
if (V.active) { if (app.last.waveKey !== 'vs') { app.last.waveKey = 'vs'; $('nextwave').textContent = ''; } return; } // versus has no waves
const n = view.wave + 1; const n = view.wave + 1;
const dif = viewDifficulty(view); const dif = viewDifficulty(view);
const key = n + ':' + view.state + ':' + dif; const key = n + ':' + view.state + ':' + dif;
@ -455,7 +485,7 @@
function onPlayers(list) { function onPlayers(list) {
const ctrl = app.ctrl; const ctrl = app.ctrl;
ui.names = {}; for (const p of list) ui.names[p.slot] = p.name; ui.names = {}; for (const p of list) ui.names[p.slot] = p.name;
ui.coop = list.length > 1; ui.coop = list.length > 1 && !V.active; // (owner flags on the towers are for co-op: in versus one side builds everything)
// join / leave toasts // join / leave toasts
if (app.prevPlayers) { if (app.prevPlayers) {
for (const p of list) if (!app.prevPlayers.find((q) => q.pid === p.pid)) { toast(p.name + ' joined', 'good'); Audio.sfx('join'); } for (const p of list) if (!app.prevPlayers.find((q) => q.pid === p.pid)) { toast(p.name + ' joined', 'good'); Audio.sfx('join'); }
@ -472,12 +502,13 @@
if (!ctrl || ctrl.kind !== 'remote') { box.hidden = true; return; } if (!ctrl || ctrl.kind !== 'remote') { box.hidden = true; return; }
box.hidden = false; box.hidden = false;
const dif = viewDifficulty(ctrl.view); const dif = viewDifficulty(ctrl.view);
let html = '<div class="panel"><h4>Room ' + esc(ctrl.room || '') + '<span class="dtag" data-d="' + dif + '" title="Difficulty">' + esc(diffName(dif)) + '</span> <span id="plPing" class="muted"></span></h4>'; // (every server string is escaped before it goes into HTML, code-28) let html = '<div class="panel"><h4>Room ' + esc(ctrl.room || '') + (V.active ? '<span class="dtag" title="Attack versus defend">VERSUS</span>' : '<span class="dtag" data-d="' + dif + '" title="Difficulty">' + esc(diffName(dif)) + '</span>') + ' <span id="plPing" class="muted"></span></h4>'; // (every server string is escaped before it goes into HTML, code-28)
for (const p of ctrl.players) { for (const p of ctrl.players) {
html += '<div class="pl"><span class="dot" style="background:' + slotColor(p.slot) + '"></span><span class="pn"></span>' + html += '<div class="pl"><span class="dot" style="background:' + slotColor(p.slot) + '"></span><span class="pn"></span>' +
(ctrl.you && p.pid === ctrl.you.pid ? '<span class="you">(you)</span>' : '') + (p.host ? '<span class="you">host</span>' : '') + (p.online ? '' : '<span class="off">offline</span>') + '</div>'; (ctrl.you && p.pid === ctrl.you.pid ? '<span class="you">(you)</span>' : '') + (p.host ? '<span class="you">host</span>' : '') + (p.online ? '' : '<span class="off">offline</span>') +
(V.active && ctrl.vs && ctrl.vs.roles && ctrl.vs.roles[p.slot] ? (ctrl.vs.roles[p.slot] === 'attacker' ? '<span class="rolebadge attacker">ATTACK</span>' : '<span class="rolebadge defender">DEFEND</span>') : '') + '</div>';
} }
if (ctrl.players.length < 2) html += '<div class="muted small">Waiting for a partner&hellip; share the invite link.</div>'; if (ctrl.players.length < 2 && !(V.active && ctrl.vs && ctrl.vs.bot)) html += '<div class="muted small">Waiting for ' + (V.active ? 'an opponent' : 'a partner') + '&hellip; share the invite link.</div>';
html += '<div class="actions"><button type="button" data-act="invite"><svg class="ic"><use href="#i-share"/></svg>Invite</button><button type="button" data-act="leave" class="danger">Leave</button></div></div>'; html += '<div class="actions"><button type="button" data-act="invite"><svg class="ic"><use href="#i-share"/></svg>Invite</button><button type="button" data-act="leave" class="danger">Leave</button></div></div>';
box.innerHTML = html; box.innerHTML = html;
const names = box.querySelectorAll('.pn'); const names = box.querySelectorAll('.pn');
@ -500,7 +531,7 @@
// ------------------------------------------------------------------ HUD // ------------------------------------------------------------------ HUD
function updateHud(view) { function updateHud(view) {
const L = app.last, ctrl = app.ctrl; const L = app.last, ctrl = app.ctrl;
if (L.gold !== view.gold) { L.gold = view.gold; $('vGold').textContent = String(view.gold); } if (!(V.active && V.role === 'attacker') && L.gold !== view.gold) { L.gold = view.gold; $('vGold').textContent = String(view.gold); } // (the attacker's top bar shows its own purse: versus.js)
if (L.lives !== view.lives) { if (L.lives !== view.lives) {
L.lives = view.lives; $('vLives').textContent = String(view.lives); L.lives = view.lives; $('vLives').textContent = String(view.lives);
$('statLives').classList.toggle('low', view.maxLives > 0 && view.lives <= view.maxLives * 0.25); $('statLives').classList.toggle('low', view.maxLives > 0 && view.lives <= view.maxLives * 0.25);
@ -526,7 +557,7 @@
// palette affordability // palette affordability
const gold = view.gold; const gold = view.gold;
const palKey = gold + ':' + view.towers.length; // prices can change when the tower count does (Orbital Uplink) const palKey = gold + ':' + view.towers.length; // prices can change when the tower count does (Orbital Uplink)
if (L.palGold !== palKey) { if (!V.shopOn && L.palGold !== palKey) {
L.palGold = palKey; L.palGold = palKey;
for (const b of $('palette').children) { for (const b of $('palette').children) {
const def = TD.TOWERS[b.dataset.type], price = priceOf(b.dataset.type), poor = gold < price; const def = TD.TOWERS[b.dataset.type], price = priceOf(b.dataset.type), poor = gold < price;
@ -537,7 +568,7 @@
} }
if (ctrl.kind === 'remote') { if (ctrl.kind === 'remote') {
const chip = $('netChip'); const chip = $('netChip');
chip.hidden = false; chip.hidden = V.active; // (a running versus match has nobody to invite: the room code is in the players panel)
$('netRoom').textContent = ctrl.room || ''; $('netRoom').textContent = ctrl.room || '';
const alone = ctrl.players.length < 2; const alone = ctrl.players.length < 2;
if (L.alone !== alone || L.room !== ctrl.room) { if (L.alone !== alone || L.room !== ctrl.room) {
@ -744,6 +775,7 @@
return app.ctrl.view.towers.find((x) => x.x === cell.x && x.y === cell.y) || null; return app.ctrl.view.towers.find((x) => x.x === cell.x && x.y === cell.y) || null;
} }
function tapSelect(cell) { function tapSelect(cell) {
if (V.active && V.tapCell(cell)) return; // versus: a tapped gateway (attacker), an armed Scan / EMP
const ctrl = app.ctrl; const ctrl = app.ctrl;
if (!ctrl.board.inBounds(cell.x, cell.y)) { selectTower(0); return; } if (!ctrl.board.inBounds(cell.x, cell.y)) { selectTower(0); return; }
const t = ctrl.view.towers.find((x) => x.x === cell.x && x.y === cell.y); const t = ctrl.view.towers.find((x) => x.x === cell.x && x.y === cell.y);
@ -917,11 +949,12 @@
if (e.repeat) return; // holding a key is one press: Space must not start 20 waves (code-6) if (e.repeat) return; // holding a key is one press: Space must not start 20 waves (code-6)
if (e.key && e.key.toLowerCase() === 'm' && !e.altKey) { Audio.toggleMuted(); return; } // M mutes anywhere: in the menu, behind a dialog, on the end screen (code-13) if (e.key && e.key.toLowerCase() === 'm' && !e.altKey) { Audio.toggleMuted(); return; } // M mutes anywhere: in the menu, behind a dialog, on the end screen (code-13)
if (!app.inGame) return; if (!app.inGame) return;
if (document.querySelector('.overlay:not([hidden])')) { if (e.key === 'Escape' && $('end').hidden) closeOverlayToGame(); return; } // (the game-over dialog is left with its buttons, never dismissed: Escape there would leave a dead board, code-9) if (document.querySelector('.overlay:not([hidden])')) { if (e.key === 'Escape' && $('end').hidden && !V.holdsOverlay()) closeOverlayToGame(); return; } // (the game-over dialog is left with its buttons, never dismissed: Escape there would leave a dead board, code-9)
const ctrl = app.ctrl, view = ctrl.view; const ctrl = app.ctrl, view = ctrl.view;
const k = e.key.toLowerCase(); const k = e.key.toLowerCase();
// Space / Enter on a focused button or link press THAT control (keyboard users), not the next-wave hotkey (code-8) // Space / Enter on a focused button or link press THAT control (keyboard users), not the next-wave hotkey (code-8)
if ((k === ' ' || k === 'enter') && e.target && e.target.closest && e.target.closest('button, a, select, [role="button"]')) return; if ((k === ' ' || k === 'enter') && e.target && e.target.closest && e.target.closest('button, a, select, [role="button"]')) return;
if (V.active && V.key(k, e)) return; // versus: attacker digits buy units, Space launches; waves, pause and speed do nothing
const keyType = k.length === 1 ? TD.TOWER_ORDER.find((t) => TD.TOWERS[t].key === k) : null; // 1-9, 0: one key per tower in the palette const keyType = k.length === 1 ? TD.TOWER_ORDER.find((t) => TD.TOWERS[t].key === k) : null; // 1-9, 0: one key per tower in the palette
if (keyType) { selectType(app.selType === keyType ? null : keyType); Audio.sfx('click'); e.preventDefault(); return; } if (keyType) { selectType(app.selType === keyType ? null : keyType); Audio.sfx('click'); e.preventDefault(); return; }
switch (k) { switch (k) {
@ -1058,9 +1091,10 @@
} }
function closeOverlayToGame() { function closeOverlayToGame() {
if (!app.inGame) return; if (!app.inGame) return;
if (!$('lobby').hidden) cancelPending(); // leaving the lobby abandons a join that is still connecting (code-3) if (!$('lobby').hidden || !$('vsSetup').hidden) cancelPending(); // leaving the lobby abandons a join that is still connecting (code-3)
showOverlay(null); showOverlay(null);
if (app.menuPaused) { app.menuPaused = false; if (app.ctrl.kind === 'local' && app.ctrl.view.paused) app.ctrl.ctl('pause', false); } if (app.menuPaused) { app.menuPaused = false; if (app.ctrl.kind === 'local' && app.ctrl.view.paused) app.ctrl.ctl('pause', false); }
if (V.active) V.refreshOverlay(); // a versus lobby / result dialog that was waiting behind the menu comes back
} }
function leaveToMenu(keep) { function leaveToMenu(keep) {
cancelPending(); cancelPending();
@ -1073,6 +1107,7 @@
} }
$('btnSolo').addEventListener('click', () => { Audio.unlock(); startSolo(app.mapId); }); $('btnSolo').addEventListener('click', () => { Audio.unlock(); startSolo(app.mapId); });
$('btnVersus').addEventListener('click', () => { Audio.unlock(); V.openSetup(); });
$('btnCloseMenu').addEventListener('click', closeOverlayToGame); $('btnCloseMenu').addEventListener('click', closeOverlayToGame);
$('btnHelp').addEventListener('click', () => showOverlay('help')); $('btnHelp').addEventListener('click', () => showOverlay('help'));
$('btnHelpClose').addEventListener('click', () => { if (app.inGame) closeOverlayToGame(); else showOverlay('menu'); }); $('btnHelpClose').addEventListener('click', () => { if (app.inGame) closeOverlayToGame(); else showOverlay('menu'); });
@ -1089,7 +1124,8 @@
else { app.ctrl.newGame(app.ctrl.board.mapId, app.ctrl.difficulty); } else { app.ctrl.newGame(app.ctrl.board.mapId, app.ctrl.difficulty); }
}); });
$('btnContinue').addEventListener('click', () => { app.ctrl.send({ c: 'continue' }); $('end').hidden = true; app.endShown = false; Audio.music('battle'); }); $('btnContinue').addEventListener('click', () => { app.ctrl.send({ c: 'continue' }); $('end').hidden = true; app.endShown = false; Audio.music('battle'); });
$('btnEndMenu').addEventListener('click', () => { if (app.ctrl.kind === 'remote') leaveToMenu(); else { app.inGame = false; previewMap(app.mapId); setScreen('menu'); openMenu(); } }); function exitToMenu() { if (app.ctrl.kind === 'remote') leaveToMenu(); else { app.inGame = false; previewMap(app.mapId); setScreen('menu'); openMenu(); } }
$('btnEndMenu').addEventListener('click', exitToMenu);
// lobby // lobby
function lobbyMsg(text, bad) { const m = $('lobbyMsg'); m.textContent = text || ''; m.className = 'msg' + (bad ? ' bad' : ''); } function lobbyMsg(text, bad) { const m = $('lobbyMsg'); m.textContent = text || ''; m.className = 'msg' + (bad ? ' bad' : ''); }
@ -1114,24 +1150,25 @@
// leaves the game that is running untouched (coop-4), Back / Play solo can cancel it (code-3), and only one attempt runs at a time (code-4). // leaves the game that is running untouched (coop-4), Back / Play solo can cancel it (code-3), and only one attempt runs at a time (code-4).
let pendingRc = null; let pendingRc = null;
const KEEP_SESSION = { connect: 1, lost: 1, replaced: 1 }; // after these the saved room is still worth another try; any other failure means it is gone const KEEP_SESSION = { connect: 1, lost: 1, replaced: 1 }; // after these the saved room is still worth another try; any other failure means it is gone
function setLobbyBusy(b) { for (const id of ['btnCreate', 'btnJoin', 'btnResume']) $(id).disabled = b; } function setLobbyBusy(b) { for (const id of ['btnCreate', 'btnJoin', 'btnResume', 'btnVsCreate', 'btnVsJoin']) $(id).disabled = b; }
function cancelPending() { function cancelPending() {
const rc = pendingRc; pendingRc = null; const rc = pendingRc; pendingRc = null;
if (rc) rc.close(); if (rc) rc.close();
setLobbyBusy(false); setLobbyBusy(false);
} }
// opts: { room, map, resume }. `resume` is a rejoin of a game left earlier (reload, "Resume"): it says "gone" instead of "does not exist". // opts: { room, map, resume, difficulty, mode:'versus'?, limit?, name?, say?(text, bad) }. `resume` is a rejoin of a game left earlier (reload, "Resume"): it says "gone" instead of "does not exist".
function connectRemote(opts) { function connectRemote(opts) {
if (root.location.protocol === 'file:') { lobbyMsg('Open the game through the Netwall server to play online.', true); return; } const say = opts.say || lobbyMsg; // where the connecting / failure text goes (the co-op lobby, or the versus dialog)
if (root.location.protocol === 'file:') { say('Open the game through the Netwall server to play online.', true); return; }
if (pendingRc) return; // a double click must not open two rooms and an orphan socket if (pendingRc) return; // a double click must not open two rooms and an orphan socket
const live = app.inGame && app.ctrl && app.ctrl.kind === 'remote' ? app.ctrl : null; const live = app.inGame && app.ctrl && app.ctrl.kind === 'remote' ? app.ctrl : null;
if (live && opts.room && live.room === opts.room) { closeOverlayToGame(); return; } // that is the room we are in if (live && opts.room && live.room === opts.room) { closeOverlayToGame(); return; } // that is the room we are in
const name = ($('inName').value || store.get('nw.name', '') || '').trim().slice(0, 16) || 'Player'; const name = ((opts.name !== undefined ? opts.name : $('inName').value) || store.get('nw.name', '') || '').trim().slice(0, 16) || 'Player';
store.set('nw.name', name); store.set('nw.name', name);
lobbyMsg('Connecting…'); say('Connecting…');
const rc = new NW.RemoteController({ pid: getPid(), name, room: opts.room, map: opts.map, difficulty: opts.difficulty, resume: !!opts.resume }); const rc = new NW.RemoteController({ pid: getPid(), name, room: opts.room, map: opts.map, difficulty: opts.difficulty, mode: opts.mode, limit: opts.limit, resume: !!opts.resume });
pendingRc = rc; setLobbyBusy(true); pendingRc = rc; setLobbyBusy(true);
const saveSession = () => { sess.set('nw.room', rc.room); store.set('nw.session', { pid: getPid(), room: rc.room, name, ts: Date.now() }); }; const saveSession = () => { sess.set('nw.room', rc.room); store.set('nw.session', { pid: getPid(), room: rc.room, name, ts: Date.now(), mode: rc.mode }); };
let first = true; let first = true;
rc.on('joined', () => { rc.on('joined', () => {
if (first && pendingRc !== rc) { rc.close(); return; } // cancelled while connecting: never take anything over if (first && pendingRc !== rc) { rc.close(); return; } // cancelled while connecting: never take anything over
@ -1145,11 +1182,15 @@
resetSelection(); setScreen('playing'); showOverlay(null); resetSelection(); setScreen('playing'); showOverlay(null);
onPlayers(rc.players); onPlayers(rc.players);
try { root.history.replaceState(null, '', root.location.pathname + '?room=' + encodeURIComponent(rc.room)); } catch (e) { /* ignore */ } try { root.history.replaceState(null, '', root.location.pathname + '?room=' + encodeURIComponent(rc.room)); } catch (e) { /* ignore */ }
toast('Room ' + rc.room + ' \u00b7 ' + diffName(viewDifficulty(rc.view)) + (rc.players.length < 2 ? '. Send the invite link to your partner!' : ''), 'good'); // (a joiner learns the host's difficulty here) if (rc.mode === 'versus') { // a versus room opens on its lobby dialog (or straight into the round that is running)
Audio.music('battle'); requestWakeLock(); V.refreshOverlay(); Audio.music(V.phase === 'lobby' ? 'theme' : 'battle'); requestWakeLock();
firstRunHelp(); // an invited player is new to the game too (code-26) } else {
toast('Room ' + rc.room + ' \u00b7 ' + diffName(viewDifficulty(rc.view)) + (rc.players.length < 2 ? '. Send the invite link to your partner!' : ''), 'good'); // (a joiner learns the host's difficulty here)
Audio.music('battle'); requestWakeLock();
firstRunHelp(); // an invited player is new to the game too (code-26)
}
} else { toast('Reconnected', 'good'); adoptBoard(); } } else { toast('Reconnected', 'good'); adoptBoard(); }
lobbyMsg(''); say('');
}); });
rc.on('status', (s) => { rc.on('status', (s) => {
if (app.ctrl !== rc || !app.inGame) return; if (app.ctrl !== rc || !app.inGame) return;
@ -1161,12 +1202,14 @@
const keep = !!KEEP_SESSION[f.code]; const keep = !!KEEP_SESSION[f.code];
if (app.ctrl === rc && app.inGame) { // the game we were playing is gone if (app.ctrl === rc && app.inGame) { // the game we were playing is gone
if (!keep) { sess.del('nw.room'); store.del('nw.session'); } if (!keep) { sess.del('nw.room'); store.del('nw.session'); }
toast(f.msg, 'bad'); leaveToMenu(keep); openLobby(); lobbyMsg(f.msg, true); const vsGame = rc.mode === 'versus';
toast(f.msg, 'bad'); leaveToMenu(keep);
if (vsGame) { V.openSetup(); V.msg(f.msg, true); } else { openLobby(); lobbyMsg(f.msg, true); }
return; return;
} }
if (opts.resume && !keep) { sess.del('nw.room'); store.del('nw.session'); } // the saved game cannot be rejoined: forget it if (opts.resume && !keep) { sess.del('nw.room'); store.del('nw.session'); } // the saved game cannot be rejoined: forget it
lobbyMsg(f.msg, true); say(f.msg, true);
if ($('lobby').hidden) toast(f.msg, 'bad'); // a Resume / reload rejoin has no lobby on screen: tell the player where they look (code-24) if ((opts.say ? $('vsSetup') : $('lobby')).hidden) toast(f.msg, 'bad'); // a Resume / reload rejoin has no lobby on screen: tell the player where they look (code-24)
updateResumeButton(); updateResumeButton();
}); });
rc.connect(); rc.connect();
@ -1176,7 +1219,7 @@
const s = store.get('nw.session', null), b = $('btnResume'); const s = store.get('nw.session', null), b = $('btnResume');
const fresh = s && s.room && Date.now() - s.ts < 15 * 60 * 1000 && !(app.ctrl && app.ctrl.kind === 'remote'); const fresh = s && s.room && Date.now() - s.ts < 15 * 60 * 1000 && !(app.ctrl && app.ctrl.kind === 'remote');
b.hidden = !fresh || root.location.protocol === 'file:'; b.hidden = !fresh || root.location.protocol === 'file:';
if (fresh) b.textContent = 'Resume co-op game · room ' + s.room; if (fresh) b.textContent = 'Resume ' + (s.mode === 'versus' ? 'versus' : 'co-op') + ' game · room ' + s.room;
} }
$('btnResume').addEventListener('click', () => { $('btnResume').addEventListener('click', () => {
const s = store.get('nw.session', null); if (!s) return; const s = store.get('nw.session', null); if (!s) return;
@ -1221,7 +1264,7 @@
const W = a.clientWidth - (parseFloat(cs.paddingLeft) || 0) - (parseFloat(cs.paddingRight) || 0); const W = a.clientWidth - (parseFloat(cs.paddingLeft) || 0) - (parseFloat(cs.paddingRight) || 0);
const H = a.clientHeight - (parseFloat(cs.paddingTop) || 0) - (parseFloat(cs.paddingBottom) || 0) - $('topbar').offsetHeight; const H = a.clientHeight - (parseFloat(cs.paddingTop) || 0) - (parseFloat(cs.paddingBottom) || 0) - $('topbar').offsetHeight;
const mg = (NW.BOARD_MARGIN || 0) * 2, dw = b.cols * NW.CELL + mg, dh = b.rows * NW.CELL + mg, pad = 8; const mg = (NW.BOARD_MARGIN || 0) * 2, dw = b.cols * NW.CELL + mg, dh = b.rows * NW.CELL + mg, pad = 8;
const minSide = clamp(Math.round(H * 0.25), 140, 210); // room for the palette row and a window onto the info panel const minSide = V.minSide(H) || clamp(Math.round(H * 0.25), 140, 210); // room for the palette row and a window onto the info panel (versus: the dock too)
const maxStage = Math.max(120, H - minSide); const maxStage = Math.max(120, H - minSide);
const sU = Math.min((W - pad) / dw, (maxStage - pad) / dh), sR = Math.min((W - pad) / dh, (maxStage - pad) / dw); const sU = Math.min((W - pad) / dw, (maxStage - pad) / dh), sR = Math.min((W - pad) / dh, (maxStage - pad) / dw);
const rot = sR > sU * 1.08; const rot = sR > sU * 1.08;
@ -1272,6 +1315,7 @@
} }
if (app.last.rev !== view.rev) { app.last.rev = view.rev; app.previewDirty = true; if (app.selTower || app.selType) renderInfo(false); } if (app.last.rev !== view.rev) { app.last.rev = view.rev; app.previewDirty = true; if (app.selTower || app.selType) renderInfo(false); }
updateHud(view); updateHud(view);
V.tick(now, view); // versus: clock, credits, cooldown rings, shop affordability
layoutBars(false); layoutBars(false);
updateFit(); // the Reset-zoom button always follows the camera, however it was reset (code-18, coop-8) updateFit(); // the Reset-zoom button always follows the camera, however it was reset (code-18, coop-8)
if (now - app.lastBossCheck > 600 && view.state === 'playing') { if (now - app.lastBossCheck > 600 && view.state === 'playing') {
@ -1280,7 +1324,7 @@
if (boss !== app.bossMusic) { app.bossMusic = boss; if (!app.endShown) Audio.music(boss ? 'boss' : 'battle'); } if (boss !== app.bossMusic) { app.bossMusic = boss; if (!app.endShown) Audio.music(boss ? 'boss' : 'battle'); }
} }
} }
ui.hover = app.pending || app.hover; ui.selType = app.selType; ui.selTower = app.selTower; ui.hover = app.pending || app.hover; ui.selType = app.selType; ui.selTower = app.selTower; ui.vs = V.uiState();
// hovering an existing tower while a build type is active: a click selects it, so show no ghost // hovering an existing tower while a build type is active: a click selects it, so show no ghost
ui.noGhost = !!(ui.hover && app.selType && view.towers.some((t) => t.x === ui.hover.x && t.y === ui.hover.y)); ui.noGhost = !!(ui.hover && app.selType && view.towers.some((t) => t.x === ui.hover.x && t.y === ui.hover.y));
refreshPreview(false); refreshPreview(false);
@ -1317,5 +1361,7 @@
} }
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot); else boot(); if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot); else boot();
app.startVersus = startVersusLocal; // (tests: a local versus game with its own limit and countdown)
app.vs = V;
NW.app = app; // handy for debugging and automated tests NW.app = app; // handy for debugging and automated tests
})(typeof self !== 'undefined' ? self : this); })(typeof self !== 'undefined' ? self : this);

View file

@ -329,6 +329,8 @@
this.rot = 0; // 0, or PI/2 when the board is drawn rotated for portrait screens this.rot = 0; // 0, or PI/2 when the board is drawn rotated for portrait screens
this.fx = (root.matchMedia && root.matchMedia('(pointer: coarse)').matches) ? 0.55 : 1; // fewer particles on phones this.fx = (root.matchMedia && root.matchMedia('(pointer: coarse)').matches) ? 0.55 : 1; // fewer particles on phones
this.names = {}; this.names = {};
// versus cues (all stay empty in solo / co-op): screen effects with seconds left, Scan zones, gateway pulses, the tower list for events that name a tower
this.fxT = { surge: 0, ddos: 0, freeze: 0 }; this.scans = []; this.gatePulse = new Map(); this._towers = [];
} }
setBoard(board) { setBoard(board) {
@ -336,6 +338,7 @@
this.wallGrid = new Uint8Array(board.cols * board.rows); this.wallGrid = new Uint8Array(board.cols * board.rows);
this.parts.length = 0; this.rings.length = 0; this.lines.length = 0; this.texts.length = 0; this.marks.length = 0; this.pulses.length = 0; this.parts.length = 0; this.rings.length = 0; this.lines.length = 0; this.texts.length = 0; this.marks.length = 0; this.pulses.length = 0;
this.aim.clear(); this.trk.clear(); this.glow.clear(); this.aim.clear(); this.trk.clear(); this.glow.clear();
this.fxT.surge = this.fxT.ddos = this.fxT.freeze = 0; this.scans.length = 0; this.gatePulse.clear();
this.resetCamera(); this.resetCamera();
} }
resize(w, h, dpr) { resize(w, h, dpr) {
@ -453,6 +456,22 @@
break; break;
} }
case 'heal': this._pulse(e.x * C, e.y * C, 10, (e.r || 2.2) * C, '#7ee08a', 0.7, 2.2, 0.07); break; // soft green wave out to the daemon's range case 'heal': this._pulse(e.x * C, e.y * C, 10, (e.r || 2.2) * C, '#7ee08a', 0.7, 2.2, 0.07); break; // soft green wave out to the daemon's range
// ---- versus
case 'emp': { // the attacker disabled a tower: a yellow burst on it (the disabled look itself follows tower.empT)
const tw = this._towers.find((x) => x.id === e.id);
if (tw) { const cx = (tw.x + 0.5) * C, cy = (tw.y + 0.5) * C; this._ring(cx, cy, 6, 44, '#ffe27a', 0.55, 3); this._ring(cx, cy, 4, 26, '#ffffff', 0.3, 2); this._burst(cx, cy, '#ffe27a', 12, 120, 0.5); this.shake = Math.min(2, this.shake + 0.3); }
break;
}
case 'surge': this.fxT.surge = e.d || 6; break;
case 'ddos': this.fxT.ddos = e.d || 4; break;
case 'quarantine': this.fxT.freeze = e.d || 2; break;
case 'scan': {
const sc = TD.VS && TD.VS.TOOLS.scan, rd = (sc ? sc.radius : 4), rv = sc ? sc.reveal : 3;
this.scans.push({ x: e.x, y: e.y, t: rv, max: rv, r: rd });
this._pulse(e.x * C, e.y * C, 8, rd * C, '#7ee8ff', 0.6, 3, 0.1);
break;
}
case 'repair': { const b = this.board; if (b) { this._ring((b.core.x + 0.5) * C, (b.core.y + 0.5) * C, 10, 52, '#35e0a1', 0.6, 3); this._burst((b.core.x + 0.5) * C, (b.core.y + 0.5) * C, '#35e0a1', 8, 80, 0.5); } break; }
default: break; default: break;
} }
} }
@ -466,6 +485,7 @@
const t = now / 1000; const t = now / 1000;
const dt = clamp((now - (this.lastNow || now)) / 1000, 0, 0.1); this.lastNow = now; const dt = clamp((now - (this.lastNow || now)) / 1000, 0, 0.1); this.lastNow = now;
const sc = this.scale; const sc = this.scale;
const vsui = ui && ui.vs ? ui.vs : null; // versus-only cues (null in solo / co-op)
ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.fillStyle = BG; ctx.fillRect(0, 0, this.W, this.H); ctx.fillStyle = BG; ctx.fillRect(0, 0, this.W, this.H);
@ -502,11 +522,11 @@
} }
this._drawRoutes(ctx, b, ui, t); this._drawRoutes(ctx, b, ui, t);
this._drawEndpoints(ctx, b, view, t, dt, rot); this._drawEndpoints(ctx, b, view, t, dt, rot, vsui);
// walls (with trace links) then turrets // walls (with trace links) then turrets
const wg = this.wallGrid; wg.fill(0); const wg = this.wallGrid; wg.fill(0);
const towers = view.towers; const towers = view.towers; this._towers = towers;
for (let i = 0; i < towers.length; i++) if (towers[i].type === 'wall') wg[towers[i].y * cols + towers[i].x] = 1; for (let i = 0; i < towers.length; i++) if (towers[i].type === 'wall') wg[towers[i].y * cols + towers[i].x] = 1;
ctx.lineCap = 'round'; ctx.lineCap = 'round';
ctx.strokeStyle = 'rgba(90,169,255,.55)'; ctx.lineWidth = 3.2; ctx.strokeStyle = 'rgba(90,169,255,.55)'; ctx.lineWidth = 3.2;
@ -545,6 +565,8 @@
const cx = (tw.x + 0.5) * C, cy = (tw.y + 0.5) * C; const cx = (tw.x + 0.5) * C, cy = (tw.y + 0.5) * C;
const gl = tw.type === 'sandbox' && this.glow.size ? this.glow.get(tw.y * cols + tw.x) : 0; const gl = tw.type === 'sandbox' && this.glow.size ? this.glow.get(tw.y * cols + tw.x) : 0;
drawGlyph(ctx, tw.type, tw.level, cx, cy, C, ang, t, 1, rot, gl ? Math.min(1, gl / 0.25) : 0); drawGlyph(ctx, tw.type, tw.level, cx, cy, C, ang, t, 1, rot, gl ? Math.min(1, gl / 0.25) : 0);
if (tw.empT > 0) this._drawEmp(ctx, tw, cx, cy, t); // versus: disabled by an EMP
else if (vsui && vsui.empArm && tw.type !== 'wall') { ctx.strokeStyle = 'rgba(255,226,122,' + (0.5 + 0.4 * Math.sin(t * 8)) + ')'; ctx.lineWidth = 2.5; rr(ctx, tw.x * C + 2, tw.y * C + 2, C - 4, C - 4, 6); ctx.stroke(); } // EMP armed: every tower it can hit
if (coop && tw.type !== 'wall') { // owner corner flag: at least ~5 CSS px, dark outline so it shows on a tile of the same colour if (coop && tw.type !== 'wall') { // owner corner flag: at least ~5 CSS px, dark outline so it shows on a tile of the same colour
const k = Math.max(12, 5.5 / sc), x0 = cx - C * 0.46, y0 = cy - C * 0.46; const k = Math.max(12, 5.5 / sc), x0 = cx - C * 0.46, y0 = cy - C * 0.46;
ctx.beginPath(); ctx.moveTo(x0, y0); ctx.lineTo(x0 + k, y0); ctx.lineTo(x0, y0 + k); ctx.closePath(); ctx.beginPath(); ctx.moveTo(x0, y0); ctx.lineTo(x0 + k, y0); ctx.lineTo(x0, y0 + k); ctx.closePath();
@ -569,8 +591,8 @@
} }
// ground monsters, then flyers on top // ground monsters, then flyers on top
this._drawMonsters(ctx, view, t, dt, false, rot); this._drawMonsters(ctx, view, t, dt, false, rot, vsui);
this._drawMonsters(ctx, view, t, dt, true, rot); this._drawMonsters(ctx, view, t, dt, true, rot, vsui);
// bullets // bullets
for (const bu of view.bullets) { for (const bu of view.bullets) {
@ -584,6 +606,7 @@
} }
this._drawFx(ctx, dt, sc, rot); this._drawFx(ctx, dt, sc, rot);
if (vsui || this.scans.length || this.fxT.surge > 0 || this.fxT.ddos > 0 || this.fxT.freeze > 0) this._drawVsFx(ctx, dt, sc, cols, rows, t, ui);
// placement ghost // placement ghost
if (ui.hover && ui.selType && !ui.noGhost && b.inBounds(ui.hover.x, ui.hover.y)) { if (ui.hover && ui.selType && !ui.noGhost && b.inBounds(ui.hover.x, ui.hover.y)) {
@ -692,15 +715,17 @@
ctx.setLineDash([]); ctx.setLineDash([]);
} }
_drawEndpoints(ctx, b, view, t, dt, rot) { _drawEndpoints(ctx, b, view, t, dt, rot, vsui) {
// spawns: red gateways // spawns: red gateways
for (const sp of b.spawns) { for (let gi = 0; gi < b.spawns.length; gi++) {
const sp = b.spawns[gi];
const p = (t * 0.7) % 1; const p = (t * 0.7) % 1;
ctx.save(); ctx.translate((sp.x + 0.5) * C, (sp.y + 0.5) * C); if (rot) ctx.rotate(-rot); ctx.save(); ctx.translate((sp.x + 0.5) * C, (sp.y + 0.5) * C); if (rot) ctx.rotate(-rot);
ctx.strokeStyle = rgba('#ff5c7a', 0.5 * (1 - p)); ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(0, 0, 12 + p * 16, 0, TAU); ctx.stroke(); ctx.strokeStyle = rgba('#ff5c7a', 0.5 * (1 - p)); ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(0, 0, 12 + p * 16, 0, TAU); ctx.stroke();
ctx.fillStyle = '#2a0c18'; ctx.beginPath(); ctx.arc(0, 0, 13, 0, TAU); ctx.fill(); ctx.fillStyle = '#2a0c18'; ctx.beginPath(); ctx.arc(0, 0, 13, 0, TAU); ctx.fill();
ctx.strokeStyle = '#ff5c7a'; ctx.lineWidth = 2; ctx.stroke(); ctx.strokeStyle = '#ff5c7a'; ctx.lineWidth = 2; ctx.stroke();
ctx.lineWidth = 1.3; ctx.beginPath(); ctx.ellipse(0, 0, 5.5, 13, 0, 0, TAU); ctx.moveTo(-13, 0); ctx.lineTo(13, 0); ctx.stroke(); ctx.lineWidth = 1.3; ctx.beginPath(); ctx.ellipse(0, 0, 5.5, 13, 0, 0, TAU); ctx.moveTo(-13, 0); ctx.lineTo(13, 0); ctx.stroke();
if (vsui) this._vsGate(ctx, gi, vsui, t, dt, b.spawns.length);
ctx.restore(); ctx.restore();
} }
// core: server rack with an integrity ring // core: server rack with an integrity ring
@ -721,7 +746,7 @@
ctx.restore(); ctx.restore();
} }
_drawMonsters(ctx, view, t, dt, air, rot) { _drawMonsters(ctx, view, t, dt, air, rot, vsui) {
const trk = this.trk; const trk = this.trk;
if (!air) { // a Daemon's heal range, faint, all in one stroke if (!air) { // a Daemon's heal range, faint, all in one stroke
let any = false; let any = false;
@ -737,7 +762,10 @@
if (!!m.air !== air) continue; if (!!m.air !== air) continue;
const def = TD.ENEMIES[m.kind]; const def = TD.ENEMIES[m.kind];
let k = trk.get(m.id); let k = trk.get(m.id);
if (!k) { k = { x: m.x, y: m.y, ang: 0, hp: m.hp, flash: 0, still: 0, sv: null }; trk.set(m.id, k); } if (!k) {
k = { x: m.x, y: m.y, ang: 0, hp: m.hp, flash: 0, still: 0, sv: null }; trk.set(m.id, k);
if (vsui) this._vsBorn(k, m, vsui, t);
}
const dm = def.shield && m.maxShield === undefined ? this._shieldView(k, m, def, dt) : m; // co-op: tell hp and shield apart (see there) const dm = def.shield && m.maxShield === undefined ? this._shieldView(k, m, def, dt) : m; // co-op: tell hp and shield apart (see there)
const v = vitals(dm, def), cur = v.hp + v.sh; const v = vitals(dm, def), cur = v.hp + v.sh;
const dx = m.x - k.x, dy = m.y - k.y; const dx = m.x - k.x, dy = m.y - k.y;
@ -749,6 +777,7 @@
// stunned: solo knows (stunT); in co-op the wire only says "slowed or stunned", and a slowed packet still moves, so a flagged packet that stands still is stunned // stunned: solo knows (stunT); in co-op the wire only says "slowed or stunned", and a slowed packet still moves, so a flagged packet that stands still is stunned
const stun = m.stunT !== undefined ? m.stunT > 0 : m.slow > 0 && k.still > 0.2 && !view.paused; const stun = m.stunT !== undefined ? m.stunT > 0 : m.slow > 0 && k.still > 0.2 && !view.paused;
if (air && !SWARM[m.kind]) { const er = def.r * C; ctx.fillStyle = 'rgba(0,0,0,.28)'; ctx.save(); ctx.translate(m.x * C, m.y * C); if (rot) ctx.rotate(-rot); ctx.beginPath(); ctx.ellipse(0, 5, er, er * 0.45, 0, 0, TAU); ctx.fill(); ctx.restore(); } if (air && !SWARM[m.kind]) { const er = def.r * C; ctx.fillStyle = 'rgba(0,0,0,.28)'; ctx.save(); ctx.translate(m.x * C, m.y * C); if (rot) ctx.rotate(-rot); ctx.beginPath(); ctx.ellipse(0, 5, er, er * 0.45, 0, 0, TAU); ctx.fill(); ctx.restore(); }
if (vsui) { this._vsUnit(ctx, dm, k, def, vsui, t, rot, stun); continue; }
drawMonster(ctx, dm, k.ang, t, k.flash, rot, stun); drawMonster(ctx, dm, k.ang, t, k.flash, rot, stun);
} }
if (air && trk.size > view.monsters.length + 60) { // drop stale trackers if (air && trk.size > view.monsters.length + 60) { // drop stale trackers
@ -778,6 +807,114 @@
return s; return s;
} }
// ---------------------------------------------------------------- versus cues
// a tower an EMP has switched off: dimmed, hazard stripes, flickering sparks and an arc that runs out with the time left
_drawEmp(ctx, tw, cx, cy, t) {
const total = (TD.VS && TD.VS.ABILITIES.emp.dur) || 6, h = C * 0.43;
ctx.save(); ctx.translate(cx, cy);
ctx.fillStyle = 'rgba(4,7,14,.66)'; rr(ctx, -h, -h, h * 2, h * 2, C * 0.12); ctx.fill();
ctx.save(); ctx.clip();
ctx.strokeStyle = 'rgba(255,210,77,.5)'; ctx.lineWidth = 3;
for (let i = -3; i <= 3; i++) { ctx.beginPath(); ctx.moveTo(i * 9 - 18, 18); ctx.lineTo(i * 9 + 18, -18); ctx.stroke(); }
ctx.restore();
ctx.strokeStyle = '#ffe27a'; ctx.lineWidth = 3; ctx.lineCap = 'round';
ctx.beginPath(); ctx.arc(0, 0, C * 0.5, -Math.PI / 2, -Math.PI / 2 + TAU * clamp(tw.empT / total, 0, 1)); ctx.stroke();
if (Math.sin(t * 26 + tw.id * 3) > 0.2) { // a spark
ctx.strokeStyle = '#fff6c9'; ctx.lineWidth = 2; ctx.beginPath();
const a = (Math.floor(t * 9 + tw.id) % 4) * 1.57;
ctx.moveTo(Math.cos(a) * 6, Math.sin(a) * 6); ctx.lineTo(Math.cos(a + 0.4) * 12, Math.sin(a + 0.4) * 12); ctx.lineTo(Math.cos(a - 0.1) * 15, Math.sin(a - 0.1) * 15); ctx.stroke();
}
ctx.restore();
}
// the gateway the attacker picked (amber ring), numbers on the gateways when there is a choice, and a pulse where a unit has just entered
_vsGate(ctx, gi, vsui, t, dt, n) {
const pl = this.gatePulse.get(gi);
if (pl > 0) {
const k = 1 - pl / 0.7;
ctx.strokeStyle = rgba('#ffffff', 0.85 * (1 - k)); ctx.lineWidth = 3; ctx.beginPath(); ctx.arc(0, 0, 13 + k * 26, 0, TAU); ctx.stroke();
this.gatePulse.set(gi, pl - dt); if (pl - dt <= 0) this.gatePulse.delete(gi);
}
if (vsui.gates > 1 && vsui.role === 'attacker') {
const on = vsui.gate === gi;
if (on) { ctx.strokeStyle = '#ffd24d'; ctx.lineWidth = 3.5; ctx.beginPath(); ctx.arc(0, 0, 18 + Math.sin(t * 6) * 1.5, 0, TAU); ctx.stroke(); }
ctx.fillStyle = on ? '#ffd24d' : 'rgba(8,13,26,.9)'; ctx.beginPath(); ctx.arc(11, -11, 7.5, 0, TAU); ctx.fill();
ctx.lineWidth = 1.5; ctx.strokeStyle = on ? '#ffd24d' : '#ff5c7a'; ctx.stroke();
ctx.fillStyle = on ? '#241a02' : '#ffd1da'; ctx.font = '700 10px system-ui, sans-serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText(String(gi + 1), 11, -10.5); ctx.textAlign = 'start';
}
}
// what the attacker knows about its own units, remembered when a unit first shows up (the wire carries neither stealth nor tech): stealth seconds and shield capacity
_vsBorn(k, m, vsui, t) {
k.born = t; k.stl = 0; k.shl = 0;
// a spawn pulse at the gateway it enters from (every client sees it: the defender too)
const b = this.board;
if (b) for (let i = 0; i < b.spawns.length; i++) { const sp = b.spawns[i], dx = m.x - (sp.x + 0.5), dy = m.y - (sp.y + 0.5); if (dx * dx + dy * dy < 1.6) { this.gatePulse.set(i, 0.7); break; } }
if (vsui.role === 'attacker' && vsui.tech && TD.VS) {
const X = TD.VS.TECH;
if (vsui.tech.stealth) k.stl = X.stealth.secs[vsui.tech.stealth - 1] || 0;
if (vsui.tech.shield) k.shl = X.shield.per * vsui.tech.shield;
}
}
_vsUnit(ctx, m, k, def, vsui, t, rot, stun) {
const r = def.r * C, now = t * 1000;
const dec = !!m.decoy || (vsui.decoys && vsui.decoys.size > 0 && (vsui.decoys.get(m.id) || 0) > now);
const hid = vsui.role === 'attacker' && (m.stealthT !== undefined ? m.stealthT > 0 : k.stl > 0 && t - k.born < k.stl);
const lift = m.kind === 'ghost' ? -7 : 0;
ctx.save();
if (dec) ctx.globalAlpha = 0.5; else if (hid) ctx.globalAlpha = 0.38;
drawMonster(ctx, m, k.ang, t, k.flash, rot, stun);
ctx.restore();
if (dec || hid || k.shl > 0 || (m.maxShield > 0 && vsui.role === 'attacker' && !def.shield)) {
ctx.save(); ctx.translate(m.x * C, m.y * C + lift); if (rot) ctx.rotate(-rot);
if (dec) { // bait: a spinning dashed ring
ctx.strokeStyle = 'rgba(126,232,255,.95)'; ctx.lineWidth = 2; ctx.setLineDash([5, 4]); ctx.lineDashOffset = -t * 20;
ctx.beginPath(); ctx.arc(0, 0, r + 7, 0, TAU); ctx.stroke(); ctx.setLineDash([]);
}
if (hid) { // cloaked: a faint shimmer ring
ctx.strokeStyle = 'rgba(190,200,255,' + (0.35 + 0.25 * Math.sin(t * 12 + m.id)) + ')'; ctx.lineWidth = 1.5; ctx.setLineDash([3, 4]); ctx.lineDashOffset = t * 10;
ctx.beginPath(); ctx.arc(0, 0, r + 4, 0, TAU); ctx.stroke(); ctx.setLineDash([]);
}
const ms = m.maxShield !== undefined && !def.shield ? m.maxShield : k.shl; // tech shield (kinds that carry their own shield draw it themselves)
if (ms > 0 && vsui.role === 'attacker' && !def.shield) {
const sh = m.shield !== undefined ? m.shield : clamp(m.hp - (m.maxhp - ms), 0, ms);
if (sh > 0.5) { ctx.strokeStyle = 'rgba(150,200,255,' + (0.3 + 0.55 * clamp(sh / ms, 0, 1)) + ')'; ctx.lineWidth = 1.2 + 1.8 * clamp(sh / ms, 0, 1); ctx.beginPath(); ctx.arc(0, 0, r + 3, 0, TAU); ctx.stroke(); }
}
ctx.restore();
}
}
// screen cues in board space: Quarantine (icy), DDoS (violet scan lines), Surge (hot edge), Scan zones, and the ring of an armed Scan
_drawVsFx(ctx, dt, sc, cols, rows, t, ui) {
const f = this.fxT, W = cols * C, H = rows * C;
if (f.freeze > 0) {
f.freeze -= dt;
ctx.fillStyle = 'rgba(160,220,255,' + (0.1 + 0.05 * Math.sin(t * 9)) + ')'; ctx.fillRect(0, 0, W, H);
ctx.strokeStyle = 'rgba(225,246,255,.85)'; ctx.lineWidth = 6 / sc; ctx.strokeRect(0, 0, W, H);
}
if (f.ddos > 0) {
f.ddos -= dt;
ctx.fillStyle = 'rgba(150,80,255,.07)'; ctx.fillRect(0, 0, W, H);
ctx.strokeStyle = 'rgba(190,130,255,.35)'; ctx.lineWidth = 1.5 / sc; ctx.beginPath();
for (let y = (t * 60) % 24; y < H; y += 24) { ctx.moveTo(0, y); ctx.lineTo(W, y); }
ctx.stroke();
}
if (f.surge > 0) {
f.surge -= dt;
ctx.strokeStyle = 'rgba(255,150,60,' + (0.45 + 0.3 * Math.sin(t * 14)) + ')'; ctx.lineWidth = 8 / sc; ctx.strokeRect(0, 0, W, H);
}
for (let i = this.scans.length - 1; i >= 0; i--) {
const z = this.scans[i]; z.t -= dt;
if (z.t <= 0) { this.scans.splice(i, 1); continue; }
const a = clamp(z.t / z.max, 0, 1), cx = z.x * C, cy = z.y * C;
ctx.fillStyle = 'rgba(126,232,255,' + 0.07 * a + ')'; ctx.beginPath(); ctx.arc(cx, cy, z.r * C, 0, TAU); ctx.fill();
ctx.strokeStyle = 'rgba(126,232,255,' + (0.35 + 0.4 * a) + ')'; ctx.lineWidth = 2; ctx.setLineDash([8, 6]); ctx.lineDashOffset = -t * 18;
ctx.beginPath(); ctx.arc(cx, cy, z.r * C, 0, TAU); ctx.stroke(); ctx.setLineDash([]);
}
const v = ui && ui.vs;
if (v && v.scanArm && ui.hover && this.board && this.board.inBounds(ui.hover.x, ui.hover.y)) {
const rd = (TD.VS && TD.VS.TOOLS.scan.radius) || 4;
this._rangeRing(ctx, (ui.hover.x + 0.5) * C, (ui.hover.y + 0.5) * C, rd * C, '#7ee8ff');
}
}
_drawFx(ctx, dt, sc, rot) { _drawFx(ctx, dt, sc, rot) {
// lines (tracers, arcs) // lines (tracers, arcs)
ctx.lineCap = 'round'; ctx.lineJoin = 'round'; ctx.lineCap = 'round'; ctx.lineJoin = 'round';

View file

@ -26,6 +26,69 @@
const CLEAR_BONUS_PER_WAVE = 1; const CLEAR_BONUS_PER_WAVE = 1;
function clearBonus(n) { return CLEAR_BONUS + CLEAR_BONUS_PER_WAVE * n; } function clearBonus(n) { return CLEAR_BONUS + CLEAR_BONUS_PER_WAVE * n; }
// ---------------------------------------------------------------- versus mode: every number in ONE table
// new Sim({ mode: 'versus' }) is attack-vs-defend (docs/VERSUS.md). One player defends (builds, as in co-op, with the credits in `sim.gold`),
// the other attacks (buys units with `vs.credits`). The table is exported as TD.VS and read at the moment a rule runs, never cached,
// so the balance pass edits numbers HERE and nothing else (tests and the bots derive their expectations from it).
// defender DEF_GOLD start credits (an explicit `gold` option wins), DEF_TRICKLE credits/s on top of kill rewards, a kill pays
// round(buyCost * KILL_REWARD) [no wave scaling: versus units are base stats x the attacker's tech]
// attacker ATT_CREDITS start credits; income ATT_INCOME/s + ATT_INCOME_GROWTH/s per second elapsed; every living unit pays
// buyCost * LIFE_RATE per second alive up to LIFE_CAP of its price in total; a leak pays the price back
// caps MAX_ALIVE units on the map (a release still queued counts), MAX_STAGED waiting in the convoy
// release a convoy / a multi-unit buy is let out as a stream: RELEASE_GAP s apart, but the whole stream takes at most LAUNCH_SPAN s
// tech level L (1..max) costs TECH_COST * 2^(L-1): armor +per armour, speed +per x base, health +per x base hp,
// regen +per x max hp per second, shield +per hit points, stealth: towers cannot acquire the unit for secs[L-1] s after it
// enters the map, crypt: slows (Rate Limiter, Uplink) work res[L-1] weaker. Tech applies to units that enter the map afterwards.
// abilities attacker, cost credits, cooldown cd s, effect lasts dur s; tools: defender, cost gold, same shape
const VS = {
LIMITS: [480, 720, 960], DEFAULT_LIMIT: 720, ROUNDS: 2,
ATT_CREDITS: 150, ATT_INCOME: 4, ATT_INCOME_GROWTH: 0.02, LIFE_RATE: 0.004, LIFE_CAP: 0.5,
MAX_ALIVE: 250, MAX_STAGED: 200, RELEASE_GAP: 0.5, LAUNCH_SPAN: 3,
DEF_GOLD: 250, DEF_TRICKLE: 2, KILL_REWARD: 0.4,
TECH_COST: 100,
TECH_ORDER: ['armor', 'speed', 'health', 'regen', 'shield', 'stealth', 'crypt'],
TECH: {
armor: { max: 5, per: 1 },
speed: { max: 5, per: 0.08 },
health: { max: 5, per: 0.15 },
regen: { max: 3, per: 0.01 },
shield: { max: 3, per: 40 },
stealth: { max: 3, secs: [1, 1.5, 2] },
crypt: { max: 3, res: [0.2, 0.4, 0.6] },
},
ABILITY_ORDER: ['emp', 'decoy', 'surge', 'ddos'],
ABILITIES: {
emp: { cost: 80, cd: 20, dur: 6 }, // one tower (tid) does nothing for dur s
decoy: { cost: 60, cd: 25, dur: 5 }, // a harmless, unkillable unit that every tower that can reach it prefers, for dur s
surge: { cost: 120, cd: 40, dur: 6, speed: 0.4 }, // every unit +speed x base speed
ddos: { cost: 200, cd: 70, dur: 4, slow: 0.4 }, // every tower's cooldown runs `slow` slower
},
TOOL_ORDER: ['scan', 'patch', 'repair', 'quarantine'],
TOOLS: {
scan: { cost: 40, cd: 15, radius: 4, reveal: 3 }, // at (x, y): clears EMP on towers within radius, units within radius can be targeted for reveal s
patch: { cost: 30, cd: 8 }, // tower tid is re-enabled at once
repair: { cost: 120, cd: 30, amount: 3 }, // +amount integrity, never above the maximum
quarantine: { cost: 150, cd: 60, dur: 2 }, // every unit on the board is frozen for dur s
},
// one-tap convoys for the shop UI and the attacker bot: [[kind, n], ...]
PRESETS: {
rush: [['ping', 20]],
swarm: [['spam', 60]],
siege: [['trojan', 4], ['daemon', 1]],
air: [['ghost', 10]],
boss: [['rootkit', 1]],
},
};
const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
// Float credits and cooldowns drift by ~1e-12 over thousands of ticks: "can pay" and "on cooldown" tolerate EPS, and the numbers the sim
// REPORTS are rounded the careful way (credits down, cooldowns up), so a side never sees "9.00 credits" or "0 s left" and then gets a refusal.
const EPS = 1e-6;
const cooling = (x) => x > EPS;
const down2 = (x) => Math.floor((x + EPS) * 100) / 100;
const up2 = (x) => (x > EPS ? Math.ceil(x * 100) / 100 : 0);
const DEFENDER_CMDS = { place: 1, sell: 1, upgrade: 1, target: 1, tool: 1 };
const ATTACKER_CMDS = { spawn: 1, stage: 1, launch: 1, tech: 1, ability: 1 };
// ---------------------------------------------------------------- difficulty // ---------------------------------------------------------------- difficulty
// One row per difficulty; every number is a multiplier on the base tables below (normal is all 1, so it plays exactly the tuned base game): // One row per difficulty; every number is a multiplier on the base tables below (normal is all 1, so it plays exactly the tuned base game):
// gold the starting credits (START_GOLD) lives the starting integrity (START_LIVES), at least 1 // gold the starting credits (START_GOLD) lives the starting integrity (START_LIVES), at least 1
@ -614,6 +677,37 @@
this.bullets = []; this.bullets = [];
this.spawnQ = []; this.spawnQ = [];
this.events = []; this.events = [];
this.vs = null; // versus state (null in solo / co-op, which then run exactly as before)
if (opts.mode === 'versus') this.initVersus(opts);
}
// Versus: no waves, no difficulty (units are base stats x the attacker's tech), the defender's credits are `gold`, the integrity is
// `lives`; the round ends when it hits 0 (attacker wins) or `limit` seconds pass (defender wins). state: 'playing' -> 'over'.
initVersus(opts) {
this.difficulty = DEFAULT_DIFFICULTY;
this.diff = DIFFICULTIES[DEFAULT_DIFFICULTY];
this.gold = opts.gold === undefined ? VS.DEF_GOLD : opts.gold;
this.lives = opts.lives === undefined ? START_LIVES : opts.lives;
this.maxLives = this.lives;
this.winWave = Infinity;
const tech = {}, acd = {}, dcd = {};
for (const k of VS.TECH_ORDER) tech[k] = 0;
for (const k of VS.ABILITY_ORDER) acd[k] = 0;
for (const k of VS.TOOL_ORDER) dcd[k] = 0;
this.vs = {
limit: Number.isFinite(opts.limit) && opts.limit > 0 ? opts.limit : VS.DEFAULT_LIMIT,
credits: opts.credits === undefined ? VS.ATT_CREDITS : opts.credits, // the attacker's (role-private)
tech, acd, dcd,
staged: [], // the convoy: [[kind, n], ...] in the order it was bought (paid, not on the map yet)
rel: [], // units being let out: { t, kind, gate } (paid, count towards the alive cap)
surgeT: 0, ddosT: 0, freezeT: 0,
scans: [], // Scan reveal zones: { x, y, t }
trickle: 0, // the defender's fractional income (gold stays a whole number)
lost: 0, // integrity taken off in total (repairs do not give it back)
result: null, // { winner, t, integrityLost } once the round is over
stats: { spawned: 0, unitsSpent: 0, techSpent: 0, abilitySpent: 0, toolSpent: 0, earned: 0, leaked: 0, kills: 0 },
};
} }
emit(e) { emit(e) {
@ -626,6 +720,7 @@
// ---- commands ------------------------------------------------------------------------- // ---- commands -------------------------------------------------------------------------
cmd(c) { cmd(c) {
if (!c || typeof c !== 'object') return { ok: false, reason: 'bad_cmd' }; if (!c || typeof c !== 'object') return { ok: false, reason: 'bad_cmd' };
if (this.vs) return this.vsCmd(c);
switch (c.c) { switch (c.c) {
case 'place': return this.place(c.type, c.x, c.y, c.by | 0); case 'place': return this.place(c.type, c.x, c.y, c.by | 0);
case 'sell': return this.sell(c.id); case 'sell': return this.sell(c.id);
@ -638,6 +733,189 @@
} }
} }
// ---- versus commands --------------------------------------------------------------------
// The command carries the issuer's `role` ('defender' | 'attacker'; the server fills it from the seat). Order of refusals, all of them
// BEFORE anything is charged or started: unknown command -> bad_cmd (waves are 'versus'), wrong or missing role -> 'role', round over
// -> 'over', then the command's own checks (bad_cmd / bad_kind / bad_target for malformed input, 'cap', 'max', 'cooldown', 'credits').
// A cooldown starts only when the command succeeded.
vsCmd(c) {
const need = hasOwn(DEFENDER_CMDS, c.c) ? 'defender' : hasOwn(ATTACKER_CMDS, c.c) ? 'attacker' : null;
if (!need) return { ok: false, reason: c.c === 'wave' || c.c === 'auto' || c.c === 'continue' ? 'versus' : 'bad_cmd' };
if (c.role !== need) return { ok: false, reason: 'role' };
if (this.state !== 'playing') return { ok: false, reason: 'over' };
let r;
switch (c.c) {
case 'place': r = this.place(c.type, c.x, c.y, c.by | 0); break;
case 'sell': r = this.sell(c.id); break;
case 'upgrade': r = this.upgrade(c.id, c.lv); break;
case 'target': r = this.setTargetMode(c.id, c.mode); break;
case 'tool': r = this.useTool(c); break;
case 'spawn': r = this.vsBuy(c, false); break;
case 'stage': r = this.vsBuy(c, true); break;
case 'launch': r = this.vsLaunch(c); break;
case 'tech': r = this.vsTech(c.id); break;
default: r = this.vsAbility(c);
}
if (r.ok && need === 'attacker') this.vsRelease(); // the first unit of a stream is on the map when the command returns
return r;
}
vsGate(g) {
if (g === undefined || g === null) return -1; // -1: round robin
return Number.isInteger(g) && g >= 0 && g < this.board.spawns.length ? g : -2;
}
vsAlive() { let n = 0; for (const m of this.monsters) if (!m.dead && !m.decoy) n++; return n + this.vs.rel.length; }
vsStaged() { let n = 0; for (const e of this.vs.staged) n += e[1]; return n; }
vsCount(c) { // units in a spawn / stage command: a positive whole number (default 1)
const n = c.n === undefined || c.n === null ? 1 : c.n;
return Number.isInteger(n) && n >= 1 && n <= VS.MAX_ALIVE ? n : 0;
}
// Queue `n` units of `kind` for release as a stream starting now (the stream's gaps: RELEASE_GAP, at most LAUNCH_SPAN s in all).
vsQueue(kind, n, gate, t0, gap) {
for (let i = 0; i < n; i++) {
const g = gate >= 0 ? gate : this.spawnRR++ % this.board.spawns.length;
this.vs.rel.push({ t: t0 + i * gap, kind, gate: g });
}
}
vsGap(n) { return n > 1 ? Math.min(VS.RELEASE_GAP, VS.LAUNCH_SPAN / n) : 0; }
// spawn (buy and release now) / stage (pay now, hold in the convoy)
vsBuy(c, stage) {
if (typeof c.kind !== 'string' || !hasOwn(ENEMIES, c.kind)) return { ok: false, reason: 'bad_kind' };
const n = this.vsCount(c);
if (!n) return { ok: false, reason: 'bad_cmd' };
const gate = this.vsGate(c.gate);
if (gate === -2) return { ok: false, reason: 'bad_target' };
const v = this.vs, cost = ENEMIES[c.kind].buyCost * n;
if (stage ? this.vsStaged() + n > VS.MAX_STAGED : this.vsAlive() + n > VS.MAX_ALIVE) return { ok: false, reason: 'cap' };
if (v.credits + EPS < cost) return { ok: false, reason: 'credits' };
v.credits -= cost; v.stats.unitsSpent += cost;
if (stage) {
const e = v.staged.find((q) => q[0] === c.kind);
if (e) e[1] += n; else v.staged.push([c.kind, n]);
return { ok: true, n, staged: this.vsStaged() };
}
this.vsQueue(c.kind, n, gate, this.time, this.vsGap(n));
return { ok: true, n };
}
// launch: let (as much as fits under the alive cap of) the convoy out as one stream
vsLaunch(c) {
const gate = this.vsGate(c.gate);
if (gate === -2) return { ok: false, reason: 'bad_target' };
const v = this.vs, total = this.vsStaged();
if (!total) return { ok: false, reason: 'empty' };
const room = VS.MAX_ALIVE - this.vsAlive();
if (room <= 0) return { ok: false, reason: 'cap' };
const k = Math.min(total, room), gap = this.vsGap(k);
let left = k, i = 0;
for (const e of v.staged) {
const take = Math.min(e[1], left);
this.vsQueue(e[0], take, gate, this.time + i * gap, gap);
e[1] -= take; left -= take; i += take;
if (!left) break;
}
v.staged = v.staged.filter((e) => e[1] > 0);
return { ok: true, n: k, staged: total - k };
}
// tech: the next level of one upgrade, TECH_COST * 2^(level now); applies to units that enter the map afterwards
vsTech(id) {
if (typeof id !== 'string' || !hasOwn(VS.TECH, id)) return { ok: false, reason: 'bad_target' };
const v = this.vs, lv = v.tech[id];
if (lv >= VS.TECH[id].max) return { ok: false, reason: 'max' };
const cost = VS.TECH_COST * Math.pow(2, lv);
if (v.credits + EPS < cost) return { ok: false, reason: 'credits' };
v.credits -= cost; v.stats.techSpent += cost;
v.tech[id] = lv + 1;
return { ok: true, level: lv + 1 };
}
techCost(id) { const lv = this.vs.tech[id]; return lv >= VS.TECH[id].max ? null : VS.TECH_COST * Math.pow(2, lv); }
// abilities: emp (tid) / decoy (gate? tid?) / surge / ddos
vsAbility(c) {
if (typeof c.id !== 'string' || !hasOwn(VS.ABILITIES, c.id)) return { ok: false, reason: 'bad_target' };
const v = this.vs, A = VS.ABILITIES[c.id];
let tower = null, gate = -1;
if (c.id === 'emp') {
tower = typeof c.tid === 'number' ? this.towerById(c.tid) : null;
if (!tower || TOWERS[tower.type].role === 'wall') return { ok: false, reason: 'bad_target' }; // a Firewall does nothing to disable
} else if (c.id === 'decoy') {
gate = this.vsGate(c.gate);
if (gate === -2) return { ok: false, reason: 'bad_target' };
if (c.tid !== undefined && c.tid !== null) { tower = typeof c.tid === 'number' ? this.towerById(c.tid) : null; if (!tower) return { ok: false, reason: 'bad_target' }; }
}
if (cooling(v.acd[c.id])) return { ok: false, reason: 'cooldown' };
if (v.credits + EPS < A.cost) return { ok: false, reason: 'credits' };
v.credits -= A.cost; v.stats.abilitySpent += A.cost; v.acd[c.id] = A.cd;
switch (c.id) {
case 'emp': tower.empT = A.dur; tower.tgt = 0; this.emit({ e: 'emp', id: tower.id, d: A.dur }); break;
case 'decoy': this.vsDecoy(gate, tower, A.dur); break;
case 'surge': v.surgeT = A.dur; this.emit({ e: 'surge', d: A.dur }); break;
default: v.ddosT = A.dur; this.emit({ e: 'ddos', d: A.dur });
}
return { ok: true };
}
// The decoy: an existing kind (a Ping) with the decoy flag, so no new wire kind. Invulnerable, harmless (leaks for nothing, pays nothing,
// earns nothing, outside the caps), gone after `dur` s. With `tower` it appears on the route cell closest to that tower, else at the gate.
vsDecoy(gate, tower, dur) {
const b = this.board, g = gate >= 0 ? gate : this.spawnRR++ % b.spawns.length;
let at = null;
if (tower) {
let bd = Infinity;
for (const cell of b.routes[g]) {
const d = (cell[0] - tower.x) * (cell[0] - tower.x) + (cell[1] - tower.y) * (cell[1] - tower.y);
if (d < bd) { bd = d; at = cell; }
}
}
const m = this.vsUnit('ping', g, at);
m.decoy = true; m.ttl = dur; m.leak = 0; m.reward = 0; m.buyCost = 0; m.stealthT = 0; m.regen = 0; m.shield = m.maxShield = 0;
this.monsters.push(m);
this.emit({ e: 'decoy', id: m.id, d: dur });
}
// defender tools: { c:'tool', id:'scan'|'patch'|'repair'|'quarantine', x?, y?, tid? }, paid with `gold`
useTool(c) {
if (typeof c.id !== 'string' || !hasOwn(VS.TOOLS, c.id)) return { ok: false, reason: 'bad_target' };
const v = this.vs, T = VS.TOOLS[c.id], b = this.board;
let tower = null;
if (c.id === 'scan') {
if (typeof c.x !== 'number' || typeof c.y !== 'number' || !isFinite(c.x) || !isFinite(c.y) || c.x < 0 || c.y < 0 || c.x > b.cols || c.y > b.rows) return { ok: false, reason: 'bad_target' };
} else if (c.id === 'patch') {
tower = typeof c.tid === 'number' ? this.towerById(c.tid) : null;
if (!tower || !(tower.empT > 0)) return { ok: false, reason: 'bad_target' }; // nothing to re-enable
} else if (c.id === 'repair') {
if (this.lives >= this.maxLives) return { ok: false, reason: 'max' };
}
if (cooling(v.dcd[c.id])) return { ok: false, reason: 'cooldown' };
if (this.gold < T.cost) return { ok: false, reason: 'credits' };
this.gold -= T.cost; v.stats.toolSpent += T.cost; v.dcd[c.id] = T.cd;
switch (c.id) {
case 'scan': {
const r2 = T.radius * T.radius;
for (const t of this.towers) {
const dx = t.x + 0.5 - c.x, dy = t.y + 0.5 - c.y;
if (t.empT > 0 && dx * dx + dy * dy <= r2) t.empT = 0;
}
v.scans.push({ x: c.x, y: c.y, t: T.reveal });
this.emit({ e: 'scan', x: round2(c.x), y: round2(c.y) });
break;
}
case 'patch': tower.empT = 0; break;
case 'repair': this.lives = Math.min(this.maxLives, this.lives + T.amount); this.emit({ e: 'repair' }); break;
default: v.freezeT = T.dur; this.emit({ e: 'quarantine', d: T.dur });
}
return { ok: true };
}
// A Scan zone reveals stealthed units (they can be targeted) for its `reveal` seconds.
vsRevealed(m) {
for (const z of this.vs.scans) { const dx = m.x - z.x, dy = m.y - z.y; if (dx * dx + dy * dy <= VS.TOOLS.scan.radius * VS.TOOLS.scan.radius) return true; }
return false;
}
// Cells monsters occupy or are about to enter; used to refuse placements that would trap or clip them. // Cells monsters occupy or are about to enter; used to refuse placements that would trap or clip them.
monsterCells() { monsterCells() {
const b = this.board, cols = b.cols; const b = this.board, cols = b.cols;
@ -692,7 +970,7 @@
} }
sell(id) { sell(id) {
if (this.state === 'lost') return { ok: false, reason: 'over' }; if (this.state === 'lost' || this.state === 'over') return { ok: false, reason: 'over' };
const t = this.towerById(id); const t = this.towerById(id);
if (!t) return { ok: false, reason: 'no_tower' }; if (!t) return { ok: false, reason: 'no_tower' };
const def = TOWERS[t.type]; const def = TOWERS[t.type];
@ -736,12 +1014,14 @@
} }
setAuto(v) { setAuto(v) {
if (this.vs) return { ok: false, reason: 'versus' };
this.autoWaves = v; this.autoWaves = v;
if (v && this.nextWaveIn < 0) this.nextWaveIn = WAVE_INTERVAL; if (v && this.nextWaveIn < 0) this.nextWaveIn = WAVE_INTERVAL;
return { ok: true }; return { ok: true };
} }
continueEndless() { continueEndless() {
if (this.vs) return { ok: false, reason: 'versus' };
if (this.state !== 'won') return { ok: false, reason: 'not_won' }; if (this.state !== 'won') return { ok: false, reason: 'not_won' };
this.state = 'playing'; this.state = 'playing';
this.winWave = Infinity; this.winWave = Infinity;
@ -751,6 +1031,7 @@
// `expect` is the wave number the sender expects this command to start (the wave it saw + 1; absent: no check; the auto-wave timer // `expect` is the wave number the sender expects this command to start (the wave it saw + 1; absent: no check; the auto-wave timer
// never passes one). A second "Next wave" pressed at the same moment by the other player is refused as 'stale', not started twice. // never passes one). A second "Next wave" pressed at the same moment by the other player is refused as 'stale', not started twice.
startWave(expect) { startWave(expect) {
if (this.vs) return { ok: false, reason: 'versus' }; // versus has no waves: the attacker brings the units
if (this.state !== 'playing') return { ok: false, reason: 'over' }; if (this.state !== 'playing') return { ok: false, reason: 'over' };
if (expect !== undefined && expect !== null && expect !== this.wave + 1) return { ok: false, reason: 'stale' }; if (expect !== undefined && expect !== null && expect !== this.wave + 1) return { ok: false, reason: 'stale' };
const n = ++this.wave; const n = ++this.wave;
@ -787,10 +1068,80 @@
this.monsters.push(m); this.monsters.push(m);
} }
// ---- versus units ---------------------------------------------------------------------
// A unit at gate `gate` (or on the route cell `at` = [x, y]): the kind's BASE stats x the attacker's tech now. No hpScale, no difficulty.
vsUnit(kind, gate, at) {
const def = ENEMIES[kind], b = this.board, T = this.vs.tech, X = VS.TECH;
const s = at ? { x: at[0], y: at[1] } : b.spawns[gate];
const hp = Math.max(1, Math.round(def.hp * (1 + X.health.per * T.health)));
const shield = (def.shield || 0) + (T.shield ? X.shield.per * T.shield : 0);
const m = {
id: this.nid++, kind, air: !!def.air,
x: s.x + 0.5, y: s.y + 0.5, cx: s.x, cy: s.y, tx: -1, ty: -1,
hp, maxhp: hp, armor: def.armor + X.armor.per * T.armor, speed: def.speed * (1 + X.speed.per * T.speed),
reward: Math.max(1, Math.round(def.buyCost * VS.KILL_REWARD)),
leak: def.leak, slow: 0, slowT: 0, slowAmt: 0, stunT: 0,
shield, maxShield: shield, shieldT: 0,
rem: 0, dead: false, wave: 0,
buyCost: def.buyCost, earned: 0, // lifetime bonus paid so far
regen: X.regen.per * T.regen, // fraction of max hp per second
crypt: T.crypt ? X.crypt.res[T.crypt - 1] : 0, // slows work this much weaker
stealthT: T.stealth ? X.stealth.secs[T.stealth - 1] : 0, // towers cannot acquire it until this runs out (or a Scan reveals it)
};
m.rem = m.air ? Math.hypot(b.core.x - s.x, b.core.y - s.y) : b.field[s.y * b.cols + s.x];
return m;
}
// Units whose release time has come enter the map (a command calls this too, so the first unit of a stream is there at once).
vsRelease() {
const rel = this.vs.rel;
let w = 0;
for (let i = 0; i < rel.length; i++) {
const q = rel[i];
if (q.t <= this.time + 1e-9) { this.monsters.push(this.vsUnit(q.kind, q.gate)); this.vs.stats.spawned++; } else rel[w++] = q;
}
rel.length = w;
}
// Start of every versus tick: income, lifetime bonus, the defender's trickle, cooldowns and effect timers, unit timers, releases.
vsBegin(dt) {
const v = this.vs;
let inc = (VS.ATT_INCOME + VS.ATT_INCOME_GROWTH * (this.time - dt / 2)) * dt; // the rate in the middle of this tick: exact for a rate that rises linearly
for (const m of this.monsters) {
if (m.dead) continue;
if (m.decoy) { m.ttl -= dt; if (m.ttl <= 0) m.dead = true; continue; }
const cap = m.buyCost * VS.LIFE_CAP;
if (m.earned < cap) { const b = Math.min(m.buyCost * VS.LIFE_RATE * dt, cap - m.earned); m.earned += b; inc += b; }
if (m.stealthT > 0) m.stealthT -= dt;
if (m.regen > 0 && m.hp < m.maxhp) m.hp = Math.min(m.maxhp, m.hp + m.maxhp * m.regen * dt);
}
v.credits += inc; v.stats.earned += inc;
v.trickle += VS.DEF_TRICKLE * dt;
const whole = Math.floor(v.trickle);
if (whole > 0) { this.gold += whole; v.trickle -= whole; }
for (const k in v.acd) if (v.acd[k] > 0) v.acd[k] = Math.max(0, v.acd[k] - dt);
for (const k in v.dcd) if (v.dcd[k] > 0) v.dcd[k] = Math.max(0, v.dcd[k] - dt);
if (v.surgeT > 0) v.surgeT = Math.max(0, v.surgeT - dt);
if (v.ddosT > 0) v.ddosT = Math.max(0, v.ddosT - dt);
if (v.freezeT > 0) v.freezeT = Math.max(0, v.freezeT - dt);
if (v.scans.length) { for (const z of v.scans) z.t -= dt; v.scans = v.scans.filter((z) => z.t > 0); }
if (v.rel.length) this.vsRelease();
}
// The round is over: `winner` is 'attacker' (integrity gone) or 'defender' (time ran out).
vsEnd(winner) {
const v = this.vs;
if (this.lives < 0) this.lives = 0;
this.state = 'over';
v.result = { winner, t: round2(this.time), integrityLost: v.lost };
this.emit({ e: 'round', winner, t: v.result.t });
}
// ---- main step ------------------------------------------------------------------------ // ---- main step ------------------------------------------------------------------------
tick(dt) { tick(dt) {
if (this.state !== 'playing') return; if (this.state !== 'playing') return;
this.time += dt; this.time += dt;
if (this.vs) this.vsBegin(dt);
if (this.autoWaves) { if (this.autoWaves) {
this.nextWaveIn -= dt; this.nextWaveIn -= dt;
if (this.nextWaveIn <= 0) this.startWave(); if (this.nextWaveIn <= 0) this.startWave();
@ -816,6 +1167,11 @@
} }
this.monsters.length = w; this.monsters.length = w;
if (this.vs) { // versus: integrity first (the attacker wins even on the last tick), then the clock
if (this.lives <= 0) this.vsEnd('attacker');
else if (this.time >= this.vs.limit) this.vsEnd('defender');
return;
}
if (this.lives <= 0) { if (this.lives <= 0) {
this.lives = 0; this.lives = 0;
this.state = 'lost'; this.state = 'lost';
@ -837,9 +1193,12 @@
// ---- monsters ------------------------------------------------------------------------- // ---- monsters -------------------------------------------------------------------------
moveMonster(m, dt) { moveMonster(m, dt) {
if (m.stunT > 0) return; // stunned (Sandbox): frozen in place if (m.stunT > 0) return; // stunned (Sandbox): frozen in place
const vs = this.vs;
if (vs && vs.freezeT > 0) return; // Quarantine: every unit is frozen
const b = this.board; const b = this.board;
const slowMul = 1 - Math.min(0.6, m.slow); const slowMul = 1 - Math.min(0.6, m.slow);
let remaining = m.speed * slowMul * dt; let remaining = m.speed * slowMul * dt;
if (vs && vs.surgeT > 0) remaining *= 1 + VS.ABILITIES.surge.speed;
if (m.air) { if (m.air) {
const gx = b.core.x + 0.5, gy = b.core.y + 0.5; const gx = b.core.x + 0.5, gy = b.core.y + 0.5;
const dx = gx - m.x, dy = gy - m.y, d = Math.hypot(dx, dy); const dx = gx - m.x, dy = gy - m.y, d = Math.hypot(dx, dy);
@ -873,13 +1232,19 @@
leak(m) { leak(m) {
m.dead = true; m.leaked = true; m.dead = true; m.leaked = true;
if (m.decoy) return; // a decoy that reaches the server is harmless and silent
const v = this.vs;
if (v) { // versus: the integrity taken off is counted, the attacker gets the unit's price back
v.lost += Math.min(m.leak, Math.max(0, this.lives));
v.credits += m.buyCost; v.stats.earned += m.buyCost; v.stats.leaked++;
}
this.lives -= m.leak; this.lives -= m.leak;
this.leaks++; this.leaks++;
this.emit({ e: 'leak', x: m.x, y: m.y, n: m.leak }); this.emit({ e: 'leak', x: m.x, y: m.y, n: m.leak });
} }
damage(m, raw, src, ignoreArmor) { damage(m, raw, src, ignoreArmor) {
if (m.dead) return; if (m.dead || m.decoy) return; // (a decoy cannot be hurt)
const d = ignoreArmor ? raw : Math.max(raw - m.armor, raw * 0.25); // armour applies once, to the damage dealt const d = ignoreArmor ? raw : Math.max(raw - m.armor, raw * 0.25); // armour applies once, to the damage dealt
let hit = d; let hit = d;
if (m.maxShield > 0) { // a shield soaks first, any damage restarts its regrow timer if (m.maxShield > 0) { // a shield soaks first, any damage restarts its regrow timer
@ -892,6 +1257,7 @@
m.dead = true; m.dead = true;
this.gold += m.reward; this.gold += m.reward;
this.kills++; this.kills++;
if (this.vs) this.vs.stats.kills++;
if (src) src.kills++; if (src) src.kills++;
this.emit({ e: 'kill', x: m.x, y: m.y, k: m.kind, rw: m.reward }); this.emit({ e: 'kill', x: m.x, y: m.y, k: m.kind, rw: m.reward });
} }
@ -900,6 +1266,7 @@
// Shield: after shieldDelay s without damage it regrows shieldRegen of its maximum per second. // Shield: after shieldDelay s without damage it regrows shieldRegen of its maximum per second.
regenShield(m, dt) { regenShield(m, dt) {
const def = ENEMIES[m.kind]; const def = ENEMIES[m.kind];
if (!def.shieldRegen) return; // a shield bought as tech on a kind that has none does not regrow
m.shieldT += dt; m.shieldT += dt;
const over = Math.min(dt, m.shieldT - def.shieldDelay); const over = Math.min(dt, m.shieldT - def.shieldDelay);
if (over > 0 && m.shield < m.maxShield) m.shield = Math.min(m.maxShield, m.shield + m.maxShield * def.shieldRegen * over); if (over > 0 && m.shield < m.maxShield) m.shield = Math.min(m.maxShield, m.shield + m.maxShield * def.shieldRegen * over);
@ -930,7 +1297,7 @@
updateAuras() { updateAuras() {
const ts = this.towers; const ts = this.towers;
let sup = null; let sup = null;
for (const t of ts) { t.buff = 0; if (TOWERS[t.type].role === 'support') (sup || (sup = [])).push(t); } for (const t of ts) { t.buff = 0; if (TOWERS[t.type].role === 'support' && !(t.empT > 0)) (sup || (sup = [])).push(t); } // (an EMPed balancer boosts nothing)
if (!sup) return; if (!sup) return;
for (const s of sup) { for (const s of sup) {
const st = TOWERS[s.type].levels[s.level - 1], r2 = st.range * st.range; const st = TOWERS[s.type].levels[s.level - 1], r2 = st.range * st.range;
@ -951,8 +1318,12 @@
if (m.air ? !def.air : !def.ground) continue; if (m.air ? !def.air : !def.ground) continue;
const dx = m.x - tx, dy = m.y - ty, d2 = dx * dx + dy * dy; const dx = m.x - tx, dy = m.y - ty, d2 = dx * dx + dy * dy;
if (d2 > r2) continue; if (d2 > r2) continue;
// versus: a stealthed unit cannot be ACQUIRED as a target (splash, beam and chain lightning still hit it once something else is
// shot) until its stealth runs out or a Scan reveals it; a decoy beats every other target, the nearest decoy first
if (m.stealthT > 0 && !this.vsRevealed(m)) continue;
let v; let v;
switch (t.mode) { if (m.decoy) v = 1e9 - d2;
else switch (t.mode) {
case 'last': v = m.rem; break; case 'last': v = m.rem; break;
case 'strong': v = m.hp + (m.shield || 0); break; case 'strong': v = m.hp + (m.shield || 0); break;
case 'close': v = -d2; break; case 'close': v = -d2; break;
@ -964,23 +1335,25 @@
} }
updateTower(t, dt) { updateTower(t, dt) {
if (t.empT > 0) { t.empT -= dt; t.tgt = 0; return; } // versus: an EMPed tower does nothing (attack, slow, stun, boost) until it runs out
const def = TOWERS[t.type]; const def = TOWERS[t.type];
if (def.role === 'wall' || def.role === 'support') return; if (def.role === 'wall' || def.role === 'support') return;
const st = def.levels[t.level - 1]; const st = def.levels[t.level - 1];
const cx = t.x + 0.5, cy = t.y + 0.5; const cx = t.x + 0.5, cy = t.y + 0.5;
if (def.role === 'control') { this.pulseStun(t, st, def, cx, cy, dt); return; } const dd = this.vs && this.vs.ddosT > 0 ? 1 - VS.ABILITIES.ddos.slow : 1; // DDoS: cooldowns run slower
if (def.role === 'control') { this.pulseStun(t, st, def, cx, cy, dt * dd); return; }
if (def.role === 'aura') { if (def.role === 'aura') {
const r2 = st.range * st.range; const r2 = st.range * st.range;
for (const m of this.monsters) { for (const m of this.monsters) {
if (m.dead) continue; if (m.dead) continue;
const dx = m.x - cx, dy = m.y - cy; const dx = m.x - cx, dy = m.y - cy;
if (dx * dx + dy * dy > r2) continue; if (dx * dx + dy * dy > r2) continue;
const eff = st.slow * (1 - (ENEMIES[m.kind].slowRes || 0)); const eff = st.slow * (1 - (ENEMIES[m.kind].slowRes || 0)) * (1 - (m.crypt || 0));
if (eff > m.slow) m.slow = eff; if (eff > m.slow) m.slow = eff;
} }
return; return;
} }
t.cd -= dt * (1 + (t.buff || 0)); // a Load Balancer makes cooldowns elapse faster t.cd -= dt * (1 + (t.buff || 0)) * dd; // a Load Balancer makes cooldowns elapse faster
const m = this.findTarget(t, st.range, def); const m = this.findTarget(t, st.range, def);
t.tgt = m ? m.id : 0; t.tgt = m ? m.id : 0;
if (!m) { if (t.cd < 0) t.cd = 0; return; } if (!m) { if (t.cd < 0) t.cd = 0; return; }
@ -1051,7 +1424,7 @@
if (dx * dx + dy * dy <= r2) blast.push(o); if (dx * dx + dy * dy <= r2) blast.push(o);
} }
const slowFor = (o) => { const slowFor = (o) => {
const eff = Math.min(0.6, st.slowOnHit * (1 - (ENEMIES[o.kind].slowRes || 0))); const eff = Math.min(0.6, st.slowOnHit * (1 - (ENEMIES[o.kind].slowRes || 0)) * (1 - (o.crypt || 0)));
if (eff >= o.slowAmt || o.slowT <= 0) o.slowAmt = eff; if (eff >= o.slowAmt || o.slowT <= 0) o.slowAmt = eff;
o.slowT = Math.max(o.slowT, st.slowFor); o.slowT = Math.max(o.slowT, st.slowFor);
}; };
@ -1120,12 +1493,35 @@
// Everything a client needs to (re)build the board from scratch. // Everything a client needs to (re)build the board from scratch.
fullState() { fullState() {
return { const f = {
map: this.mapId, rev: this.rev, towers: this.towerList(), map: this.mapId, rev: this.rev, towers: this.towerList(),
winWave: this.winWave === Infinity ? 0 : this.winWave, winWave: this.winWave === Infinity ? 0 : this.winWave,
maxLives: this.maxLives, maxLives: this.maxLives,
difficulty: this.difficulty, difficulty: this.difficulty,
}; };
if (this.vs) { f.mode = 'versus'; f.limit = this.vs.limit; } // only versus carries these: a co-op state is exactly what it was
return f;
}
// What ONE side may know that the other may not (the shared snapshot carries only snapshot().vs). The server sends it to the seat that
// holds the role; copies, so a caller cannot reach into the sim.
// attacker { credits, income (credits per second now), tech {id: level}, staged [[kind, n]], cd {ability: seconds left}, active {surge, ddos: seconds left} }
// defender { cd {tool: seconds left} } (its credits are `gold` in the shared snapshot)
privateState(role) {
const v = this.vs;
if (!v) return null;
const left = (o) => { const r = {}; for (const k in o) r[k] = up2(o[k]); return r; };
if (role === 'defender') return { cd: left(v.dcd) };
if (role !== 'attacker') return null;
let income = VS.ATT_INCOME + VS.ATT_INCOME_GROWTH * this.time;
for (const m of this.monsters) if (!m.dead && !m.decoy && m.earned < m.buyCost * VS.LIFE_CAP) income += m.buyCost * VS.LIFE_RATE;
return {
credits: down2(v.credits), income: round2(income),
tech: Object.assign({}, v.tech),
staged: v.staged.map((e) => [e[0], e[1]]),
cd: left(v.acd),
active: { surge: up2(v.surgeT), ddos: up2(v.ddosT) },
};
} }
// Compact per-tick state for the wire. Arrays, not objects, to keep it small. // Compact per-tick state for the wire. Arrays, not objects, to keep it small.
@ -1134,20 +1530,23 @@
const mo = this.monsters.map((m) => [m.id, ENEMY_ORDER.indexOf(m.kind), round2(m.x), round2(m.y), Math.ceil(m.hp + (m.shield || 0)), m.maxhp + (m.maxShield || 0), m.slow > 0 || m.stunT > 0 ? 1 : 0]); const mo = this.monsters.map((m) => [m.id, ENEMY_ORDER.indexOf(m.kind), round2(m.x), round2(m.y), Math.ceil(m.hp + (m.shield || 0)), m.maxhp + (m.maxShield || 0), m.slow > 0 || m.stunT > 0 ? 1 : 0]);
const bu = this.bullets.map((b) => [b.id, b.k === 'mortar' ? 1 : 0, round2(b.x), round2(b.y)]); const bu = this.bullets.map((b) => [b.id, b.k === 'mortar' ? 1 : 0, round2(b.x), round2(b.y)]);
const tt = []; const tt = [];
for (const t of this.towers) if (t.type !== 'wall') tt.push([t.id, t.tgt, t.kills]); const v = this.vs;
return { for (const t of this.towers) if (t.type !== 'wall') tt.push(v ? [t.id, t.tgt, t.kills, t.empT > 0 ? round2(t.empT) : 0] : [t.id, t.tgt, t.kills]); // versus: a 4th field, seconds left of an EMP
const snap = {
time: round2(this.time), g: this.gold, l: this.lives, w: this.wave, s: this.state, time: round2(this.time), g: this.gold, l: this.lives, w: this.wave, s: this.state,
au: this.autoWaves ? 1 : 0, nw: this.autoWaves ? round2(this.nextWaveIn) : -1, au: this.autoWaves ? 1 : 0, nw: this.autoWaves ? round2(this.nextWaveIn) : -1,
k: this.kills, rev: this.rev, mo, bu, tt, k: this.kills, rev: this.rev, mo, bu, tt,
q: this.spawnQ.length, q: this.spawnQ.length,
}; };
if (v) snap.vs = { t: round2(this.time), lim: v.limit, st: this.vsStaged() }; // the SHARED part only: how big the convoy is, never what is in it
return snap;
} }
} }
function round2(v) { return Math.round(v * 100) / 100; } function round2(v) { return Math.round(v * 100) / 100; }
return { return {
STEP, WAVE_INTERVAL, START_GOLD, START_LIVES, SELL_RATIO, WIN_WAVE, HEAL_EVERY, HEAL_CAP, STEP, WAVE_INTERVAL, START_GOLD, START_LIVES, SELL_RATIO, WIN_WAVE, HEAL_EVERY, HEAL_CAP, VS,
DIFFICULTIES, DIFFICULTY_ORDER, DEFAULT_DIFFICULTY, isDifficulty, difficultyId, DIFFICULTIES, DIFFICULTY_ORDER, DEFAULT_DIFFICULTY, isDifficulty, difficultyId,
MAPS, MAP_ORDER, TOWERS, TOWER_ORDER, TARGET_MODES, ENEMIES, ENEMY_ORDER, MAPS, MAP_ORDER, TOWERS, TOWER_ORDER, TARGET_MODES, ENEMIES, ENEMY_ORDER,
priceFor, priceMult, upgradePrice, waveGroups, waveSummary, hpScale, rewardScale, clearBonus, priceFor, priceMult, upgradePrice, waveGroups, waveSummary, hpScale, rewardScale, clearBonus,

815
public/js/versus.js Normal file
View file

@ -0,0 +1,815 @@
/*
* NETWALL versus UI (docs/VERSUS.md, docs/PROTOCOL.md "Versus"). Everything that is specific to the attack-vs-defend mode lives here: the setup and
* room dialogs, the round / match result dialog, the role-aware HUD (attacker: unit shop, convoy + Launch, abilities, tech; defender: counter-tools),
* the countdown card and the sounds for the new actions. main.js owns the rest (board, input, co-op, solo) and calls into this module at a few
* guarded places; with no versus game running (V.active false) none of it does anything, so solo and co-op behave as they always did.
*
* The module talks to a controller (LocalController against the computer, or RemoteController in an online room) only through the documented
* surface: ctrl.vs (match message), ctrl.priv (role-private data), ctrl.role, ctrl.view, ctrl.send(cmd), ctrl.vsRole / vsReady / vsBot / vsStart /
* vsNext / vsRematch. The role of a command is never set here: the controller (or the server) knows the seat.
*/
(function (root) {
'use strict';
const NW = root.NW = root.NW || {};
const TD = root.TD;
const VS = TD.VS;
const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
const other = (r) => (r === 'attacker' ? 'defender' : 'attacker');
const roleCls = (r) => (r === 'attacker' ? 'attacker' : 'defender'); // (a role from the server goes into HTML only through this)
const cap1 = (s) => String(s).charAt(0).toUpperCase() + String(s).slice(1);
const mmss = (sec) => { sec = Math.max(0, Math.round(sec)); return Math.floor(sec / 60) + ':' + (sec % 60 < 10 ? '0' : '') + (sec % 60); };
const SVGNS = 'http://www.w3.org/2000/svg';
const icon = (id) => '<svg class="ic" aria-hidden="true"><use href="#' + id + '"/></svg>';
const SKILLS = [{ id: 'easy', name: 'Easy', v: 0.35 }, { id: 'normal', name: 'Normal', v: 0.7 }, { id: 'hard', name: 'Hard', v: 1 }];
const QTYS = [1, 5, 10];
const NAMES = {
armor: 'Armor', speed: 'Speed', health: 'Health', regen: 'Regen', shield: 'Shield', stealth: 'Stealth', crypt: 'Crypt',
emp: 'EMP', decoy: 'Decoy', surge: 'Surge', ddos: 'DDoS', scan: 'Scan', patch: 'Patch', repair: 'Repair', quarantine: 'Quarantine',
};
const nameOf = (id) => NAMES[id] || cap1(id);
const REASONS = {
role: "That is the other player's job", credits: 'Not enough credits', cooldown: 'Still cooling down', cap: 'Too many packets on the board', max: 'Nothing to do',
bad_target: 'Not a valid target', bad_kind: 'Unknown packet', empty: 'The convoy is empty', phase: 'The round has not started yet', frozen: 'Paused: waiting for the other player to come back',
versus: 'Not available in versus', not_host: 'Only the host can do that', no_opponent: 'Waiting for an opponent', offline: 'The opponent is offline',
not_ready: 'The opponent is not ready yet', full: 'Both seats are taken', over: 'The round is over',
};
// What a level of a tech upgrade does, worded from the table (a retune cannot leave this text wrong).
function techText(id, lv) {
const X = VS.TECH[id];
if (!X) return '';
switch (id) {
case 'armor': return '+' + +(X.per * lv).toFixed(2) + ' armour';
case 'speed': return '+' + Math.round(X.per * lv * 100) + '% speed';
case 'health': return '+' + Math.round(X.per * lv * 100) + '% hit points';
case 'regen': return Math.round(X.per * lv * 100) + '% of max hp back per second';
case 'shield': return '+' + Math.round(X.per * lv) + ' shield';
case 'stealth': return 'towers cannot target a packet for its first ' + X.secs[lv - 1] + ' s';
case 'crypt': return 'slows work ' + Math.round(X.res[lv - 1] * 100) + '% weaker';
default: return '';
}
}
function abilityText(id) {
const A = VS.ABILITIES[id];
if (!A) return '';
switch (id) {
case 'emp': return 'Disable one tower for ' + A.dur + ' s';
case 'decoy': return 'A harmless packet every tower shoots at for ' + A.dur + ' s';
case 'surge': return 'All packets ' + Math.round(A.speed * 100) + '% faster for ' + A.dur + ' s';
case 'ddos': return 'All towers fire ' + Math.round(A.slow * 100) + '% slower for ' + A.dur + ' s';
default: return '';
}
}
function toolText(id) {
const T = VS.TOOLS[id];
if (!T) return '';
switch (id) {
case 'scan': return 'Clear EMP and reveal stealth within ' + T.radius + ' cells for ' + T.reveal + ' s (tap the map)';
case 'patch': return 'Re-enable a disabled tower at once';
case 'repair': return 'Restore ' + T.amount + ' integrity';
case 'quarantine': return 'Freeze every packet for ' + T.dur + ' s';
default: return '';
}
}
// A segmented radiogroup (the same pattern as the difficulty picker): items [{ id, label, title? }]
function buildSeg(box, items, onPick) {
box.textContent = '';
for (const it of items) {
const b = document.createElement('button');
b.type = 'button'; b.dataset.v = it.id; b.setAttribute('role', 'radio'); b.setAttribute('aria-checked', 'false');
b.textContent = it.label; if (it.title) b.title = it.title;
b.addEventListener('click', () => onPick(it.id));
box.appendChild(b);
}
}
function segSet(box, id) { for (const b of box.children) b.setAttribute('aria-checked', b.dataset.v === String(id) ? 'true' : 'false'); }
function create(api) {
const { $, app, renderer, Audio, store, esc, toast, banner, showOverlay } = api;
const S = {
ctrl: null, active: false, role: null, vs: null, priv: null, privAt: 0, phase: '',
qty: 1, mode: 'now', gate: -1, shopOn: false, scanArm: false, empArm: false,
cd: {}, act: {}, fx: { surge: 0, ddos: 0, freeze: 0 }, confirm: { key: '', until: 0 },
endTimer: 0, sentNext: false, sentRematch: false, el: {}, last: {}, built: '', decoys: new Map(),
setup: { role: store.get('nw.vs.role', 'random'), limit: store.get('nw.vs.limit', VS.DEFAULT_LIMIT), skill: store.get('nw.vs.skill', 'normal') },
};
if (!['attacker', 'defender', 'random'].includes(S.setup.role)) S.setup.role = 'random';
if (!VS.LIMITS.includes(S.setup.limit)) S.setup.limit = VS.DEFAULT_LIMIT;
if (!SKILLS.some((k) => k.id === S.setup.skill)) S.setup.skill = 'normal';
const UIS = { role: null, tech: null, gate: -1, gates: 1, scanArm: false, empArm: false, decoys: S.decoys }; // what the renderer needs (reused every frame)
const now = () => performance.now();
// ------------------------------------------------------------------ small helpers
const ctrl = () => S.ctrl;
const mySlot = () => (S.ctrl && S.ctrl.you && Number.isInteger(S.ctrl.you.slot) ? S.ctrl.you.slot : 0);
const roleOf = () => (S.ctrl && S.vs ? S.vs.roles[mySlot()] || null : null);
const players = () => (S.ctrl && S.ctrl.players) || [];
const playerName = (slot) => {
if (slot === mySlot()) return 'You';
if (S.vs && S.vs.bot && S.vs.bot.slot === slot) return S.vs.bot.name || 'Computer';
const p = players().find((q) => q.slot === slot);
return p ? p.name : 'Opponent';
};
const phasePlaying = () => !!S.vs && S.vs.phase === 'playing' && !S.vs.frozen;
const gates = () => (S.ctrl && S.ctrl.board ? S.ctrl.board.spawns.length : 1);
const skillValue = () => (SKILLS.find((k) => k.id === S.setup.skill) || SKILLS[1]).v;
const credits = () => { // the attacker's purse, run forward from the last private message (4 Hz) so it moves smoothly
const p = S.priv; if (!p || p.role !== 'attacker') return 0;
return Math.max(0, Math.floor(p.credits + p.income * clamp((now() - S.privAt) / 1000, 0, 0.6)));
};
const stagedTotal = () => { let n = 0; if (S.priv && S.priv.staged) for (const e of S.priv.staged) n += e[1]; return n; };
const cdLeft = (id) => { const c = S.cd[id]; return c ? Math.max(0, c.left - (now() - c.at) / 1000) : 0; };
const actLeft = (id) => { const c = S.act[id]; return c ? Math.max(0, c.left - (now() - c.at) / 1000) : 0; };
const fxLeft = (id) => Math.max(0, (S.fx[id] - now()) / 1000);
function say(text, kind) { // the pill at the top of the stage (armed states)
const n = $('vsNote');
if (!text) { n.hidden = true; return; }
n.hidden = false; n.textContent = text; n.className = 'hint ' + (kind || 'info');
}
function disarm() {
if (!S.scanArm && !S.empArm) return;
S.scanArm = false; S.empArm = false; say(null);
}
function confirmTap(key, text) { // a costly action asks for a second tap within 2.5 s
const t = now();
if (S.confirm.key === key && t < S.confirm.until) { S.confirm.key = ''; return true; }
S.confirm.key = key; S.confirm.until = t + 2500;
toast(text || 'Tap again to confirm', 'good');
return false;
}
function send(cmd) {
const c = S.ctrl; if (!c) return { ok: false };
return c.send(cmd);
}
function gateArg(cmd) { if (S.gate >= 0 && S.gate < gates()) cmd.gate = S.gate; return cmd; }
// ------------------------------------------------------------------ attach / detach (called by main.useController)
function attach(c) {
const on = !!c && c.mode === 'versus';
if (!on) {
if (S.active) teardown();
S.ctrl = c;
return;
}
S.ctrl = c; S.active = true;
S.vs = c.vs || null; S.priv = c.priv || null; S.privAt = now(); S.phase = '';
S.role = null; S.gate = -1; S.scanArm = false; S.empArm = false; S.sentNext = false; S.sentRematch = false;
S.cd = {}; S.act = {}; S.fx = { surge: 0, ddos: 0, freeze: 0 }; S.decoys.clear(); S.last = {};
clearTimeout(S.endTimer);
$('app').dataset.mode = 'versus';
if (c.kind === 'remote') { c.sendCursor = () => {}; c.sendMark = () => {}; } // the server ignores them in versus (an opponent must not see where you aim)
c.on('vs', (m) => { if (S.ctrl === c) onVs(m); });
c.on('priv', (m) => { if (S.ctrl === c) onPriv(m); });
c.on('newgame', () => { if (S.ctrl === c) { disarm(); S.gate = -1; S.last = {}; S.cd = {}; S.act = {}; S.decoys.clear(); S.fx = { surge: 0, ddos: 0, freeze: 0 }; } });
if (c.priv) onPriv(c.priv);
if (c.vs) onVs(c.vs);
}
function teardown() {
S.active = false; S.role = null; S.vs = null; S.priv = null; S.phase = '';
clearTimeout(S.endTimer); say(null);
const a = $('app'); delete a.dataset.mode; delete a.dataset.role;
for (const id of ['vsbar', 'vstech', 'vsHud', 'vsCount']) $(id).hidden = true;
$('vsbar').textContent = ''; $('vstech').textContent = ''; $('vsFx').textContent = '';
S.built = ''; S.el = {};
if (S.shopOn) { S.shopOn = false; api.buildPalette(); }
app.last.gold = undefined;
for (const id of ['vsRoom', 'vsEnd']) if (!$(id).hidden) showOverlay(null);
api.resize();
}
// ------------------------------------------------------------------ messages
function onPriv(m) {
if (!m || m.role !== roleOf() && m.role !== (S.ctrl && S.ctrl.role)) return; // the first priv of a new round can race the vs message: a stale role is dropped
S.priv = m; S.privAt = now();
const t = now();
if (m.cd) for (const id in m.cd) S.cd[id] = { left: m.cd[id], at: t };
if (m.active) for (const id in m.active) S.act[id] = { left: m.active[id], at: t };
}
function onVs(m) {
if (!m) return;
const prev = S.phase;
S.vs = m; S.phase = m.phase;
syncRole();
if (m.phase !== prev) onPhase(prev, m.phase);
if (m.phase === 'lobby') renderRoom();
if (m.phase === 'roundover' || m.phase === 'matchover') { if (!$('vsEnd').hidden) renderEnd(); }
renderCount();
}
function onPhase(prev, ph) {
disarm(); S.confirm.key = '';
clearTimeout(S.endTimer);
if (ph === 'lobby') { showOverlay('vsRoom'); renderRoom(); }
else if (ph === 'countdown') {
S.sentNext = false; S.sentRematch = false;
hideMine(); S.gate = -1; S.last = {};
api.adoptBoard(); api.resetSelection(); // (a local match builds a new board for every round; the renderer must follow it)
Audio.music('battle');
} else if (ph === 'playing') {
hideMine();
if (prev === 'countdown') { banner(S.role === 'attacker' ? 'ATTACK!' : 'DEFEND!', S.role === 'attacker'); Audio.sfx('go'); }
} else if (ph === 'roundover' || ph === 'matchover') {
S.sentNext = false; S.sentRematch = false;
const won = ph === 'matchover' ? matchResult() === 'win' : roundWon();
Audio.music(null);
const show = () => { if (S.active && (S.phase === 'roundover' || S.phase === 'matchover')) { renderEnd(); showOverlay('vsEnd'); Audio.stinger(won ? 'win' : 'lose'); } };
if (prev === 'playing') S.endTimer = setTimeout(show, 1100); else show(); // a beat to watch the last second
}
}
function hideMine() { for (const id of ['vsRoom', 'vsEnd']) if (!$(id).hidden) { showOverlay(null); break; } }
function roundWon() { const r = S.vs && S.vs.result; return !!r && r.winner === roleOf(); }
function matchResult() { // 'win' | 'lose' | 'draw' for me, from the SERVER's verdict (never recomputed here)
const w = S.vs ? S.vs.winner : null;
if (w === null || w === undefined) return 'draw';
return w === mySlot() ? 'win' : 'lose';
}
// A role change (round 2, or the host moved the computer) rebuilds the dock: the palette becomes the unit shop for the attacker and the
// tower palette again for the defender.
function syncRole() {
const role = roleOf();
if (role === S.role) return;
S.role = role; S.priv = S.priv && S.priv.role === role ? S.priv : null;
disarm(); S.gate = -1; S.cd = {}; S.act = {};
$('app').dataset.role = role || '';
app.last.gold = undefined;
const att = role === 'attacker';
if (att) buildShop(); else if (S.shopOn) { S.shopOn = false; api.buildPalette(); }
buildDock();
app.selTower = 0; if (role) { api.selectType(null); }
api.renderInfo(true);
api.resize();
}
// ------------------------------------------------------------------ the dock: unit shop, convoy row, abilities / tools, tech
function drawUnitIcon(cv, kind) {
const def = TD.ENEMIES[kind]; if (!def || !NW.drawMonster) return;
const dpr = Math.min(2, root.devicePixelRatio || 1), size = cv.clientWidth || 34;
cv.width = cv.height = Math.round(size * dpr);
const ctx = cv.getContext('2d');
ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, size, size);
const k = size * 0.36 / Math.max(def.r * NW.CELL * 1.3, 8);
ctx.translate(size / 2, size / 2 + (kind === 'ghost' ? 4 : 0)); ctx.scale(k, k);
NW.drawMonster(ctx, { kind, x: 0, y: 0, hp: 1, maxhp: 1, id: 1, slow: 0 }, -0.6, 0.3, 0, 0, false);
}
function drawShopIcons() { for (const b of $('palette').children) if (b.dataset.kind) drawUnitIcon(b.querySelector('canvas'), b.dataset.kind); }
function unitTip(kind) {
const d = TD.ENEMIES[kind];
return d.name + ', ' + d.buyCost + ' credits: ' + d.hp + ' hp' + (d.armor ? ', armour ' + d.armor : '') + ', speed ' + d.speed + (d.air ? ', flies' : '') + (d.heal || d.healRange ? ', heals others' : '');
}
function buildShop() {
const pal = $('palette');
pal.textContent = '';
pal.classList.toggle('many', TD.ENEMY_ORDER.length > 6);
pal.classList.add('shop');
for (const kind of TD.ENEMY_ORDER) {
const d = TD.ENEMIES[kind];
const b = document.createElement('button');
b.className = 'tbtn ubtn'; b.dataset.kind = kind; b.type = 'button';
b.innerHTML = '<span class="key"></span><canvas></canvas><span class="nm"></span><span class="cost"></span>';
b.querySelector('.nm').textContent = d.name;
b.title = unitTip(kind);
b.addEventListener('click', () => { Audio.unlock(); buy(kind); b.classList.add('hit'); setTimeout(() => b.classList.remove('hit'), 160); });
pal.appendChild(b);
}
[...pal.children].forEach((b, i) => { b.querySelector('.key').textContent = i < 9 ? String(i + 1) : ''; });
S.shopOn = true; S.last.shop = '';
drawShopIcons();
api.updatePaletteHint();
}
function buildDock() {
const bar = $('vsbar'), tech = $('vstech');
bar.textContent = ''; tech.textContent = ''; S.el = {};
const att = S.role === 'attacker', def = S.role === 'defender';
bar.hidden = !(att || def); tech.hidden = !att;
$('vsHud').hidden = !S.role;
if (att) {
const abil = VS.ABILITY_ORDER.map((id) => dockBtn('ab', id, VS.ABILITIES[id].cost)).join('');
bar.innerHTML =
'<div class="vsrow vsctlrow"><button type="button" class="vsctl" id="vsQty"></button><button type="button" class="vsctl" id="vsMode"></button>' +
'<button type="button" class="vsctl" id="vsGateBtn" hidden></button>' +
'<button type="button" class="primary vslaunch" id="vsLaunch" disabled>' + icon('i-launch') + '<span class="lt"><b>LAUNCH</b><small></small></span></button></div>' +
'<div class="vsrow vsabil" id="vsAbil">' + abil + '</div>';
tech.innerHTML = '<div class="vshead"><span>Tech</span><small>permanent, for packets sent from now on</small></div><div class="vstiles" id="vsTiles"></div>';
const tiles = tech.querySelector('#vsTiles');
for (const id of VS.TECH_ORDER) {
const b = document.createElement('button');
b.type = 'button'; b.className = 'tbtn techbtn'; b.dataset.tech = id;
b.innerHTML = icon('i-te-' + id) + '<span class="nm"></span><span class="pips"></span><span class="cost"></span>';
b.querySelector('.nm').textContent = nameOf(id);
tiles.appendChild(b);
}
S.el = { qty: bar.querySelector('#vsQty'), mode: bar.querySelector('#vsMode'), gate: bar.querySelector('#vsGateBtn'), launch: bar.querySelector('#vsLaunch'), launchSub: bar.querySelector('#vsLaunch small'), tiles };
S.el.qty.addEventListener('click', () => { S.qty = QTYS[(QTYS.indexOf(S.qty) + 1) % QTYS.length]; Audio.sfx('click'); S.last.shop = ''; });
S.el.mode.addEventListener('click', () => { S.mode = S.mode === 'now' ? 'stage' : 'now'; Audio.sfx('click'); });
S.el.gate.addEventListener('click', () => { Audio.sfx('click'); setGate(S.gate + 1 >= gates() ? -1 : S.gate + 1); });
S.el.launch.addEventListener('click', launch);
bar.querySelector('#vsAbil').addEventListener('click', (e) => { const b = e.target.closest('button[data-ab]'); if (b) { Audio.unlock(); ability(b.dataset.ab); } });
tiles.addEventListener('click', (e) => { const b = e.target.closest('button[data-tech]'); if (b) { Audio.unlock(); buyTech(b.dataset.tech); } });
S.last.dock = ''; S.last.shop = '';
} else if (def) {
bar.innerHTML = '<div class="vsrow vsabil vstools" id="vsAbil">' + VS.TOOL_ORDER.map((id) => dockBtn('tl', id, VS.TOOLS[id].cost)).join('') + '</div>';
bar.querySelector('#vsAbil').addEventListener('click', (e) => { const b = e.target.closest('button[data-tl]'); if (b) { Audio.unlock(); useTool(b.dataset.tl); } });
S.last.dock = '';
}
if (att || def) {
for (const b of bar.querySelectorAll('.vsbtn')) { const id = b.dataset.ab || b.dataset.tl; S.el[id] = { b, cd: b.querySelector('.cd'), cost: b.querySelector('.cost'), ring: -1 }; }
}
}
function dockBtn(kind, id, cost) {
const tip = kind === 'ab' ? abilityText(id) : toolText(id);
return '<button type="button" class="vsbtn" data-' + kind + '="' + id + '" title="' + esc(nameOf(id) + ': ' + tip) + '" aria-label="' + esc(nameOf(id) + ', ' + cost + ' credits. ' + tip) + '">' +
icon(kind === 'ab' ? 'i-ab-' + id : 'i-tl-' + id) + '<span class="nm">' + esc(nameOf(id)) + '</span><span class="cost">' + cost + '</span><span class="cd"></span></button>';
}
// ------------------------------------------------------------------ actions: attacker
function buy(kind) {
if (!ready()) return;
const d = TD.ENEMIES[kind], have = credits();
let n = S.qty;
if (have < d.buyCost) { toast(REASONS.credits, 'bad'); Audio.sfx('error'); return; }
if (have < d.buyCost * n) { n = Math.floor(have / d.buyCost); toast('Only ' + n + ' affordable: buying ' + n); }
const res = send(gateArg({ c: S.mode === 'stage' ? 'stage' : 'spawn', kind, n }));
if (res && res.ok) {
Audio.sfx(S.mode === 'stage' ? 'stage' : 'buy');
if (S.ctrl.kind === 'remote' && S.priv) S.priv.credits = Math.max(0, S.priv.credits - d.buyCost * n);
}
}
function launch() {
if (!ready()) return;
if (!stagedTotal()) { toast(REASONS.empty, 'bad'); return; }
const res = send(gateArg({ c: 'launch' }));
if (res && res.ok) {
Audio.sfx('launch');
if (S.ctrl.kind === 'remote' && S.priv) S.priv.staged = [];
}
}
function buyTech(id) {
if (!ready()) return;
const lv = S.priv && S.priv.tech ? S.priv.tech[id] || 0 : 0, X = VS.TECH[id];
if (!X || lv >= X.max) { toast(REASONS.max === 'Nothing to do' ? nameOf(id) + ' is at its maximum' : REASONS.max); return; }
const cost = VS.TECH_COST * Math.pow(2, lv);
if (credits() < cost) { toast(REASONS.credits, 'bad'); Audio.sfx('error'); return; }
const res = send({ c: 'tech', id });
if (res && res.ok) {
Audio.sfx('tech');
if (S.ctrl.kind === 'remote' && S.priv) { S.priv.credits = Math.max(0, S.priv.credits - cost); S.priv.tech = Object.assign({}, S.priv.tech, { [id]: lv + 1 }); }
}
}
function ability(id) {
if (!ready()) return;
const A = VS.ABILITIES[id]; if (!A) return;
if (id === 'emp') {
if (S.empArm) { disarm(); return; }
const t = app.selTower ? S.ctrl.view.towers.find((x) => x.id === app.selTower) : null;
if (t && t.type !== 'wall') { castEmp(t.id); return; }
disarm(); S.empArm = true; say('Tap a tower to EMP it (' + A.dur + ' s)'); Audio.sfx('click');
return;
}
if (cdLeft(id) > 0.05) { toast(nameOf(id) + ' is cooling down', 'bad'); return; }
if (credits() < A.cost) { toast(REASONS.credits, 'bad'); Audio.sfx('error'); return; }
if (A.cost >= 150 && !confirmTap(id, 'Tap ' + nameOf(id) + ' again to fire it (' + A.cost + ')')) { flashConfirm(id); return; }
cast({ c: 'ability', id }, id, A.cost, A.cd, id === 'decoy');
}
function castEmp(tid) {
const A = VS.ABILITIES.emp;
disarm();
if (cdLeft('emp') > 0.05) { toast('EMP is cooling down', 'bad'); return; }
if (credits() < A.cost) { toast(REASONS.credits, 'bad'); Audio.sfx('error'); return; }
cast({ c: 'ability', id: 'emp', tid }, 'emp', A.cost, A.cd, false);
app.selTower = 0; api.renderInfo(true);
}
function cast(cmd, id, cost, cd, useGate) {
const res = send(useGate ? gateArg(cmd) : cmd);
if (res && res.ok && S.ctrl.kind === 'remote' && S.priv) { S.priv.credits = Math.max(0, S.priv.credits - cost); S.cd[id] = { left: cd, at: now() }; }
}
function flashConfirm(id) {
const e = S.el[id]; if (!e) return;
e.b.classList.add('confirm'); setTimeout(() => e.b.classList.remove('confirm'), 2500);
}
function setGate(i) {
S.gate = i;
toast(i < 0 ? 'Gateways: automatic' : 'Gateway ' + (i + 1) + ' chosen', 'good');
}
// ------------------------------------------------------------------ actions: defender
function useTool(id) {
if (!ready()) return;
const T = VS.TOOLS[id]; if (!T) return;
const view = S.ctrl.view;
if (id === 'scan' && S.scanArm) { disarm(); return; }
if (cdLeft(id) > 0.05) { toast(nameOf(id) + ' is cooling down', 'bad'); return; }
if (view.gold < T.cost) { toast(REASONS.credits, 'bad'); Audio.sfx('error'); return; }
if (id === 'scan') { disarm(); api.selectType(null); S.scanArm = true; say('Tap the map to scan (radius ' + T.radius + ')'); Audio.sfx('click'); return; }
let cmd = { c: 'tool', id };
if (id === 'patch') {
const sel = app.selTower ? view.towers.find((t) => t.id === app.selTower && t.empT > 0) : null;
let t = sel;
if (!t) for (const x of view.towers) if (x.empT > 0 && (!t || x.empT > t.empT)) t = x;
if (!t) { toast('No tower is disabled', 'bad'); return; }
cmd.tid = t.id;
} else if (id === 'repair') {
if (view.lives >= view.maxLives) { toast('Integrity is already full', 'bad'); return; }
} else if (T.cost >= 150 && !confirmTap(id, 'Tap ' + nameOf(id) + ' again to use it (' + T.cost + ')')) { flashConfirm(id); return; }
const res = send(cmd);
if (res && res.ok) {
Audio.sfx(id === 'patch' ? 'patch' : 'click');
if (S.ctrl.kind === 'remote') S.cd[id] = { left: T.cd, at: now() };
}
}
function scanAt(cell) {
disarm();
const T = VS.TOOLS.scan;
if (cdLeft('scan') > 0.05) { toast('Scan is cooling down', 'bad'); return; }
if (S.ctrl.view.gold < T.cost) { toast(REASONS.credits, 'bad'); return; }
const res = send({ c: 'tool', id: 'scan', x: cell.x + 0.5, y: cell.y + 0.5 });
if (res && res.ok && S.ctrl.kind === 'remote') S.cd.scan = { left: T.cd, at: now() };
}
function ready() {
if (!S.active || !S.role) return false;
if (S.vs && S.vs.frozen) { toast(REASONS.frozen, 'bad'); return false; }
if (!phasePlaying()) { toast(REASONS.phase, 'bad'); return false; }
return true;
}
// ------------------------------------------------------------------ board taps and keys (called by main)
function tapCell(cell) {
if (!S.active || !S.role || !S.ctrl.board || !S.ctrl.board.inBounds(cell.x, cell.y)) return false;
const view = S.ctrl.view;
if (S.role === 'defender') {
if (S.scanArm && ready()) { scanAt(cell); return true; }
return false;
}
const tw = view.towers.find((x) => x.x === cell.x && x.y === cell.y);
if (S.empArm) {
if (tw && tw.type !== 'wall') { if (ready()) castEmp(tw.id); return true; }
if (tw) { toast("A Firewall can't be disabled", 'bad'); return true; }
disarm(); return true;
}
if (tw) return false; // an ordinary tap on a tower selects it (its panel offers EMP)
const sp = S.ctrl.board.spawns;
if (sp.length > 1) {
let best = -1, bd = 3;
for (let i = 0; i < sp.length; i++) { const d = Math.max(Math.abs(sp[i].x - cell.x), Math.abs(sp[i].y - cell.y)); if (d <= 1 && d < bd) { bd = d; best = i; } }
if (best >= 0) { Audio.sfx('click'); setGate(S.gate === best ? -1 : best); return true; }
}
return false;
}
// Keys: attacker digits buy units, Space launches; the wave / pause / speed keys do nothing in versus. Returns true when handled.
function key(k, e) {
if (!S.active) return false;
if (k === 'p' || k === 'f' || k === 'a') return true;
if (k === 'escape' || k === 'q') { disarm(); return false; }
if (S.role === 'attacker') {
if (k === ' ' || k === 'enter') { launch(); e.preventDefault(); return true; }
const i = k.length === 1 && k >= '1' && k <= '9' ? +k - 1 : k === '0' ? 9 : -1;
if (i >= 0 && TD.ENEMY_ORDER[i]) { buy(TD.ENEMY_ORDER[i]); e.preventDefault(); return true; }
return false;
}
if (k === ' ' || k === 'enter') return true;
return false;
}
const holdsOverlay = () => S.active && (S.phase === 'lobby' || S.phase === 'roundover' || S.phase === 'matchover');
function refreshOverlay() {
if (!S.active) return;
if (S.phase === 'lobby') { renderRoom(); showOverlay('vsRoom'); }
else if (S.phase === 'roundover' || S.phase === 'matchover') { renderEnd(); showOverlay('vsEnd'); }
}
// The stacked layout needs more room under the board in versus: the attacker's dock is shop + convoy + abilities + tech.
function minSide(H) {
if (!S.active || !S.role) return 0;
return S.role === 'attacker' ? clamp(Math.round(H * 0.4), 295, 340) : clamp(Math.round(H * 0.3), 190, 250);
}
function uiState() {
if (!S.active) return null;
UIS.role = S.role; UIS.tech = S.role === 'attacker' && S.priv ? S.priv.tech || null : null;
UIS.gate = S.gate; UIS.gates = gates(); UIS.scanArm = S.scanArm; UIS.empArm = S.empArm;
return UIS;
}
// ------------------------------------------------------------------ events (sounds and cues for the new actions)
function onEvent(e) {
if (!S.active) return;
const t = now();
switch (e.e) {
case 'emp': Audio.sfx('emp'); if (S.role === 'defender') toast('EMP: a tower went offline. Patch or Scan it', 'bad'); break;
case 'decoy': Audio.sfx('decoy'); if (e.id !== undefined) S.decoys.set(e.id, t + (e.d || 5) * 1000); break;
case 'surge': S.fx.surge = t + (e.d || 6) * 1000; Audio.sfx('surge'); banner('SURGE', true); break;
case 'ddos': S.fx.ddos = t + (e.d || 4) * 1000; Audio.sfx('ddos'); banner('DDoS', true); break;
case 'quarantine': S.fx.freeze = t + (e.d || 2) * 1000; Audio.sfx('quarantine'); banner('QUARANTINE'); break;
case 'scan': Audio.sfx('scan'); break;
case 'repair': Audio.sfx('repair'); break;
default: break;
}
}
const leakSfx = () => (S.active && S.role === 'attacker' ? 'breach' : 'leak');
const isDecoy = (m) => !!m.decoy || (S.decoys.size > 0 && S.decoys.has(m.id));
// ------------------------------------------------------------------ per frame: top bar, dock, cooldown rings
function setText(el, v) { if (el && el.textContent !== v) el.textContent = v; }
function setCls(el, c, on) { if (el && el.classList.contains(c) !== on) el.classList.toggle(c, on); }
function tick(t, view) {
if (!S.active) return;
const att = S.role === 'attacker', L = S.last, vsb = view.vs;
// clock
const left = vsb ? Math.max(0, vsb.lim - vsb.t) : S.vs ? S.vs.limit : 0;
const tt = mmss(left);
if (L.time !== tt) { L.time = tt; $('vTime').textContent = tt; }
const low = left <= 30 && phasePlaying();
if (L.low !== low) { L.low = low; $('statTime').classList.toggle('low', low); }
// the attacker's credits and income replace the defender's gold in the top bar
if (att) {
const c = credits(), inc = S.priv && S.priv.role === 'attacker' ? S.priv.income : 0;
if (L.cr !== c) { L.cr = c; $('vGold').textContent = String(c); }
const it = inc ? '+' + (Math.round(inc * 10) / 10) + '/s' : '';
if (L.inc !== it) { L.inc = it; $('vIncome').textContent = it; }
$('statGold').title = 'Your credits (income ' + it + ')';
} else if (L.inc !== '') { L.inc = ''; $('vIncome').textContent = ''; $('statGold').title = 'Credits'; }
// shop / tech / convoy
if (att) tickAttacker(view);
tickDock(view);
tickHud(view);
tickFx(t);
}
function tickAttacker(view) {
const L = S.last, c = credits(), E = S.el;
const shopKey = c + '|' + S.qty + '|' + S.mode;
if (E.qty && L.shop !== shopKey) {
L.shop = shopKey;
setText(E.qty, '×' + S.qty); E.qty.setAttribute('aria-label', 'Quantity ' + S.qty + ' per tap. Tap to change');
setText(E.mode, S.mode === 'stage' ? 'Stage' : 'Send');
E.mode.setAttribute('aria-label', S.mode === 'stage' ? 'Stage: pay now and hold the units in the convoy. Tap to switch to Send now' : 'Send now: units enter at once. Tap to switch to Stage');
E.mode.classList.toggle('on', S.mode === 'stage');
for (const b of $('palette').children) {
const d = TD.ENEMIES[b.dataset.kind]; if (!d) continue;
const price = d.buyCost * S.qty, poor = c < d.buyCost;
setText(b.querySelector('.cost'), String(price));
setCls(b, 'poor', poor);
b.setAttribute('aria-label', d.name + ', ' + price + ' credits' + (S.qty > 1 ? ' for ' + S.qty : '') + (poor ? ', not enough credits' : ''));
}
}
// convoy + Launch
const n = stagedTotal();
const comp = S.priv && S.priv.staged ? S.priv.staged.map((e) => e[1] + ' ' + (TD.ENEMIES[e[0]] ? TD.ENEMIES[e[0]].name : e[0])).join(', ') : '';
const lk = n + '|' + comp;
if (L.launch !== lk && E.launch) {
L.launch = lk;
E.launch.disabled = n === 0;
E.launch.querySelector('b').textContent = n ? 'LAUNCH ' + n : 'LAUNCH';
setText(E.launchSub, n ? comp : 'convoy empty');
E.launch.setAttribute('aria-label', n ? 'Launch the convoy: ' + comp : 'Launch (the convoy is empty: use Stage to hold units)');
}
const ng = gates();
if (E.gate) {
E.gate.hidden = ng < 2;
const gt = S.gate < 0 ? 'Gate: auto' : 'Gate ' + (S.gate + 1);
if (L.gate !== gt) { L.gate = gt; E.gate.textContent = S.gate < 0 ? 'Any gate' : 'Gate ' + (S.gate + 1); E.gate.setAttribute('aria-label', gt + '. Tap to change (or tap a gateway on the map)'); E.gate.classList.toggle('on', S.gate >= 0); }
}
// tech tiles
const tech = S.priv && S.priv.tech ? S.priv.tech : {};
for (const b of E.tiles ? E.tiles.children : []) {
const id = b.dataset.tech, X = VS.TECH[id], lv = tech[id] || 0, max = lv >= X.max;
const cost = max ? 0 : VS.TECH_COST * Math.pow(2, lv);
const key = lv + '|' + (max ? 'm' : c >= cost ? 'y' : 'n');
if (b.dataset.k === key) continue;
b.dataset.k = key;
b.querySelector('.pips').textContent = '●'.repeat(lv) + '○'.repeat(X.max - lv);
setText(b.querySelector('.cost'), max ? 'MAX' : String(cost));
setCls(b, 'poor', !max && c < cost); setCls(b, 'maxed', max);
const nxt = max ? 'maxed out' : 'next: ' + techText(id, lv + 1);
b.title = nameOf(id) + ' ' + lv + '/' + X.max + ', ' + nxt;
b.setAttribute('aria-label', nameOf(id) + ', level ' + lv + ' of ' + X.max + ', ' + nxt + (max ? '' : ', ' + cost + ' credits') + (!max && c < cost ? ', not enough credits' : ''));
}
}
function tickDock(view) {
const att = S.role === 'attacker', c = att ? credits() : view.gold, table = att ? VS.ABILITIES : VS.TOOLS;
for (const id in table) {
const e = S.el[id]; if (!e) continue;
const T = table[id], left = cdLeft(id), frac = T.cd ? clamp(left / T.cd, 0, 1) : 0;
const q = Math.round(frac * 50);
if (e.ring !== q) { e.ring = q; e.b.style.setProperty('--p', String(q / 50)); }
const act = att ? actLeft(id) : 0;
const txt = act > 0 ? Math.ceil(act) + 's' : left > 0.05 ? Math.ceil(left) + 's' : '';
setText(e.cd, txt);
setCls(e.b, 'cooling', left > 0.05);
setCls(e.b, 'poor', left <= 0.05 && c < T.cost);
setCls(e.b, 'live', act > 0);
setCls(e.b, 'armed', (id === 'emp' && S.empArm) || (id === 'scan' && S.scanArm));
if (id === 'patch') { let any = false; for (const t of view.towers) if (t.empT > 0) { any = true; break; } setCls(e.b, 'idle', !any); }
if (id === 'repair') setCls(e.b, 'idle', view.lives >= view.maxLives);
if (id === 'emp') { // a selected tower makes EMP a one-tap action
const sel = app.selTower ? view.towers.find((t) => t.id === app.selTower) : null;
setCls(e.b, 'ready', !!sel && sel.type !== 'wall');
}
}
// the EMP button in the selected tower's action bar (attacker)
const eb = $('info').querySelector('[data-act="emp"]');
if (eb) {
const left = cdLeft('emp'), A = VS.ABILITIES.emp;
setCls(eb, 'poor', c < A.cost || left > 0.05);
const cost = eb.querySelector('.cost'); setText(cost, left > 0.05 ? Math.ceil(left) + 's' : String(A.cost));
}
}
function tickHud(view) {
const L = S.last, hud = $('vsHud');
let txt;
const alive = view.monsters.length;
if (S.role === 'attacker') txt = (S.priv && S.priv.income ? '+' + (Math.round(S.priv.income * 10) / 10) + '/s · ' : '') + alive + ' alive · def ' + view.gold + 'cr';
else txt = alive + ' alive' + (view.vs && view.vs.st ? ' · ' + view.vs.st + ' staged' : '');
if (L.hud !== txt) { L.hud = txt; hud.textContent = txt; }
}
function tickFx(t) {
const box = $('vsFx'), L = S.last;
if (S.decoys.size > 12) for (const [id, until] of S.decoys) if (until < t) S.decoys.delete(id);
const parts = [];
for (const id of ['surge', 'ddos', 'freeze']) {
const left = fxLeft(id);
if (left > 0) parts.push([id, Math.ceil(left)]);
}
const key = parts.map((p) => p.join(':')).join(',');
if (L.fx === key) return;
L.fx = key;
const label = { surge: 'SURGE: packets faster', ddos: 'DDoS: towers slowed', freeze: 'QUARANTINE: packets frozen' };
box.innerHTML = parts.map((p) => '<span class="fxchip ' + p[0] + '">' + label[p[0]] + ' ' + p[1] + 's</span>').join('');
}
// ------------------------------------------------------------------ countdown / paused card on the stage
function renderCount() {
const box = $('vsCount'), m = S.vs;
if (!m || !S.role || m.phase === 'lobby' || m.phase === 'roundover' || m.phase === 'matchover' || (m.phase === 'playing' && !m.frozen)) { box.hidden = true; return; }
const att = S.role === 'attacker';
let html;
if (m.frozen) {
html = '<div class="vsc-big">PAUSED</div><div class="vsc-sub">The other player lost the connection. The round waits for them (up to a minute), then you win.</div>';
} else {
const n = m.countdown !== undefined ? m.countdown : 0;
html = '<div class="vsc-top">ROUND ' + m.round + ' OF ' + m.rounds + '</div>' +
'<div class="vsc-role ' + (att ? 'att' : 'def') + '">YOU ' + (att ? 'ATTACK' : 'DEFEND') + '</div>' +
'<div class="vsc-sub">' + (att ? 'Spend credits on packets and break the server before the clock runs out.' : 'Build walls and turrets, keep the server alive until the clock runs out.') + '</div>' +
'<div class="vsc-num" aria-hidden="true">' + n + '</div>';
if (S.last.cd !== n) { S.last.cd = n; if (n > 0) Audio.sfx('tick'); }
}
if (S.last.countHtml !== html) { S.last.countHtml = html; box.innerHTML = html; }
box.hidden = false;
}
// ------------------------------------------------------------------ dialogs: setup, room, result
function initDialogs() {
buildSeg($('vsRolePick'), [{ id: 'attacker', label: 'Attack' }, { id: 'defender', label: 'Defend' }, { id: 'random', label: 'Random' }], (v) => { Audio.sfx('click'); S.setup.role = v; store.set('nw.vs.role', v); segSet($('vsRolePick'), v); });
buildSeg($('vsLimitPick'), VS.LIMITS.map((s) => ({ id: s, label: Math.round(s / 60) + ' min' })), (v) => { Audio.sfx('click'); S.setup.limit = +v; store.set('nw.vs.limit', +v); segSet($('vsLimitPick'), v); });
buildSeg($('vsSkillPick'), SKILLS.map((k) => ({ id: k.id, label: k.name })), (v) => { Audio.sfx('click'); S.setup.skill = v; store.set('nw.vs.skill', v); segSet($('vsSkillPick'), v); });
segSet($('vsRolePick'), S.setup.role); segSet($('vsLimitPick'), S.setup.limit); segSet($('vsSkillPick'), S.setup.skill);
$('vsCode').addEventListener('input', (e) => { e.target.value = e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 4); });
$('vsCode').addEventListener('keydown', (e) => { if (e.key === 'Enter') $('btnVsJoin').click(); });
$('btnVsBack').addEventListener('click', () => { msg(''); api.cancelPending(); if (app.inGame) api.closeOverlayToGame(); else api.openMenu(); });
$('btnVsComputer').addEventListener('click', () => { Audio.unlock(); msg(''); api.startLocal({ role: S.setup.role, limit: S.setup.limit, skill: skillValue() }); });
$('btnVsCreate').addEventListener('click', () => { Audio.unlock(); api.connect({ room: null, map: app.mapId, mode: 'versus', limit: S.setup.limit, name: $('vsName').value, say: msg }); });
$('btnVsJoin').addEventListener('click', () => {
const code = $('vsCode').value.trim().toUpperCase();
if (!/^[A-Z0-9]{4}$/.test(code)) { msg('Enter the 4 character room code.', true); return; }
api.connect({ room: code, name: $('vsName').value, say: msg });
});
// room
buildSeg($('vsRoomRole'), [{ id: 'attacker', label: 'Attack' }, { id: 'defender', label: 'Defend' }, { id: 'random', label: 'Random' }], (v) => { Audio.sfx('click'); if (S.ctrl) S.ctrl.vsRole(v); });
buildSeg($('vsRoomOpp'), [{ id: 'friend', label: 'A friend' }, { id: 'computer', label: 'Computer' }], (v) => {
Audio.sfx('click');
if (!S.ctrl) return;
if (v === 'computer') { const mine = roleOf() || 'attacker'; S.ctrl.vsBot(other(mine), skillValue()); } else S.ctrl.vsBot(null);
});
$('btnVsReady').addEventListener('click', () => { Audio.sfx('click'); const me = mySlot(); S.ctrl.vsReady(!(S.vs && S.vs.ready && S.vs.ready[me])); });
$('btnVsStart').addEventListener('click', () => { Audio.sfx('click'); S.ctrl.vsStart(); });
$('btnVsInvite').addEventListener('click', () => api.invite());
$('btnVsLeave').addEventListener('click', () => api.exitToMenu());
// result
$('btnVsNext').addEventListener('click', () => { Audio.sfx('click'); S.sentNext = true; S.ctrl.vsNext(); renderEnd(); });
$('btnVsRematch').addEventListener('click', () => { Audio.sfx('click'); S.sentRematch = true; S.ctrl.vsRematch(); renderEnd(); });
$('btnVsEndMenu').addEventListener('click', () => api.exitToMenu());
}
function msg(text, bad) { const m = $('vsMsg'); m.textContent = text || ''; m.className = 'msg' + (bad ? ' bad' : ''); }
function openSetup(code) {
$('vsName').value = store.get('nw.name', '') || '';
$('vsMapName').textContent = 'Map: ' + TD.MAPS[app.mapId].name + ' (pick another in the menu)';
segSet($('vsRolePick'), S.setup.role); segSet($('vsLimitPick'), S.setup.limit); segSet($('vsSkillPick'), S.setup.skill);
msg(root.location.protocol === 'file:' ? 'Online play needs the Netwall server (npm start). Against the computer works from the file.' : '');
showOverlay('vsSetup'); api.setScreen(app.inGame ? 'playing' : 'menu');
if (code) { $('vsCode').value = code; $('btnVsJoin').focus({ preventScroll: true }); }
}
// ---- the online room (lobby phase)
function renderRoom() {
const c = S.ctrl, m = S.vs;
if (!c || !m || m.phase !== 'lobby') return;
const me = mySlot(), isHost = !!(c.you && c.you.host), opp = 1 - me;
const oppP = players().find((p) => p.slot === opp), botOpp = !!(m.bot && m.bot.slot === opp);
$('vsRoomCode').textContent = 'Room ' + (c.room || '');
$('vsRoomLimit').textContent = 'Round: ' + mmss(m.limit) + ' · 2 rounds, roles swap';
let seats = '';
for (const slot of [0, 1]) {
const p = players().find((q) => q.slot === slot), isBot = !!(m.bot && m.bot.slot === slot), role = roleCls(m.roles[slot]);
const nm = isBot ? (m.bot.name || 'Computer') : p ? p.name : null;
const rdy = isBot || (p && p.host) || (m.ready && m.ready[slot]);
seats += '<div class="vsseat' + (nm ? '' : ' empty') + '"><span class="dot" style="background:' + api.slotColor(slot) + '"></span>' +
'<span class="sn">' + (nm ? esc(nm) : 'Waiting for an opponent&hellip;') + '</span>' +
(p && c.you && p.pid === c.you.pid ? '<span class="you">(you)</span>' : '') + (p && p.host ? '<span class="you">host</span>' : '') + (p && !p.online ? '<span class="off">offline</span>' : '') +
(nm ? '<span class="rolebadge ' + role + '">' + (role === 'attacker' ? 'ATTACK' : 'DEFEND') + '</span><span class="rdy' + (rdy ? ' ok' : '') + '">' + (rdy ? '&#10003; ready' : 'not ready') + '</span>' : '') + '</div>';
}
$('vsSeats').innerHTML = seats;
segSet($('vsRoomRole'), m.random ? 'random' : roleOf());
$('vsOppField').hidden = !isHost;
segSet($('vsRoomOpp'), m.bot ? 'computer' : 'friend');
$('vsRoomNote').textContent = m.random ? 'Roles are drawn at random: you ' + (roleOf() === 'attacker' ? 'attack' : 'defend') + ' first, then it swaps.' : 'You ' + (roleOf() === 'attacker' ? 'attack' : 'defend') + ' first, then it swaps.';
let why = '';
if (!oppP && !botOpp) why = 'Waiting for an opponent to join. Share the invite, or play the computer.';
else if (oppP && !oppP.online) why = oppP.name + ' is offline.';
else if (oppP && !(m.ready && m.ready[opp])) why = 'Waiting for ' + oppP.name + ' to get ready.';
const imReady = !!(m.ready && m.ready[me]);
$('btnVsStart').hidden = !isHost;
$('btnVsStart').disabled = !!why;
$('btnVsReady').hidden = isHost;
$('btnVsReady').textContent = imReady ? 'Ready (tap to undo)' : "I'm ready";
$('btnVsReady').setAttribute('aria-pressed', imReady ? 'true' : 'false');
$('btnVsReady').classList.toggle('on', imReady);
const mm = $('vsRoomMsg');
mm.textContent = isHost ? why : imReady ? 'Waiting for the host to start.' : 'Press ready when you are.';
mm.className = 'msg';
}
// ---- round over / match over
function entryText(h) {
const r = h.result;
if (r.forfeit) return 'Forfeited';
return r.winner === 'attacker' ? 'Server fell at ' + mmss(r.t) : 'Server held for ' + mmss(r.t);
}
function renderEnd() {
const m = S.vs; if (!m || (m.phase !== 'roundover' && m.phase !== 'matchover')) return;
const me = mySlot(), over = m.phase === 'matchover', c = S.ctrl;
const hist = (m.history || []).slice();
if (m.result && !hist.some((h) => h.round === m.round)) hist.push({ round: m.round, roles: m.roles, result: m.result });
let title, text, color;
if (over) {
const res = matchResult();
title = res === 'win' ? 'You win the match!' : res === 'lose' ? 'You lose the match' : 'A draw';
color = res === 'win' ? 'var(--green)' : res === 'lose' ? 'var(--red)' : 'var(--amber)';
if (m.forfeit !== null && m.forfeit !== undefined) text = m.forfeit === me ? 'You left the match.' : playerName(m.forfeit) + ' left the match. You win by forfeit.';
else text = reasonText(m);
} else {
const won = roundWon(), r = m.result || {};
title = 'Round ' + m.round + ': ' + (won ? 'you won' : 'you lost');
color = won ? 'var(--green)' : 'var(--red)';
text = (r.winner === 'attacker' ? 'The server fell after ' + mmss(r.t) + '.' : 'The server held for the whole ' + mmss(r.t) + '.') + ' Integrity lost: ' + (r.integrityLost || 0) + '. ' +
'Next round you ' + (other(roleOf()) === 'attacker' ? 'attack' : 'defend') + '.';
}
$('vsEndTitle').textContent = title; $('vsEndTitle').style.color = color;
$('vsEndText').textContent = text;
// both rounds side by side
const cols = hist.map((h) => {
const mine = roleCls(h.roles[me]), won = h.result.winner === mine;
return '<div class="vsround"><h4>Round ' + h.round + '</h4>' +
'<div class="vsrow2"><span>You were</span><b class="rolebadge ' + mine + '">' + (mine === 'attacker' ? 'ATTACKER' : 'DEFENDER') + '</b></div>' +
'<div class="vsrow2"><span>Result</span><b>' + esc(entryText(h)) + '</b></div>' +
'<div class="vsrow2"><span>Integrity lost</span><b>' + esc(h.result.integrityLost || 0) + '</b></div>' +
'<div class="vsrow2"><span>Round won by</span><b class="' + (won ? 'good' : 'bad') + '">' + (won ? 'you' : esc(playerName(1 - me))) + '</b></div></div>';
});
if (!over) cols.push('<div class="vsround pending"><h4>Round ' + (m.round + 1) + '</h4><div class="vsrow2"><span>You will</span><b class="rolebadge ' + other(roleOf()) + '">' + (other(roleOf()) === 'attacker' ? 'ATTACK' : 'DEFEND') + '</b></div></div>');
let score = '';
if (over && m.scores && !(m.forfeit !== null && m.forfeit !== undefined)) {
score = '<div class="vsscore"><h4>Who attacked best</h4>' + m.scores.map((s) =>
'<div class="vsrow2"><span>' + esc(s.slot === me ? 'You' : playerName(s.slot)) + '</span><b>' + (s.fellAt !== null && s.fellAt !== undefined ? 'felled the server at ' + mmss(s.fellAt) : 'did not fell it, took off ' + (s.integrityLost || 0)) + '</b></div>').join('') + '</div>';
}
$('vsEndRounds').innerHTML = '<div class="vscols">' + cols.join('') + '</div>' + score;
// buttons and waiting text
const oppHere = c.kind === 'local' || !!(m.bot) || players().some((p) => p.slot !== me && p.online);
$('btnVsNext').hidden = over; $('btnVsRematch').hidden = !over;
$('btnVsNext').disabled = S.sentNext;
$('btnVsRematch').disabled = S.sentRematch || !oppHere;
$('btnVsRematch').textContent = 'Rematch (roles swap)';
const w = $('vsEndWait'); let wt = '';
if (!over && S.sentNext) wt = 'Waiting for the other player' + (m.nextIn ? ' (the next round starts anyway in ' + m.nextIn + ' s)' : '') + '…';
else if (!over && m.next && m.next[1 - me] && c.kind === 'remote' && !m.bot) wt = playerName(1 - me) + ' is ready for the next round.';
else if (over && S.sentRematch) wt = 'Waiting for the other player to accept the rematch…';
else if (over && m.rematch && m.rematch[1 - me] && !S.sentRematch && !m.bot) wt = playerName(1 - me) + ' wants a rematch.';
else if (over && !oppHere) wt = 'The other player has left.';
w.hidden = !wt; w.textContent = wt;
}
function reasonText(m) {
const sc = m.scores; if (!sc) return '';
const a = sc[0], b = sc[1], nm = (s) => (s.slot === mySlot() ? 'you' : playerName(s.slot));
if (a.fellAt !== null && b.fellAt !== null) return a.fellAt === b.fellAt ? 'Both servers fell at the same second.' : 'The faster fall wins: ' + nm(a) + ' ' + mmss(a.fellAt) + ', ' + nm(b) + ' ' + mmss(b.fellAt) + '.';
if (a.fellAt !== null || b.fellAt !== null) { const w = a.fellAt !== null ? a : b; return 'Only ' + nm(w) + ' felled the server (' + mmss(w.fellAt) + ').'; }
if (a.integrityLost === b.integrityLost) return 'Neither server fell, and the same integrity was taken off.';
return 'Neither server fell: the attacker who took off more integrity wins (' + nm(a) + ' ' + (a.integrityLost || 0) + ', ' + nm(b) + ' ' + (b.integrityLost || 0) + ').';
}
// the room code box of the setup dialog is filled by an invite link (?room=ABCD)
function onRoomWait(code) { openSetup(code); }
initDialogs();
return {
get active() { return S.active; }, get role() { return S.role; }, get shopOn() { return S.shopOn; }, get phase() { return S.phase; }, state: S,
attach, tick, tapCell, key, onEvent, leakSfx, isDecoy, minSide, uiState, holdsOverlay, refreshOverlay, openSetup, onRoomWait, renderRoom, renderEnd,
drawShopIcons, castEmp, disarm, msg, say, decoys: S.decoys, REASONS, matchResult,
};
}
NW.Versus = { create, techText, abilityText, toolText };
})(typeof self !== 'undefined' ? self : this);

View file

@ -1,6 +1,6 @@
/* Netwall service worker: network-first so updates always win, cache as an offline fallback (solo play offline). */ /* Netwall service worker: network-first so updates always win, cache as an offline fallback (solo play offline). */
const CACHE = 'netwall-v1'; const CACHE = 'netwall-v1';
const CORE = ['./', 'index.html', 'css/style.css', 'js/sim.js', 'js/audio.js', 'js/controllers.js', 'js/render.js', 'js/main.js', const CORE = ['./', 'index.html', 'css/style.css', 'js/sim.js', 'js/bot.js', 'js/audio.js', 'js/controllers.js', 'js/render.js', 'js/versus.js', 'js/main.js',
'manifest.webmanifest', 'icons/icon.svg', 'icons/icon-192.png', 'assets/music/tracks.json']; 'manifest.webmanifest', 'icons/icon.svg', 'icons/icon-192.png', 'assets/music/tracks.json'];
self.addEventListener('install', (e) => { self.addEventListener('install', (e) => {

View file

@ -23,7 +23,7 @@ const PID_RE = /^[A-Za-z0-9_-]{8,40}$/;
const ROOM_RE = /^[A-Za-z0-9]{4}$/; const ROOM_RE = /^[A-Za-z0-9]{4}$/;
const NAME_STRIP = new RegExp('[\\u0000-\\u001f\\u007f-\\u009f\\u200b-\\u200f\\u2028-\\u202e\\u2066-\\u2069\\ufeff]', 'g'); const NAME_STRIP = new RegExp('[\\u0000-\\u001f\\u007f-\\u009f\\u200b-\\u200f\\u2028-\\u202e\\u2066-\\u2069\\ufeff]', 'g');
// Close codes for a failed join (the 'error' message carries the machine-readable code). // Close codes for a failed join (the 'error' message carries the machine-readable code).
const JOIN_CLOSE = { bad_request: 4400, bad_map: 4400, bad_difficulty: 4400, no_room: 4404, full: 4409, too_many_rooms: 4503 }; const JOIN_CLOSE = { bad_request: 4400, bad_map: 4400, bad_difficulty: 4400, bad_mode: 4400, bad_limit: 4400, bad_rounds: 4400, no_room: 4404, full: 4409, too_many_rooms: 4503 };
const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k); const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
const noop = () => {}; const noop = () => {};
@ -42,6 +42,8 @@ async function createServer(userOpts) {
graceMs: 60000, snapshotHz: 20, maxRooms: 50, graceMs: 60000, snapshotHz: 20, maxRooms: 50,
trustProxy: 'auto', trustedProxies: null, allowedOrigins: [], maxConnPerIp: 40, pingMs: 25000, log: defaultLog, trustProxy: 'auto', trustedProxies: null, allowedOrigins: [], maxConnPerIp: 40, pingMs: 25000, log: defaultLog,
joinTimeoutMs: 10000, // not in the protocol's option list: lets tests shorten the 10 s join window joinTimeoutMs: 10000, // not in the protocol's option list: lets tests shorten the 10 s join window
vsCountdownMs: 3000, // versus: the pause before each round (tests shorten it)
vsNextMs: 30000, // versus: how long a round result waits for everybody's `next` before the next round starts anyway
}; };
for (const k of Object.keys(userOpts || {})) if (userOpts[k] !== undefined) o[k] = userOpts[k]; for (const k of Object.keys(userOpts || {})) if (userOpts[k] !== undefined) o[k] = userOpts[k];
o.trustProxy = parseTrustProxy(o.trustProxy); o.trustProxy = parseTrustProxy(o.trustProxy);
@ -50,7 +52,7 @@ async function createServer(userOpts) {
o.snapshotHz = Math.min(60, Math.max(1, Number(o.snapshotHz) || 20)); o.snapshotHz = Math.min(60, Math.max(1, Number(o.snapshotHz) || 20));
const log = typeof o.log === 'function' ? o.log : noop; const log = typeof o.log === 'function' ? o.log : noop;
const manager = new RoomManager({ maxRooms: o.maxRooms, graceMs: o.graceMs, snapshotHz: o.snapshotHz, log }); const manager = new RoomManager({ maxRooms: o.maxRooms, graceMs: o.graceMs, snapshotHz: o.snapshotHz, log, vsCountdownMs: o.vsCountdownMs, vsNextMs: o.vsNextMs });
const serveStatic = createStaticHandler(o.publicDir); const serveStatic = createStaticHandler(o.publicDir);
const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_PAYLOAD, perMessageDeflate: false }); const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_PAYLOAD, perMessageDeflate: false });
wss.on('error', (err) => log('websocket server error: ' + (err && err.message))); wss.on('error', (err) => log('websocket server error: ' + (err && err.message)));
@ -207,7 +209,20 @@ async function createServer(userOpts) {
if (!TD.isDifficulty(msg.difficulty)) return failJoin(ctx, 'bad_difficulty', 'unknown difficulty'); if (!TD.isDifficulty(msg.difficulty)) return failJoin(ctx, 'bad_difficulty', 'unknown difficulty');
difficulty = msg.difficulty; difficulty = msg.difficulty;
} }
room = manager.create(map, difficulty); // Game mode: only a creating join carries it (like the map). Absent or null is co-op; versus also takes the round limit and the number of rounds.
let vsOpts = null;
if (msg.mode !== undefined && msg.mode !== null) {
if (msg.mode !== 'coop' && msg.mode !== 'versus') return failJoin(ctx, 'bad_mode', 'unknown mode');
if (msg.mode === 'versus') {
vsOpts = { limit: TD.VS.DEFAULT_LIMIT, rounds: TD.VS.ROUNDS };
if (msg.limit !== undefined && msg.limit !== null) {
if (typeof msg.limit !== 'number' || !TD.VS.LIMITS.includes(msg.limit)) return failJoin(ctx, 'bad_limit', 'unknown round limit');
vsOpts.limit = msg.limit;
}
if (msg.rounds !== undefined && msg.rounds !== null && msg.rounds !== TD.VS.ROUNDS) return failJoin(ctx, 'bad_rounds', 'unsupported number of rounds');
}
}
room = manager.create(map, difficulty, vsOpts);
if (!room) return failJoin(ctx, 'too_many_rooms', 'the server has reached its room limit'); if (!room) return failJoin(ctx, 'too_many_rooms', 'the server has reached its room limit');
why = 'created'; why = 'created';
} else { } else {
@ -222,6 +237,7 @@ async function createServer(userOpts) {
if (ctx.joinTimer) { clearTimeout(ctx.joinTimer); ctx.joinTimer = null; } if (ctx.joinTimer) { clearTimeout(ctx.joinTimer); ctx.joinTimer = null; }
send(ctx, room.joinedMsg(r.player, r.resumed)); send(ctx, room.joinedMsg(r.player, r.resumed));
room.broadcastPlayers(ctx); room.broadcastPlayers(ctx);
room.afterJoin(r.player, r.resumed, ctx);
room.log(name + ' ' + (r.resumed ? 'resumed' : (why || 'joined')) + ' as slot ' + r.player.slot + (r.player.host ? ' (host)' : '') + ' from ' + ctx.ip); room.log(name + ' ' + (r.resumed ? 'resumed' : (why || 'joined')) + ' as slot ' + r.player.slot + (r.player.host ? ' (host)' : '') + ' from ' + ctx.ip);
} }

View file

@ -6,6 +6,7 @@
*/ */
const crypto = require('crypto'); const crypto = require('crypto');
const TD = require('../public/js/sim.js'); // fixed path on purpose: independent of publicDir const TD = require('../public/js/sim.js'); // fixed path on purpose: independent of publicDir
const { Versus } = require('./versus');
const CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; const CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
const CMDS = new Set(['place', 'sell', 'upgrade', 'target', 'wave', 'auto', 'continue']); const CMDS = new Set(['place', 'sell', 'upgrade', 'target', 'wave', 'auto', 'continue']);
@ -32,10 +33,16 @@ function sendRaw(conn, str) {
} }
class Room { class Room {
constructor(manager, code, mapId, difficulty) { // `vsOpts` ({ limit, rounds }) makes it a versus room (docs/PROTOCOL.md "Versus"): `this.vsc` then runs the match and every co-op code path
// below that it replaces is guarded by it; without it nothing here changes.
constructor(manager, code, mapId, difficulty, vsOpts) {
this.manager = manager; this.manager = manager;
this.code = code; this.code = code;
this.sim = new TD.Sim({ map: mapId, difficulty }); this.vsc = null;
if (vsOpts) {
this.sim = new TD.Sim({ map: mapId, mode: 'versus', limit: vsOpts.limit }); // the lobby's board; every round gets a fresh sim
this.vsc = new Versus(this, vsOpts);
} else this.sim = new TD.Sim({ map: mapId, difficulty });
this.speed = 1; this.speed = 1;
this.paused = false; this.paused = false;
this.seq = 0; this.seq = 0;
@ -90,14 +97,19 @@ class Room {
} }
joinedMsg(player, resumed) { joinedMsg(player, resumed) {
return { const m = {
t: 'joined', room: this.code, resumed, t: 'joined', room: this.code, resumed,
you: { pid: player.pid, slot: player.slot, host: player.host }, you: { pid: player.pid, slot: player.slot, host: player.host },
players: this.publicPlayers(player), players: this.publicPlayers(player),
state: this.sim.fullState(), snap: this.sim.snapshot(), speed: this.speed, paused: this.paused, state: this.sim.fullState(), snap: this.sim.snapshot(), speed: this.speed, paused: this.paused,
}; };
if (this.vsc) { this.vsc.updateFrozen(); m.vs = this.vsc.msg(); } // (a player who just came back is online: `frozen` must not be stale in what it is told)
return m;
} }
// Called by index.js after `joined` went to the new connection: a versus room tells the others and sends the joiner its private data.
afterJoin(player, resumed, conn) { if (this.vsc) this.vsc.onJoined(player, resumed, conn); }
// Binds `conn` to a slot. Returns { player, resumed } or null when both slots belong to other pids. // Binds `conn` to a slot. Returns { player, resumed } or null when both slots belong to other pids.
join(pid, name, conn) { join(pid, name, conn) {
let p = this.players.find((x) => x && x.pid === pid); let p = this.players.find((x) => x && x.pid === pid);
@ -113,13 +125,14 @@ class Room {
try { old.ws.close(4001, 'replaced by a newer connection'); } catch (e) { /* already closing */ } try { old.ws.close(4001, 'replaced by a newer connection'); } catch (e) { /* already closing */ }
} }
} else { } else {
const slot = this.players.indexOf(null); const slot = this.vsc ? this.vsc.freeSlot() : this.players.indexOf(null);
if (slot < 0) return null; if (slot < 0) return null;
p = { p = {
pid, alias: this.alias(pid), slot, name, host: !this.players.some((x) => x && x.host), pid, alias: this.alias(pid), slot, name, host: !this.players.some((x) => x && x.host),
conn, cursor: null, lastMarkAt: -Infinity, graceTimer: null, conn, cursor: null, lastMarkAt: -Infinity, graceTimer: null,
}; };
this.players[slot] = p; this.players[slot] = p;
if (this.vsc) this.vsc.onSeated(p);
} }
p.cursor = null; p.cursor = null;
this.touchPresence(); this.touchPresence();
@ -142,6 +155,7 @@ class Room {
this.log(p.name + ' (slot ' + p.slot + ') disconnected; holding the slot for ' + this.manager.graceMs + ' ms'); this.log(p.name + ' (slot ' + p.slot + ') disconnected; holding the slot for ' + this.manager.graceMs + ' ms');
p.graceTimer = setTimeout(() => { p.graceTimer = null; this.removePlayer(p, 'grace expired'); }, this.manager.graceMs); p.graceTimer = setTimeout(() => { p.graceTimer = null; this.removePlayer(p, 'grace expired'); }, this.manager.graceMs);
this.broadcastPlayers(); this.broadcastPlayers();
if (this.vsc) this.vsc.onPresence();
} }
// Frees the slot for good, migrates the host, deletes the room when nobody is left. // Frees the slot for good, migrates the host, deletes the room when nobody is left.
@ -160,6 +174,7 @@ class Room {
} }
this.touchPresence(); this.touchPresence();
this.broadcastPlayers(); this.broadcastPlayers();
if (this.vsc) this.vsc.onRemoved(p);
} }
leave(conn) { leave(conn) {
@ -174,15 +189,16 @@ class Room {
handleMessage(p, msg) { handleMessage(p, msg) {
switch (msg.t) { switch (msg.t) {
case 'cmd': return this.handleCmd(p, msg); case 'cmd': return this.handleCmd(p, msg);
case 'ctl': return this.handleCtl(msg); case 'ctl': return this.handleCtl(p, msg);
case 'cursor': return this.handleCursor(p, msg); case 'cursor': return this.handleCursor(p, msg);
case 'mark': return this.handleMark(p, msg); case 'mark': return this.handleMark(p, msg);
case 'rtt': case 'rtt':
if (!finite(msg.ts) && !(typeof msg.ts === 'string' && msg.ts.length <= 32)) return false; if (!finite(msg.ts) && !(typeof msg.ts === 'string' && msg.ts.length <= 32)) return false;
this.send(p, { t: 'rtt', ts: msg.ts }); this.send(p, { t: 'rtt', ts: msg.ts });
return true; return true;
case 'sync': this.send(p, this.stateMsg()); return true; case 'sync': this.send(p, this.stateMsg()); if (this.vsc) this.vsc.sendTo(p); return true;
case 'newgame': return this.handleNewgame(p, msg); case 'newgame': return this.handleNewgame(p, msg);
case 'vs': return this.vsc ? this.vsc.handleMessage(p, msg) : false; // a co-op room has no such message: malformed, as before
default: return false; default: return false;
} }
} }
@ -193,11 +209,14 @@ class Room {
if (finite(msg.x)) out.x = msg.x; if (finite(msg.x)) out.x = msg.x;
if (finite(msg.y)) out.y = msg.y; if (finite(msg.y)) out.y = msg.y;
if (finite(msg.id)) out.id = msg.id; if (finite(msg.id)) out.id = msg.id;
else if (this.vsc && typeof msg.id === 'string' && msg.id.length <= 24) out.id = msg.id; // versus: which tool / ability / tech track
if (this.vsc && finite(msg.tid)) out.tid = msg.tid;
} }
this.send(p, out); this.send(p, out);
} }
handleCmd(p, msg) { handleCmd(p, msg) {
if (this.vsc) return this.vsc.handleCmd(p, msg);
const c = msg.c; const c = msg.c;
if (typeof c !== 'string' || !CMDS.has(c)) return false; if (typeof c !== 'string' || !CMDS.has(c)) return false;
const sim = this.sim; const sim = this.sim;
@ -216,7 +235,8 @@ class Room {
return true; return true;
} }
handleCtl(msg) { handleCtl(p, msg) {
if (this.vsc) return this.vsc.handleCtl(p, msg);
if (msg.c === 'pause' && typeof msg.v === 'boolean') { this.paused = msg.v; return true; } if (msg.c === 'pause' && typeof msg.v === 'boolean') { this.paused = msg.v; return true; }
if (msg.c === 'speed' && (msg.v === 1 || msg.v === 2 || msg.v === 3)) { this.speed = msg.v; return true; } if (msg.c === 'speed' && (msg.v === 1 || msg.v === 2 || msg.v === 3)) { this.speed = msg.v; return true; }
return false; return false;
@ -230,12 +250,14 @@ class Room {
handleCursor(p, msg) { handleCursor(p, msg) {
if (msg.x === null) { p.cursor = null; return true; } if (msg.x === null) { p.cursor = null; return true; }
if (!finite(msg.x) || !finite(msg.y)) return false; if (!finite(msg.x) || !finite(msg.y)) return false;
if (this.vsc) return true; // versus: the opponent does not see where you hover (what you are about to build or target)
p.cursor = this.boardPoint(msg); p.cursor = this.boardPoint(msg);
return true; return true;
} }
handleMark(p, msg) { handleMark(p, msg) {
if (!finite(msg.x) || !finite(msg.y)) return false; if (!finite(msg.x) || !finite(msg.y)) return false;
if (this.vsc) return true; // versus: no map pings to an opponent (valid, ignored)
const now = nowMs(); // monotonic: immune to wall-clock steps const now = nowMs(); // monotonic: immune to wall-clock steps
if (now - p.lastMarkAt < MARK_GAP_MS) return true; // rate limited: dropped silently if (now - p.lastMarkAt < MARK_GAP_MS) return true; // rate limited: dropped silently
p.lastMarkAt = now; p.lastMarkAt = now;
@ -245,6 +267,7 @@ class Room {
} }
handleNewgame(p, msg) { handleNewgame(p, msg) {
if (this.vsc) { this.reject(p, 'newgame', 'versus'); return true; } // a versus room is replayed with { t:'vs', c:'rematch' }
if (!p.host) { this.reject(p, 'newgame', 'not_host'); return true; } if (!p.host) { this.reject(p, 'newgame', 'not_host'); return true; }
const map = msg.map === undefined || msg.map === null ? this.sim.mapId : msg.map; const map = msg.map === undefined || msg.map === null ? this.sim.mapId : msg.map;
if (typeof map !== 'string' || !hasOwn(TD.MAPS, map)) { this.reject(p, 'newgame', 'bad_map'); return true; } if (typeof map !== 'string' || !hasOwn(TD.MAPS, map)) { this.reject(p, 'newgame', 'bad_map'); return true; }
@ -261,6 +284,7 @@ class Room {
// ---------------------------------------------------------------- loop // ---------------------------------------------------------------- loop
// Called every LOOP_MS by the manager with process.hrtime.bigint(). // Called every LOOP_MS by the manager with process.hrtime.bigint().
step(now) { step(now) {
if (this.vsc) { this.vsc.step(now); return; }
const last = this.lastNs; const last = this.lastNs;
this.lastNs = now; this.lastNs = now;
const online = this.onlinePlayers().length > 0; const online = this.onlinePlayers().length > 0;
@ -285,6 +309,10 @@ class Room {
} }
if (!online) { this.nextSnapNs = now; return; } if (!online) { this.nextSnapNs = now; return; }
this.snapIfDue(now);
}
snapIfDue(now) {
if (now >= this.nextSnapNs) { if (now >= this.nextSnapNs) {
this.broadcastSnap(); this.broadcastSnap();
this.nextSnapNs += this.manager.snapPeriodNs; this.nextSnapNs += this.manager.snapPeriodNs;
@ -340,6 +368,9 @@ class RoomManager {
this.graceMs = opts.graceMs; this.graceMs = opts.graceMs;
this.snapPeriodNs = BigInt(Math.max(1, Math.round(1e9 / opts.snapshotHz))); this.snapPeriodNs = BigInt(Math.max(1, Math.round(1e9 / opts.snapshotHz)));
this.log = opts.log; this.log = opts.log;
this.vsCountdownMs = opts.vsCountdownMs === undefined ? 3000 : opts.vsCountdownMs; // versus: the pause before a round
this.vsNextMs = opts.vsNextMs === undefined ? 30000 : opts.vsNextMs; // versus: how long the round result waits for everybody's `next`
this.botSpentNs = 0n; // versus: computer-player time spent in this loop iteration
this.timer = null; this.timer = null;
this.closed = false; this.closed = false;
} }
@ -365,7 +396,7 @@ class RoomManager {
// null when the room limit is reached. A full table first drops a room that nobody is online in (it is only // null when the room limit is reached. A full table first drops a room that nobody is online in (it is only
// being held for its grace period): otherwise one client could fill all slots for a minute at a time by // being held for its grace period): otherwise one client could fill all slots for a minute at a time by
// creating rooms and closing the sockets, which costs nothing and is not limited by any per-IP socket cap. // creating rooms and closing the sockets, which costs nothing and is not limited by any per-IP socket cap.
create(mapId, difficulty) { create(mapId, difficulty, vsOpts) {
if (this.closed) return null; if (this.closed) return null;
if (this.rooms.size >= this.maxRooms) { if (this.rooms.size >= this.maxRooms) {
const victim = this.abandonedRoom(); const victim = this.abandonedRoom();
@ -374,9 +405,9 @@ class RoomManager {
} }
const code = this.newCode(); const code = this.newCode();
if (!code) return null; if (!code) return null;
const room = new Room(this, code, mapId, difficulty); const room = new Room(this, code, mapId, difficulty, vsOpts);
this.rooms.set(code, room); this.rooms.set(code, room);
room.log('created (map ' + mapId + ', ' + room.sim.difficulty + '); ' + this.rooms.size + ' room(s)'); room.log('created (map ' + mapId + ', ' + (vsOpts ? 'versus, ' + vsOpts.limit + ' s' : room.sim.difficulty) + '); ' + this.rooms.size + ' room(s)');
this.startLoop(); this.startLoop();
return room; return room;
} }
@ -400,6 +431,7 @@ class RoomManager {
tick() { tick() {
const now = process.hrtime.bigint(); const now = process.hrtime.bigint();
this.botSpentNs = 0n;
for (const room of Array.from(this.rooms.values())) { for (const room of Array.from(this.rooms.values())) {
try { room.step(now); } catch (err) { room.crash(err); } try { room.step(now); } catch (err) { room.crash(err); }
} }
@ -413,4 +445,6 @@ class RoomManager {
} }
} }
Room.LIMITS = { MAX_CATCHUP_S, STEP_BUDGET_NS, MAX_BUFFERED }; // read by versus.js (which room.js requires, so it cannot require this file)
module.exports = { Room, RoomManager, CODE_ALPHABET, CMDS, MAX_MONSTER_LOAD, MAX_BUFFERED }; module.exports = { Room, RoomManager, CODE_ALPHABET, CMDS, MAX_MONSTER_LOAD, MAX_BUFFERED };

487
server/versus.js Normal file
View file

@ -0,0 +1,487 @@
'use strict';
/*
* Versus rooms (docs/VERSUS.md, docs/PROTOCOL.md "Versus"): the lobby / countdown / round / round-over / match-over state machine, the
* seats and roles, the optional computer seat and the role-private data messages. A Room (room.js) owns one of these when it was
* created with mode 'versus' and calls into it at a handful of hooks; a co-op room has none and never gets here.
*
* Phases: lobby -> countdown -> playing -> roundover -> countdown -> playing -> matchover -> (rematch) countdown ...
* lobby roles / ready / computer seat are being agreed. The sim exists (so a joiner has a board to look at) but NEVER ticks.
* countdown a fresh Sim for the round exists and the players are told; nothing ticks, no command is accepted.
* playing the sim ticks (only while every human seat is online) and the bot thinks. Commands are accepted.
* roundover the round's result is shown; waits for every human's `next` (or vsNextMs).
* matchover both rounds are done (or somebody forfeited); `rematch` starts a new match with the first roles swapped.
* The sim is replaced for every round (a new Sim + a `state` message with newgame:true), so nothing leaks from one round to the next.
*/
const crypto = require('crypto');
const TD = require('../public/js/sim.js');
const NWBot = require('../public/js/bot.js');
const { VS } = TD;
const BOT_NAME = 'Computer';
const BOT_THINK_S = 0.25; // the bot is asked to think at about 4 Hz of game time (it decides about once per second itself)
const BOT_BUDGET_NS = 15000000n; // all the bots on the server together may start thinking only while less than this was spent this loop
const PRIV_NS = 250000000n; // role-private data goes out at 4 Hz
const MAX_KIND_LEN = 24;
const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
const finite = (v) => typeof v === 'number' && Number.isFinite(v);
const opposite = (r) => (r === 'attacker' ? 'defender' : 'attacker');
const swapRoles = (roles) => ({ 0: opposite(roles[0]), 1: opposite(roles[1]) });
const slotOf = (roles, role) => (roles[0] === role ? 0 : 1);
const coin = () => (crypto.randomInt(2) ? 'attacker' : 'defender');
const nowNs = () => process.hrtime.bigint();
// What a client may send as a game command in a versus room. `wave`, `auto` and `continue` are valid messages that the sim refuses with
// 'versus' (so a stray co-op client gets a reject, not a disconnect); everything else is malformed, exactly like in a co-op room.
const VS_CMDS = new Set(['place', 'sell', 'upgrade', 'target', 'tool', 'spawn', 'stage', 'launch', 'tech', 'ability', 'wave', 'auto', 'continue']);
const STRING_ID_CMDS = new Set(['tool', 'ability', 'tech']); // `id` names a tool / ability / tech track here, a tower id elsewhere
const NUMBER_ID_CMDS = new Set(['sell', 'upgrade', 'target']);
// ------------------------------------------------------------------------------------------------------ match rules (pure)
// history entry: { round, roles: {0, 1}, result: { winner, t, integrityLost, attacker: slot, defender: slot, forfeit? } }
function historyEntry(round, roles, result) {
return { round, roles: { 0: roles[0], 1: roles[1] }, result: Object.assign({}, result, { attacker: slotOf(roles, 'attacker'), defender: slotOf(roles, 'defender') }) };
}
// Each player's ATTACKING performance: the time the server fell (null when it did not) and the integrity taken off in total.
// A forfeited round never counts as "the server fell".
function matchScores(history, names) {
return [0, 1].map((slot) => {
let fellAt = null, lost = 0;
for (const h of history) {
if (h.roles[slot] !== 'attacker') continue;
lost += h.result.integrityLost || 0;
if (h.result.winner === 'attacker' && !h.result.forfeit && (fellAt === null || h.result.t < fellAt)) fellAt = h.result.t;
}
return { slot, name: names[slot], fellAt, integrityLost: lost };
});
}
// The match winner's slot, or null for a draw: the faster fall; if only one felled the server, that player; if neither did, the one who took
// off more integrity.
function matchWinner(scores) {
const a = scores[0], b = scores[1];
if (a.fellAt !== null && b.fellAt !== null) return a.fellAt === b.fellAt ? null : a.fellAt < b.fellAt ? a.slot : b.slot;
if (a.fellAt !== null) return a.slot;
if (b.fellAt !== null) return b.slot;
return a.integrityLost === b.integrityLost ? null : a.integrityLost > b.integrityLost ? a.slot : b.slot;
}
class Versus {
constructor(room, opts) {
this.room = room;
this.limit = opts.limit;
this.rounds = opts.rounds;
this.phase = 'lobby';
this.round = 1;
this.roles = { 0: coin(), 1: null }; // roles by seat; the creator's is a coin flip until somebody chooses
this.roles[1] = opposite(this.roles[0]);
this.random = true; // true while the roles are still the coin flip
this.firstRoles = null; // the roles of round 1 of the current match (a rematch swaps them)
this.ready = [false, false];
this.nextVotes = [false, false];
this.rematchVotes = [false, false];
this.bot = null; // { slot, skill }: a computer holds that seat (its role is roles[slot])
this.botCtl = null; // the NWBot of the current round
this.botAcc = 0; this.botNextNs = 0n;
this.history = [];
this.result = null; this.winner = null; this.forfeit = null; this.scores = null;
this.cdLeftMs = 0; this.cdSent = -1;
this.nextLeftMs = 0;
this.nextPrivNs = 0n;
this.frozen = false;
}
get mgr() { return this.room.manager; }
humans() { return this.room.players.filter(Boolean); }
// `gone`: a player that was just removed from the room (its seat is already empty) but still belongs in the result
names(gone) { return [0, 1].map((s) => (this.room.players[s] ? this.room.players[s].name : this.bot && this.bot.slot === s ? BOT_NAME : gone && gone.slot === s ? gone.name : '')); }
seated() { return this.humans().length + (this.bot ? 1 : 0); }
// ---------------------------------------------------------------- what clients are told
readyMap() { return { 0: this.bot && this.bot.slot === 0 ? true : this.ready[0], 1: this.bot && this.bot.slot === 1 ? true : this.ready[1] }; }
msg() {
const m = {
t: 'vs', phase: this.phase, round: this.round, rounds: this.rounds,
roles: { 0: this.roles[0], 1: this.roles[1] }, random: this.random,
bot: this.bot ? { slot: this.bot.slot, role: this.roles[this.bot.slot], skill: this.bot.skill, name: BOT_NAME } : null,
limit: this.limit, ready: this.readyMap(), frozen: this.frozen,
};
if (this.phase === 'countdown') m.countdown = Math.max(0, Math.ceil(this.cdLeftMs / 1000));
if (this.phase === 'roundover') { m.next = { 0: this.isVoted(this.nextVotes, 0), 1: this.isVoted(this.nextVotes, 1) }; m.nextIn = Math.max(0, Math.ceil(this.nextLeftMs / 1000)); }
if (this.phase === 'roundover' || this.phase === 'matchover') m.result = this.result;
if (this.history.length) m.history = this.history; // the finished rounds of this match (also while round 2 is played: a reconnecting client can show round 1)
if (this.phase === 'matchover') {
m.scores = this.scores; m.winner = this.winner; m.forfeit = this.forfeit;
m.rematch = { 0: this.isVoted(this.rematchVotes, 0), 1: this.isVoted(this.rematchVotes, 1) };
}
return m;
}
isVoted(votes, slot) { return this.bot && this.bot.slot === slot ? true : votes[slot]; }
broadcastVs() { this.room.broadcast(this.msg()); }
// Role-private data for ONE human: only what the sim says that role may see, addressed by the seat's current role.
sendPriv(p) {
if (!p || !p.conn || this.phase === 'lobby') return;
const role = this.roles[p.slot];
const ps = this.room.sim.privateState(role);
if (ps) this.room.send(p, Object.assign({ t: 'priv', role }, ps));
}
sendPrivAll() { for (const p of this.humans()) this.sendPriv(p); }
// sync / a (re)joining client: the whole picture for one player
sendTo(p) { this.room.send(p, this.msg()); this.sendPriv(p); }
// ---------------------------------------------------------------- seats (hooks called by Room)
// The seat a joining pid gets, or -1. A computer holds its seat during a match; in the lobby the next human takes it over.
freeSlot() {
const pl = this.room.players;
for (let s = 0; s < 2; s++) if (!pl[s] && !(this.bot && this.bot.slot === s)) return s;
if (this.phase === 'lobby' && this.bot && !pl[this.bot.slot]) return this.bot.slot;
return -1;
}
onSeated(p) { // a NEW player took a seat (not a reconnect)
if (this.bot && this.bot.slot === p.slot) this.bot = null;
this.ready = [false, false]; this.rematchVotes[p.slot] = false; this.nextVotes[p.slot] = false;
}
// after `joined` was sent to `ctx`: everybody else hears the new picture, the joiner gets its private data
onJoined(p, resumed, exceptConn) {
this.updateFrozen();
this.room.broadcast(this.msg(), exceptConn);
this.sendPriv(p);
this.checkProgress(); // (a vote that was only waiting for this player to be back)
}
onPresence() { this.updateFrozen(true); }
updateFrozen(announce) {
const humans = this.humans();
const f = (this.phase === 'playing' || this.phase === 'countdown' || this.phase === 'roundover') && humans.some((h) => !h.conn);
if (f !== this.frozen) { this.frozen = f; if (announce) this.broadcastVs(); }
return f;
}
// A human left for good (deliberate leave, or the grace period ran out).
onRemoved(p) {
const slot = p.slot;
this.ready = [false, false]; this.nextVotes[slot] = false; this.rematchVotes[slot] = false;
switch (this.phase) {
case 'playing': this.forfeitMatch(p, true); break;
case 'countdown':
if (this.round === 1) this.toLobby(); else this.forfeitMatch(p, false);
break;
case 'roundover': this.forfeitMatch(p, false); break;
default: this.updateFrozen(); this.broadcastVs(); // lobby, matchover: the picture just changes
}
this.updateFrozen();
}
// ---------------------------------------------------------------- the lobby messages ({ t:'vs', c, v })
// Returns false only for a malformed message (the caller counts those); refusals are rejects.
handleMessage(p, msg) {
switch (msg.c) {
case 'role':
if (msg.v !== 'attacker' && msg.v !== 'defender' && msg.v !== 'random') return false;
return this.doRole(p, msg.v);
case 'ready':
if (typeof msg.v !== 'boolean') return false;
return this.doReady(p, msg.v);
case 'bot': {
if (msg.v !== null && msg.v !== 'attacker' && msg.v !== 'defender') return false;
if (msg.skill !== undefined && msg.skill !== null && !(finite(msg.skill) && msg.skill >= 0 && msg.skill <= 1)) return false;
return this.doBot(p, msg.v, msg.skill);
}
case 'start': return this.doStart(p);
case 'next': return this.doNext(p);
case 'rematch': return this.doRematch(p);
default: return false;
}
}
rej(p, c, reason) { this.room.reject(p, c, reason); return true; }
doRole(p, v) {
if (this.phase !== 'lobby') return this.rej(p, 'role', 'phase');
if (v === 'random') { this.roles[p.slot] = coin(); this.random = true; } else { this.roles[p.slot] = v; this.random = false; }
this.roles[1 - p.slot] = opposite(this.roles[p.slot]);
this.ready = [false, false]; // everybody agrees to the roles they actually get
this.broadcastVs();
return true;
}
doReady(p, v) {
if (this.phase !== 'lobby') return this.rej(p, 'ready', 'phase');
this.ready[p.slot] = v;
this.broadcastVs();
return true;
}
doBot(p, v, skill) {
if (!p.host) return this.rej(p, 'bot', 'not_host');
if (this.phase !== 'lobby') return this.rej(p, 'bot', 'phase');
if (v === null) {
if (this.bot) { this.bot = null; this.ready = [false, false]; this.broadcastVs(); }
return true;
}
const humans = this.humans();
if (humans.length !== 1 || humans[0] !== p) return this.rej(p, 'bot', 'full'); // the computer takes the EMPTY seat
const sk = skill === undefined || skill === null ? (this.bot ? this.bot.skill : 1) : skill;
this.bot = { slot: 1 - p.slot, skill: sk };
this.roles[this.bot.slot] = v; this.roles[p.slot] = opposite(v); this.random = false;
this.ready = [false, false];
this.broadcastVs();
return true;
}
doStart(p) {
if (!p.host) return this.rej(p, 'start', 'not_host');
if (this.phase !== 'lobby') return this.rej(p, 'start', 'phase');
if (this.seated() < 2) return this.rej(p, 'start', 'no_opponent');
const humans = this.humans();
if (humans.some((h) => !h.conn)) return this.rej(p, 'start', 'offline');
if (humans.some((h) => h !== p && !this.ready[h.slot])) return this.rej(p, 'start', 'not_ready');
this.beginMatch();
return true;
}
doNext(p) {
if (this.phase !== 'roundover') return this.rej(p, 'next', 'phase');
this.nextVotes[p.slot] = true;
this.broadcastVs();
this.checkProgress();
return true;
}
doRematch(p) {
if (this.phase !== 'matchover') return this.rej(p, 'rematch', 'phase');
if (this.seated() < 2) return this.rej(p, 'rematch', 'no_opponent');
this.rematchVotes[p.slot] = true;
this.broadcastVs();
this.checkProgress();
return true;
}
// Votes that completed: roundover -> the next round, matchover -> a new match. Needs every human online (an absent one is waited for).
checkProgress() {
const humans = this.humans();
if (!humans.length || humans.some((h) => !h.conn)) return;
if (this.phase === 'roundover' && humans.every((h) => this.nextVotes[h.slot])) this.nextRound();
else if (this.phase === 'matchover' && this.seated() === 2 && humans.every((h) => this.rematchVotes[h.slot])) this.rematch();
}
// ---------------------------------------------------------------- rounds
beginMatch() {
this.round = 1; this.history = []; this.result = null; this.winner = null; this.forfeit = null; this.scores = null;
this.firstRoles = { 0: this.roles[0], 1: this.roles[1] };
this.startRound();
}
nextRound() {
this.round++;
this.roles = swapRoles(this.roles);
this.startRound();
}
rematch() {
this.roles = swapRoles(this.firstRoles);
this.random = false;
this.rematchVotes = [false, false];
this.beginMatch();
}
// A fresh Sim for the round, a bot for the computer seat, and the countdown. Clients get a new `state` (newgame:true) and the vs picture.
startRound() {
const room = this.room;
room.sim = new TD.Sim({ map: room.sim.mapId, mode: 'versus', limit: this.limit });
room.lastSentRev = room.sim.rev;
room.acc = 0;
this.botAcc = 0; this.botNextNs = 0n;
this.botCtl = null;
if (this.bot) {
try {
this.botCtl = NWBot.create(this.guardedSim(room.sim), this.roles[this.bot.slot], { seed: crypto.randomInt(1, 0x7fffffff), skill: this.bot.skill, by: this.bot.slot });
} catch (e) { room.log('could not create the computer player: ' + (e && e.stack || e)); }
}
this.nextVotes = [false, false];
this.rematchVotes = [false, false];
this.result = null;
this.phase = 'countdown';
this.cdLeftMs = this.mgr.vsCountdownMs; this.cdSent = -1;
this.updateFrozen();
room.broadcast(room.stateMsg({ newgame: true }));
this.broadcastVs();
this.sendPrivAll();
this.cdSent = Math.ceil(this.cdLeftMs / 1000);
room.log('versus round ' + this.round + '/' + this.rounds + ' (' + this.limit + ' s): countdown; roles ' + this.roles[0] + '/' + this.roles[1] + (this.bot ? ', computer is seat ' + this.bot.slot : ''));
}
beginPlay() {
this.phase = 'playing';
this.room.acc = 0; this.botAcc = 0;
this.broadcastVs();
this.sendPrivAll();
}
// The sim says the round is over (integrity gone / time up).
endRound() {
const sim = this.room.sim, res = sim.vs.result;
this.finishRound({ winner: res.winner, t: res.t, integrityLost: res.integrityLost });
}
finishRound(result) {
this.botCtl = null;
const entry = historyEntry(this.round, this.roles, result);
this.result = entry.result;
this.history.push(entry);
this.room.log('versus round ' + this.round + ' over: the ' + result.winner + ' wins at ' + result.t + ' s, integrity lost ' + result.integrityLost);
if (this.round < this.rounds) {
this.phase = 'roundover';
this.nextVotes = [false, false];
this.nextLeftMs = this.mgr.vsNextMs;
} else {
this.phase = 'matchover';
this.scores = matchScores(this.history, this.names());
const w = matchWinner(this.scores);
this.winner = w;
this.forfeit = null;
this.rematchVotes = [false, false];
}
this.updateFrozen();
this.broadcastVs();
this.sendPrivAll();
}
// A human is gone for good while a match was on: the one who stays wins it. `inRound`: the round was being played (its result is the
// forfeit); otherwise it is between rounds / in the countdown.
forfeitMatch(gone, inRound) {
const sim = this.room.sim, leaver = gone.slot, stay = 1 - leaver;
this.botCtl = null;
if (inRound) {
sim.vsEnd(this.roles[stay]); // the sim's own end of round: state 'over', the round event
const res = sim.vs.result;
const entry = historyEntry(this.round, this.roles, { winner: res.winner, t: res.t, integrityLost: res.integrityLost, forfeit: true });
this.history.push(entry); this.result = entry.result;
}
this.phase = 'matchover';
this.scores = matchScores(this.history, this.names(gone));
this.winner = stay; this.forfeit = leaver;
this.room.log('versus match forfeited by seat ' + leaver + (inRound ? ' during round ' + this.round : ' between rounds'));
this.rematchVotes = [false, false];
this.updateFrozen();
this.broadcastVs();
this.sendPrivAll();
}
toLobby() {
this.botCtl = null;
this.room.log('versus: back to the lobby (a player left before the first round began)');
this.phase = 'lobby'; this.round = 1; this.history = []; this.result = null; this.winner = null; this.forfeit = null; this.scores = null;
this.room.acc = 0;
this.updateFrozen();
this.broadcastVs();
}
// ---------------------------------------------------------------- game commands
// One door for every command that reaches the sim in a versus room, humans and the computer alike: the phase gate, the role of the
// seat for THIS round (never taken from the message), the seat as `by`.
applyCmd(slot, cmd) {
if (this.phase !== 'playing') return { ok: false, reason: this.phase === 'roundover' || this.phase === 'matchover' ? 'over' : 'phase' };
if (this.frozen) return { ok: false, reason: 'frozen' };
try { return this.room.sim.cmd(Object.assign({}, cmd, { role: this.roles[slot], by: slot })); } catch (e) {
this.room.log('sim.cmd threw: ' + (e && e.stack || e));
return { ok: false, reason: 'error' };
}
}
// Returns false when the message is malformed.
handleCmd(p, msg) {
const c = msg.c;
if (typeof c !== 'string' || !VS_CMDS.has(c)) return false;
for (const k of ['lv', 'n']) if (msg[k] !== undefined && msg[k] !== null && !Number.isInteger(msg[k])) return false;
for (const k of ['gate', 'tid']) if (msg[k] !== undefined && msg[k] !== null && !Number.isInteger(msg[k])) return false;
if (msg.kind !== undefined && (typeof msg.kind !== 'string' || msg.kind.length > MAX_KIND_LEN)) return false;
if (msg.id !== undefined) {
if (STRING_ID_CMDS.has(c) ? (typeof msg.id !== 'string' || msg.id.length > MAX_KIND_LEN) : (NUMBER_ID_CMDS.has(c) && !finite(msg.id))) return false;
}
// Whitelisted fields only; `role` and `by` come from the seat, never from the client.
const cmd = { c, type: msg.type, x: msg.x, y: msg.y, id: msg.id, mode: msg.mode, v: msg.v, lv: msg.lv, n: msg.n, kind: msg.kind, gate: msg.gate, tid: msg.tid };
const r = this.applyCmd(p.slot, cmd);
if (!r || !r.ok) this.room.reject(p, c, (r && r.reason) || 'error', msg);
return true;
}
// pause / speed exist in co-op only (either would be exploitable here): a well-formed one is refused, a malformed one is malformed.
handleCtl(p, msg) {
if ((msg.c === 'pause' && typeof msg.v === 'boolean') || (msg.c === 'speed' && (msg.v === 1 || msg.v === 2 || msg.v === 3))) {
this.room.reject(p, msg.c, 'versus');
return true;
}
return false;
}
// ---------------------------------------------------------------- the loop
// The computer sees the sim through this: reads and queries go straight through, `cmd` goes through applyCmd (the same door as a human's,
// with the computer seat's role), writes are dropped.
guardedSim(sim) {
const self = this, bound = new Map();
return new Proxy(sim, {
get(target, key) {
if (key === 'cmd') return (c) => (self.room.sim === sim && self.bot ? self.applyCmd(self.bot.slot, c) : { ok: false, reason: 'over' });
const v = target[key];
if (typeof v !== 'function') return v;
let f = bound.get(key);
if (!f) { f = v.bind(target); bound.set(key, f); }
return f;
},
set() { return true; },
});
}
thinkBot(now) {
if (!this.botCtl || this.phase !== 'playing' || this.botAcc < BOT_THINK_S) return;
const mgr = this.mgr;
if (mgr.botSpentNs >= BOT_BUDGET_NS || now < this.botNextNs) return; // over budget: it will think a little later with the time it saved up
const dt = this.botAcc; this.botAcc = 0;
const t0 = nowNs();
try { this.botCtl.think(dt); } catch (e) {
this.room.log('the computer player failed and is switched off: ' + (e && e.stack || e));
this.botCtl = null;
}
const spent = nowNs() - t0;
mgr.botSpentNs += spent;
this.botNextNs = now + spent * 3n; // a heavy decision buys a quiet period: at most ~25% of the loop
}
// Called by Room.step in place of the co-op step.
step(now) {
const room = this.room, L = room.constructor.LIMITS;
const last = room.lastNs;
room.lastNs = now;
const humans = this.humans();
if (!humans.some((h) => h.conn)) { room.acc = 0; room.nextSnapNs = now; return; }
const dt = last === null ? 0 : Math.min(L.MAX_CATCHUP_S, Number(now - last) / 1e9);
const frozen = this.updateFrozen(true);
if (frozen) room.acc = 0; // a human seat is offline: the round waits (the grace period decides)
else if (this.phase === 'countdown') {
this.cdLeftMs -= dt * 1000;
const sec = Math.max(0, Math.ceil(this.cdLeftMs / 1000));
if (this.cdLeftMs <= 0) this.beginPlay();
else if (sec !== this.cdSent) { this.cdSent = sec; this.broadcastVs(); }
} else if (this.phase === 'roundover') {
this.nextLeftMs -= dt * 1000;
if (this.nextLeftMs <= 0) this.nextRound();
} else if (this.phase === 'playing') {
const sim = room.sim;
room.acc += dt;
let n = 0, ticked = 0;
const t0 = nowNs();
while (room.acc >= TD.STEP && sim.state === 'playing') {
sim.tick(TD.STEP); room.acc -= TD.STEP; ticked++;
if ((++n & 7) === 0 && nowNs() - t0 > L.STEP_BUDGET_NS) { room.acc = Math.min(room.acc, TD.STEP); break; }
}
this.botAcc += ticked * TD.STEP;
this.thinkBot(now);
if (sim.state !== 'playing') this.endRound();
} else room.acc = 0;
room.snapIfDue(now);
if ((this.phase === 'countdown' || this.phase === 'playing') && now >= this.nextPrivNs) { this.sendPrivAll(); this.nextPrivNs = now + PRIV_NS; }
}
}
module.exports = { Versus, VS_CMDS, historyEntry, matchScores, matchWinner, swapRoles, opposite, BOT_NAME, BOT_THINK_S, BOT_BUDGET_NS };

View file

@ -0,0 +1,433 @@
'use strict';
/*
* Versus in the controllers: RemoteController speaks the versus protocol (vs / priv messages, the create-join fields, no pause / speed) and
* LocalController plays a whole match against NWBot in the browser, with the SAME vs / priv messages the server sends. controllers.js runs in a
* vm context with a fake WebSocket and a manual clock, like test/controllers.test.js.
*/
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const vm = require('node:vm');
const WebSocket = require('ws');
const TD = require('../public/js/sim.js');
const V = require('../server/versus');
const { createServer } = require('../server');
const JS = path.join(__dirname, '..', 'public', 'js');
const SRC = fs.readFileSync(path.join(JS, 'controllers.js'), 'utf8');
const BOT = fs.readFileSync(path.join(JS, 'bot.js'), 'utf8');
const { VS } = TD;
function harness({ bot = true } = {}) {
const H = { now: 1000, timers: [], seq: 0, sockets: [] };
const timer = (fn, ms, repeat) => { const t = { id: ++H.seq, at: H.now + ms, fn, ms, repeat }; H.timers.push(t); return t.id; };
class FakeWS {
constructor(url) { this.url = url; this.readyState = 0; this.sent = []; H.sockets.push(this); }
send(s) { this.sent.push(JSON.parse(s)); }
close() { this.readyState = 2; }
open() { this.readyState = 1; if (this.onopen) this.onopen(); }
recv(o) { if (this.onmessage) this.onmessage({ data: JSON.stringify(o) }); }
}
const sandbox = {
TD, console, URL, WebSocket: FakeWS,
document: { hidden: false, addEventListener() {}, removeEventListener() {} },
performance: { now: () => H.now },
location: { href: 'http://localhost/index.html' },
addEventListener() {}, removeEventListener() {},
setTimeout: (fn, ms) => timer(fn, ms, false), clearTimeout: (id) => { H.timers = H.timers.filter((t) => t.id !== id); },
setInterval: (fn, ms) => timer(fn, ms, true), clearInterval: (id) => { H.timers = H.timers.filter((t) => t.id !== id); },
};
sandbox.self = sandbox;
vm.runInNewContext(SRC, sandbox, { filename: 'controllers.js' });
if (bot) vm.runInNewContext(BOT, sandbox, { filename: 'bot.js' });
H.NW = sandbox.NW;
H.sandbox = sandbox;
H.advance = (ms) => { // runs the timers that fall due, in order, moving the clock along
const end = H.now + ms;
for (;;) {
const due = H.timers.filter((t) => t.at <= end).sort((a, b) => a.at - b.at || a.id - b.id)[0];
if (!due) break;
H.now = Math.max(H.now, due.at);
if (due.repeat) due.at += due.ms; else H.timers = H.timers.filter((t) => t !== due);
due.fn();
}
H.now = end;
};
return H;
}
// Objects built inside the controllers' vm context have another Object.prototype: compare them as plain JSON (assert/strict is prototype-strict).
const plain = (v) => JSON.parse(JSON.stringify(v));
// the messages a versus server would send for a sim
function joinedVs(sim, vs, extra) {
return Object.assign({
t: 'joined', room: 'ABCD', resumed: false, you: { pid: 'pidpidpid1', slot: 1, host: false },
players: [{ pid: 'pidpidpid1', slot: 1, name: 'Bob', host: false, online: true }, { pid: 'aliasaliasalias', slot: 0, name: 'Alice', host: true, online: true }],
state: sim.fullState(), snap: sim.snapshot(), speed: 1, paused: false, vs,
}, extra);
}
const lobbyVs = (extra) => Object.assign({ t: 'vs', phase: 'lobby', round: 1, rounds: 2, roles: { 0: 'attacker', 1: 'defender' }, random: false, bot: null, limit: 720, ready: { 0: false, 1: false }, frozen: false }, extra);
let seq = 0;
const snapMsg = (sim, tw) => { const m = Object.assign({ t: 'snap', seq: ++seq }, sim.snapshot(), { ev: [], cur: [], pa: 0, sp: 1 }); if (tw) m.tw = sim.towerList(); return m; };
// ================================================================== RemoteController
test('remote versus: a creating join says so; a co-op or joining one does not', () => {
let H = harness();
let rc = new H.NW.RemoteController({ pid: 'pidpidpid1', name: 'A', url: 'ws://x/ws', mode: 'versus', limit: 480, map: 'twin' });
rc.connect(); H.sockets[0].open();
assert.deepEqual(H.sockets[0].sent[0], { t: 'join', pid: 'pidpidpid1', name: 'A', map: 'twin', difficulty: 'normal', mode: 'versus', limit: 480 });
assert.equal(rc.mode, 'versus');
assert.equal(rc.view.mode, 'versus');
H = harness();
rc = new H.NW.RemoteController({ pid: 'pidpidpid1', name: 'A', url: 'ws://x/ws', map: 'twin' });
rc.connect(); H.sockets[0].open();
assert.deepEqual(H.sockets[0].sent[0], { t: 'join', pid: 'pidpidpid1', name: 'A', map: 'twin', difficulty: 'normal' }, 'co-op: exactly the old message');
assert.equal(rc.mode, 'coop');
H = harness();
rc = new H.NW.RemoteController({ pid: 'pidpidpid1', name: 'A', url: 'ws://x/ws', mode: 'versus', limit: 480, room: 'ABCD' });
rc.connect(); H.sockets[0].open();
assert.deepEqual(H.sockets[0].sent[0], { t: 'join', pid: 'pidpidpid1', name: 'A', room: 'ABCD' }, 'a joiner takes the room\'s settings');
});
test('remote versus: joined carries the match picture; vs and priv messages are stored and announced; role follows the seat', () => {
const H = harness();
const sim = new TD.Sim({ map: 'open', mode: 'versus', limit: 480 });
const rc = new H.NW.RemoteController({ pid: 'pidpidpid1', name: 'Bob', room: 'ABCD', url: 'ws://x/ws' });
const log = [];
rc.on('joined', () => log.push('joined')); rc.on('vs', (m) => log.push('vs:' + m.phase)); rc.on('priv', (m) => log.push('priv:' + m.role));
rc.connect(); const ws = H.sockets[0]; ws.open();
assert.equal(rc.role, null);
ws.recv(joinedVs(sim, lobbyVs()));
assert.deepEqual(log, ['joined', 'vs:lobby']);
assert.equal(rc.mode, 'versus');
assert.equal(rc.limit, 480);
assert.equal(rc.view.mode, 'versus');
assert.equal(rc.vs.phase, 'lobby');
assert.equal(rc.role, 'defender', 'seat 1 is the defender in this picture');
ws.recv(lobbyVs({ phase: 'countdown', countdown: 3, roles: { 0: 'defender', 1: 'attacker' } }));
assert.equal(rc.role, 'attacker');
assert.equal(rc.vs.countdown, 3);
ws.recv({ t: 'priv', role: 'attacker', credits: 150, income: 4, tech: {}, staged: [], cd: {}, active: { surge: 0, ddos: 0 } });
assert.equal(rc.priv.role, 'attacker');
assert.equal(rc.priv.credits, 150);
assert.deepEqual(log, ['joined', 'vs:lobby', 'vs:countdown', 'priv:attacker']);
});
test('remote versus: the shared round block and the EMP field reach the view', () => {
const H = harness();
const sim = new TD.Sim({ map: 'open', mode: 'versus', limit: 480 });
sim.cmd({ c: 'place', type: 'filter', x: 6, y: 6, role: 'defender', by: 0 });
const rc = new H.NW.RemoteController({ pid: 'pidpidpid1', name: 'Bob', room: 'ABCD', url: 'ws://x/ws' });
rc.connect(); const ws = H.sockets[0]; ws.open();
ws.recv(joinedVs(sim, lobbyVs()));
sim.cmd({ c: 'stage', kind: 'trojan', n: 2, role: 'attacker', by: 1 });
sim.cmd({ c: 'ability', id: 'emp', tid: sim.towers[0].id, role: 'attacker', by: 1 });
for (let i = 0; i < 30; i++) sim.tick(TD.STEP);
ws.recv(snapMsg(sim));
H.advance(500); rc.update(H.now);
assert.deepEqual(Object.keys(rc.view.vs).sort(), ['lim', 'st', 't']);
assert.equal(rc.view.vs.lim, 480);
assert.equal(rc.view.vs.st, 2);
assert.ok(rc.view.vs.t > 0.4);
assert.equal(rc.view.towers.length, 1);
assert.ok(rc.view.towers[0].empT > 5 && rc.view.towers[0].empT <= 6, 'seconds of EMP left: ' + rc.view.towers[0].empT);
// a co-op controller's towers and view carry none of it
const H2 = harness(), s2 = new TD.Sim({ map: 'open' });
const rc2 = new H2.NW.RemoteController({ pid: 'pidpidpid1', name: 'Bob', room: 'ABCD', url: 'ws://x/ws' });
rc2.connect(); H2.sockets[0].open();
H2.sockets[0].recv({ t: 'joined', room: 'ABCD', resumed: false, you: { pid: 'pidpidpid1', slot: 1, host: false }, players: [], state: s2.fullState(), snap: s2.snapshot(), speed: 1, paused: false });
H2.advance(500); rc2.update(H2.now);
assert.equal(rc2.mode, 'coop');
assert.equal(rc2.view.vs, null);
assert.equal(rc2.vs, null);
});
test('remote versus: commands carry no role, the lobby has methods, pause / speed are not even sent', () => {
const H = harness();
const sim = new TD.Sim({ map: 'open', mode: 'versus', limit: 480 });
const rc = new H.NW.RemoteController({ pid: 'pidpidpid1', name: 'Bob', room: 'ABCD', url: 'ws://x/ws' });
rc.connect(); const ws = H.sockets[0]; ws.open();
ws.recv(joinedVs(sim, lobbyVs()));
const sent = () => ws.sent.slice(1);
rc.send({ c: 'spawn', kind: 'ping', n: 3, role: 'attacker', by: 0 });
rc.send({ c: 'tool', id: 'scan', x: 5, y: 6 });
assert.deepEqual(sent(), [{ t: 'cmd', c: 'spawn', kind: 'ping', n: 3 }, { t: 'cmd', c: 'tool', id: 'scan', x: 5, y: 6 }]);
rc.ctl('pause', true); rc.ctl('speed', 2);
assert.equal(sent().length, 2, 'versus: no pause / speed messages');
rc.vsRole('random'); rc.vsReady(true); rc.vsBot('attacker', 0.5); rc.vsBot(null); rc.vsStart(); rc.vsNext(); rc.vsRematch();
assert.deepEqual(sent().slice(2), [
{ t: 'vs', c: 'role', v: 'random' }, { t: 'vs', c: 'ready', v: true }, { t: 'vs', c: 'bot', v: 'attacker', skill: 0.5 }, { t: 'vs', c: 'bot', v: null },
{ t: 'vs', c: 'start' }, { t: 'vs', c: 'next' }, { t: 'vs', c: 'rematch' },
]);
// co-op still sends them
const H2 = harness(), s2 = new TD.Sim({ map: 'open' });
const rc2 = new H2.NW.RemoteController({ pid: 'pidpidpid1', name: 'Bob', room: 'ABCD', url: 'ws://x/ws' });
rc2.connect(); H2.sockets[0].open();
H2.sockets[0].recv({ t: 'joined', room: 'ABCD', resumed: false, you: { pid: 'pidpidpid1', slot: 1, host: false }, players: [], state: s2.fullState(), snap: s2.snapshot(), speed: 1, paused: false });
rc2.ctl('pause', true);
assert.deepEqual(H2.sockets[0].sent.slice(1), [{ t: 'ctl', c: 'pause', v: true }]);
});
test('remote versus: the new join errors have readable messages', () => {
const H = harness();
const rc = new H.NW.RemoteController({ pid: 'pidpidpid1', name: 'A', url: 'ws://x/ws', mode: 'versus' });
const fatal = [];
rc.on('fatal', (f) => fatal.push(f));
rc.connect(); H.sockets[0].open();
H.sockets[0].recv({ t: 'error', code: 'bad_limit', msg: 'x' });
assert.equal(fatal[0].code, 'bad_limit');
assert.match(fatal[0].msg, /round length/);
});
// ================================================================== LocalController
// runs the controller's clock `seconds` forward in 50 ms frames
function run(H, ctrl, seconds, until) {
for (let i = 0; i < Math.round(seconds * 20); i++) {
H.now += 50;
ctrl.update(H.now);
if (until && until()) return true;
}
return !until;
}
const localOpts = (o) => Object.assign({ map: 'open', mode: 'versus', role: 'attacker', countdownMs: 1000, seed: 7 }, o);
test('local versus: needs the computer player script, with a clear message', () => {
const H = harness({ bot: false });
assert.throws(() => new H.NW.LocalController(localOpts()), /bot\.js/);
// a normal solo game never needs it
assert.doesNotThrow(() => new H.NW.LocalController({ map: 'open' }));
assert.equal(new H.NW.LocalController({ map: 'open' }).mode, 'solo');
});
test('local versus: starts in a countdown, nothing is accepted until the round starts, then the human plays its role against the computer', () => {
const H = harness();
const c = new H.NW.LocalController(localOpts({ role: 'attacker' }));
const log = [];
c.on('vs', (m) => log.push(m.phase + (m.countdown !== undefined ? ':' + m.countdown : ''))); c.on('reject', (r) => log.push('reject:' + r.reason));
assert.equal(c.kind, 'local');
assert.equal(c.mode, 'versus');
assert.equal(c.vs.phase, 'countdown');
assert.equal(c.vs.round, 1);
assert.equal(c.role, 'attacker');
assert.deepEqual(plain(c.vs.bot), { slot: 1, role: 'defender', skill: 1, name: 'Computer' });
assert.equal(c.priv.role, 'attacker');
assert.equal(c.priv.credits, VS.ATT_CREDITS);
assert.equal(c.view.mode, 'versus');
assert.deepEqual(Object.keys(c.view.vs).sort(), ['lim', 'st', 't']);
// countdown: the sim does not move; commands are refused
assert.equal(c.send({ c: 'spawn', kind: 'ping' }).reason, 'phase');
run(H, c, 0.5);
assert.equal(c.sim.time, 0);
assert.deepEqual(log.slice(0, 1), ['reject:phase']);
run(H, c, 1);
assert.equal(c.vs.phase, 'playing');
assert.ok(c.sim.time > 0);
// the human attacks: spawn works, place is across the role line, pause / speed do nothing
c.sim.vs.credits = 500;
const r = c.send({ c: 'spawn', kind: 'ping', n: 2 });
assert.equal(r.ok, true);
assert.equal(c.priv.credits, 480, 'the private data is refreshed at once');
assert.equal(c.send({ c: 'place', type: 'filter', x: 3, y: 3 }).reason, 'role');
assert.equal(c.send({ c: 'tool', id: 'scan', x: 3, y: 3 }).reason, 'role');
c.ctl('pause', true); c.ctl('speed', 3);
assert.equal(c.paused, false); assert.equal(c.speed, 1);
const t0 = c.sim.time;
run(H, c, 2);
assert.ok(c.sim.time > t0 + 1.5, 'not paused');
assert.ok(c.view.monsters.length >= 1);
// the computer defender builds on its own
run(H, c, 6);
assert.ok(c.sim.towers.length >= 1, 'the computer defends: ' + c.sim.towers.length);
assert.ok(c.sim.towers.every((t) => t.owner === 1), 'its towers are owned by seat 1');
// `by` is always the human's seat 0: a forged one changes nothing
assert.equal(c.send({ c: 'launch', by: 5, role: 'defender' }).reason, 'empty');
assert.ok(c.priv.cd);
// lobby messages mean nothing locally
for (const m of ['role', 'ready', 'bot', 'start', 'next', 'rematch']) assert.equal(c.vsSend(m, 'x').ok, false, m);
});
test('local versus: as the defender the human builds with the tools, and the computer attacks', () => {
const H = harness();
const c = new H.NW.LocalController(localOpts({ role: 'defender' }));
assert.equal(c.role, 'defender');
assert.equal(c.vs.bot.role, 'attacker');
assert.deepEqual(Object.keys(c.priv).sort(), ['cd', 'role', 't']);
run(H, c, 1.2);
assert.equal(c.vs.phase, 'playing');
const r = c.send({ c: 'place', type: 'filter', x: 10, y: 6 });
assert.equal(r.ok, true, JSON.stringify(r));
assert.equal(c.sim.towers[0].owner, 0);
assert.equal(c.send({ c: 'spawn', kind: 'ping' }).reason, 'role');
assert.equal(c.send({ c: 'wave' }).reason, 'versus');
assert.equal(c.send({ c: 'tool', id: 'scan', x: 5, y: 5 }).ok, true);
assert.equal(c.send({ c: 'tool', id: 'scan', x: 5, y: 5 }).reason, 'cooldown');
assert.ok(c.priv.cd.scan > 0);
c.sim.vs.credits = 3000; // (a purse that makes the computer attacker act at once)
run(H, c, 8);
assert.ok(c.sim.vs.stats.unitsSpent > 0, 'the computer attacker buys units');
assert.ok(c.view.monsters.length > 0);
});
test('local versus: a whole match: round over, next, swapped roles, match over with scores and a winner, rematch swaps again', () => {
const H = harness();
const c = new H.NW.LocalController(localOpts({ role: 'attacker' }));
const phases = [c.vs.phase + c.vs.round]; // (the constructor already announced the first countdown)
c.on('vs', (m) => { if (phases[phases.length - 1] !== m.phase + m.round) phases.push(m.phase + m.round); });
run(H, c, 1.2);
assert.equal(c.vs.phase, 'playing');
// the server falls (the human attacks): round over
c.sim.lives = 0;
run(H, c, 0.5);
assert.equal(c.vs.phase, 'roundover');
assert.equal(c.vs.result.winner, 'attacker');
assert.equal(c.vs.result.attacker, 0);
assert.equal(c.vs.result.defender, 1);
assert.equal(c.vs.history.length, 1);
assert.deepEqual(plain(c.vs.next), { 0: false, 1: true });
assert.equal(c.send({ c: 'spawn', kind: 'ping' }).reason, 'over');
const frozenAt = c.sim.time;
run(H, c, 1);
assert.equal(c.sim.time, frozenAt, 'a finished round does not run on');
// next: round 2, roles swapped, a fresh sim, a countdown
const sim1 = c.sim;
assert.equal(c.vsNext().ok, true);
assert.equal(c.vs.phase, 'countdown');
assert.equal(c.vs.round, 2);
assert.equal(c.role, 'defender');
assert.equal(c.vs.bot.role, 'attacker');
assert.notEqual(c.sim, sim1);
assert.equal(c.priv.role, 'defender');
run(H, c, 1.2);
assert.equal(c.vs.phase, 'playing');
assert.equal(c.vs.history.length, 1, 'round 1 stays on the picture while round 2 is played');
// the clock runs out: the defender (the human) wins round 2; the match is over, the computer's attack felled the server first
c.sim.time = c.sim.vs.limit - 0.05;
run(H, c, 0.5);
assert.equal(c.vs.phase, 'matchover');
assert.equal(c.vs.result.winner, 'defender');
assert.equal(c.vs.history.length, 2);
assert.equal(c.vs.scores.length, 2);
assert.equal(c.vs.scores[0].name, 'You');
assert.equal(c.vs.scores[1].name, 'Computer');
assert.equal(typeof c.vs.scores[0].fellAt, 'number');
assert.equal(c.vs.scores[1].fellAt, null);
assert.equal(c.vs.winner, 0);
assert.equal(c.vs.forfeit, null);
assert.deepEqual(phases, ['countdown1', 'playing1', 'roundover1', 'countdown2', 'playing2', 'matchover2']);
// rematch: a new match, the first round's roles swapped (I attacked first, so now I defend first)
assert.equal(c.vsRematch().ok, true);
assert.equal(c.vs.phase, 'countdown');
assert.equal(c.vs.round, 1);
assert.equal(c.role, 'defender');
assert.equal(c.vs.history, undefined, 'a new match has no finished rounds');
// newGame restarts a match at once, in any phase
run(H, c, 1.2);
c.newGame();
assert.equal(c.vs.phase, 'countdown');
assert.equal(c.role, 'attacker', 'swapped again');
assert.equal(c.vs.round, 1);
});
test('local versus: a random role is one of the two; a bot that throws is dropped and the match goes on', () => {
const H = harness();
const roles = new Set();
for (let i = 0; i < 40; i++) roles.add(new H.NW.LocalController(localOpts({ role: 'random' })).role);
assert.deepEqual([...roles].sort(), ['attacker', 'defender'], 'both come up');
const c = new H.NW.LocalController(localOpts());
run(H, c, 1.2);
c.bot = { think() { throw new Error('boom'); } };
const err = console.error; console.error = () => {};
try { run(H, c, 1); } finally { console.error = err; }
assert.equal(c.bot, null);
assert.equal(c.vs.phase, 'playing');
});
// ================================================================== the same language as the server
test('the match rules in controllers.js are the server\'s rules: the same winner and scores for 400 random match histories', () => {
const H = harness();
let a = 12345;
const rnd = () => { a = (a + 0x6D2B79F5) >>> 0; let t = Math.imul(a ^ (a >>> 15), a | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
const names = ['A', 'B'];
for (let i = 0; i < 400; i++) {
const first = rnd() < 0.5 ? { 0: 'attacker', 1: 'defender' } : { 0: 'defender', 1: 'attacker' };
const rounds = 1 + Math.floor(rnd() * 3);
const history = [];
let roles = first;
for (let r = 1; r <= rounds; r++) {
const fell = rnd() < 0.55;
const res = { winner: fell ? 'attacker' : 'defender', t: fell ? Math.round(rnd() * 5) * 60 : 720, integrityLost: Math.floor(rnd() * 4) * 5, forfeit: rnd() < 0.1 ? true : undefined };
if (res.forfeit === undefined) delete res.forfeit;
history.push(V.historyEntry(r, roles, res));
roles = V.swapRoles(roles);
}
const server = V.matchScores(history, names);
const client = H.NW.matchScores(history, names);
assert.deepEqual(JSON.parse(JSON.stringify(client)), server);
assert.equal(H.NW.matchWinner(client), V.matchWinner(server));
}
});
test('the local match speaks the same vs messages as the server: the same fields in every phase', async () => {
// what the real server sends for a human against a computer, phase by phase
const srv = await createServer({ port: 0, host: '127.0.0.1', log: () => {}, vsCountdownMs: 100, pingMs: 0 });
const msgs = [];
const privs = [];
const ws = new WebSocket('ws://127.0.0.1:' + srv.port + '/ws');
try {
await new Promise((res, rej) => { ws.on('open', res); ws.on('error', rej); });
ws.on('message', (d) => { const m = JSON.parse(d.toString()); if (m.t === 'vs') msgs.push(m); else if (m.t === 'joined') msgs.push(m.vs); else if (m.t === 'priv') privs.push(m); }); // (the joiner's first picture is `joined.vs`)
const wait = async (fn, what) => { const end = Date.now() + 5000; while (!fn()) { if (Date.now() > end) throw new Error('timed out: ' + what); await new Promise((r) => setTimeout(r, 10)); } };
ws.send(JSON.stringify({ t: 'join', pid: 'localparity01', name: 'Me', mode: 'versus' }));
await wait(() => msgs.length, 'joined');
ws.send(JSON.stringify({ t: 'vs', c: 'role', v: 'attacker' }));
ws.send(JSON.stringify({ t: 'vs', c: 'bot', v: 'defender' }));
await wait(() => msgs.some((m) => m.bot), 'bot');
ws.send(JSON.stringify({ t: 'vs', c: 'start' }));
await wait(() => msgs.some((m) => m.phase === 'playing'), 'playing');
const room = [...srv.rooms.values()][0];
room.sim.lives = 0;
await wait(() => msgs.some((m) => m.phase === 'roundover'), 'roundover');
ws.send(JSON.stringify({ t: 'vs', c: 'next' }));
await wait(() => msgs.some((m) => m.phase === 'playing' && m.round === 2), 'round 2');
room.sim.time = room.sim.vs.limit - 0.05;
await wait(() => msgs.some((m) => m.phase === 'matchover'), 'matchover');
const byPhase = (arr, ph) => arr.find((m) => m.phase === ph);
const keys = (m) => Object.keys(m).filter((k) => k !== 'nextIn').sort(); // `nextIn` (the server's auto-advance timer) has no local counterpart
const H = harness();
const c = new H.NW.LocalController(localOpts({ role: 'attacker', countdownMs: 1000 }));
const local = [];
c.on('vs', (m) => local.push(m));
local.push(c.vs);
run(H, c, 1.2);
c.sim.lives = 0; run(H, c, 0.3);
c.vsNext(); run(H, c, 1.2);
c.sim.time = c.sim.vs.limit - 0.05; run(H, c, 0.3);
for (const ph of ['countdown', 'playing', 'roundover', 'matchover']) {
assert.deepEqual(keys(byPhase(local, ph)), keys(byPhase(msgs, ph)), 'the vs message of phase ' + ph);
assert.deepEqual(Object.keys(byPhase(local, ph).bot).sort(), Object.keys(byPhase(msgs, ph).bot).sort(), 'bot of ' + ph);
assert.deepEqual(Object.keys(byPhase(local, ph).roles), Object.keys(byPhase(msgs, ph).roles));
}
const lm = byPhase(local, 'matchover'), sm = byPhase(msgs, 'matchover');
assert.deepEqual(Object.keys(lm.result).sort(), Object.keys(sm.result).sort());
assert.deepEqual(Object.keys(lm.scores[0]).sort(), Object.keys(sm.scores[0]).sort());
assert.deepEqual(Object.keys(lm.history[0]).sort(), Object.keys(sm.history[0]).sort());
// and the private data
const pa = privs.find((p) => p.role === 'defender');
assert.ok(pa, 'the server sent the human defender its private data');
const ld = new H.NW.LocalController(localOpts({ role: 'defender' }));
assert.deepEqual(Object.keys(ld.priv).sort(), Object.keys(pa).sort());
const la = new H.NW.LocalController(localOpts({ role: 'attacker' }));
assert.deepEqual(Object.keys(la.priv).sort(), Object.keys(privs.find((p) => p.role === 'attacker')).sort());
} finally {
try { ws.terminate(); } catch (e) { /* gone */ }
await srv.close();
}
});

1097
test/server-versus.test.js Normal file

File diff suppressed because it is too large Load diff

1188
test/sim-versus.test.js Normal file

File diff suppressed because it is too large Load diff

159
tools/versus.js Normal file
View file

@ -0,0 +1,159 @@
#!/usr/bin/env node
'use strict';
/*
* NETWALL versus balance runner - plays bot-vs-bot ROUNDS (public/js/bot.js: the attacker bot against the defender bot, each driven only
* through sim.cmd like a human) and prints who won, how fast the server fell and what each side spent. It is a DEV TOOL (not a test) for
* tuning the VS table at the top of public/js/sim.js; the numbers it prints move when that table moves.
*
* node tools/versus.js --maps open,twin --limit 600 --seeds 6 [--attacker-skill 1 --defender-skill 1]
* node tools/versus.js --maps all --seeds 4 --json out.json --detail (every map, raw rows, one line per round)
*
* --maps comma list of map ids, or "all" (default open,twin,hub)
* --limit the round timer in sim seconds (default 600)
* --seeds N N rounds per map, seeds --seed-start .. +N-1 (each seed gives both bots a different personality) (default 6)
* --attacker-skill / --defender-skill 0..1, how well each bot plays (default 1)
* --jobs N parallel child processes (default: all cores)
* --json FILE write the raw rows --detail print one line per round --verbose progress on stderr
*
* As a module: const { playRound } = require('./tools/versus'); playRound({ map, limit, seed, attackerSkill, defenderSkill }) -> one row.
*/
const path = require('path');
const os = require('os');
const SIM_PATH = path.join(__dirname, '..', 'public', 'js', 'sim.js');
const BOT_PATH = path.join(__dirname, '..', 'public', 'js', 'bot.js');
function playRound(o) {
const TD = require(SIM_PATH), Bot = require(BOT_PATH);
const map = o.map || 'open', limit = o.limit || 600, seed = o.seed === undefined ? 1 : o.seed;
const sim = new TD.Sim({ map, mode: 'versus', limit, events: false });
const refusals = {}; // every refusal by "role:command:reason" (a healthy bot has none but wall / turret site clashes)
const send = sim.cmd.bind(sim);
sim.cmd = (c) => { const r = send(c); if (!r.ok) { const k = c.role + ':' + c.c + ':' + r.reason; refusals[k] = (refusals[k] || 0) + 1; } return r; };
const att = Bot.create(sim, 'attacker', { seed, skill: o.attackerSkill === undefined ? 1 : o.attackerSkill, by: 1 });
const def = Bot.create(sim, 'defender', { seed, skill: o.defenderSkill === undefined ? 1 : o.defenderSkill, by: 0 });
const t0 = Date.now();
let ticks = 0, peakAlive = 0;
const hard = (limit + 5) * 60;
while (sim.state === 'playing' && ticks++ < hard) {
def.think(TD.STEP); att.think(TD.STEP);
sim.tick(TD.STEP);
if (ticks % 60 === 0 && sim.monsters.length > peakAlive) peakAlive = sim.monsters.length;
}
const v = sim.vs, st = v.stats, mix = {};
let invested = 0;
for (const t of sim.towers) { invested += t.spent; if (t.type !== 'wall') mix[t.type] = (mix[t.type] || 0) + 1; }
const res = v.result || { winner: 'none', t: Math.round(sim.time), integrityLost: v.lost };
return {
map, seed, limit, winner: res.winner, t: res.t, integrityLost: res.integrityLost, maxLives: sim.maxLives,
unitsSpawned: st.spawned, creditsSpent: Math.round(st.unitsSpent + st.techSpent + st.abilitySpent), unitsSpent: st.unitsSpent, techSpent: st.techSpent,
abilitySpent: st.abilitySpent, creditsEarned: Math.round(st.earned), toolSpent: st.toolSpent, kills: st.kills, leaked: st.leaked,
towers: mix, walls: sim.towers.filter((t) => t.type === 'wall').length, defenderInvested: invested, goldEnd: sim.gold, peakAlive,
tech: sim.privateState('attacker').tech, refusals, wallMs: Date.now() - t0,
};
}
// ---------------------------------------------------------------------- CLI
function parseArgs(argv) {
const a = { maps: ['open', 'twin', 'hub'], limit: 600, seeds: 6, seedStart: 1, attackerSkill: 1, defenderSkill: 1, jobs: Math.max(1, os.cpus().length), json: null, detail: false, verbose: false };
for (let i = 2; i < argv.length; i++) {
const k = argv[i], next = () => argv[++i];
if (k === '--maps') { const v = next(); a.maps = v === 'all' ? require(SIM_PATH).MAP_ORDER.slice() : v.split(','); }
else if (k === '--limit') a.limit = +next();
else if (k === '--seeds') a.seeds = +next();
else if (k === '--seed-start') a.seedStart = +next();
else if (k === '--attacker-skill') a.attackerSkill = +next();
else if (k === '--defender-skill') a.defenderSkill = +next();
else if (k === '--jobs') a.jobs = +next();
else if (k === '--json') a.json = next();
else if (k === '--detail') a.detail = true;
else if (k === '--verbose') a.verbose = true;
else if (k === '--worker') a.worker = true;
else if (k === '--help' || k === '-h') { console.log(require('fs').readFileSync(__filename, 'utf8').split('*/')[0].replace(/^[^]*?\/\*/, '')); process.exit(0); }
else { console.error('unknown option ' + k); process.exit(2); }
}
return a;
}
const mean = (xs) => (xs.length ? xs.reduce((s, v) => s + v, 0) / xs.length : 0);
const pad = (v, n) => String(v).padStart(n);
const padr = (v, n) => String(v).padEnd(n);
const pct = (n, d) => (d ? Math.round(100 * n / d) + '%' : '-');
function table(rows, label) {
const att = rows.filter((r) => r.winner === 'attacker'), def = rows.filter((r) => r.winner === 'defender');
const fell = att.map((r) => r.t).sort((p, q) => p - q), med = fell.length ? fell[Math.floor(fell.length / 2)] : 0;
return padr(label, 13) + pad(rows.length, 6) + pad(pct(att.length, rows.length), 8) + pad(pct(def.length, rows.length), 8)
+ pad(fell.length ? mean(fell).toFixed(0) + 's' : '-', 8) + pad(fell.length ? med.toFixed(0) + 's' : '-', 8)
+ pad(mean(rows.map((r) => r.integrityLost)).toFixed(1), 8) + pad(Math.round(mean(rows.map((r) => r.unitsSpawned))), 8)
+ pad(Math.round(mean(rows.map((r) => r.creditsSpent))), 8) + pad(Math.round(mean(rows.map((r) => r.creditsEarned))), 8)
+ pad(Math.round(mean(rows.map((r) => r.kills))), 7) + pad(Math.round(mean(rows.map((r) => r.defenderInvested))), 8)
+ pad(mean(rows.map((r) => Object.keys(r.towers).reduce((s, k) => s + r.towers[k], 0))).toFixed(1), 7) + pad(Math.round(mean(rows.map((r) => r.wallMs))) + 'ms', 8);
}
function printTables(rows, a) {
console.log('\nversus bots: attacker skill ' + a.attackerSkill + ' vs defender skill ' + a.defenderSkill + ', round limit ' + a.limit + ' s, ' + a.seeds + ' seeds per map');
console.log(padr('map', 13) + pad('rounds', 6) + pad('att win', 8) + pad('def win', 8) + pad('fall avg', 8) + pad('fall med', 8) + pad('int lost', 8) + pad('units', 8) + pad('att cr', 8) + pad('earned', 8) + pad('kills', 7) + pad('def inv', 8) + pad('towers', 7) + pad('cpu', 8));
for (const map of a.maps) { const rs = rows.filter((r) => r.map === map); if (rs.length) console.log(table(rs, map)); }
if (a.maps.length > 1) console.log(table(rows, 'ALL MAPS'));
const mix = {}, tech = {};
for (const r of rows) {
for (const k of Object.keys(r.towers)) mix[k] = (mix[k] || 0) + r.towers[k] / rows.length;
for (const k of Object.keys(r.tech)) tech[k] = (tech[k] || 0) + r.tech[k] / rows.length;
}
console.log('\naverage final tower mix: ' + Object.keys(mix).map((k) => k + ' ' + mix[k].toFixed(1)).join(' '));
console.log('average attacker tech: ' + Object.keys(tech).map((k) => k + ' ' + tech[k].toFixed(1)).join(' '));
console.log('average spend (attacker): units ' + Math.round(mean(rows.map((r) => r.unitsSpent))) + ' tech ' + Math.round(mean(rows.map((r) => r.techSpent))) + ' abilities ' + Math.round(mean(rows.map((r) => r.abilitySpent)))
+ ' (defender): towers+walls ' + Math.round(mean(rows.map((r) => r.defenderInvested))) + ' tools ' + Math.round(mean(rows.map((r) => r.toolSpent))));
const ref = {};
for (const r of rows) for (const k of Object.keys(r.refusals)) ref[k] = (ref[k] || 0) + r.refusals[k];
const keys = Object.keys(ref).sort();
console.log('refused commands (all rounds): ' + (keys.length ? keys.map((k) => k + ' x' + ref[k]).join(' ') : 'none'));
const bad = keys.filter((k) => /:(role|bad_[a-z]+|over|max|cooldown|credits|cap|empty)$/.test(k));
if (bad.length) console.log('WARNING: a bot sent commands a human UI would not have allowed: ' + bad.join(', '));
const stuck = rows.filter((r) => r.winner === 'none');
if (stuck.length) console.log('WARNING: ' + stuck.length + ' round(s) hit the tick guard without a result');
}
function printDetail(rows) {
console.log('\nmap seed winner t lost units spent earned kills leaked defender mix');
for (const r of rows) console.log(padr(r.map, 12) + pad(r.seed, 5) + pad(r.winner, 9) + pad(Math.round(r.t), 6) + pad(r.integrityLost, 5) + pad(r.unitsSpawned, 6) + pad(r.creditsSpent, 6) + pad(r.creditsEarned, 7) + pad(r.kills, 6) + pad(r.leaked, 7) + ' ' + JSON.stringify(r.towers) + ' walls ' + r.walls);
}
function main() {
const a = parseArgs(process.argv);
const jobs = [];
for (const map of a.maps) for (let s = 0; s < a.seeds; s++) jobs.push({ map, limit: a.limit, seed: a.seedStart + s, attackerSkill: a.attackerSkill, defenderSkill: a.defenderSkill });
const { fork } = require('child_process');
const rows = [];
let next = 0, running = 0;
const t0 = Date.now();
const startOne = () => {
if (next >= jobs.length) return;
const job = jobs[next++];
running++;
const child = fork(__filename, ['--worker'], { stdio: ['ignore', 'inherit', 'inherit', 'ipc'] });
child.on('message', (m) => {
rows.push(m);
if (a.verbose) process.stderr.write('[' + rows.length + '/' + jobs.length + '] ' + m.map + ' s' + m.seed + ' ' + m.winner + ' t=' + Math.round(m.t) + ' ' + m.wallMs + 'ms\n');
child.kill();
});
child.on('exit', () => { running--; if (next < jobs.length) startOne(); else if (!running) finish(); });
child.send(job);
};
const finish = () => {
rows.sort((p, q) => (p.map + String(1000 + p.seed)).localeCompare(q.map + String(1000 + q.seed)));
if (a.json) require('fs').writeFileSync(a.json, JSON.stringify(rows));
printTables(rows, a);
if (a.detail) printDetail(rows);
console.log('\n(' + jobs.length + ' rounds, ' + ((Date.now() - t0) / 1000).toFixed(1) + ' s wall clock, ' + a.jobs + ' jobs)');
};
for (let i = 0; i < Math.min(a.jobs, jobs.length); i++) startOne();
}
if (require.main === module) {
if (process.argv.includes('--worker')) process.on('message', (job) => process.send(playRound(job)));
else main();
}
module.exports = { playRound, parseArgs };