Phone UI and touch precision overhaul, proxy fixes, Orbital Uplink, four new maps

Phone panels (reviewed + QA'd, matrix of 22 layouts with real taps/bounding boxes):
- selected-tower action bar over the board (Upgrade/Sell/Target/close), info panel
  updated in place so taps are never lost, scrollable palette for 7+ towers,
  overlays with pinned footers (Help "Got it", Play solo, Join always visible),
  tappable room chip to invite, reduced-motion/contrast/forced-colors fixes,
  paused state, partner cursor labels, bigger level pips and owner flags
- touch input rewritten around "pointerdown commits nothing": pinch never builds,
  10px tap slop, palm-proof pinch, long-press pings with any tool armed, nudge
  arrows for precise placement, hotkey repeat guard, proportional wheel zoom
- new e2e: select/sell, info-panel stability, UI states, touch precision;
  camera unit tests

Proxy/server (reproduced against real nginx 1.26 with NPM v2.16 config):
- Origin check works when the proxy drops a non-default port, TRUSTED_PROXIES for
  proxies on global IPv6/CGNAT addresses, service worker no longer serves nginx's
  502 page, DEPLOY.md corrected (NPM default read timeout is 90 s, Advanced-tab
  limits, path-prefix, cookie size, per-IP cap behaviour)

Content:
- Orbital Uplink: 4-level endgame tower (450 + 500/800/1200 credits): piercing
  armour-ignoring beam, blast and lingering slow, ground+air, range 11-14;
  glyph, beam effect, sound, help text, unit tests
- Maps: The Canyon, Archipelago, Fortress, Pinwheel (7 maps total)

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-10 18:03:24 +00:00
parent dad0382e10
commit a5bd09d505
22 changed files with 2423 additions and 405 deletions

View file

@ -31,19 +31,50 @@ room and send the invite link (or the 4-letter code) to a friend.
Solo only: you can also just open `public/index.html` in a browser (the built-in synth music plays; your own tracks Solo only: you can also just open `public/index.html` in a browser (the built-in synth music plays; your own tracks
need the server, because browsers block loading the track list from a `file://` page). need the server, because browsers block loading the track list from a `file://` page).
Environment variables: `PORT` (8080), `HOST` (`::`, dual-stack IPv4 + IPv6), `TRUST_PROXY`, `ALLOWED_ORIGINS`, Environment variables: `PORT` (8080), `HOST` (`::`, dual-stack IPv4 + IPv6), `TRUST_PROXY`, `TRUSTED_PROXIES`,
`MAX_CONN_PER_IP`, `GRACE_MS`. Full reference and troubleshooting: [docs/DEPLOY.md](docs/DEPLOY.md). `ALLOWED_ORIGINS`, `MAX_CONN_PER_IP`, `GRACE_MS`. Full reference and troubleshooting: [docs/DEPLOY.md](docs/DEPLOY.md).
## Setup guide: Debian 13 LXC behind nginx Proxy Manager ## Setup guide: Debian 13 LXC behind nginx Proxy Manager
The game is one small Node process (static files + a WebSocket at `/ws`), so the proxy only has to forward HTTP and The game is one small Node process (static files + a WebSocket at `/ws`), so the proxy only has to forward HTTP and
WebSockets. Nothing is stored on disk; a restart ends running games. WebSockets. Nothing is stored on disk; a restart ends running games.
What was tested and what was not: the proxy side was run against a real nginx 1.26.3 loaded with the configuration that
nginx Proxy Manager (NPM) v2.16.0 generates, not against the NPM application itself, Let's Encrypt, a Proxmox LXC or a
phone. The details and the observations behind every statement below are in [docs/DEPLOY.md](docs/DEPLOY.md).
**You need first**
* A Debian 13 LXC (any Linux with Node 18+ works) with an IP address that NPM can reach, for example `192.168.1.50`
(`ip -br a` inside the container shows it).
* NPM already running, and a DNS name for the game (here `game.example.com`) that points at it. NPM's Let's Encrypt
request needs the name to resolve to your public address and ports 80 and 443 forwarded to NPM; that part is NPM's
own setup, see its documentation.
### 1. Install it in the LXC (as root) ### 1. Install it in the LXC (as root)
```bash ```bash
apt update && apt install -y nodejs npm git # Debian 13 ships Node 20, which is plenty (18+ works) apt update && apt install -y nodejs npm git rsync # Debian 13 ships Node 20, which is plenty (18+ works)
```
Get the code into `/opt/netwall`, either **(a)** copied from your own computer (no keys needed on the LXC; run this in
the repository folder; `rsync` is needed on both sides):
```bash
rsync -a --exclude node_modules --exclude test --exclude .git ./ root@192.168.1.50:/opt/netwall/
```
or **(b)** cloned inside the LXC. That only works if the LXC may read the repository: for a private one create a key in
the LXC (`ssh-keygen -t ed25519`) and add the public key (`~/.ssh/id_ed25519.pub`) to the repository as a read-only
deploy key on your git server first (not tested here):
```bash
git clone ssh://forgejo@int.git.vanvikinternet.no/jvanvik/towerdef.git /opt/netwall git clone ssh://forgejo@int.git.vanvikinternet.no/jvanvik/towerdef.git /opt/netwall
```
Then, in the LXC:
```bash
cd /opt/netwall && npm install --omit=dev # only "ws" cd /opt/netwall && npm install --omit=dev # only "ws"
useradd --system --home-dir /opt/netwall --shell /usr/sbin/nologin netwall useradd --system --home-dir /opt/netwall --shell /usr/sbin/nologin netwall
@ -56,28 +87,46 @@ journalctl -u netwall -f # live log
``` ```
The service listens on `[::]:8080` (dual stack) and runs as the unprivileged `netwall` user. Change `PORT`, `HOST`, The service listens on `[::]:8080` (dual stack) and runs as the unprivileged `netwall` user. Change `PORT`, `HOST`,
`TRUST_PROXY` or `ALLOWED_ORIGINS` in the unit's `Environment=` lines (or `systemctl edit netwall`) and `TRUST_PROXY`, `TRUSTED_PROXIES` or `ALLOWED_ORIGINS` in the unit's `Environment=` lines (or `systemctl edit netwall`) and
`systemctl restart netwall`. If the unit fails with a sandboxing error inside an unprivileged Proxmox container, `systemctl restart netwall`. If the unit fails with a sandboxing error inside an unprivileged Proxmox container,
comment out the line it names (see the notes in `deploy/netwall.service`). comment out the line it names (see the notes in `deploy/netwall.service`). Before going on, check from the NPM host that
it can reach the game: `curl http://192.168.1.50:8080/healthz` must print `ok`.
### 2. Add a Proxy Host in nginx Proxy Manager ### 2. Add a Proxy Host in nginx Proxy Manager
**Hosts > Proxy Hosts > Add Proxy Host** **Hosts > Proxy Hosts > Add Proxy Host** (labels as in NPM v2.16.0)
| Tab / field | Value | | Tab / field | Value |
|---|---| |---|---|
| Details: Domain Names | `game.example.com` (your name for it) | | Details: Domain Names | `game.example.com` (your name for it) |
| Details: Scheme | `http` | | Details: Scheme | `http` |
| Details: Forward Hostname / IP | the LXC's IP address | | Details: Forward Hostname / IP | the LXC's IP address (`192.168.1.50`), not `127.0.0.1` |
| Details: Forward Port | `8080` | | Details: Forward Port | `8080` |
| Details: Cache Assets | **off** | | Details: Cache Assets | **off** |
| Details: **Websockets Support** | **on** (without it the page loads but co-op cannot connect) | | Details: **Websockets Support** | **on** (without it the page loads but co-op cannot connect: HTTP 426 on `/ws`) |
| Custom Locations | leave empty |
| SSL: Certificate | Request a new SSL Certificate (Let's Encrypt), **Force SSL** on, **HTTP/2** on | | SSL: Certificate | Request a new SSL Certificate (Let's Encrypt), **Force SSL** on, **HTTP/2** on |
| Advanced (optional) | `proxy_read_timeout 3600s;` and `proxy_send_timeout 3600s;` for very long idle games | | Advanced (the gear icon) | nothing needed (NPM's default 90 s timeouts are fine: a joined game streams data all the time) |
NPM passes the original `Host` header through, which is what the server's WebSocket origin check expects, so no On the standard ports (80/443) that is all: NPM sends the public name as `Host`, which is what the server's WebSocket
extra configuration is needed. If the server log ever shows `refused websocket ... does not match Host` (HTTP 403 on origin check expects. **If you publish NPM on another port** (for example `https://game.example.com:8443`): NPM drops the
the upgrade), set `ALLOWED_ORIGINS=https://game.example.com` in the unit and restart. port from `Host`; the server accepts that from a proxy on a private address. If co-op still answers 403 (the log says
`refused websocket ... Origin "https://game.example.com:8443" does not match Host`), the proxy reaches the game from a
non-private address (global IPv6, Tailscale): set `TRUSTED_PROXIES=<that address>`, or
`ALLOWED_ORIGINS=https://game.example.com:8443` (**with the port**) in the unit and restart. The Advanced tab cannot
add `X-Forwarded-Host` (NPM ignores it there), so do not follow advice that says it can.
**If something does not work.** The lobby only ever says "Could not reach the game server."; the real reason is the
HTTP status of the `/ws` request in the browser's developer tools (Network or Console) and the server log
(`journalctl -u netwall -f`):
| Status of `/ws` | Meaning |
|---|---|
| 426 | Websockets Support is off in the Proxy Host |
| 403 | Origin check, see the paragraph above and `docs/DEPLOY.md` section 9 |
| 429 | too many sockets from one address; usually the proxy is not recognised as a proxy (`TRUSTED_PROXIES`) |
| 400 `Request Header Or Cookie Too Large` | big cookies from another app on the same domain; Advanced box: `large_client_header_buffers 4 16k;` |
| 502 | NPM cannot reach `192.168.1.50:8080`: service down, wrong IP or port, or a firewall |
### 3. IPv6 (optional) ### 3. IPv6 (optional)
@ -98,35 +147,38 @@ Lock the LXC down so that only the proxy can reach port 8080 (firewall example i
### 5. Update ### 5. Update
```bash If you cloned it: `cd /opt/netwall && git pull && npm install --omit=dev && systemctl restart netwall`. If you copied it
cd /opt/netwall && git pull && npm install --omit=dev && systemctl restart netwall with rsync: run the same `rsync` again, then `cd /opt/netwall && npm install --omit=dev && systemctl restart netwall`.
```
Running games end with the restart (players see the room is gone and can create a new one). Running games end with the restart (players see the room is gone and can create a new one).
Under a path prefix such as `https://example.com/netwall/`, the proxy must strip the prefix; see section 7 of Under a path prefix such as `https://example.com/netwall/`, the proxy must strip the prefix; see section 7 of
[docs/DEPLOY.md](docs/DEPLOY.md). A dedicated sub-domain is simpler. [docs/DEPLOY.md](docs/DEPLOY.md) (in NPM: a Custom Location `/netwall/` with Forward Hostname `192.168.1.50/`, both with
the trailing slash). A dedicated sub-domain is simpler.
## How to play ## How to play
| | | | | |
|---|---| |---|---|
| **Goal** | Survive 30 waves (then keep going in endless mode). Every packet that reaches the server costs integrity. | | **Goal** | Survive 30 waves (then keep going in endless mode) on one of seven maps. Every packet that reaches the server costs integrity. |
| **Firewall** (5) | A wall. Packets path-find around it; the route preview shows how much longer it makes their trip. | | **Firewall** (5) | A wall. Packets path-find around it; the route preview shows how much longer it makes their trip. |
| **Packet Filter** | Fast and cheap. Weak against armour. | | **Packet Filter** | Fast and cheap. Weak against armour. |
| **IDS Sniper** | Long range, hits hard, slow. The answer to armour and bosses. | | **IDS Sniper** | Long range, hits hard, slow. The answer to armour and bosses. |
| **Flood Mortar** | Splash damage on ground swarms. Cannot hit flyers. | | **Flood Mortar** | Splash damage on ground swarms. Cannot hit flyers. |
| **Rate Limiter** | Slows everything in range. Rootkits resist it. | | **Rate Limiter** | Slows everything in range. Rootkits resist it. |
| **Router Arc** | Chain lightning between nearby packets. | | **Router Arc** | Chain lightning between nearby packets. |
| **Orbital Uplink** | The endgame weapon: a piercing beam that ignores armour, hits ground and air, blasts and slows around the target and reaches across most of the map. Very expensive to buy and to upgrade (4 levels). |
| **Spoofed packets** | Fly straight over your maze: keep some anti-air. | | **Spoofed packets** | Fly straight over your maze: keep some anti-air. |
| **Credits** | From kills and cleared waves. Upgrade turrets to level 3; selling returns 70% (walls 100%). | | **Credits** | From kills and cleared waves. Upgrade turrets (3 levels, 4 for the Uplink); selling returns 70% (walls 100%). |
Controls, desktop: click to build, drag to paint walls, right-click cancels, `1`-`6` pick a tower, `Space` next wave, Controls, desktop: click to build, drag to paint walls, right-click cancels, `1`-`7` 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.
Controls, touch: tap a tower type, tap the map to preview (the new route is drawn), tap the check mark (or the same cell Controls, touch: tap a tower type, tap the map to preview (the new route is drawn), nudge the preview with the arrow
again) to build. Walls paint as you drag. Two fingers pan and zoom; long-press pings your partner. In portrait the board buttons if you missed the cell, then tap the check mark to build. A tap only ever acts when the finger lifts, so a pinch
turns 90 degrees so the cells stay big. never builds by accident. Walls paint as you drag. Two fingers pan and zoom; long-press pings your partner with any tool
armed. Tap a tower to get an action bar over the board (Upgrade, Sell, Target). In portrait the board turns 90 degrees
when that makes the cells bigger.
## Music ## Music
@ -170,7 +222,7 @@ reconnects automatically and resumes the same seat for a minute.
npm test # rules + server: placement validation, route sealing, corner cutting, targeting, waves, economy, npm test # rules + server: placement validation, route sealing, corner cutting, targeting, waves, economy,
# protocol, rooms, reconnects, security checks, static files, dual stack # protocol, rooms, reconnects, security checks, static files, dual stack
npm run e2e # real browsers: desktop, phone touch (tap-to-build, drag-paint, pinch, long-press), end screens, npm run e2e # real browsers: desktop, phone touch (tap-to-build, drag-paint, pinch, long-press), end screens,
# two-browser co-op incl. reconnect, and a 14-size layout matrix # two-browser co-op incl. reconnect, and a 22-layout matrix (phones, tablets, desktop, thumb reach of every control)
``` ```
`npm run e2e` drives Chromium through Playwright (a devDependency). Install the browser once with `npm run e2e` drives Chromium through Playwright (a devDependency). Install the browser once with

View file

@ -27,8 +27,12 @@ Environment=PORT=8080
Environment=HOST=:: Environment=HOST=::
# auto: believe X-Forwarded-For / X-Forwarded-Host only from loopback / private-range peers (your proxy). # auto: believe X-Forwarded-For / X-Forwarded-Host only from loopback / private-range peers (your proxy).
Environment=TRUST_PROXY=auto Environment=TRUST_PROXY=auto
# Only needed when the proxy rewrites the Host header (symptom: 403 on the WebSocket upgrade). # Only needed when your proxy reaches this server from an address that is NOT private: a global IPv6 address,
# Comma separated, e.g. https://game.example.com # Tailscale / CGNAT (100.64.0.0/10), ... (symptom: the log says "from <the proxy's address>" for every player, or
# "this connection is not from a trusted proxy"). Comma separated IPs / CIDRs, added to the private ranges.
#Environment=TRUSTED_PROXIES=100.64.0.0/10,2001:db8::6
# Only needed when the proxy rewrites the Host header or you serve several public names (symptom: 403 on the
# WebSocket upgrade). Comma separated; include the port when it is not 80/443, e.g. https://game.example.com:8443
#Environment=ALLOWED_ORIGINS=https://game.example.com #Environment=ALLOWED_ORIGINS=https://game.example.com
#Environment=MAX_CONN_PER_IP=40 #Environment=MAX_CONN_PER_IP=40
#Environment=GRACE_MS=60000 #Environment=GRACE_MS=60000

View file

@ -8,13 +8,25 @@ the co-op rooms. There is no database and no build step; games live in memory (a
◀──wss── (HOST=::, IPv4 + IPv6) ◀──wss── (HOST=::, IPv4 + IPv6)
``` ```
What was actually run while writing this: the server and its test suite (Node 20.20.2 and 24.21), the real What was actually run while writing and re-checking this:
`node server/index.js` over IPv4 and IPv6 on loopback (`curl`, a two-player WebSocket session, `SIGTERM` exit 0), the
IPv6-disabled case in a throwaway network namespace, and `systemd-analyze verify` on the unit (syntax only). The * The server and its test suite (Node 20.20.2 and 24.21), the real `node server/index.js` over IPv4 and IPv6 on loopback
proxy behaviour was only *simulated* by sending the headers a proxy would send (`Host`, `X-Forwarded-For`, (`curl`, two-player WebSocket sessions, `SIGTERM` exit 0), the IPv6-disabled case in a throwaway network namespace,
`X-Forwarded-Host`, `Origin`) straight to the server. **Never run here:** nginx Proxy Manager or any nginx, a started and `systemd-analyze verify` on the unit (syntax only).
systemd unit, a Proxmox LXC, a real browser or phone. Everything about NPM below is what its documented UI and * **A real nginx 1.26.3** (the Debian 13 package, unpacked without root and run in a private network namespace) loaded
nginx's behaviour lead one to expect; labels differ between NPM versions, so check each step against your version. with the server and location blocks that **nginx Proxy Manager v2.16.0** renders: its own `nginx.conf` (timeouts,
`real_ip`, headers), `proxy.conf` and the proxy-host and custom-location templates, taken from the NPM v2.16.0 source
and filled in by hand. Behind it ran the real game server, headless Chromium (page, service worker, co-op lobby, the
e2e scenarios over https), `curl` and raw WebSocket clients, with extra loopback addresses acting as distinct client
and proxy addresses (`203.0.113.x`, `2001:db8::x`, `192.168.77.9`). Everything marked **observed** below comes from
that setup.
* NPM's UI labels (Details / Custom Locations / SSL tabs, "Websockets Support", "Cache Assets", "Forward Hostname / IP",
the gear icon for the Advanced box) and its path-prefix handling were **read from the v2.16.0 source**
(`frontend/src/...`, `backend/internal/nginx.js`), not clicked through. Those are marked **from source**.
**Never run:** the NPM application itself (its UI, its Docker image, its database), NPM versions other than 2.16.0,
Let's Encrypt, NPM in Docker with published ports (see "Client addresses" in section 4), a real phone, a Proxmox LXC, a
started systemd unit, a git deploy key. Labels differ between NPM versions, so check each step against yours.
## 1. Requirements ## 1. Requirements
@ -37,7 +49,9 @@ useradd --system --home-dir /opt/netwall --shell /usr/sbin/nologin netwall
# copy the project to /opt/netwall (from your workstation, for example): # copy the project to /opt/netwall (from your workstation, for example):
# rsync -a --exclude node_modules --exclude test --exclude .git ./ root@<lxc>:/opt/netwall/ # rsync -a --exclude node_modules --exclude test --exclude .git ./ root@<lxc>:/opt/netwall/
# it needs server/, public/, package.json, package-lock.json (docs/ and deploy/ are optional) # it needs server/, public/, package.json, package-lock.json and deploy/ (for the unit file in section 3; docs/ is optional)
# or clone it there: `git clone <repository url> /opt/netwall`. That works from inside the LXC only if the LXC can read the
# repository: a private one needs an SSH key on the LXC that the git server knows (a read-only "deploy key"); see the README.
cd /opt/netwall cd /opt/netwall
npm install --omit=dev # only "ws"; `npm ci --omit=dev` also works and follows the lockfile exactly npm install --omit=dev # only "ws"; `npm ci --omit=dev` also works and follows the lockfile exactly
chown -R root:root /opt/netwall # the service user only needs read access chown -R root:root /opt/netwall # the service user only needs read access
@ -78,8 +92,9 @@ Environment variables, read when the server is started directly (`node server/in
|---|---|---| |---|---|---|
| `PORT` | `8080` | TCP port. `0` picks a free one (the banner prints the real port). | | `PORT` | `8080` | TCP port. `0` picks a free one (the banner prints the real port). |
| `HOST` | `::` | Address to bind. `::` is **one dual-stack socket serving IPv4 and IPv6** (`ipv6Only:false`). `0.0.0.0` = IPv4 only. `127.0.0.1` = this container only. Any explicit address is used as given. | | `HOST` | `::` | Address to bind. `::` is **one dual-stack socket serving IPv4 and IPv6** (`ipv6Only:false`). `0.0.0.0` = IPv4 only. `127.0.0.1` = this container only. Any explicit address is used as given. |
| `TRUST_PROXY` | `auto` | `auto`: believe `X-Forwarded-For` / `X-Real-IP` / `X-Forwarded-Host` only when the TCP peer is loopback, RFC1918 (`10/8`, `172.16/12`, `192.168/16`), `fc00::/7` or link-local. `1` (also `true`, `yes`, `on`): always believe them. `0` (also `false`, `no`, `off`): never. | | `TRUST_PROXY` | `auto` | `auto`: believe `X-Forwarded-For` / `X-Real-IP` / `X-Forwarded-Host` (and the stripped-port rule of the "Origin check") only when the TCP peer is loopback, RFC1918 (`10/8`, `172.16/12`, `192.168/16`), `fc00::/7` or link-local, **or is listed in `TRUSTED_PROXIES`**. `1` (also `true`, `yes`, `on`): always believe them, from any peer (then firewall the port). `0` (also `false`, `no`, `off`): never. |
| `ALLOWED_ORIGINS` | empty | Comma separated list of extra origins allowed to open the WebSocket, for example `https://game.example.com,https://play.example.org` (list every public name if the game has more than one). See "Origin check". | | `TRUSTED_PROXIES` | empty | Comma separated IPs and CIDRs (IPv4 or IPv6) that `TRUST_PROXY=auto` believes **in addition to** the private ranges above, for example `100.64.0.0/10,2001:db8::6`. Needed when your proxy reaches the game from an address the built-in list does not call private: a global IPv6 address, Tailscale / CGNAT (`100.64.0.0/10`) or any other routable one. Ignored when `TRUST_PROXY` is `1` or `0`. A malformed entry stops the start-up with a message. See "Client addresses". |
| `ALLOWED_ORIGINS` | empty | Comma separated list of extra origins allowed to open the WebSocket, for example `https://game.example.com,https://play.example.org` (list every public name if the game has more than one). **Include the port when it is not 80/443**: `https://game.example.com:8443`. See "Origin check". |
| `MAX_CONN_PER_IP` | `40` | Open WebSockets per client IP; more get HTTP `429` on the upgrade. `0` disables the cap. | | `MAX_CONN_PER_IP` | `40` | Open WebSockets per client IP; more get HTTP `429` on the upgrade. `0` disables the cap. |
| `GRACE_MS` | `60000` | How long a disconnected player keeps their slot (so a phone can come back after a screen lock or a network switch). | | `GRACE_MS` | `60000` | How long a disconnected player keeps their slot (so a phone can come back after a screen lock or a network switch). |
@ -95,20 +110,37 @@ What the server does, relevant to a proxy setup:
it comes from `X-Forwarded-For` (else `X-Real-IP`); otherwise it is the TCP peer. From `X-Forwarded-For` the server it comes from `X-Forwarded-For` (else `X-Real-IP`); otherwise it is the TCP peer. From `X-Forwarded-For` the server
takes the **rightmost entry that is not a private address**: proxies such as NPM *append* the address they saw to takes the **rightmost entry that is not a private address**: proxies such as NPM *append* the address they saw to
whatever header the client sent, so the entries further left are the client's own claim and are never believed (a whatever header the client sent, so the entries further left are the client's own claim and are never believed (a
chain that is private all the way gives its rightmost entry; a client with a private LAN address cannot be told chain that is private all the way gives its rightmost entry). IPv4-mapped IPv6 peers (`::ffff:a.b.c.d`) are shown
apart from your own proxy hops, so it can still choose its own address). IPv4-mapped IPv6 peers (`::ffff:a.b.c.d`) are shown as plain IPv4. `X-Forwarded-Proto` is never used. See "Client addresses" below for what this does and does not protect
as plain IPv4. `X-Forwarded-Proto` is never used. when the proxy is nginx Proxy Manager.
* **Player ids.** A player's id (`pid`, kept in the browser's session storage) is what lets a browser take its slot * **Player ids.** A player's id (`pid`, kept in the browser's session storage) is what lets a browser take its slot
back after a disconnect, so the server only ever sends it to its owner; the other player is shown under an opaque, back after a disconnect, so the server only ever sends it to its owner; the other player is shown under an opaque,
stable alias. stable alias.
* **Keep-alive.** Every 25 s the server sends a WebSocket protocol ping to each socket and terminates a socket that did * **Keep-alive and dead peers.** Every 25 s the server sends a WebSocket protocol ping to each socket and terminates a
not answer the previous one (browsers answer automatically). The ping traffic also keeps nginx's `proxy_read_timeout` socket that did not answer the previous one (browsers answer automatically), so a phone that silently lost the
(default 60 s) from firing on an idle but healthy game. A terminated player stays in the room for `GRACE_MS`. network is dropped after 25 to 50 s (observed through nginx: first ping at 24.8 s, socket closed at 49.8 s). A
terminated player stays in the room for `GRACE_MS`. The pings are for finding dead peers; they are **not** what keeps a
proxy's idle timer quiet: a joined game receives about 20 snapshots a second, also while paused, so nginx never sees
the connection idle. Observed: a paused two-player room behind a 20 s `proxy_read_timeout` stayed connected for
60 s (three timeouts' worth) with no reconnect, at 20.5 frames/s per browser. nginx Proxy Manager's own default is 90 s
(`proxy_connect_timeout`, `proxy_send_timeout`, `proxy_read_timeout` and `keepalive_timeout` in its v2.16.0
`nginx.conf`), so no timeout setting is needed for the game. A socket that never joins is closed by the server after
10 s, whatever the proxy does.
* **Origin check** (WebSocket upgrade only, path `/ws`). A request without `Origin` is allowed (non-browser clients). * **Origin check** (WebSocket upgrade only, path `/ws`). A request without `Origin` is allowed (non-browser clients).
Otherwise the origin host must equal the `Host` header, **or** the first entry of `X-Forwarded-Host` (only from a Otherwise the origin host must equal the `Host` header, **or** the first entry of `X-Forwarded-Host` (only from a
trusted proxy), **or** be listed in `ALLOWED_ORIGINS`. Comparison is on lower-case `host[:port]` with the scheme trusted proxy), **or** (trusted proxy only) the `Host` header has **no port** and the origin has the same host name on
ignored and ports 80/443 treated as "no port" (so listing `https://game.example.com` also admits any port, **or** be listed in `ALLOWED_ORIGINS`. Comparison is on lower-case `host[:port]` with the scheme ignored
`http://game.example.com`). Everything else gets `403`; the reason is logged. and ports 80/443 treated as "no port" (so listing `https://game.example.com` also admits `http://game.example.com`,
but not `https://game.example.com:8443`). Everything else gets `403`; the reason is logged.
The "no port" rule exists because nginx's `proxy_set_header Host $host` (which nginx Proxy Manager uses) **drops the
port**: published on `https://game.example.com:8443`, the browser's Origin is `https://game.example.com:8443` but the
server sees `Host: game.example.com`. Observed before the fix: 403 for both http and https on a non-default port
(`refused websocket ... Origin "https://highport.test:8332" does not match Host "highport.test"`), and the same
proxy host worked on 80/443; after it, both join. A browser talking to the server directly on its default
port 8080 (or any port other than 80/443) always sends that port in `Host`, so direct connections are still matched
exactly (observed: Origin `:9999` against Host `127.0.0.1:8331` is refused), and a different host name is still
refused (observed through the proxy). The one exception is a server you run on `PORT=80` or `443` itself: a direct
connection from a private address then also has a port-less `Host` and gets the same-host-name rule (other host names are still refused).
* **Path prefix.** The server only knows `/ws` and `/`; the browser builds the socket URL relative to the page, so a * **Path prefix.** The server only knows `/ws` and `/`; the browser builds the socket URL relative to the page, so a
proxy that strips a prefix works (section 7). proxy that strips a prefix works (section 7).
* `GET /healthz` (and `HEAD`) returns `200 ok`. Static files are only served from `public/`, with * `GET /healthz` (and `HEAD`) returns `200 ok`. Static files are only served from `public/`, with
@ -119,9 +151,41 @@ What the server does, relevant to a proxy setup:
* **Shutdown.** `SIGTERM`/`SIGINT`: all sockets are closed with code 1001, the process exits 0 (within about a * **Shutdown.** `SIGTERM`/`SIGINT`: all sockets are closed with code 1001, the process exits 0 (within about a
second, forced after 5 s). Running games are lost; clients that reconnect are told the room no longer exists. second, forced after 5 s). Running games are lost; clients that reconnect are told the room no longer exists.
### Client addresses (per-IP cap, log) behind nginx Proxy Manager
`MAX_CONN_PER_IP` (default 40 open WebSockets per address) counts the client address the server works out: from
`X-Forwarded-For` / `X-Real-IP` when the TCP peer is a trusted proxy, otherwise the peer itself. All of the following
was **observed** against nginx 1.26.3 with NPM v2.16.0's configuration, with the cap set to 3 to make it visible:
* **A proxy on an address the built-in list does not call private** (a global IPv6 address, Tailscale / CGNAT
`100.64.0.0/10`; the built-in check says "not private" for `2001:db8::6` and `100.64.1.1`): with
`TRUST_PROXY=auto` the server believes no forwarded header. Three client addresses behind a proxy at `2001:db8::6`
got 3 sockets in total and `429` for the rest, and the log said `from 2001:db8::6` for everybody; with
`TRUSTED_PROXIES=2001:db8::6` each client address got its own budget (2 joined each, 6 in total) and the log named
`203.0.113.5`, `.6`, `.7`. `TRUST_PROXY=1` does the same without a list but trusts every peer, so firewall port 8080
to the proxy if you use it. Symptom of the problem: every log line says `from <the proxy>`, and a few players
exhaust the cap for everyone. The same untrusted-proxy case also ignores `X-Forwarded-Host` and the stripped-port
rule of the Origin check; the 403 line in the log then says `this connection is not from a trusted proxy`.
* **Public clients cannot fake an address.** A public client sending its own `X-Forwarded-For` and `X-Real-IP`
(`198.51.100.1`, `.2`) was still counted as its real address (`203.0.113.5`): 3 sockets joined, 2 refused.
* **Clients on a private (LAN or VPN) address can choose any address.** NPM's `nginx.conf` has
`set_real_ip_from 10.0.0.0/8; 172.16.0.0/12; 192.168.0.0/16; real_ip_header X-Real-IP;`, so when the connection to NPM
comes from such an address, nginx replaces its idea of the client address with the client's own `X-Real-IP` header
*before* it builds the forwarded headers. Eight sockets from one LAN address (`192.168.77.9`), each sending a
different `X-Real-IP`, all joined and were logged as `198.51.100.1` to `.8` although the cap was 3; five sockets from the
same LAN address without the header were capped at 3. The cap is therefore a guard against accidents and against
public abuse, **not** against someone on your own LAN: rely on the firewall and on who is on the network. Nothing else
in the game depends on the client address (it only affects the cap and the log).
* **LAN players that nginx sees as one address share one budget.** Players whose connections reach nginx from the same
address (a household behind one public IP, or a router in front of the proxy) count together, which is fine at 40
sockets (the game uses one socket per player). **Not run:** NPM in Docker with published ports and the default bridge
network, where nginx may see every LAN client as the Docker gateway address. If all your LAN players get `429`
there, raise `MAX_CONN_PER_IP`, or set it to `0` for a private game.
## 5. nginx Proxy Manager (NPM) ## 5. nginx Proxy Manager (NPM)
In NPM, **Hosts > Proxy Hosts > Add Proxy Host**. In NPM, **Hosts > Proxy Hosts > Add Proxy Host** (tab names and labels as in the v2.16.0 source: *Details*, *Custom
Locations*, *SSL*, and the gear icon at the right end of the tab row for the Advanced box).
**Details tab** **Details tab**
@ -129,39 +193,77 @@ In NPM, **Hosts > Proxy Hosts > Add Proxy Host**.
|---|---| |---|---|
| Domain Names | `game.example.com` | | Domain Names | `game.example.com` |
| Scheme | `http` | | Scheme | `http` |
| Forward Hostname / IP | the LXC's IP address (for example `192.168.1.50`) or a name NPM can resolve | | Forward Hostname / IP | the LXC's IP address (for example `192.168.1.50`) or a name NPM can resolve. Not `127.0.0.1` / `localhost` when NPM runs in its own container or on another machine: that would be NPM itself |
| Forward Port | `8080` | | Forward Port | `8080` |
| Cache Assets | **off** (the game files must revalidate; the server already sends `no-cache`) | | Cache Assets | **off** (the game files must revalidate; the server already sends `no-cache`) |
| Block Common Exploits | optional, can stay on | | Block Common Exploits | optional, can stay on |
| **Websockets Support** | **on** (required: it adds the `Upgrade` / `Connection` headers and HTTP/1.1 to the upstream) | | **Websockets Support** | **on** (required: it adds the `Upgrade` / `Connection` headers and HTTP/1.1 to the upstream). Observed with it off: the page loads, the browser's WebSocket gets HTTP `426`, and the lobby only says "Could not reach the game server." |
**Custom Locations tab**: leave empty (only needed for a path prefix, section 7).
**SSL tab**: SSL Certificate = *Request a new SSL Certificate* (Let's Encrypt), then switch on **Force SSL** and **SSL tab**: SSL Certificate = *Request a new SSL Certificate* (Let's Encrypt), then switch on **Force SSL** and
**HTTP/2 Support** (HSTS is optional), agree to the terms, Save. Browsers fall back to HTTP/1.1 for the WebSocket; **HTTP/2 Support** (HSTS is optional), agree to the terms, Save. Browsers fall back to HTTP/1.1 for the WebSocket;
that is normal. that is normal. (The Let's Encrypt request itself was not run; it needs the name to resolve to your proxy and ports
80/443 reachable from the internet, see NPM's own documentation.)
**Advanced tab** (Custom Nginx Configuration): paste **Advanced tab** (gear icon, *Custom Nginx Configuration*): nothing is required. In particular no
`proxy_read_timeout` / `proxy_send_timeout` is needed: NPM's default is 90 s, and a joined game never goes quiet
(see "Keep-alive and dead peers" in section 4). Save, then open `https://game.example.com/`.
```nginx ### The Host header, ports other than 443, and what the Advanced tab can and cannot do
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
```
Not strictly needed (the server pings every 25 s), but it makes a long-idle game survive proxies and middleboxes What NPM v2.16.0's `proxy.conf` sends upstream is `Host $host`, `X-Forwarded-Scheme`, `X-Forwarded-Proto`,
with short idle timers. Save, then open `https://game.example.com/`. `X-Forwarded-For $proxy_add_x_forwarded_for` and `X-Real-IP`, plus `Upgrade` / `Connection` when Websockets Support is
on. Observed with an echo server behind the rendered config: `host` is the public name **without a port**, and there is
**no `X-Forwarded-Host` and no `X-Forwarded-Port`**. The browser's `Origin` and that `Host` match on 80/443, so
nothing needs configuring there.
NPM is expected to pass the original `Host` header through unchanged (not verified here); then the browser's `Origin` * **Public port other than 80/443** (for example NPM published on `8443`, or Docker `-p 8443:443`): `$host` drops the
and the `Host` the server sees match and no configuration is needed. If the server log shows port, so Origin `https://game.example.com:8443` meets `Host: game.example.com`. Older versions of the server answered
`refused websocket ... does not match Host` (HTTP 403 on the upgrade), or if you set `Host` yourself in a custom `403` (observed: both `http://highport.test:8330` and `https://highport.test:8332` failed with `HTTP 403`; the same
config, either make the proxy send `X-Forwarded-Host` with the public name, or set host on 80/443 worked). The current server accepts the same host name on any port **when the connection comes from a
`ALLOWED_ORIGINS=https://game.example.com`. trusted proxy** (private address, or one listed in `TRUSTED_PROXIES`); observed: both now join, and a different host
name or a direct connection with a mismatching port is still refused. If your proxy is **not** trusted (a global IPv6 or
Tailscale address and no `TRUSTED_PROXIES`, or `TRUST_PROXY=0`), the log says `this connection is not from a trusted
proxy`: list the proxy in `TRUSTED_PROXIES`, or set `ALLOWED_ORIGINS=https://game.example.com:8443` **with the port**
(observed: an entry without the port does not match an origin with one).
* **You cannot add `X-Forwarded-Host` (or change `Host`) from the Advanced tab for the default location.** Observed:
`proxy_set_header X-Forwarded-Host $host;` and `proxy_set_header Host an.internal.name;` typed into the Advanced box
were silently ignored (the upstream still saw `Host: <public name>` and no `X-Forwarded-Host`), because NPM renders the
Advanced text at the `server {}` level and its own `location /` sets its own `proxy_set_header` lines, so nginx
inherits none of the server-level ones. The same two lines inside a *custom location's* gear box do take effect
(observed). From source: an Advanced box that contains its own `location / {` replaces NPM's default location
completely, and then you must repeat every proxy header and the `Upgrade` / `Connection` pair yourself.
So for an NPM user the one fix that always works is `ALLOWED_ORIGINS=https://game.example.com` (with the port if it
is not 443). `X-Forwarded-Host` is for hand-written nginx: observed with a hand-written `location /` that sets
`Host an.internal.name` and `X-Forwarded-Host $host`, `TRUST_PROXY=auto` joined, `TRUST_PROXY=0` got `403`, and
`TRUST_PROXY=0` with `ALLOWED_ORIGINS=http://rw2.test` joined again.
Optional, in the same Advanced box, to compress text for phones on mobile data (the Node server does not): Optional, in the Advanced box, to compress text for phones on mobile data (the Node server does not; NPM's own
`gzip on` only covers `text/html` by default, observed):
```nginx ```nginx
gzip on; gzip on;
gzip_types text/css text/javascript application/javascript application/json image/svg+xml; gzip_types text/css text/javascript application/javascript application/json application/manifest+json image/svg+xml;
``` ```
Observed with this list: `/`, `js/*.js`, `css/style.css`, `sw.js`, `icons/icon.svg`, `assets/music/tracks.json` and
`manifest.webmanifest` come back `Content-Encoding: gzip`; the PNG icons and mp3 files are left alone.
Optional, if **co-op never connects but the page loads** and the browser's developer tools show the `/ws` request
answered `400 Request Header Or Cookie Too Large`: another application on the same parent domain has set big cookies,
and the browser sends them to the game too. nginx's default `large_client_header_buffers 4 8k` refuses a single header
line above 8 KB (NPM leaves that default). Observed with an 8300-byte cookie: `400` on HTTP/1.1 requests and on the
WebSocket upgrade, while the page itself still loaded over HTTP/2 (`200`); up to about 7.8 KB everything worked. Put
```nginx
large_client_header_buffers 4 16k;
```
in the Advanced box (observed: cookies up to 16000 bytes then pass, upgrade included). Do not expect more: the Node
server itself refuses request headers above about 16 KB with `431` (observed at 16.3 KB), so beyond that clear the
cookies or serve the game from a name outside the cookie's domain. The game sets no cookies of its own.
## 6. Dual stack (IPv4 + IPv6) ## 6. Dual stack (IPv4 + IPv6)
* **The app side is automatic.** `HOST=::` (the default) is a single dual-stack socket: IPv4 clients arrive as * **The app side is automatic.** `HOST=::` (the default) is a single dual-stack socket: IPv4 clients arrive as
@ -195,9 +297,10 @@ gzip_types text/css text/javascript application/javascript application/json imag
``` ```
`systemctl enable --now nftables`. The Proxmox firewall (Datacenter / Node / CT > Firewall) can do the same. `systemctl enable --now nftables`. The Proxmox firewall (Datacenter / Node / CT > Firewall) can do the same.
`TRUST_PROXY=auto` is meant for exactly this setup: only private-range peers (the proxy) are believed. If the port `TRUST_PROXY=auto` is meant for exactly this setup: only private-range peers (the proxy) are believed, plus the
is reachable by other LAN machines they could forge `X-Forwarded-For`; the effect is limited to the per-IP cap addresses in `TRUSTED_PROXIES` if your proxy reaches the LXC over a global IPv6, Tailscale / `100.64.0.0/10` or other
and the log. routable address. If the port is reachable by other LAN machines they could forge `X-Forwarded-For`; the effect is
limited to the per-IP cap and the log (and see "Client addresses" for what NPM lets LAN clients do on its own).
* **IPv6 disabled in the container.** If IPv6 is switched off by sysctl (`net.ipv6.conf.all.disable_ipv6=1`) the * **IPv6 disabled in the container.** If IPv6 is switched off by sysctl (`net.ipv6.conf.all.disable_ipv6=1`) the
`::` socket still binds and still serves IPv4 (tested in a throwaway Linux network namespace with `::` socket still binds and still serves IPv4 (tested in a throwaway Linux network namespace with
`disable_ipv6=1`, not in an LXC). Only a kernel without IPv6 at all fails to bind `::` `disable_ipv6=1`, not in an LXC). Only a kernel without IPv6 at all fails to bind `::`
@ -210,11 +313,39 @@ gzip_types text/css text/javascript application/javascript application/json imag
The client never uses absolute URLs: it opens `new URL('ws', location.href)`, so at `https://example.com/netwall/` The client never uses absolute URLs: it opens `new URL('ws', location.href)`, so at `https://example.com/netwall/`
it connects to `wss://example.com/netwall/ws`. The proxy must **strip the prefix** so the server sees `/` and `/ws`, it connects to `wss://example.com/netwall/ws`. The proxy must **strip the prefix** so the server sees `/` and `/ws`,
and the page must be opened **with the trailing slash** (`/netwall/`, not `/netwall`, or the relative URLs resolve to and the page must be opened **with the trailing slash** (`/netwall/`, not `/netwall`, or the relative URLs resolve to
the wrong place). The behaviour you need is this nginx block (a trailing slash on `proxy_pass` replaces the matched the wrong place; nginx itself redirects `/netwall` to `/netwall/` for the locations below, observed). The simpler route
prefix): is a dedicated sub-domain (`game.example.com`), which needs none of this. Origin check: the browser's `Origin` is
`https://example.com` and `Host` is `example.com`, so it passes unchanged.
**Way 1, in the NPM UI: the Custom Locations tab of the proxy host.** Add a location with
| Field | Value | Why |
|---|---|---|
| Location | `/netwall/` | **with the trailing slash** |
| Scheme / Forward Port | `http` / `8080` | |
| Forward Hostname / IP | `192.168.1.50/` | **with a trailing slash after the address**: NPM turns everything after the first `/` into the path it puts on `proxy_pass`, so this renders `proxy_pass http://192.168.1.50:8080/;`, and that trailing `/` is what strips the `/netwall/` prefix |
and keep **Websockets Support** on in the Details tab (NPM copies it into each location). The Details tab still needs a
forward target for the host's own `/`; point it at whatever else the name serves.
What was run and what was not: NPM's `_location.conf` template, filled in the way its backend does it for exactly these
values, was run in nginx (observed: `/netwall/healthz` `200`, `/netwall` answered `301` to `/netwall/`, a WebSocket
join through `wss://.../netwall/ws`, and the repo's e2e smoke scenario and two-browser co-op scenario, invite link and
reconnect included, over https at `https://.../netwall/`). That a slash typed into the
Forward Hostname field is split into the forward path is **from source** (`backend/internal/nginx.js`
`renderLocations` in v2.16.0, and the field's own placeholder there, `eg: 10.0.0.1/path/`); the UI itself was not clicked.
Two near misses, both observed, that make this fail:
* Location `/netwall` **without** the trailing slash and a forward target ending in `/`: the page and its files load,
but `/netwall/healthz` and `/netwall/ws` are `404` (the upstream sees `//ws`), so co-op reports "Could not reach the
game server" (`WebSocket ... Unexpected response code: 404`).
* Forward Hostname `192.168.1.50` **without** the slash: nothing is stripped, so every `/netwall/...` request is `404`.
**Way 2: the host's Advanced tab** (gear icon). Paste this block; it adds its own location next to NPM's default one,
so the host's Details tab still needs *some* forward target. Observed working verbatim (the proxy address replaced by a
local one): `/netwall/healthz` `200`, `/netwall` `301` to `/netwall/`, `manifest.webmanifest` `200`, a music file with a
`Range` header `206`, a WebSocket join through `wss://.../netwall/ws`, and the e2e smoke and co-op scenarios over https.
```nginx ```nginx
location = /netwall { return 301 /netwall/; }
location /netwall/ { location /netwall/ {
proxy_pass http://192.168.1.50:8080/; proxy_pass http://192.168.1.50:8080/;
proxy_http_version 1.1; proxy_http_version 1.1;
@ -223,15 +354,12 @@ location /netwall/ {
proxy_set_header Host $host; proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Real-IP $remote_addr;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
} }
``` ```
In NPM the dialog differs between versions (Proxy Host > **Custom locations** tab, or the Advanced tab of a host). (An earlier version of this guide also had `location = /netwall { return 301 /netwall/; }` in front: redundant, because
Whichever you use, the result must be the block above; check with `curl -i https://example.com/netwall/healthz` nginx already answers `/netwall` with `301` to `/netwall/` for a prefix location ending in a slash; observed.) Check with
(expect `200 ok`). The simpler route is a dedicated sub-domain (`game.example.com`), which needs none of this. `curl -i https://example.com/netwall/healthz` (expect `200 ok`).
Origin check: the browser's `Origin` is `https://example.com` and `Host` is `example.com`, so it passes unchanged.
## 8. Verify ## 8. Verify
@ -241,19 +369,23 @@ curl -i https://game.example.com/healthz # 200 ok
curl -I https://game.example.com/ # 200, Content-Security-Policy etc. curl -I https://game.example.com/ # 200, Content-Security-Policy etc.
curl -6 -I https://game.example.com/ # over IPv6 (once the AAAA record exists) curl -6 -I https://game.example.com/ # over IPv6 (once the AAAA record exists)
# WebSocket through the proxy (run in /opt/netwall, uses the installed "ws"). # WebSocket through the proxy (run in /opt/netwall, uses the installed "ws"). It creates a room that disappears
# (Run here only against the local server, with the URL and origin pointed at it.) # again after the 60 s grace period. For a public name on a non-default port use that port in both places.
node -e " node -e "
const WebSocket=require('ws'); const WebSocket=require('ws');
const ws=new WebSocket('wss://game.example.com/ws',{origin:'https://game.example.com'}); const ws=new WebSocket('wss://game.example.com/ws',{origin:'https://game.example.com'});
ws.on('open',()=>ws.send(JSON.stringify({t:'join',pid:'deploy-check-0001',name:'check'}))); ws.on('open',()=>ws.send(JSON.stringify({t:'join',pid:'deploy-check-0001',name:'check'})));
ws.on('message',d=>{const m=JSON.parse(d);console.log(m.t,m.room||'');if(m.t==='joined'){ws.close();}}); ws.on('message',d=>{const m=JSON.parse(d);if(m.t==='joined'){console.log('joined',m.room);process.exit(0)}});
ws.on('unexpected-response',(q,r)=>{console.log('HTTP',r.statusCode);process.exit(1)}); ws.on('unexpected-response',(q,r)=>{console.log('HTTP',r.statusCode);process.exit(1)});
ws.on('error',e=>{console.log(e.message);process.exit(1)}); ws.on('error',e=>{console.log(e.message);process.exit(1)});
setTimeout(()=>{console.log('no reply');process.exit(1)},5000);
" "
# prints: joined XXXX # prints: joined XXXX (or HTTP 403 / 426 / 429 / 502, see section 9)
``` ```
The snippet was run (with the host replaced by a test name and certificate checking off for the self-signed
certificate) through nginx with NPM's configuration and printed `joined XXXX`.
Then open the URL on two phones, create a room on one and enter the 4-letter code on the other. Then open the URL on two phones, create a room on one and enter the 4-letter code on the other.
## 9. Troubleshooting ## 9. Troubleshooting
@ -261,11 +393,14 @@ Then open the URL on two phones, create a room on one and enter the 4-letter cod
| Symptom | Cause and fix | | Symptom | Cause and fix |
|---|---| |---|---|
| Page loads, but the game says it cannot reach the server / WebSocket never opens | **Websockets Support** is off in the Proxy Host, or something in front strips the `Upgrade` header. Turn it on. | | Page loads, but the game says it cannot reach the server / WebSocket never opens | **Websockets Support** is off in the Proxy Host, or something in front strips the `Upgrade` header. Turn it on. |
| WebSocket upgrade answered with **403** | Origin check: the browser's `Origin` host differs from the `Host` the server sees. The log says `refused websocket ... Origin "..." does not match Host "..."`. Fix the proxy so `Host` is the public name, or set `ALLOWED_ORIGINS=https://game.example.com` (comma separated for several) and restart. | | The lobby only says "Could not reach the game server." | That one message covers every failed WebSocket upgrade. The browser's developer-tools console shows the real reason as `Unexpected response code: NNN`; the rows below are by that code. The server log (`journalctl -u netwall -f`) names the reason for 403 and 429. |
| Upgrade answered with **429** | More than `MAX_CONN_PER_IP` sockets from one IP. If every visitor appears to come from the proxy, `TRUST_PROXY` is `0`, or the proxy connects from a non-private address; set `TRUST_PROXY=1`. | | WebSocket upgrade answered with **426** | **Websockets Support** is off in the Proxy Host (observed). Turn it on. |
| WebSocket dies after exactly 60 s | Should not happen with the defaults: the server's 25 s pings keep nginx's 60 s `proxy_read_timeout` fed. If it does, something else sits in the path with its own idle timer (a CDN, a second proxy, a firewall) that is not passing the pings, or the proxy's read timeout is shorter than 25 s. Add the `proxy_read_timeout`/`proxy_send_timeout` snippet (section 5) and check every hop. | | WebSocket upgrade answered with **403** | Origin check: the browser's `Origin` host differs from the `Host` the server sees. The log says `refused websocket from ...: Origin "..." does not match Host "..."`. On a **non-default public port** this is handled automatically for a trusted proxy (section 4, "Origin check"); if the log says `this connection is not from a trusted proxy`, list the proxy in `TRUSTED_PROXIES` (or set `TRUST_PROXY=1`). Otherwise (a proxy that rewrites `Host`, several public names) set `ALLOWED_ORIGINS=https://game.example.com` (comma separated for several, **with `:port` when it is not 80/443**) and restart. |
| Upgrade answered with **429** | More than `MAX_CONN_PER_IP` sockets from one address. If the log shows every visitor as the proxy (`from <the proxy's address>`), the proxy is not trusted: it connects from an address the `auto` list does not call private (global IPv6, `100.64.0.0/10`, ...). Set `TRUSTED_PROXIES=<its address>` (section 4, "Client addresses"). If all LAN players share one address in front of nginx, raise `MAX_CONN_PER_IP`. |
| Page loads, upgrade answered with **400** `Request Header Or Cookie Too Large` | Big cookies from another application on the same parent domain. Add `large_client_header_buffers 4 16k;` in the Advanced box (section 5), or clear the cookies. |
| WebSocket dies after exactly 60 s (or another round number) | Should not happen with the defaults: a joined game receives about 20 snapshots a second, so a proxy idle timer never fires (observed with a 20 s `proxy_read_timeout`). If it does, something else sits in the path that drops connections after a fixed time (a CDN, a second proxy, a firewall, a `proxy_read_timeout` / `proxy_send_timeout` set in the Advanced box that is far lower). Check every hop. |
| Players are dropped every few seconds and reconnect | The current client treats a socket as dead after 5 s without data (snapshots arrive 20 times a second). Something is buffering or throttling the stream; look at the proxy's buffering settings and at CPU use of the LXC. | | Players are dropped every few seconds and reconnect | The current client treats a socket as dead after 5 s without data (snapshots arrive 20 times a second). Something is buffering or throttling the stream; look at the proxy's buffering settings and at CPU use of the LXC. |
| **502 Bad Gateway** | NPM cannot reach the upstream. `systemctl status netwall`; from the NPM host run `curl -i http://<lxc>:8080/healthz`; check forward IP/port, the firewall (section 6) and that `HOST` is not `127.0.0.1`. | | **502 Bad Gateway** | NPM cannot reach the upstream. (A browser that has loaded the game before still gets the cached app and can play solo while this lasts: observed in Chromium through nginx for 502; 503 and 504 take the same path in the service worker and are covered by a unit test.) `systemctl status netwall`; from the NPM host run `curl -i http://<lxc>:8080/healthz`; check forward IP/port, the firewall (section 6) and that `HOST` is not `127.0.0.1`. |
| `listen EADDRINUSE` in the log, service restarts in a loop | Another process uses the port (`ss -ltnp | grep 8080`), or two copies are running. Change `PORT` and the NPM forward port together. | | `listen EADDRINUSE` in the log, service restarts in a loop | Another process uses the port (`ss -ltnp | grep 8080`), or two copies are running. Change `PORT` and the NPM forward port together. |
| `IPv6 is not available (...); falling back to 0.0.0.0` | The kernel has no IPv6 at all. IPv4 keeps working; nothing to do, or set `HOST=0.0.0.0` to silence it. With IPv6 merely disabled by sysctl the `::` bind still works. | | `IPv6 is not available (...); falling back to 0.0.0.0` | The kernel has no IPv6 at all. IPv4 keeps working; nothing to do, or set `HOST=0.0.0.0` to silence it. With IPv6 merely disabled by sysctl the `::` bind still works. |
| IPv6 visitors cannot connect, IPv4 can | The `AAAA` record points somewhere that does not answer on 443, or NPM/the firewall is not listening on IPv6. Test `curl -6 -I https://game.example.com/`. The app itself is dual-stack. | | IPv6 visitors cannot connect, IPv4 can | The `AAAA` record points somewhere that does not answer on 443, or NPM/the firewall is not listening on IPv6. Test `curl -6 -I https://game.example.com/`. The app itself is dual-stack. |

View file

@ -14,7 +14,7 @@ Development was paused on purpose before the fix stage. This file is the entry p
| `tools/bot.js` | Headless balance bot (dev tool). Complete; its results are summarised in `docs/BALANCE.md`. | | `tools/bot.js` | Headless balance bot (dev tool). Complete; its results are summarised in `docs/BALANCE.md`. |
| Deploy | `docs/DEPLOY.md`, `deploy/netwall.service`, README setup guide. Never run against a real nginx Proxy Manager or on a phone yet (an NPM-style review found doc inaccuracies, listed in the findings). | | Deploy | `docs/DEPLOY.md`, `deploy/netwall.service`, README setup guide. Never run against a real nginx Proxy Manager or on a phone yet (an NPM-style review found doc inaccuracies, listed in the findings). |
`npm test` = 80 passing (20 sim + 59 server + 1 balance-table shape test). Verified from a fresh `git clone`. `npm test` = 91 passing. `npm run e2e` = 9 scenarios (22-layout matrix, touch precision, selection/sell, info-panel stability, UI states, co-op). Verified from a fresh `git clone` earlier (2026-10-09).
## Fixed since this was written ## Fixed since this was written
@ -29,9 +29,9 @@ and a check that the layout holds on **tablets and foldables**.
| Wave | Content | State | | Wave | Content | State |
|---|---|---| |---|---|---|
| 1 | Phone panels/layout + touch precision (one owner of main.js/style.css), proxy/server doc fixes, QA | running / see git log | | 1 | Phone panels/layout + touch precision (one owner of main.js/style.css), proxy/server doc fixes, QA | **done 2026-10-10** (QA passed) |
| 2 | Co-op robustness (stalled-render tower loss, half-open sockets, idempotent upgrade/wave), audio + keyboard + a11y | drafted | | 2 | Co-op robustness (stalled-render tower loss, half-open sockets, idempotent upgrade/wave), audio + keyboard + a11y | drafted |
| 3 | Content: Orbital Uplink client side (glyph, beam, hotkey), new towers/enemies (healer, shielded, Sandbox, Load Balancer), 4 new maps (in sim already) | sim half done | | 3 | Content: new towers/enemies (healer, shielded, Sandbox, Load Balancer). Done already: Orbital Uplink (sim, glyph, beam, sound, help), 4 new maps (Canyon, Archipelago, Fortress, Pinwheel) | in progress |
| 4 | Attack-vs-defend versus mode, bots for both sides | design in `docs/VERSUS.md` | | 4 | Attack-vs-defend versus mode, bots for both sides | design in `docs/VERSUS.md` |
| 5 | Difficulty picker + ONE time-boxed balance pass (IDS dominance, weak Mortar/Arc, credit pile-up; maze stays strong) | after 3 and 4 | | 5 | Difficulty picker + ONE time-boxed balance pass (IDS dominance, weak Mortar/Arc, credit pile-up; maze stays strong) | after 3 and 4 |
| 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 |

View file

@ -15,11 +15,13 @@ Transport: one WebSocket per player at `ws(s)://<host>/ws`, JSON text frames, on
``` ```
createServer({ port = 8080, host = '::', publicDir = <repo>/public, createServer({ port = 8080, host = '::', publicDir = <repo>/public,
graceMs = 60000, snapshotHz = 20, maxRooms = 50, graceMs = 60000, snapshotHz = 20, maxRooms = 50,
trustProxy = 'auto', allowedOrigins = [], maxConnPerIp = 40, pingMs = 25000, log = console.log }) trustProxy = 'auto', trustedProxies = null, allowedOrigins = [], maxConnPerIp = 40, pingMs = 25000,
log = console.log })
-> Promise<{ port, addresses: string[], close(): Promise<void>, rooms: Map }> -> Promise<{ port, addresses: string[], close(): Promise<void>, rooms: Map }>
``` ```
Env when run directly: `PORT` (8080), `HOST` (`::`), `TRUST_PROXY` (`auto`|`1`|`0`), `ALLOWED_ORIGINS` Env when run directly: `PORT` (8080), `HOST` (`::`), `TRUST_PROXY` (`auto`|`1`|`0`), `TRUSTED_PROXIES` (comma separated
(comma separated, e.g. `https://game.example.com`), `MAX_CONN_PER_IP`, `GRACE_MS`. IPs / CIDRs added to the private ranges that `auto` trusts; a bad entry stops the start-up), `ALLOWED_ORIGINS`
(comma separated, e.g. `https://game.example.com`; include `:port` when it is not 80/443), `MAX_CONN_PER_IP`, `GRACE_MS`.
Prints `http://localhost:PORT/` and every non-internal LAN URL from `os.networkInterfaces()` (IPv4 as Prints `http://localhost:PORT/` and every non-internal LAN URL from `os.networkInterfaces()` (IPv4 as
`http://a.b.c.d:PORT/`, IPv6 as `http://[addr]:PORT/`, skip link-local `fe80::`). `http://a.b.c.d:PORT/`, IPv6 as `http://[addr]:PORT/`, skip link-local `fe80::`).
Handles SIGINT/SIGTERM by closing sockets and exiting 0. Handles SIGINT/SIGTERM by closing sockets and exiting 0.
@ -33,17 +35,20 @@ IPv6** (IPv4 arrives as `::ffff:a.b.c.d`; normalise it for logs). If binding `::
### Behind a reverse proxy (nginx Proxy Manager, nginx, Caddy, Traefik) ### Behind a reverse proxy (nginx Proxy Manager, nginx, Caddy, Traefik)
The server is meant to sit behind TLS-terminating proxies with "Websockets Support" enabled and must work both The server is meant to sit behind TLS-terminating proxies with "Websockets Support" enabled and must work both
at a domain root and under a path prefix the proxy strips. at a domain root and under a path prefix the proxy strips.
* **Keep-alive.** Proxies drop idle connections (nginx `proxy_read_timeout` defaults to 60 s). Every `pingMs` * **Keep-alive.** Every `pingMs` the server sends a WebSocket *protocol* ping to each socket and terminates sockets
the server sends a WebSocket *protocol* ping to each socket and terminates sockets that did not pong since the that did not pong since the previous round (so a dead mobile client is noticed within ~2 rounds and goes into the
previous round (so a dead mobile client is noticed within ~2 rounds and goes into the grace period). grace period). The pings are for dead-peer detection: a joined socket gets ~20 snapshots/s anyway, which is what
keeps a proxy's idle timer (nginx `proxy_read_timeout`; 60 s by default, 90 s in nginx Proxy Manager) quiet.
* **Real client IP** is used only for logging and the per-IP socket cap `maxConnPerIp`. `trustProxy:'auto'` * **Real client IP** is used only for logging and the per-IP socket cap `maxConnPerIp`. `trustProxy:'auto'`
means: if the TCP peer is loopback / RFC1918 / `fc00::/7` / link-local, take the client IP from means: if the TCP peer is loopback / RFC1918 / `fc00::/7` / link-local (or listed in `trustedProxies`), take the client IP from
`X-Forwarded-For` (else `X-Real-IP`): the *rightmost* entry that is not a private address (proxies append, so `X-Forwarded-For` (else `X-Real-IP`): the *rightmost* entry that is not a private address (proxies append, so
entries further left are the client's own forgeable claim); otherwise use the TCP peer and ignore those headers. entries further left are the client's own forgeable claim); otherwise use the TCP peer and ignore those headers.
`true`/`false` force it. `maxConnPerIp: 0` disables the cap. Reject extra sockets with HTTP `429` on upgrade. `true`/`false` force it. `maxConnPerIp: 0` disables the cap. Reject extra sockets with HTTP `429` on upgrade.
* **Origin check** (see below) accepts: Origin host == `Host` header; or == `X-Forwarded-Host` when the proxy is * **Origin check** (see below) accepts: Origin host == `Host` header; or == `X-Forwarded-Host` when the proxy is
trusted; or the Origin is listed in `allowedOrigins`. Compare scheme-less `host[:port]`, treat default ports trusted; or, when the proxy is trusted and `Host` has **no port**, the same host name on any port (nginx's
(80/443) as equal to "no port", case-insensitive. `Host $host`, which nginx Proxy Manager uses, drops the port of `https://game.example.com:8443`); or the Origin is
listed in `allowedOrigins`. Compare scheme-less `host[:port]`, treat default ports (80/443) as equal to "no port",
case-insensitive.
* **No absolute URLs, no hard-coded port** anywhere in served content; the client builds the socket URL relative * **No absolute URLs, no hard-coded port** anywhere in served content; the client builds the socket URL relative
to the page (`new URL('ws', location.href)` with `http->ws`, `https->wss`), so `https://x.example/netwall/` to the page (`new URL('ws', location.href)` with `http->ws`, `https->wss`), so `https://x.example/netwall/`
proxied to `/` works. The server therefore accepts the upgrade on path `/ws` only (the proxy strips any prefix). proxied to `/` works. The server therefore accepts the upgrade on path `/ws` only (the proxy strips any prefix).
@ -61,8 +66,9 @@ at a domain root and under a path prefix the proxy strips.
`Content-Security-Policy: default-src 'self'; connect-src 'self' ws: wss:; img-src 'self' data:; style-src 'self' 'unsafe-inline'; media-src 'self' data:; base-uri 'none'; frame-ancestors 'none'`. `Content-Security-Policy: default-src 'self'; connect-src 'self' ws: wss:; img-src 'self' data:; style-src 'self' 'unsafe-inline'; media-src 'self' data:; base-uri 'none'; frame-ancestors 'none'`.
### WebSocket upgrade ### WebSocket upgrade
* Only on path `/ws`. If the request has an `Origin` header, its host must equal the `Host` header, * Only on path `/ws`. If the request has an `Origin` header, its host must equal the `Host` header (or one of the
else `403` (stops random web pages from driving a LAN server). No `Origin` (non-browser clients/tests) is fine. trusted-proxy / `allowedOrigins` cases above), else `403` (stops random web pages from driving a LAN server). No
`Origin` (non-browser clients/tests) is fine.
* A socket that has not sent a valid `join` within **10 s** is closed (4408). * A socket that has not sent a valid `join` within **10 s** is closed (4408).
* Per-socket rate limit: token bucket 60 msg/s, burst 120; beyond that close with 4429. * Per-socket rate limit: token bucket 60 msg/s, burst 120; beyond that close with 4429.
* More than 20 malformed/unknown messages on a socket -> close 4400. * More than 20 malformed/unknown messages on a socket -> close 4400.

View file

@ -1,32 +1,288 @@
const sleep = (ms) => new Promise(r => setTimeout(r, ms)); // Layout matrix: every control a player needs must be fully on screen, uncovered and big enough at every viewport size,
const sizes = [[320,568],[360,640],[375,667],[390,844],[414,896],[768,1024],[1024,768],[568,320],[667,375],[740,360],[844,390],[932,430],[1280,720],[1920,1080]]; // for 6 towers (today) and for a stress palette of 10 towers and 8 maps (the planned content).
//
// For each size we drive the real UI (taps on phones, clicks on desktop) and ask the browser where things really are
// (getBoundingClientRect + document.elementFromPoint at the corners and centre), so overlapping panels, content cut by
// the screen edge and tiny targets all show up as failures. Failures are collected per size and thrown at the end.
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// [width, height, kind, towers] kind: 'touch' = phone/tablet (coarse pointer), 'mouse' = desktop (fine pointer);
// towers: 10 = stress palette (10+ towers, 8 maps), 6 = the content as it ships (whatever the sim defines)
const SIZES = [];
for (const [w, h] of [[320, 568], [360, 640], [375, 667], [390, 844], [414, 896], [768, 1024], [1024, 768], [568, 320], [667, 375], [740, 360], [844, 390], [932, 430], [1280, 720], [1920, 1080]]) {
SIZES.push([w, h, Math.min(w, h) < 800 ? 'touch' : 'mouse', 10]);
}
SIZES.push([1280, 720, 'mouse', 10], [1024, 768, 'mouse', 10], [800, 600, 'mouse', 10], [640, 400, 'mouse', 10]); // desktop windows (incl. 200% zoom of 1280x800)
SIZES.push([320, 568, 'touch', 6], [667, 375, 'touch', 6], [390, 844, 'touch', 6], [1280, 720, 'mouse', 6]); // the palette as it ships today
// pretend the game ships 10 towers and 8 maps (the sim is untouched: clones of existing definitions)
function stressContent() {
let td;
Object.defineProperty(window, 'TD', {
configurable: true,
get() { return td; },
set(v) {
td = v;
if (!v || !v.TOWERS || v.TOWERS.x7) return;
[['x7', '7', 'Test Seven'], ['x8', '8', 'Test Eight'], ['x9', '9', 'Test Nine'], ['x0', '0', 'Test Ten']].forEach(([id, key, name]) => {
v.TOWERS[id] = Object.assign({}, v.TOWERS.filter, { name, key });
v.TOWER_ORDER.push(id);
});
for (let i = 4; i <= 8; i++) {
const id = 'm' + i;
v.MAPS[id] = Object.assign({}, v.MAPS.open, { id, name: 'Test Map ' + i, difficulty: 1 + (i % 3) });
v.MAP_ORDER.push(id);
}
},
});
}
// ---------------------------------------------------------------- in-page probes
// Where is this element, is it entirely on screen, and does it receive pointer events at its centre and corners?
function probeFn(sel) {
const el = typeof sel === 'string' ? document.querySelector(sel) : sel;
if (!el) return { err: 'missing' };
const cs = getComputedStyle(el), b = el.getBoundingClientRect();
if (cs.display === 'none' || cs.visibility === 'hidden' || b.width < 1 || b.height < 1) return { err: 'hidden' };
const e = 0.6;
const on = b.left >= -e && b.top >= -e && b.right <= innerWidth + e && b.bottom <= innerHeight + e;
let blocked = 0;
const ins = Math.min(5, b.width / 4, b.height / 4);
for (const [x, y] of [[b.left + b.width / 2, b.top + b.height / 2], [b.left + ins, b.top + ins], [b.right - ins, b.top + ins], [b.left + ins, b.bottom - ins], [b.right - ins, b.bottom - ins]]) {
const hit = document.elementFromPoint(x, y);
if (!hit || !(hit === el || el.contains(hit))) blocked++;
}
return { on, blocked, w: +b.width.toFixed(1), h: +b.height.toFixed(1), l: +b.left.toFixed(1), t: +b.top.toFixed(1), r: +b.right.toFixed(1), b: +b.bottom.toFixed(1) };
}
const centre = (p) => ({ x: (p.l + p.r) / 2, y: (p.t + p.b) / 2 });
module.exports = async function ({ browser, url: URL, out: OUT }) { module.exports = async function ({ browser, url: URL, out: OUT }) {
let bad = 0; let bad = 0;
for (const [w, h] of sizes) { const allFails = [];
const touch = Math.min(w, h) < 800;
const ctx = await browser.newContext({ viewport: { width: w, height: h }, deviceScaleFactor: 1, isMobile: touch, hasTouch: touch }); for (const [w, h, kind, nTowers] of SIZES) {
const touch = kind === 'touch';
const tag = `${w}x${h} ${kind} t${nTowers}`;
const fails = [];
const check = (ok, what) => { if (!ok) fails.push(what); };
const mk = async (extra) => {
const ctx = await browser.newContext({ viewport: { width: w, height: h }, deviceScaleFactor: 1, isMobile: touch, hasTouch: touch, ...(extra || {}) });
if (nTowers > 6) await ctx.addInitScript(stressContent);
const page = await ctx.newPage(); const page = await ctx.newPage();
await page.goto(URL); await sleep(250); const errors = [];
await page.click('#btnSolo'); await sleep(150); await page.click('#btnHelpClose'); await sleep(150); page.on('pageerror', (e) => errors.push('pageerror: ' + e.message));
await page.evaluate(() => { document.getElementById('netChip').hidden = false; document.getElementById('netRoom').textContent = 'ABCD'; document.getElementById('netPing').textContent = '123 ms'; }); return { ctx, page, errors };
await page.tap ? 0 : 0; };
await page.click('.tbtn[data-type="ids"]'); await sleep(100); const probe = (page, sel) => page.evaluate(probeFn, sel).then((p) => p, () => ({ err: 'probe failed' }));
const m = await page.evaluate(() => { const tapAt = (page, x, y) => (touch ? page.touchscreen.tap(x, y) : page.mouse.click(x, y));
const r = (id) => document.getElementById(id).getBoundingClientRect(); // the element is on screen, fully uncovered, and (on phones) big enough to hit
const tb = document.getElementById('topbar'), st = r('stage'), side = r('side'), pal = r('palette'); const must = async (page, sel, what, o) => {
const overflowX = document.documentElement.scrollWidth > innerWidth + 1; const p = await probe(page, sel);
const tbOver = tb.scrollWidth > tb.clientWidth + 1; if (p.err) { fails.push(`${what} [${sel}] ${p.err}`); return p; }
const kids = [...tb.children].filter(c => !c.hidden && getComputedStyle(c).display !== 'none').map(c => c.getBoundingClientRect()); if (!p.on) fails.push(`${what} [${sel}] not fully on screen (${p.l},${p.t} - ${p.r},${p.b} in ${w}x${h})`);
const clipped = kids.some(k => k.right > innerWidth + 1); if (p.blocked) fails.push(`${what} [${sel}] covered by another element (${p.blocked}/5 probe points)`);
const cell = NW.app.renderer.cellSizePx(); if (touch && !(o && o.small) && Math.min(p.w, p.h) < 43.5) fails.push(`${what} [${sel}] touch target ${p.w}x${p.h} < 44`);
return { stage: [Math.round(st.width), Math.round(st.height)], topbarH: Math.round(tb.getBoundingClientRect().height), cell: +cell.toFixed(1), rot: NW.app.renderer.rot > 0, overflowX, tbOver, clipped, sideH: Math.round(side.height), palVisible: pal.bottom <= innerHeight && pal.height > 40 }; return p;
};
const tapBtn = async (page, sel, what) => {
const p = await must(page, sel, what);
if (p.err) return p;
const c = centre(p); await tapAt(page, c.x, c.y); await sleep(touch ? 170 : 120);
return p;
};
const noOverflow = async (page, what) => {
const o = await page.evaluate(() => ({ sw: document.documentElement.scrollWidth, bw: document.body.scrollWidth, iw: innerWidth, sh: document.documentElement.scrollHeight, ih: innerHeight }));
check(o.sw <= o.iw + 1 && o.bw <= o.iw + 1, `${what}: horizontal page overflow (${o.sw}/${o.bw} > ${o.iw})`);
check(o.sh <= o.ih + 1, `${what}: vertical page overflow (${o.sh} > ${o.ih})`);
};
const allButtonsBigEnough = async (page, what) => {
if (!touch) return;
const small = await page.evaluate(() => [...document.querySelectorAll('button')].filter((b) => {
const cs = getComputedStyle(b), r = b.getBoundingClientRect();
if (cs.display === 'none' || cs.visibility === 'hidden' || r.width < 1) return false;
if (r.bottom <= 0 || r.right <= 0 || r.top >= innerHeight || r.left >= innerWidth) return false;
let p = b.parentElement; while (p) { if (p.hidden) return false; p = p.parentElement; }
return Math.min(r.width, r.height) < 43.5;
}).map((b) => (b.id || b.className || b.textContent.trim().slice(0, 12)) + ' ' + Math.round(b.getBoundingClientRect().width) + 'x' + Math.round(b.getBoundingClientRect().height)));
if (small.length) fails.push(`${what}: touch targets < 44px: ${small.join(', ')}`);
};
// ------------------------------------------------ solo: menu -> help -> palette -> build -> select tower
{
const { ctx, page, errors } = await mk();
await page.goto(URL); await sleep(300);
// main menu: primary buttons always reachable (with 8 maps in the picker)
await must(page, '#btnSolo', 'menu Play solo'); await must(page, '#btnCoop', 'menu Co-op');
await noOverflow(page, 'menu'); await allButtonsBigEnough(page, 'menu');
await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-menu.png` });
const p0 = await probe(page, '#btnSolo');
await tapAt(page, centre(p0).x, centre(p0).y); await sleep(250);
// first-run help opens by itself: it must have a visible "Got it"
const helpOpen = await page.evaluate(() => !document.getElementById('help').hidden);
check(helpOpen, 'first run: help overlay did not open');
await must(page, '#btnHelpClose', 'help Got it');
await noOverflow(page, 'help'); await allButtonsBigEnough(page, 'help');
await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-help.png` });
const p1 = await probe(page, '#btnHelpClose');
if (!p1.err) await tapAt(page, centre(p1).x, centre(p1).y);
await sleep(250);
check(await page.evaluate(() => document.getElementById('help').hidden && NW.app.inGame), 'Got it did not close the help overlay');
// HUD: nothing clipped, no overflow, targets big enough
await noOverflow(page, 'game');
const hud = await page.evaluate(() => {
const tb = document.getElementById('topbar');
const kids = [...tb.children].filter((c) => !c.hidden && getComputedStyle(c).display !== 'none' && getComputedStyle(c).visibility !== 'hidden').map((c) => c.getBoundingClientRect());
return { tbOver: tb.scrollWidth > tb.clientWidth + 1, clipped: kids.some((k) => k.right > innerWidth + 1 || k.left < -1), tbH: Math.round(tb.getBoundingClientRect().height), cell: NW.app.renderer.cellSizePx(), rot: NW.app.renderer.rot > 0 };
}); });
const flag = (m.overflowX || m.tbOver || m.clipped || !m.palVisible || m.cell < 12) ? ' <== CHECK' : ''; check(!hud.tbOver && !hud.clipped, 'top bar content overflows or is cut off');
if (flag) bad++; // stacked (portrait) layout: the stage hugs the board (no dead band above/below it, touch-4 / visual-10) and the cells are not smaller than before
console.log(`${w}x${h}`.padEnd(10), JSON.stringify(m), flag); const lay = await page.evaluate(() => { const st = document.getElementById('stage').getBoundingClientRect(), r = NW.app.renderer, b = r.board, rot = r.rot > 0; return { stacked: matchMedia('(orientation: portrait), (max-width: 760px) and (min-height: 521px)').matches, deadY: st.height - (rot ? b.cols : b.rows) * r.cellSizePx(), cell: r.cellSizePx() }; });
if (flag) await page.screenshot({ path: `${OUT}matrix-${w}x${h}.png` }); if (lay.stacked) check(lay.deadY <= 26, `stage has ${Math.round(lay.deadY)}px of dead band above/below the board`);
const minCell = { '320x568': 11.5, '360x640': 14.3, '375x667': 15, '390x844': 19.5, '414x896': 21, '768x1024': 27 }[`${w}x${h}`];
if (minCell && touch) check(lay.cell >= minCell, `board cells are ${lay.cell.toFixed(1)}px, expected at least ${minCell}px`);
if (touch) console.log(` ${w}x${h} cell ${lay.cell.toFixed(1)}px, stage dead band ${Math.round(lay.deadY)}px`);
await allButtonsBigEnough(page, 'game HUD');
for (const id of ['btnMenu', 'btnWave', 'btnAuto', 'btnSpeed', 'btnPause', 'btnSound']) await must(page, '#' + id, 'top bar ' + id);
await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-game.png` });
// every tower in the palette can be picked with a real tap, and the selected state is visible
const order = await page.evaluate(() => TD.TOWER_ORDER.slice());
check(order.length >= (nTowers > 6 ? 10 : 1), `palette has only ${order.length} towers`);
let reachable = 0;
for (const type of order) {
let p = await probe(page, `.tbtn[data-type="${type}"]`);
if (p.err) { fails.push(`palette tile ${type}: ${p.err}`); continue; }
if (!p.on || p.blocked) { // off screen: scrolling the palette is allowed (and must be possible)
await page.evaluate((t) => { // what a swipe on the palette does: scroll it so the tile sits in the middle
const pal = document.getElementById('palette'), el = pal.querySelector(`.tbtn[data-type="${t}"]`), pr = pal.getBoundingClientRect(), er = el.getBoundingClientRect();
pal.scrollLeft += er.left + er.width / 2 - (pr.left + pr.width / 2); pal.scrollTop += er.top + er.height / 2 - (pr.top + pr.height / 2);
}, type);
await sleep(60);
p = await probe(page, `.tbtn[data-type="${type}"]`);
}
if (!p.on || p.blocked) { fails.push(`palette tile ${type} cannot be brought fully on screen (on=${p.on} blocked=${p.blocked})`); continue; }
await tapAt(page, centre(p).x, centre(p).y); await sleep(260); // (the selected border fades in over 120 ms)
const st = await page.evaluate((t) => ({ selType: NW.app.selType, sel: !!document.querySelector(`.tbtn[data-type="${t}"].sel`) }), type);
if (st.selType !== type) { fails.push(`palette tile ${type}: tap did not select it (selType=${st.selType})`); continue; }
const sp = await probe(page, `.tbtn[data-type="${type}"]`);
const vis = await page.evaluate((t) => { const e = document.querySelector(`.tbtn[data-type="${t}"]`); return { pressed: e.getAttribute('aria-pressed'), border: getComputedStyle(e).borderTopColor, cls: e.classList.contains('sel') }; }, type);
if (!sp.on || sp.blocked || !st.sel || vis.pressed !== 'true' || vis.border !== 'rgb(77, 227, 255)') fails.push(`palette tile ${type}: selected state not visible (${JSON.stringify({ on: sp.on, blocked: sp.blocked, ...vis })})`);
else reachable++;
}
check(reachable === order.length, `only ${reachable}/${order.length} palette towers selectable and visibly selected`);
// a palette that scrolls must say so (fade / chevron hint)
const pal = await page.evaluate(() => { const p = document.getElementById('palette'); return { sx: p.scrollWidth > p.clientWidth + 1, sy: p.scrollHeight > p.clientHeight + 1, more: p.dataset.more || '' }; });
if (pal.sx || pal.sy) check(!!pal.more, 'palette scrolls but shows no scroll affordance (data-more is empty)');
await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-armed.png` });
// build a Packet Filter at cell (10,8) with real input
const board = await page.locator('#board').boundingBox();
const cellPt = async (cx, cy) => { const r = await page.evaluate(([a, b]) => NW.app.renderer.cellToScreen(a, b), [cx, cy]); return { x: board.x + r.x, y: board.y + r.y }; };
await page.evaluate(() => { document.querySelector('.tbtn[data-type="filter"]').click(); });
let cp = await cellPt(10, 8);
await tapAt(page, cp.x, cp.y); await sleep(200);
if (touch) {
await must(page, '#btnConfirmBuild', 'build bar Build'); await must(page, '#btnCancelBuild', 'build bar Cancel');
const bar = await probe(page, '#confirm');
const cellBox = await page.evaluate(([a, b]) => { const r = NW.app.renderer, p = r.cellToScreen(a, b), s = r.cellSizePx() / 2; const bb = document.getElementById('board').getBoundingClientRect(); return { l: bb.left + p.x - s, r: bb.left + p.x + s, t: bb.top + p.y - s, b: bb.top + p.y + s }; }, [10, 8]);
if (!bar.err) check(bar.r < cellBox.l || bar.l > cellBox.r || bar.b < cellBox.t || bar.t > cellBox.b, 'build bar covers the cell being previewed');
await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-confirm.png` });
await tapBtn(page, '#btnConfirmBuild', 'build bar Build');
}
await sleep(150);
check(await page.evaluate(() => NW.app.ctrl.view.towers.length === 1), 'tower was not built');
if (!touch) await page.keyboard.press('Escape');
// select the placed tower (tap on the board)
cp = await cellPt(10, 8);
await tapAt(page, cp.x, cp.y); await sleep(250);
check(await page.evaluate(() => NW.app.selTower > 0), 'tapping the tower did not select it');
const compact = await page.evaluate(() => matchMedia('(pointer: coarse), (orientation: portrait), (max-width: 760px) and (min-height: 521px), (orientation: landscape) and (max-height: 520px)').matches);
const acts = {};
for (const a of ['up', 'sell', 'mode']) acts[a] = await must(page, `[data-act="${a}"]`, `selected tower ${a}`);
if (compact) acts.close = await must(page, '[data-act="close"]', 'selected tower close');
await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-selected.png` });
// the action bar must stay clear of the selected tower
const tb = await page.evaluate(() => { const r = NW.app.renderer, t = NW.app.ctrl.view.towers[0]; if (!t) return null; const p = r.cellToScreen(t.x, t.y), s = r.cellSizePx() / 2, bb = document.getElementById('board').getBoundingClientRect(); return { l: bb.left + p.x - s, r: bb.left + p.x + s, t: bb.top + p.y - s, b: bb.top + p.y + s }; });
if (compact && tb) for (const [a, p] of Object.entries(acts)) {
if (p.err) continue;
if (!(p.r < tb.l || p.l > tb.r || p.b < tb.t || p.t > tb.b)) fails.push(`action ${a} covers the selected tower`);
}
await allButtonsBigEnough(page, 'tower actions');
// upgrade and target with real taps on the buttons
if (acts.up && !acts.up.err) { const c = centre(acts.up); await tapAt(page, c.x, c.y); await sleep(200); }
check(await page.evaluate(() => (NW.app.ctrl.view.towers[0] || {}).level === 2), 'Upgrade tap did not upgrade');
const am = await probe(page, '[data-act="mode"]');
if (!am.err) { await tapAt(page, centre(am).x, centre(am).y); await sleep(200); }
check(await page.evaluate(() => (NW.app.ctrl.view.towers[0] || { mode: 'first' }).mode !== 'first'), 'Target tap did not change the targeting mode');
for (const a of ['up', 'sell', 'mode']) await must(page, `[data-act="${a}"]`, `after upgrade ${a}`);
// deselect: close button (phones), then tapping empty board
if (compact) {
await tapBtn(page, '[data-act="close"]', 'close');
check(await page.evaluate(() => NW.app.selTower === 0), 'close button did not deselect');
cp = await cellPt(10, 8); await tapAt(page, cp.x, cp.y); await sleep(200);
check(await page.evaluate(() => NW.app.selTower > 0), 'could not select the tower again');
}
const empty = await cellPt(11, 8); // an empty cell next to the tower (the action bar is on the other half of the stage)
await tapAt(page, empty.x, empty.y); await sleep(250);
check(await page.evaluate(() => NW.app.selTower === 0), 'tapping empty board did not deselect');
// sell
cp = await cellPt(10, 8); await tapAt(page, cp.x, cp.y); await sleep(200);
await tapBtn(page, '[data-act="sell"]', 'Sell');
check(await page.evaluate(() => NW.app.ctrl.view.towers.length === 0), 'Sell tap did not sell');
// end overlay buttons
await page.evaluate(() => { NW.app.ctrl.sim.lives = 0; NW.app.ctrl.sim.state = 'lost'; });
await sleep(400);
if (await page.evaluate(() => !document.getElementById('end').hidden)) {
await must(page, '#btnAgain', 'end Play again'); await must(page, '#btnEndMenu', 'end Menu');
await noOverflow(page, 'end'); await allButtonsBigEnough(page, 'end');
await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-end.png` });
} else fails.push('end overlay did not open when the game was lost');
for (const e of errors) fails.push(e);
await ctx.close(); await ctx.close();
} }
if (bad) throw new Error(bad + ' layouts have problems');
console.log('all layouts ok'); // ------------------------------------------------ co-op host waiting for a partner (real room on the real server)
{
const { ctx, page, errors } = await mk();
await page.goto(URL); await sleep(250);
await tapBtn(page, '#btnCoop', 'menu Co-op');
await must(page, '#btnCreate', 'lobby Create room'); await must(page, '#btnJoin', 'lobby Join'); await must(page, '#btnLobbyBack', 'lobby Back');
await noOverflow(page, 'lobby'); await allButtonsBigEnough(page, 'lobby');
await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-lobby.png` });
await tapBtn(page, '#btnCreate', 'lobby Create room');
let joined = false;
for (let i = 0; i < 60 && !joined; i++) { joined = await page.evaluate(() => NW.app.inGame && NW.app.ctrl.kind === 'remote' && NW.app.ctrl.status === 'joined'); if (!joined) await sleep(100); }
if (!joined) fails.push('could not create a co-op room');
else {
await sleep(300);
const room = await page.evaluate(() => NW.app.ctrl.room);
const chip = await must(page, '#netChip', 'room chip');
const txt = await page.evaluate(() => document.getElementById('netChip').innerText + ' ' + (document.getElementById('netChip').getAttribute('aria-label') || ''));
check(txt.includes(room), `room chip does not show the room code ${room}: "${txt}"`);
check(/invite|share/i.test(txt), `room chip does not offer to invite/share: "${txt}"`);
await noOverflow(page, 'co-op game');
const hud = await page.evaluate(() => { const tb = document.getElementById('topbar'); const kids = [...tb.children].filter((c) => !c.hidden && getComputedStyle(c).display !== 'none').map((c) => c.getBoundingClientRect()); return { clipped: kids.some((k) => k.right > innerWidth + 1 || k.left < -1), tbOver: tb.scrollWidth > tb.clientWidth + 1 }; });
check(!hud.clipped && !hud.tbOver, 'co-op top bar content overflows or is cut off');
for (const id of ['btnMenu', 'btnWave', 'btnPause', 'btnSound']) await must(page, '#' + id, 'co-op top bar ' + id);
await allButtonsBigEnough(page, 'co-op HUD');
await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-coop.png` });
void chip;
}
for (const e of errors) fails.push(e);
await page.evaluate(() => { try { NW.app.ctrl.close(); } catch (e) { /* ignore */ } }); // leave the room for good (no 60 s grace period)
await ctx.close();
}
if (fails.length) { bad++; console.log('FAIL', tag); for (const f of fails) console.log(' - ' + f); allFails.push(tag + ': ' + fails.length); }
else console.log('ok ', tag);
}
if (bad) throw new Error(bad + ' of ' + SIZES.length + ' layouts have problems: ' + allFails.join(' | '));
console.log('all ' + SIZES.length + ' layouts ok');
}; };

View file

@ -0,0 +1,71 @@
// code-2: the selected-tower panel used to be rebuilt (innerHTML) on every view.rev change. In co-op the partner's actions
// bump rev constantly, so the button under a finger was replaced between press and release and the tap was lost.
// Here a page-side timer hammers rev (a wall is built and sold every 30 ms, standing in for a busy partner) while real
// presses (down, hold 150 ms, up) land on Upgrade and Target. Every one of them must arrive, and the buttons must be the
// very same DOM nodes at the end. On the old code only a small fraction of the presses produced a click.
module.exports = async function ({ browser, url: URL }) {
const assert = (c, m) => { if (!c) throw new Error('ASSERT: ' + m); console.log('ok -', m); };
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const errors = [];
for (const [name, opts, touch] of [
['desktop mouse', { viewport: { width: 1100, height: 700 } }, false],
['phone touch', { viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true }, true],
]) {
console.log('=== ' + name);
const ctx = await browser.newContext(opts);
const page = await ctx.newPage();
page.on('pageerror', (e) => errors.push(`[${name}] pageerror: ${e.message}`));
page.on('console', (m) => { if (m.type() === 'error') errors.push(`[${name}] console.error: ${m.text()}`); });
const cdp = touch ? await ctx.newCDPSession(page) : null;
await page.goto(URL); await sleep(300);
await page.evaluate(() => document.getElementById('btnSolo').click()); await sleep(200);
await page.evaluate(() => document.getElementById('btnHelpClose').click()); await sleep(100);
await page.evaluate(() => { const c = NW.app.ctrl; c.sim.gold = 100000; c.send({ c: 'place', type: 'filter', x: 10, y: 8 }); });
await sleep(200);
const board = await page.locator('#board').boundingBox();
const cp = await page.evaluate(() => NW.app.renderer.cellToScreen(10, 8));
if (touch) await page.touchscreen.tap(board.x + cp.x, board.y + cp.y); else await page.mouse.click(board.x + cp.x, board.y + cp.y);
await sleep(250);
assert(await page.evaluate(() => NW.app.selTower > 0), 'tower selected');
// watch: clicks that reach an action button, and any action button being removed from the DOM
await page.evaluate(() => {
window.__clicks = { up: 0, mode: 0 }; window.__removed = 0;
document.addEventListener('click', (e) => { const b = e.target.closest && e.target.closest('[data-act]'); if (b && window.__clicks[b.dataset.act] !== undefined) window.__clicks[b.dataset.act]++; }, true);
new MutationObserver((muts) => { for (const m of muts) for (const n of m.removedNodes) if (n.nodeType === 1 && (n.matches('[data-act]') || n.querySelector('[data-act]'))) window.__removed++; }).observe(document.getElementById('info'), { childList: true, subtree: true });
window.__els = { up: document.querySelector('[data-act="up"]'), mode: document.querySelector('[data-act="mode"]'), sell: document.querySelector('[data-act="sell"]') };
// the busy partner: build / sell a wall every 30 ms (each one bumps view.rev)
let i = 0;
window.__rev0 = NW.app.ctrl.view.rev;
window.__hammer = setInterval(() => {
const c = NW.app.ctrl, x = 2 + (i % 6), y = 2 + ((i >> 3) % 2), ex = c.view.towers.find((t) => t.x === x && t.y === y);
if (ex) c.send({ c: 'sell', id: ex.id }); else c.send({ c: 'place', type: 'wall', x, y });
i++;
}, 30);
});
const press = async (act) => {
const r = await page.evaluate((a) => { const e = document.querySelector(`[data-act="${a}"]`).getBoundingClientRect(); return { x: e.left + e.width / 2, y: e.top + e.height / 2 }; }, act);
if (touch) { await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x: r.x, y: r.y, id: 1 }] }); await sleep(150); await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }); }
else { await page.mouse.move(r.x, r.y); await page.mouse.down(); await sleep(150); await page.mouse.up(); }
await sleep(120);
};
for (let i = 0; i < 2; i++) await press('up');
for (let i = 0; i < 10; i++) await press('mode');
const res = await page.evaluate(() => {
clearInterval(window.__hammer);
const t = NW.app.ctrl.view.towers.find((x) => x.id === NW.app.selTower);
return { clicks: window.__clicks, removed: window.__removed, revBumps: NW.app.ctrl.view.rev - window.__rev0, level: t && t.level, mode: t && t.mode,
same: ['up', 'mode', 'sell'].every((k) => document.querySelector(`[data-act="${k}"]`) === window.__els[k]) };
});
console.log(JSON.stringify(res));
assert(res.revBumps > 40, `rev changed ${res.revBumps} times during the presses`);
assert(res.clicks.up === 2 && res.level === 3, `both Upgrade presses arrived (clicks ${res.clicks.up}, level ${res.level})`);
assert(res.clicks.mode === 10, `all 10 Target presses arrived (${res.clicks.mode})`);
assert(res.mode === 'strong', `10 Target taps cycled the mode to ${res.mode}`);
assert(res.removed === 0 && res.same, `no action button was replaced in the DOM (${res.removed} removals)`);
await ctx.close();
}
if (errors.length) throw new Error('console errors:\n' + errors.join('\n'));
console.log('no console errors');
};

View file

@ -0,0 +1,99 @@
// Small UI states that were broken or missing on phones: toasts under reduced motion (touch-5, visual-6), toasts hidden behind
// the build bar (visual-5), the static low-integrity cue, the paused state (visual-18), the tappable room chip (visual-4).
module.exports = async function ({ browser, url: URL, out: OUT }) {
const failures = [];
const assert = (c, m) => { if (!c) { failures.push(m); console.log('FAIL -', m); } else console.log('ok -', m); }; // collect every failure (the old code fails several)
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const errors = [];
const phone = { viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true };
const start = async (opts) => {
const ctx = await browser.newContext(opts);
const page = await ctx.newPage();
page.on('pageerror', (e) => errors.push('pageerror: ' + e.message));
page.on('console', (m) => { if (m.type() === 'error') errors.push('console.error: ' + m.text()); });
await page.goto(URL); await sleep(300);
await page.evaluate(() => document.getElementById('btnSolo').click()); await sleep(200);
await page.evaluate(() => document.getElementById('btnHelpClose').click()); await sleep(150);
return { ctx, page };
};
const tryTap = (page, sel) => page.tap(sel, { timeout: 3000 }).then(() => true, () => false); // (the old UI has no such button: fail fast instead of waiting 30 s)
const rect = (page, sel) => page.evaluate((s) => { const r = document.querySelector(s).getBoundingClientRect(); return { l: r.left, t: r.top, r: r.right, b: r.bottom }; }, sel);
const overlap = (a, b) => !(a.r <= b.l || a.l >= b.r || a.b <= b.t || a.t >= b.b);
// ---- reduced motion: the toast text stays visible, the low-integrity cue is static, and the build bar never hides the toast
for (const half of ['upper', 'lower']) {
const { ctx, page } = await start({ ...phone, reducedMotion: 'reduce' });
await page.evaluate(() => { NW.app.ctrl.sim.gold = 0; });
await page.evaluate(() => document.querySelector('.tbtn[data-type="filter"]').click());
const board = await page.locator('#board').boundingBox();
const cell = await page.evaluate((h) => NW.app.renderer.cellToScreen(h === 'upper' ? 12 : 12, h === 'upper' ? 2 : 13), half);
await page.touchscreen.tap(board.x + cell.x, board.y + cell.y); await sleep(200); // first tap: preview + build bar
await tryTap(page, '#btnConfirmBuild'); await sleep(250); // not enough credits -> toast
const t = await page.evaluate(() => { const e = document.querySelector('.toast'); if (!e) return null; const cs = getComputedStyle(e), r = e.getBoundingClientRect(); return { text: e.textContent, opacity: +cs.opacity, l: r.left, t: r.top, r: r.right, b: r.bottom }; });
assert(t && /credits/i.test(t.text), `reduced motion (${half} half): toast exists "${t && t.text}"`);
assert(t && t.opacity > 0.9, `reduced motion (${half} half): toast is visible (opacity ${t && t.opacity})`);
const bar = await rect(page, '#confirm');
assert(t && !overlap(t, bar), `${half} half: the toast does not overlap the build bar`);
// the server (core) stays clear of the toast
const core = await page.evaluate(() => { const b = NW.app.ctrl.board, p = NW.app.renderer.cellToScreen(b.core.x, b.core.y), bb = document.getElementById('board').getBoundingClientRect(), s = NW.app.renderer.cellSizePx() * 0.6; return { l: bb.left + p.x - s, r: bb.left + p.x + s, t: bb.top + p.y - s, b: bb.top + p.y + s }; });
assert(t && !overlap(t, core), `${half} half: the toast does not cover the server`);
if (half === 'upper') {
await page.evaluate(() => { NW.app.ctrl.sim.lives = 3; }); await sleep(300);
const low = await page.evaluate(() => { const e = document.getElementById('statLives'), cs = getComputedStyle(e); return { cls: e.classList.contains('low'), border: cs.borderTopColor, shadow: cs.boxShadow, anim: cs.animationName }; });
assert(low.cls && low.border === 'rgb(255, 92, 122)' && low.shadow !== 'none', 'reduced motion: low integrity shows a static red border + glow: ' + JSON.stringify(low));
}
await page.screenshot({ path: OUT + `ui-states-toast-${half}.png` });
await ctx.close();
}
// ---- paused: dimmed board, a resume pill that works, and a pause button that is not a second play triangle
{
const { ctx, page } = await start(phone);
await page.tap('#btnPause'); await sleep(250);
const p = await page.evaluate(() => ({ paused: NW.app.ctrl.view.paused, tag: !document.getElementById('pausedTag').hidden, tagText: document.getElementById('pausedTag').innerText, stage: document.getElementById('stage').classList.contains('paused'), dim: getComputedStyle(document.getElementById('stage'), '::after').backgroundColor, pressed: document.getElementById('btnPause').getAttribute('aria-pressed'), icon: document.querySelector('#btnPause use').getAttribute('href') }));
assert(p.paused && p.tag && p.stage && p.pressed === 'true', 'paused: pill shown, stage marked, button pressed ' + JSON.stringify(p));
assert(/resume/i.test(p.tagText) && p.dim !== 'rgba(0, 0, 0, 0)', 'paused: the board is dimmed and the pill says how to resume');
assert(p.icon === '#i-pause', 'paused: the pause button keeps its pause icon (the Wave button owns the play triangle)');
await page.screenshot({ path: OUT + 'ui-states-paused.png' });
const tapped = await tryTap(page, '#pausedTag'); await sleep(250);
assert(tapped && await page.evaluate(() => !NW.app.ctrl.view.paused && document.getElementById('pausedTag').hidden), 'tapping the pill resumes');
await ctx.close();
}
// ---- reconnecting: the whole HUD looks dead (not only the board), apart from the menu and the room chip
{
const { ctx, page } = await start(phone);
await page.evaluate(() => { document.getElementById('reconnect').hidden = false; }); await sleep(250);
const o = await page.evaluate(() => { const g = (id) => { const cs = getComputedStyle(document.getElementById(id)); return { op: +cs.opacity, pe: cs.pointerEvents }; }; return { app: document.getElementById('app').classList.contains('offline'), wave: g('btnWave'), pause: g('btnPause'), palette: g('side'), menu: g('btnMenu') }; });
assert(o.app && o.wave.pe === 'none' && o.wave.op < 0.6 && o.palette.pe === 'none' && o.menu.pe !== 'none', 'reconnecting: HUD dims and stops taking taps, the menu stays usable ' + JSON.stringify(o));
await page.screenshot({ path: OUT + 'ui-states-offline.png' });
await ctx.close();
}
// ---- the room chip: shows the code, pulses while alone, copies / shares the invite link when tapped
{
const ctx = await browser.newContext({ ...phone, permissions: ['clipboard-read', 'clipboard-write'] });
const page = await ctx.newPage();
page.on('pageerror', (e) => errors.push('pageerror: ' + e.message));
await page.goto(URL); await sleep(300);
await page.evaluate(() => document.getElementById('btnCoop').click()); await sleep(100);
await page.evaluate(() => document.getElementById('btnCreate').click());
for (let i = 0; i < 60 && !(await page.evaluate(() => NW.app.inGame && NW.app.ctrl.status === 'joined')); i++) await sleep(100);
await sleep(300);
const room = await page.evaluate(() => NW.app.ctrl.room);
const chip = await page.evaluate(() => { const e = document.getElementById('netChip'), r = e.getBoundingClientRect(); return { text: e.innerText, waiting: e.classList.contains('waiting'), w: r.width, h: r.height, inView: r.left >= 0 && r.right <= innerWidth && r.top >= 0 && r.bottom <= innerHeight }; });
assert(chip.text.includes(room) && chip.inView && chip.h >= 43.5, `room chip shows ${room}, is on screen and 44px tall (${JSON.stringify(chip)})`);
assert(chip.waiting, 'room chip pulses while waiting for a partner');
await page.evaluate(() => { navigator.share = undefined; });
await tryTap(page, '#netChip'); await sleep(400);
const toast = await page.evaluate(() => [...document.querySelectorAll('.toast')].map((t) => t.textContent).join('|'));
assert(/copied/i.test(toast), 'tapping the chip copies the invite link: "' + toast + '"');
const clip = await page.evaluate(() => navigator.clipboard.readText()).catch(() => '');
assert(clip.includes('?room=' + room), 'the clipboard holds the invite link: ' + clip);
await page.evaluate(() => { try { NW.app.ctrl.close(); } catch (e) { /* ignore */ } });
await ctx.close();
}
if (errors.length) throw new Error('console errors:\n' + errors.join('\n'));
if (failures.length) throw new Error(failures.length + ' UI state checks failed:\n - ' + failures.join('\n - '));
console.log('no console errors');
};

View file

@ -0,0 +1,464 @@
// Touch precision: a pinch or a pan must never build or move anything, a long press pings, a tap with a little drift still builds,
// the nudge buttons move the pending cell one cell on screen (also when the board is drawn turned 90 degrees), and the partner sees
// where a touch is aiming. Plus the keyboard / wheel / sound fixes that went in with it (touch-1 2 9 10 11 12 16 17, coop-7,
// code-6 8 22 23). Real touch events (CDP) and real clicks, no calls into the game's own handlers. Every failure is collected, so the
// old code lists all of them.
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
module.exports = async function ({ browser, url: URL, out: OUT }) {
const failures = [], errors = [];
let tag = '';
const assert = (c, m) => { if (!c) { failures.push(`[${tag}] ${m}`); console.log(`FAIL - [${tag}] ${m}`); } else console.log(`ok - [${tag}] ${m}`); };
// a fresh solo game in a phone-sized touch context (or a desktop mouse context)
async function open(w, h, kind) {
const touch = kind !== 'mouse';
const ctx = await browser.newContext({ viewport: { width: w, height: h }, deviceScaleFactor: 2, isMobile: touch, hasTouch: touch });
const page = await ctx.newPage();
page.on('pageerror', (e) => errors.push(`[${tag}] pageerror: ${e.message}`));
page.on('console', (m) => { if (m.type() === 'error') errors.push(`[${tag}] console.error: ${m.text()}`); });
const cdp = touch ? await ctx.newCDPSession(page) : null;
await page.goto(URL); await sleep(300);
await page.evaluate(() => document.getElementById('btnSolo').click()); await sleep(200);
await page.evaluate(() => { const b = document.getElementById('btnHelpClose'); if (!document.getElementById('help').hidden) b.click(); }); await sleep(150);
const T = { ctx, page, box: await page.locator('#board').boundingBox() };
T.touch = (type, pts) => cdp.send('Input.dispatchTouchEvent', { type, touchPoints: pts.map((p, i) => ({ x: p.x, y: p.y, id: p.id || i + 1 })) });
T.pt = async (cx, cy) => { const r = await page.evaluate(([a, b]) => NW.app.renderer.cellToScreen(a, b), [cx, cy]); return { x: T.box.x + r.x, y: T.box.y + r.y }; };
T.cs = () => page.evaluate(() => NW.app.renderer.cellSizePx());
T.st = () => page.evaluate(() => {
const a = NW.app, v = a.ctrl.view, r = a.renderer, c = document.getElementById('confirm');
return { towers: v.towers.length, walls: v.towers.filter((t) => t.type === 'wall').length, gold: v.gold, pending: a.pending, selType: a.selType, selTower: a.selTower,
zoom: r.zoom, marks: r.marks.length, barHidden: c.hidden, hint: document.getElementById('confirmHint').textContent, wave: v.wave };
});
T.tap = async (p, hold) => { await T.touch('touchStart', [p]); await sleep(hold || 40); await T.touch('touchEnd', []); await sleep(70); };
// arm a tower type; `fresh` re-arms it from scratch (no pending cell left over)
T.arm = async (type, fresh) => { await page.evaluate(([t, f]) => { const b = document.querySelector(`.tbtn[data-type="${t}"]`); if (f && NW.app.selType === t) b.click(); if (NW.app.selType !== t) b.click(); }, [type, !!fresh]); await sleep(80); };
// a canvas point just inside the stage edge that is NOT a board cell
T.outside = () => page.evaluate(() => { const r = NW.app.renderer, b = NW.app.ctrl.board, W = r.W, H = r.H; const cv = document.getElementById('board'), bb = cv.getBoundingClientRect();
for (const [x, y] of [[W / 2, 8], [8, H / 2], [W / 2, H - 8], [W - 8, H / 2], [10, 10], [W - 10, 10], [10, H - 10], [W - 10, H - 10]]) { const c = r.screenToCell(x, y); if (!b.inBounds(c.x, c.y) && document.elementFromPoint(bb.left + x, bb.top + y) === cv) return { x, y }; } return null; });
T.build = (type, x, y) => page.evaluate(([t, a, b]) => NW.app.ctrl.send({ c: 'place', type: t, x: a, y: b }), [type, x, y]);
return T;
}
const close = (T) => T.ctx.close();
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
for (const [w, h] of [[390, 844], [844, 390]]) {
tag = `${w}x${h}`;
console.log('=== ' + tag);
// ---- touch-1: Firewall armed, pinch: no wall, no credits spent
{
const T = await open(w, h); await T.arm('wall');
const a = await T.pt(8, 6), b = await T.pt(12, 6), s0 = await T.st();
await T.touch('touchStart', [{ ...a, id: 1 }]); await sleep(30);
await T.touch('touchStart', [{ ...a, id: 1 }, { ...b, id: 2 }]);
for (let i = 1; i <= 10; i++) { await T.touch('touchMove', [{ x: a.x - i * 4, y: a.y, id: 1 }, { x: b.x + i * 4, y: b.y, id: 2 }]); await sleep(12); }
await T.touch('touchEnd', []); await sleep(100);
const s = await T.st();
assert(s.walls === 0 && s.gold === s0.gold, `touch-1: a pinch with the Firewall armed builds no wall and spends nothing (walls ${s.walls}, gold ${s0.gold} -> ${s.gold})`);
assert(s.zoom > 1.2, `touch-1: ...and it still zooms (zoom ${s.zoom.toFixed(2)})`);
await close(T);
}
// ---- touch-2: turret armed with a pending cell: a pinch, or one finger left after it, never moves the pending cell
{
const T = await open(w, h); await T.arm('filter');
await T.tap(await T.pt(10, 8));
const p0 = (await T.st()).pending;
assert(p0 && p0.x === 10 && p0.y === 8, 'touch-2: first tap previews the cell (pending 10,8)');
const a = await T.pt(6, 5), b = await T.pt(14, 5);
await T.touch('touchStart', [{ ...a, id: 1 }]); await sleep(30);
await T.touch('touchStart', [{ ...a, id: 1 }, { ...b, id: 2 }]);
for (let i = 1; i <= 8; i++) { await T.touch('touchMove', [{ x: a.x - i * 3, y: a.y, id: 1 }, { x: b.x + i * 3, y: b.y, id: 2 }]); await sleep(12); }
const mid = (await T.st()).pending;
await T.touch('touchEnd', [{ x: b.x + 24, y: b.y, id: 2 }]); await sleep(40); // finger 1 up, finger 2 stays down
for (let i = 1; i <= 6; i++) { await T.touch('touchMove', [{ x: b.x + 24 + i * 5, y: b.y + i * 3, id: 2 }]); await sleep(12); }
const left = await T.st();
await T.touch('touchEnd', []); await sleep(100);
const end = await T.st();
assert(same(mid, p0), `touch-2: pending stays ${JSON.stringify(p0)} during a pinch (${JSON.stringify(mid)})`);
assert(same(left.pending, p0) && same(end.pending, p0) && end.towers === 0, `touch-2: ...and with one finger left and after lifting (${JSON.stringify(left.pending)}, ${JSON.stringify(end.pending)}, towers ${end.towers})`);
assert(!end.barHidden, 'touch-2: the build bar is still up');
await close(T);
}
// ---- touch-2 (b): a pinch whose first finger lands on a tower must not select it and drop the armed type
{
const T = await open(w, h); await T.build('filter', 9, 6); await T.arm('filter');
const a = await T.pt(9, 6), b = await T.pt(14, 6);
await T.touch('touchStart', [{ ...a, id: 1 }]); await sleep(30);
await T.touch('touchStart', [{ ...a, id: 1 }, { ...b, id: 2 }]);
for (let i = 1; i <= 6; i++) { await T.touch('touchMove', [{ x: a.x - i * 3, y: a.y, id: 1 }, { x: b.x + i * 3, y: b.y, id: 2 }]); await sleep(12); }
await T.touch('touchEnd', []); await sleep(100);
const s = await T.st();
assert(s.selType === 'filter' && s.selTower === 0, `touch-2: a pinch that starts on a tower keeps the armed type and selects nothing (selType ${s.selType}, selTower ${s.selTower})`);
await close(T);
}
// ---- touch-12: a third finger (palm) neither freezes the pinch nor makes the zoom jump when it lifts
{
const T = await open(w, h); const c = await T.pt(13, 8);
const f = (dx, dy, id) => ({ x: c.x + dx, y: c.y + dy, id });
await T.touch('touchStart', [f(-30, 0, 1), f(30, 0, 2)]);
for (let i = 1; i <= 6; i++) { await T.touch('touchMove', [f(-30 - i * 6, 0, 1), f(30 + i * 6, 0, 2)]); await sleep(12); }
const z1 = (await T.st()).zoom;
await T.touch('touchStart', [f(-66, 0, 1), f(66, 0, 2), f(0, 90, 3)]); await sleep(30);
const zs = [];
for (let i = 1; i <= 4; i++) { await T.touch('touchMove', [f(-66 - i * 4, 0, 1), f(66 + i * 4, 0, 2), f(0, 90, 3)]); await sleep(12); zs.push((await T.st()).zoom); }
assert(zs[3] > z1 + 0.15, `touch-12: the pinch keeps tracking the two fingers while a palm rests on the screen (zoom ${z1.toFixed(2)} -> ${zs[3].toFixed(2)})`);
await T.touch('touchEnd', [f(-82, 0, 1), f(82, 0, 2)]); await sleep(40); // the palm lifts
const z2 = (await T.st()).zoom;
await T.touch('touchMove', [f(-84, 0, 1), f(84, 0, 2)]); await sleep(30);
const z3 = (await T.st()).zoom;
assert(Math.abs(z3 - z2) < 0.12, `touch-12: the zoom does not jump when the palm lifts (${z2.toFixed(2)} -> ${z3.toFixed(2)})`);
await T.touch('touchEnd', []);
await close(T);
}
// ---- the cell under the fingertip, after a real pinch-zoom and a two-finger pan (rotated on the tall phone): random taps pick the cell they hit
{
const T = await open(w, h);
const d0 = await T.page.evaluate(() => { const c = document.getElementById('board').getBoundingClientRect(), st = document.getElementById('stage').getBoundingClientRect(), r = NW.app.renderer; return { c: [c.width, c.height], st: [st.width, st.height], r: [r.W, r.H] }; });
assert(Math.abs(d0.c[0] - d0.r[0]) < 0.6 && Math.abs(d0.c[1] - d0.r[1]) < 0.6 && Math.abs(d0.c[0] - d0.st[0]) < 0.6 && Math.abs(d0.c[1] - d0.st[1]) < 0.6, `hit cell: the canvas, the stage and the renderer agree on the size (${JSON.stringify(d0)})`);
const c = await T.pt(10, 8), f = (dx, dy, id) => ({ x: c.x + dx, y: c.y + dy, id });
await T.touch('touchStart', [f(-30, 0, 1), f(30, 0, 2)]);
for (let i = 1; i <= 10; i++) { await T.touch('touchMove', [f(-30 - i * 6, 0, 1), f(30 + i * 6, 0, 2)]); await sleep(12); }
for (let i = 1; i <= 8; i++) { await T.touch('touchMove', [f(-90 - i * 5, i * 4, 1), f(90 - i * 5, i * 4, 2)]); await sleep(12); } // pan with both fingers
await T.touch('touchEnd', []); await sleep(150);
const z = await T.page.evaluate(() => ({ zoom: NW.app.renderer.zoom, px: NW.app.renderer.cam.px, py: NW.app.renderer.cam.py, rot: NW.app.renderer.rot }));
assert(z.zoom > 1.8 && (z.px !== 0 || z.py !== 0), `hit cell: zoomed and panned for real (zoom ${z.zoom.toFixed(2)}, pan ${z.px.toFixed(0)},${z.py.toFixed(0)}, rot ${z.rot.toFixed(2)})`);
let seed = 12345; const rand = () => { seed = (seed * 1664525 + 1013904223) >>> 0; return seed / 4294967296; };
const vis = await T.page.evaluate(() => { // every cell whose centre is comfortably on screen at this zoom and pan
const r = NW.app.renderer, b = NW.app.ctrl.board, out = [];
for (let y = 0; y < b.rows; y++) for (let x = 0; x < b.cols; x++) { const p = r.cellToScreen(x, y), m = r.cellSizePx() * 0.5 + 6; if (p.x >= m && p.y >= m && p.x <= r.W - m && p.y <= r.H - m) out.push({ x, y, sx: p.x, sy: p.y, cs: r.cellSizePx() }); }
return out;
});
let tried = 0; const wrong = [];
for (let k = vis.length - 1; k > 0; k--) { const j = Math.floor(rand() * (k + 1)); [vis[k], vis[j]] = [vis[j], vis[k]]; }
for (const v of vis) {
if (tried >= 14) break;
await T.arm('filter', true);
const p = { x: T.box.x + v.sx + (rand() - 0.5) * 0.7 * v.cs, y: T.box.y + v.sy + (rand() - 0.5) * 0.7 * v.cs };
const top = await T.page.evaluate(([x, y]) => { const e = document.elementFromPoint(x, y); return e && e.id; }, [p.x, p.y]);
if (top !== 'board') continue; // (under a floating bar)
await T.tap(p); tried++;
const got = (await T.st()).pending;
if (!got || got.x !== v.x || got.y !== v.y) wrong.push(`${v.x},${v.y} -> ${got ? got.x + ',' + got.y : 'none'}`);
}
assert(tried >= 8 && wrong.length === 0, `hit cell: ${tried} random taps after a pinch-zoom and pan all picked the cell they hit (wrong: ${wrong.join(' ') || 'none'})`);
await close(T);
}
// ---- touch-10: a long press pings whatever is armed, and never builds or moves the pending cell
{
const T = await open(w, h); await T.arm('filter');
await T.page.evaluate(() => { const c = NW.app.ctrl, o = c.sendMark.bind(c); window.__pings = []; c.sendMark = (x, y) => { window.__pings.push([x, y]); return o(x, y); }; }); // count the real ping calls (marks fade after 1.6 s)
const pings = () => T.page.evaluate(() => window.__pings.map((p) => p.join(',')));
await T.tap(await T.pt(10, 8)); // pending 10,8
const lp = await T.pt(14, 5);
await T.touch('touchStart', [lp]); await sleep(700); await T.touch('touchEnd', []); await sleep(100);
const s = await T.st();
assert(same(await pings(), ['14,5']), `touch-10: a long press pings cell 14,5 once with a turret armed (pings ${JSON.stringify(await pings())})`);
assert(same(s.pending, { x: 10, y: 8 }) && s.towers === 0, `touch-10: ...and leaves the pending cell alone (${JSON.stringify(s.pending)}, towers ${s.towers})`);
const on = await T.pt(10, 8); // a long press ON the pending cell must not count as "tap again to build"
await T.touch('touchStart', [on]); await sleep(700); await T.touch('touchEnd', []); await sleep(100);
assert((await T.st()).towers === 0 && (await pings()).length === 2, `touch-10: a long press on the previewed cell pings and does not build it (pings ${(await pings()).length})`);
await T.arm('wall');
const wp = await T.pt(6, 9);
await T.touch('touchStart', [wp]); await sleep(700); await T.touch('touchEnd', []); await sleep(100);
const s1 = await T.st();
assert((await pings()).length === 3 && (await pings())[2] === '6,9' && s1.walls === 0, `touch-10: a long press with the Firewall armed pings 6,9 and builds no wall (pings ${JSON.stringify(await pings())}, walls ${s1.walls})`);
await close(T);
}
// ---- touch-11: the second tap on the preview, with the finger drifting across the cell edge but inside the tap slop, still builds
{
const T = await open(w, h); await T.arm('filter');
const c = await T.pt(10, 8), cs = await T.cs();
await T.tap(c);
const start = { x: c.x + cs / 2 - 2, y: c.y }; // 2 px inside the cell edge ...
await T.touch('touchStart', [start]); await sleep(40);
await T.touch('touchMove', [{ x: start.x + 4, y: start.y }]); await sleep(40); // ... drifts 4 px: over the edge, under the slop
await T.touch('touchEnd', []); await sleep(120);
const s = await T.st();
assert(s.towers === 1, `touch-11: tapping the previewed cell again with 4 px of drift builds it (towers ${s.towers}, pending ${JSON.stringify(s.pending)})`);
await close(T);
}
// ---- touch-17: a wall stroke that starts on a turret keeps the tool and paints; a plain tap on the turret still selects it
{
const T = await open(w, h); await T.build('filter', 10, 5); await T.arm('wall');
const a = await T.pt(10, 5), b = await T.pt(10, 9);
await T.touch('touchStart', [a]);
for (let i = 1; i <= 8; i++) { await T.touch('touchMove', [{ x: a.x + (b.x - a.x) * i / 8, y: a.y + (b.y - a.y) * i / 8 }]); await sleep(16); }
await T.touch('touchEnd', []); await sleep(100);
const s = await T.st();
assert(s.selType === 'wall' && s.selTower === 0 && s.walls >= 3, `touch-17: the stroke from a turret keeps the Firewall tool and paints (selType ${s.selType}, walls ${s.walls})`);
await T.tap(a); await sleep(100);
const s2 = await T.st();
assert(s2.selTower > 0 && s2.selType === null, `touch-17: a plain tap on the turret selects it (selTower ${s2.selTower})`);
await close(T);
}
// ---- drag-paint still paints every cell including the first, and tap-confirm still builds
{
const T = await open(w, h); await T.arm('wall');
const a = await T.pt(8, 5), b = await T.pt(8, 11);
await T.touch('touchStart', [a]);
for (let i = 1; i <= 12; i++) { await T.touch('touchMove', [{ x: a.x + (b.x - a.x) * i / 12, y: a.y + (b.y - a.y) * i / 12 }]); await sleep(14); }
await T.touch('touchEnd', []); await sleep(100);
const cells = await T.page.evaluate(() => NW.app.ctrl.view.towers.filter((t) => t.type === 'wall').map((t) => t.x + ',' + t.y));
const want = []; for (let y = 5; y <= 11; y++) want.push('8,' + y);
const missing = want.filter((c) => !cells.includes(c));
assert(missing.length === 0, `drag-paint: every cell of the stroke gets a wall, including the first (missing ${missing.join(' ') || 'none'})`);
await T.arm('filter');
await T.tap(await T.pt(12, 8));
const p = await T.st();
await T.page.tap('#btnConfirmBuild'); await sleep(150);
const s = await T.st();
assert(p.pending && p.pending.x === 12 && !p.barHidden && s.towers === cells.length + 1, `tap + Build button still builds (towers ${s.towers})`);
await close(T);
}
// ---- code-23: tapping off the board clears the pending cell and hides the build bar
{
const T = await open(w, h); await T.arm('filter');
await T.tap(await T.pt(10, 8));
const before = await T.st();
const out = await T.outside();
await T.tap({ x: T.box.x + out.x, y: T.box.y + out.y });
const s = await T.st();
assert(!before.barHidden && s.pending === null && s.barHidden, `code-23: a tap outside the board clears the pending cell (pending ${JSON.stringify(s.pending)}, bar hidden ${s.barHidden})`);
await close(T);
}
// ---- pointercancel: a cancelled aim drag puts the pending cell back; a cancelled stroke stops; the next tap works
{
const T = await open(w, h); await T.arm('filter');
await T.tap(await T.pt(10, 8));
const a = await T.pt(14, 5), b = await T.pt(15, 6);
await T.touch('touchStart', [a]); await sleep(30);
await T.touch('touchMove', [{ x: a.x + 12, y: a.y + 12 }]); await sleep(30);
const dragging = (await T.st()).pending;
await T.touch('touchCancel', []); await sleep(60);
const s = await T.st();
assert(!same(dragging, { x: 10, y: 8 }), `pointercancel: (the aim drag did move the pending cell: ${JSON.stringify(dragging)})`);
assert(same(s.pending, { x: 10, y: 8 }), `pointercancel: a cancelled aim drag restores the pending cell (${JSON.stringify(s.pending)})`);
await T.tap(await T.pt(12, 8));
await T.tap(await T.pt(12, 8));
assert((await T.st()).towers === 1, 'pointercancel: a fresh tap-tap builds normally afterwards');
await T.arm('wall');
const w0 = (await T.st()).walls, c0 = await T.pt(6, 3), c1 = await T.pt(6, 6), c2 = await T.pt(6, 9);
await T.touch('touchStart', [c0]); await T.touch('touchMove', [c1]); await sleep(30);
await T.touch('touchCancel', []); await sleep(40);
const w1 = (await T.st()).walls;
await T.touch('touchStart', [c1]); await sleep(20); await T.touch('touchEnd', []); await sleep(60); // (a tap: one wall at most)
assert(w1 > w0, `pointercancel: the stroke before the cancel painted (${w0} -> ${w1})`);
await close(T);
}
// ---- touch-16: a stroke that is rejected cell after cell plays the error sound once
{
const T = await open(w, h);
await T.page.evaluate(() => { NW.app.ctrl.sim.gold = 12; window.__sfx = {}; const o = NW.Audio.sfx; NW.Audio.sfx = function (n) { window.__sfx[n] = (window.__sfx[n] || 0) + 1; return o.apply(this, arguments); }; });
await T.arm('wall');
const a = await T.pt(5, 4), b = await T.pt(5, 13);
await T.touch('touchStart', [a]);
for (let i = 1; i <= 3; i++) { await T.touch('touchMove', [{ x: a.x + (b.x - a.x) * i / 3, y: a.y + (b.y - a.y) * i / 3 }]); await sleep(20); }
await T.touch('touchEnd', []); await sleep(100);
const n = await T.page.evaluate(() => window.__sfx.error || 0);
assert(n >= 1 && n <= 1, `touch-16: one error sound for the whole stroke, not one per cell (${n})`);
await close(T);
}
// ---- coop-7: the partner builds on the previewed cell -> the preview is dropped with a toast; aiming over your own tower is not
{
const T = await open(w, h); await T.arm('filter');
await T.tap(await T.pt(10, 8));
await T.build('wall', 10, 8); await sleep(250);
const s = await T.st();
const toast = await T.page.evaluate(() => [...document.querySelectorAll('.toast')].map((t) => t.textContent).join('|'));
assert(s.pending === null && s.barHidden && /just built there/.test(toast), `coop-7: a tower appearing on the previewed cell drops the preview with a toast (pending ${JSON.stringify(s.pending)}, "${toast}")`);
await T.build('filter', 12, 8);
await T.tap(await T.pt(11, 5));
const a = await T.pt(11, 5), b = await T.pt(12, 8); // drag-aim the preview onto the tower you already own
await T.touch('touchStart', [a]); await sleep(30);
for (let i = 1; i <= 6; i++) { await T.touch('touchMove', [{ x: a.x + (b.x - a.x) * i / 6, y: a.y + (b.y - a.y) * i / 6 }]); await sleep(20); }
await T.touch('touchEnd', []); await sleep(300);
const s2 = await T.st();
assert(same(s2.pending, { x: 12, y: 8 }), `coop-7: aiming at a cell that already holds a tower is not wiped (${JSON.stringify(s2.pending)})`);
await close(T);
}
await sleep(50);
}
// ================================================================ nudge buttons (several sizes, also rotated)
for (const [w, h] of [[390, 844], [844, 390], [360, 640], [568, 320], [320, 568]]) {
tag = `nudge ${w}x${h}`;
console.log('=== ' + tag);
const T = await open(w, h); const page = T.page;
await T.arm('filter');
const info = () => page.evaluate(() => {
const r = NW.app.renderer, p = NW.app.pending; if (!p) return null;
const s = r.cellToScreen(p.x, p.y), b = document.getElementById('board').getBoundingClientRect(), c = document.getElementById('confirm').getBoundingClientRect();
return { x: p.x, y: p.y, sx: s.x + b.left, sy: s.y + b.top, cs: r.cellSizePx(), bar: { l: c.left, t: c.top, r: c.right, b: c.bottom }, hint: (document.getElementById('app').dataset.barrows === '0' ? document.getElementById('hint') : document.getElementById('confirmHint')).textContent, rot: r.rot };
});
const btnRect = (dir) => page.evaluate((d) => {
const el = document.querySelector(`#nudge [data-dx="${d[0]}"][data-dy="${d[1]}"]`); if (!el) return null;
const r = el.getBoundingClientRect(), hit = (x, y) => { const e = document.elementFromPoint(x, y); return e && (e === el || el.contains(e)); };
return { l: r.left, t: r.top, r: r.right, b: r.bottom, w: r.width, h: r.height, on: r.left >= 0 && r.top >= 0 && r.right <= innerWidth && r.bottom <= innerHeight,
free: hit(r.left + 5, r.top + 5) && hit(r.right - 5, r.bottom - 5) && hit((r.left + r.right) / 2, (r.top + r.bottom) / 2) };
}, dir);
const tapBtn = async (dir) => { const r = await btnRect(dir); await page.touchscreen.tap((r.l + r.r) / 2, (r.t + r.b) / 2); await sleep(90); };
const overlap = (a, r, pad) => !(a.r + pad <= r.l || a.l - pad >= r.r || a.b + pad <= r.t || a.t - pad >= r.b);
// the buttons exist, are big, on screen, uncovered, and never cover the cell being aimed at (five different cells)
let all = true, why = '';
for (const [cx, cy] of [[3, 3], [16, 3], [3, 11], [16, 11], [10, 7]]) {
await T.arm('filter', true); // (a fresh preview each time: the bar covers part of the other half)
await T.tap(await T.pt(cx, cy));
const i = await info();
if (!i) { all = false; why += ` no pending at ${cx},${cy};`; continue; }
for (const d of [[-1, 0], [0, -1], [0, 1], [1, 0]]) {
const r = await btnRect(d);
if (!r) { all = false; why += ` button ${d} missing;`; continue; }
if (!r.on || !r.free || r.w < 43.5 || r.h < 43.5) { all = false; why += ` button ${d} at cell ${cx},${cy}: on=${r.on} free=${r.free} ${r.w}x${r.h};`; }
}
const cell = { l: i.sx - i.cs / 2, r: i.sx + i.cs / 2, t: i.sy - i.cs / 2, b: i.sy + i.cs / 2 };
if (overlap(i.bar, cell, 0)) { all = false; why += ` the build bar covers cell ${cx},${cy};`; }
}
assert(all, `nudge: four on-screen, uncovered buttons of at least 44 px, and the bar never covers the aimed cell${why}`);
await page.screenshot({ path: `${OUT}touch-nudge-${w}x${h}.png` });
if (!all) { await close(T); continue; } // (no buttons: the rest of this size cannot run)
// each button moves the cell by one cell in that SCREEN direction (the board may be turned 90 degrees)
const dirs = { left: [-1, 0], up: [0, -1], down: [0, 1], right: [1, 0] };
let ok = true, detail = '';
for (const [name, d] of Object.entries(dirs)) {
const i0 = await info(); await tapBtn(d); const i1 = await info();
const ex = i0.cs * d[0], ey = i0.cs * d[1];
if (!i1 || Math.abs((i1.sx - i0.sx) - ex) > 1.5 || Math.abs((i1.sy - i0.sy) - ey) > 1.5) { ok = false; detail += ` ${name}: moved (${(i1.sx - i0.sx).toFixed(1)}, ${(i1.sy - i0.sy).toFixed(1)}) not (${ex.toFixed(1)}, ${ey.toFixed(1)});`; }
}
assert(ok, `nudge: left/up/down/right move the cell one cell on screen (rot ${(await info()).rot.toFixed(2)})${detail}`);
// Build builds at the nudged cell
const i2 = await info(), t0 = (await T.st()).towers;
await page.tap('#btnConfirmBuild'); await sleep(150);
const built = await page.evaluate(() => NW.app.ctrl.view.towers.map((t) => t.x + ',' + t.y));
assert((await T.st()).towers === t0 + 1 && built.includes(i2.x + ',' + i2.y), `nudge: Build builds at the nudged cell ${i2.x},${i2.y}`);
// the preview and route hint follow: nudge onto a dead node and the hint turns into the reason
const dead = await page.evaluate(() => {
const b = NW.app.ctrl.board, r = NW.app.renderer;
for (let y = 0; y < b.rows; y++) for (let x = 0; x < b.cols; x++) {
if (b.obst[y * b.cols + x]) continue;
const n = r.stepCell(x, y, 0, -1);
if (b.inBounds(n.x, n.y) && b.obst[n.y * b.cols + n.x] && !NW.app.ctrl.view.towers.some((t) => t.x === x && t.y === y)) return { x, y, nx: n.x, ny: n.y };
}
return null;
});
await T.arm('filter', true);
if (dead) {
await T.tap(await T.pt(dead.x, dead.y));
const h0 = (await info()).hint; await tapBtn([0, -1]); const i3 = await info();
assert(i3.x === dead.nx && i3.y === dead.ny && /dead|✕/.test(i3.hint) && h0 !== i3.hint, `nudge: the route hint follows the nudged cell ("${h0}" -> "${i3.hint}")`);
}
// the edge of the board: nudging past it stays put (no error, no off-board cell)
await T.tap(await T.pt(0, 0));
const e0 = await info(); for (let k = 0; k < 2; k++) { await tapBtn([-1, 0]); await tapBtn([0, -1]); } const e1 = await info();
assert(e1 && e1.x >= 0 && e1.y >= 0, `nudge: the cell stays on the board when nudged past the edge (${e1 && e1.x},${e1 && e1.y})`);
// the bar does not hop to the other half while you nudge across the middle: tap down, down, down... on the SAME button
await T.arm('filter', true);
await T.tap(await T.pt(2, 2));
let flips = 0, landed = 0, steps = 0, covered = false, lastBar = (await info()).bar.t;
for (let k = 0; k < 12; k++) {
const i0 = await info(); if (!i0) break;
const r = await btnRect([0, 1]); if (!r) break;
await page.touchscreen.tap((r.l + r.r) / 2, (r.t + r.b) / 2); await sleep(90);
const i1 = await info(); steps++;
if (i1 && Math.abs((i1.sy - i0.sy) - i0.cs) < 1.5) landed++;
if (i1 && Math.abs(i1.bar.t - lastBar) > 2) { flips++; lastBar = i1.bar.t; }
if (i1 && overlap(i1.bar, { l: i1.sx - i1.cs / 2, r: i1.sx + i1.cs / 2, t: i1.sy - i1.cs / 2, b: i1.sy + i1.cs / 2 }, 0)) covered = true;
if (i1 && (i1.y >= 15 || i1.x >= 19)) break;
}
assert(landed >= 6 && flips <= 1 && !covered, `nudge: ${landed}/${steps} taps on the same button each moved the cell, the bar flipped ${flips}x and never covered the cell`);
await close(T);
}
// ================================================================ co-op: the partner sees the touch aim and it goes away again (touch-9)
{
tag = 'coop 390x844';
console.log('=== ' + tag);
const T = await open(390, 844); const page = T.page;
await page.evaluate(() => document.getElementById('btnMenu').click()); await sleep(100);
await page.evaluate(() => document.getElementById('btnCoop').click()); await sleep(100);
await page.fill('#inName', 'Tess');
await page.evaluate(() => document.getElementById('btnCreate').click());
await page.waitForFunction(() => NW.app.ctrl && NW.app.ctrl.kind === 'remote' && NW.app.ctrl.room && !document.getElementById('lobby').hidden === false, null, { timeout: 8000 }).catch(() => {});
await sleep(600);
const remote = await page.evaluate(() => NW.app.ctrl.kind === 'remote' && !!NW.app.ctrl.room);
assert(remote, 'co-op room created');
if (remote) {
T.box = await page.locator('#board').boundingBox();
await page.evaluate(() => { const c = NW.app.ctrl; window.__cur = []; const o = c._send.bind(c); c._send = (m) => { if (m.t === 'cursor') window.__cur.push({ x: m.x, y: m.y }); return o(m); }; });
const cur = () => page.evaluate(() => window.__cur.slice());
await T.arm('filter');
await T.tap(await T.pt(10, 8)); await sleep(150);
let c = await cur();
assert(c.some((m) => m.x === 10.5 && m.y === 8.5), `touch-9: a plain tap shows a cursor on the partner's board (${JSON.stringify(c.slice(-2))})`);
await page.tap('#btnCancelBuild'); await sleep(150);
c = await cur();
assert(c.length && c[c.length - 1].x === null, `touch-9: Cancel clears it (last ${JSON.stringify(c[c.length - 1])})`);
await T.arm('wall'); const before = (await cur()).length;
const a = await T.pt(6, 4), b = await T.pt(6, 9);
await T.touch('touchStart', [a]);
for (let i = 1; i <= 8; i++) { await T.touch('touchMove', [{ x: a.x + (b.x - a.x) * i / 8, y: a.y + (b.y - a.y) * i / 8 }]); await sleep(40); }
c = await cur();
const during = c.slice(before).some((m) => m.x !== null);
await T.touch('touchEnd', []); await sleep(150);
c = await cur();
assert(during && c[c.length - 1].x === null, `touch-9: a wall stroke shows the cursor and lifting the finger clears it (shown ${during}, last ${JSON.stringify(c[c.length - 1])})`);
// a clear straight after a move is not swallowed by the 70 ms throttle
const r = await page.evaluate(() => { const c = NW.app.ctrl; c.lastCursor = -1e9; window.__cur.length = 0; c.sendCursor(3, 3); c.sendCursor(null, null); return window.__cur.slice(); });
assert(r.length === 2 && r[1].x === null, `touch-9: sendCursor(null) bypasses the throttle (${JSON.stringify(r)})`);
}
await close(T);
}
// ================================================================ desktop: keyboard, wheel, mouse
{
tag = 'desktop 1280x800';
console.log('=== ' + tag);
// code-6: a held Space is one wave
let T = await open(1280, 800, 'mouse'); let page = T.page;
await page.keyboard.down(' ');
for (let i = 0; i < 20; i++) { await page.keyboard.down(' '); await sleep(15); }
await page.keyboard.up(' '); await sleep(150);
let s = await T.st();
assert(s.wave === 1, `code-6: holding Space (20 key repeats) starts one wave (wave ${s.wave})`);
// code-8: Enter on the focused Menu button opens the menu instead of starting a wave
await page.focus('#btnMenu'); await page.keyboard.press('Enter'); await sleep(200);
const menuOpen = await page.evaluate(() => !document.getElementById('menu').hidden);
s = await T.st();
assert(menuOpen && s.wave === 1, `code-8: Enter on the focused Menu button opens the menu and starts no wave (menu open ${menuOpen}, wave ${s.wave})`);
await page.keyboard.press('Escape'); await sleep(100);
// code-22: the wheel zooms in proportion to the scroll distance
const c = await T.pt(10, 8);
await page.mouse.move(c.x, c.y);
for (let i = 0; i < 6; i++) await page.mouse.wheel(0, -1);
await sleep(100);
const z1 = (await T.st()).zoom;
assert(z1 < 1.05, `code-22: six tiny wheel events barely zoom (zoom ${z1.toFixed(3)})`);
await page.mouse.wheel(0, -100); await sleep(100);
const z2 = (await T.st()).zoom;
assert(z2 > 1.08 && z2 < 1.3, `code-22: one 100-unit wheel notch is about 1.16x (zoom ${z2.toFixed(3)})`);
await close(T);
// touch-17 with the mouse: press on a turret with the Firewall armed and drag
T = await open(1280, 800, 'mouse'); page = T.page;
await T.build('filter', 10, 5); await T.arm('wall');
const a = await T.pt(10, 5), b = await T.pt(10, 9);
await page.mouse.move(a.x, a.y); await page.mouse.down();
for (let i = 1; i <= 8; i++) { await page.mouse.move(a.x + (b.x - a.x) * i / 8, a.y + (b.y - a.y) * i / 8); await sleep(16); }
await page.mouse.up(); await sleep(100);
s = await T.st();
assert(s.selType === 'wall' && s.selTower === 0 && s.walls >= 3, `touch-17 (mouse): a stroke from a turret keeps the Firewall tool and paints (selType ${s.selType}, walls ${s.walls})`);
await page.mouse.click(a.x, a.y); await sleep(100);
s = await T.st();
assert(s.selTower > 0, `touch-17 (mouse): a plain click on the turret selects it (selTower ${s.selTower})`);
await close(T);
}
if (errors.length) failures.push('console errors:\n' + errors.join('\n'));
if (failures.length) throw new Error(failures.length + ' check(s) failed:\n ' + failures.join('\n '));
console.log('touch precision: all checks passed');
};

View file

@ -1,11 +1,20 @@
/* Netwall - styles. Dark "network operations" theme. Mobile-first: portrait phones, landscape phones, desktop. */ /* Netwall - styles. Dark "network operations" theme. Mobile-first: portrait phones, landscape phones, desktop.
*
* Layout modes (see main.js layoutApp for the JS half):
* wide stage | side panel (320px). Desktop and tablets in landscape. Tower actions live in the side panel.
* stacked top bar / stage / side panel. Portrait phones and narrow windows: (orientation: portrait), (max-width: 760px) and (min-height: 521px)
* short stage | narrow side panel, one-row top bar. Landscape phones: (orientation: landscape) and (max-height: 520px)
* compact #app[data-ui="compact"]: stacked OR short OR a coarse pointer. Here the selected tower's actions float over the
* stage as a bar (placed on the half of the stage away from the tower), and every target is at least 44px.
* Everything that has to be reachable (primary buttons, tower actions, room code) is positioned, never scrolled to.
*/
:root { :root {
--bg: #070b16; --bg: #070b16;
--panel: #0c1322; --panel: #0c1322;
--panel2: #111b30; --panel2: #111b30;
--line: #1d2c4c; --line: #1d2c4c;
--text: #d3e6ff; --text: #d3e6ff;
--dim: #7f97bd; --dim: #8ea6cc;
--cyan: #4de3ff; --cyan: #4de3ff;
--amber: #ffd24d; --amber: #ffd24d;
--red: #ff5c7a; --red: #ff5c7a;
@ -16,11 +25,13 @@
--safe-b: env(safe-area-inset-bottom, 0px); --safe-b: env(safe-area-inset-bottom, 0px);
--safe-l: env(safe-area-inset-left, 0px); --safe-l: env(safe-area-inset-left, 0px);
--btn: 40px; --btn: 40px;
--tile-h: 66px;
--bar-h: 54px;
--nudge-h: 52px; /* the build bar is this much taller than the tower bar: it has a row of nudge buttons */
--aspect: 26 / 16; --aspect: 26 / 16;
--font: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; --font: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace; --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;
} }
@media (pointer: coarse) { :root { --btn: 46px; } }
* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; } * { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
html, body { html, body {
@ -40,7 +51,7 @@ svg.ic { width: 1.25em; height: 1.25em; flex: none; }
grid-template-columns: minmax(0, 1fr) var(--side-w); grid-template-columns: minmax(0, 1fr) var(--side-w);
grid-template-rows: auto minmax(0, 1fr); grid-template-rows: auto minmax(0, 1fr);
grid-template-areas: "top top" "stage side"; grid-template-areas: "top top" "stage side";
padding: var(--safe-t) var(--safe-r) var(--safe-b) var(--safe-l); padding: var(--safe-t) var(--safe-r) var(--safe-b) var(--safe-l); /* the one place the safe-area insets are applied */
background: background:
radial-gradient(1200px 600px at 20% -10%, #0f1f3d 0%, transparent 60%), radial-gradient(1200px 600px at 20% -10%, #0f1f3d 0%, transparent 60%),
radial-gradient(900px 500px at 100% 110%, #1b1035 0%, transparent 55%), var(--bg); radial-gradient(900px 500px at 100% 110%, #1b1035 0%, transparent 55%), var(--bg);
@ -48,18 +59,19 @@ svg.ic { width: 1.25em; height: 1.25em; flex: none; }
#topbar { grid-area: top; display: flex; align-items: center; flex-wrap: wrap; gap: 6px 8px; padding: 6px 10px; background: rgba(8, 13, 26, .85); border-bottom: 1px solid var(--line); } #topbar { grid-area: top; display: flex; align-items: center; flex-wrap: wrap; gap: 6px 8px; padding: 6px 10px; background: rgba(8, 13, 26, .85); border-bottom: 1px solid var(--line); }
#stage { grid-area: stage; position: relative; min-width: 0; min-height: 0; overflow: hidden; touch-action: none; } #stage { grid-area: stage; position: relative; min-width: 0; min-height: 0; overflow: hidden; touch-action: none; }
#side > * { flex: none; } #side > * { flex: none; }
#side { grid-area: side; display: flex; flex-direction: column; gap: 10px; padding: 10px; overflow-y: auto; border-left: 1px solid var(--line); background: rgba(8, 13, 26, .7); -webkit-overflow-scrolling: touch; } /* (no transform / filter / mask / contain on #side or #info: the tower action bar is position:fixed inside them) */
#side { grid-area: side; display: flex; flex-direction: column; gap: 10px; padding: 10px; overflow-y: auto; border-left: 1px solid var(--line); background: rgba(8, 13, 26, .7); }
#board { position: absolute; inset: 0; width: 100%; height: 100%; display: block; touch-action: none; outline: none; } #board { position: absolute; inset: 0; width: 100%; height: 100%; display: block; touch-action: none; outline: none; }
/* portrait phones / narrow windows: board on top, panels underneath */ /* stacked: portrait phones and narrow windows. main.js sets --stage-h so the stage hugs the board (no dead bands) and the side panel gets the rest */
@media (orientation: portrait), (max-width: 760px) and (min-height: 521px) { @media (orientation: portrait), (max-width: 760px) and (min-height: 521px) {
#app { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto auto minmax(0, 1fr); grid-template-areas: "top" "stage" "side"; } #app { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto var(--stage-h, 56dvh) minmax(0, 1fr); grid-template-areas: "top" "stage" "side"; }
#stage { aspect-ratio: var(--aspect-p, 16 / 26); max-height: 58dvh; width: 100%; } #stage { width: 100%; }
#side { border-left: 0; border-top: 1px solid var(--line); padding: 8px 10px calc(8px + var(--safe-b)); gap: 8px; } #side { border-left: 0; border-top: 1px solid var(--line); padding: 0 10px 8px; gap: 8px; }
} }
/* landscape phones: short viewport, narrow side panel */ /* landscape phones: short viewport, narrow side panel */
@media (orientation: landscape) and (max-height: 520px) { @media (orientation: landscape) and (max-height: 520px) {
:root { --side-w: 236px; --btn: 40px; } :root { --side-w: 236px; --btn: 40px; --tile-h: 58px; }
#topbar { padding: 3px 8px; gap: 4px 6px; flex-wrap: nowrap; } #topbar { padding: 3px 8px; gap: 4px 6px; flex-wrap: nowrap; }
#side { gap: 6px; padding: 6px; } #side { gap: 6px; padding: 6px; }
} }
@ -72,82 +84,139 @@ svg.ic { width: 1.25em; height: 1.25em; flex: none; }
.stat .lbl { color: var(--dim); font-size: 11px; letter-spacing: .12em; } .stat .lbl { color: var(--dim); font-size: 11px; letter-spacing: .12em; }
#statLives { color: var(--red); } #statLives { color: var(--red); }
#statGold { color: var(--amber); } #statGold { color: var(--amber); }
#statLives.low { animation: pulse 0.8s infinite; } #statLives.low { border-color: var(--red); box-shadow: 0 0 0 2px rgba(255, 92, 122, .35); background: #2a0e18; animation: pulse 0.8s infinite; } /* static cue first, the pulse is extra */
@keyframes pulse { 50% { background: #3a1020; } } @keyframes pulse { 50% { background: #4a1426; } }
.spacer { flex: 1 1 8px; } .spacer { flex: 1 1 8px; }
.chip { display: flex; align-items: center; gap: 6px; padding: 0 10px; height: var(--btn); border-radius: 10px; background: var(--panel); border: 1px solid var(--line); font-family: var(--mono); font-size: 13px; color: var(--cyan); } button.chip { gap: 6px; padding: 0 10px; border-radius: 10px; background: var(--panel); font-family: var(--mono); font-size: 13px; color: var(--cyan); }
button.chip .share { width: 1.1em; height: 1.1em; opacity: .85; }
button.chip:hover { background: #15233f; }
.chip #netPing { color: var(--dim); } .chip #netPing { color: var(--dim); }
.chip.bad #netPing { color: var(--red); } .chip.bad #netPing { color: var(--red); }
.chip.waiting { border-color: var(--amber); color: var(--amber); animation: glow 1.4s infinite; } /* alone in the room: tap to invite */
button { min-height: var(--btn); border-radius: 10px; border: 1px solid var(--line); background: var(--panel2); padding: 0 14px; display: inline-flex; align-items: center; justify-content: center; gap: 8px; touch-action: manipulation; transition: background .12s, border-color .12s, transform .05s; } button { min-height: var(--btn); border-radius: 10px; border: 1px solid var(--line); background: var(--panel2); padding: 0 14px; display: inline-flex; align-items: center; justify-content: center; gap: 8px; touch-action: manipulation; transition: background .12s, border-color .12s, transform .05s; }
button:hover { border-color: #35538a; background: #15233f; } button:hover { border-color: #35538a; background: #15233f; }
button:active { transform: translateY(1px); } button:active { transform: translateY(1px); }
button:disabled { opacity: .4; cursor: default; } button:disabled { opacity: 1; cursor: default; color: #8da3c8; background: #0c1426; border-color: #172540; }
button:focus-visible, input:focus-visible { outline: 2px solid var(--cyan); outline-offset: 2px; } button:focus-visible, input:focus-visible { outline: 2px solid var(--cyan); outline-offset: 2px; }
button.icon { min-width: var(--btn); padding: 0 8px; font-family: var(--mono); font-size: 13px; } button.icon { min-width: var(--btn); padding: 0 8px; font-family: var(--mono); font-size: 13px; }
button.icon.toggle[aria-pressed="true"] { background: #0f3550; border-color: var(--cyan); color: var(--cyan); } button.icon.toggle[aria-pressed="true"] { background: #0f3550; border-color: var(--cyan); color: var(--cyan); }
button#btnPause[aria-pressed="true"] { background: #3a2c08; border-color: var(--amber); color: var(--amber); }
button.primary { background: linear-gradient(#1b7a96, #135872); border-color: #2fb4d6; color: #eaffff; font-weight: 600; } button.primary { background: linear-gradient(#1b7a96, #135872); border-color: #2fb4d6; color: #eaffff; font-weight: 600; }
button.primary:hover { background: linear-gradient(#2290b0, #176b8a); } button.primary:hover { background: linear-gradient(#1b7a96, #135872); border-color: #8fe6ff; }
button.danger { color: var(--red); } button.danger { color: var(--red); }
button.big { min-height: calc(var(--btn) + 6px); font-size: 16px; padding: 0 20px; } button.big { min-height: calc(var(--btn) + 6px); font-size: 16px; padding: 0 20px; }
button.link { background: none; border: 0; color: var(--dim); text-decoration: underline; min-height: 36px; padding: 0 8px; } button.link { background: none; border: 0; color: var(--dim); text-decoration: underline; min-height: 36px; padding: 0 8px; }
button.link:hover { color: var(--text); background: none; } button.link:hover { color: var(--text); background: none; }
button.floating { position: absolute; right: 8px; bottom: 8px; background: rgba(12, 19, 34, .85); } button.floating { position: absolute; right: 8px; bottom: 8px; background: rgba(12, 19, 34, .85); }
#btnWave { white-space: nowrap; min-width: 0; } /* long label ("Wave 12 · 28s") shrinks with an ellipsis instead of wrapping or pushing Sound off screen */
#btnWaveText { overflow: hidden; text-overflow: ellipsis; }
#btnWave.attn { animation: glow 1.4s infinite; } #btnWave.attn { animation: glow 1.4s infinite; }
@keyframes glow { 50% { box-shadow: 0 0 0 4px rgba(77, 227, 255, .25); } } @keyframes glow { 50% { box-shadow: 0 0 0 4px rgba(77, 227, 255, .25); } }
@media (orientation: portrait), (max-width: 760px) and (min-height: 521px) { @media (orientation: portrait), (max-width: 760px) and (min-height: 521px) {
#topbar { padding: 6px 8px; } #topbar { padding: 6px 8px; }
.stat { padding: 0 8px; font-size: 15px; } .stat { padding: 0 8px; font-size: 15px; }
#btnWave { flex: 1 1 auto; } #btnWave { flex: 1 1 130px; }
.spacer { flex: 0 0 0; } .spacer { display: none; }
button.chip { margin-left: auto; font-size: 12.5px; padding: 0 8px; }
.chip #netPing { display: none; }
} }
/* ---------------------------------------------------------------- stage overlays */ /* ---------------------------------------------------------------- stage overlays */
.hint { position: absolute; top: 8px; left: 50%; transform: translateX(-50%); max-width: calc(100% - 20px); padding: 6px 12px; border-radius: 999px; background: rgba(8, 13, 26, .92); border: 1px solid var(--line); font-family: var(--mono); font-size: 13px; pointer-events: none; white-space: nowrap; } .hint { position: absolute; top: 8px; left: 50%; transform: translateX(-50%); max-width: calc(100% - 20px); padding: 6px 12px; border-radius: 999px; background: rgba(8, 13, 26, .92); border: 1px solid var(--line); font-family: var(--mono); font-size: 13px; pointer-events: none; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.hint.ok { color: var(--green); border-color: #1c6a55; } .hint.ok { color: var(--green); border-color: #1c6a55; }
.hint.bad { color: var(--red); border-color: #6a2336; } .hint.bad { color: var(--red); border-color: #6a2336; }
.hint.info { color: var(--cyan); } .hint.info { color: var(--cyan); }
.paused-tag { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); padding: 10px 26px; border-radius: 999px; background: rgba(8, 13, 26, .88); border: 1px solid var(--amber); color: var(--amber); font-weight: 800; letter-spacing: .3em; font-size: 18px; pointer-events: none; z-index: 2; } /* paused: the board is dimmed and the pill is a button that resumes */
#stage.paused::after { content: ""; position: absolute; inset: 0; background: rgba(4, 7, 14, .5); pointer-events: none; z-index: 1; }
.paused-tag { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); padding: 8px 22px 8px 16px; min-height: 52px; border-radius: 999px; background: rgba(8, 13, 26, .94); border: 2px solid var(--amber); color: var(--amber); font-weight: 800; letter-spacing: .24em; font-size: 17px; z-index: 2; }
.paused-tag:hover { background: rgba(30, 24, 8, .96); border-color: var(--amber); }
.paused-tag span { display: flex; flex-direction: column; align-items: flex-start; line-height: 1.15; }
.paused-tag small { font-size: 11px; letter-spacing: .08em; font-weight: 600; color: #e8d9a0; }
.paused-tag .ic { width: 1.5em; height: 1.5em; }
.banner { position: absolute; left: 0; right: 0; top: 34%; text-align: center; pointer-events: none; font-weight: 800; font-size: clamp(22px, 5vw, 44px); letter-spacing: .14em; color: var(--cyan); text-shadow: 0 0 24px rgba(77, 227, 255, .6); opacity: 0; transform: scale(.96); transition: opacity .3s, transform .3s; } .banner { position: absolute; left: 0; right: 0; top: 34%; text-align: center; pointer-events: none; font-weight: 800; font-size: clamp(22px, 5vw, 44px); letter-spacing: .14em; color: var(--cyan); text-shadow: 0 0 24px rgba(77, 227, 255, .6); opacity: 0; transform: scale(.96); transition: opacity .3s, transform .3s; }
.banner.show { opacity: 1; transform: none; } .banner.show { opacity: 1; transform: none; }
.banner.boss { color: var(--red); text-shadow: 0 0 24px rgba(255, 92, 122, .7); } .banner.boss { color: var(--red); text-shadow: 0 0 24px rgba(255, 92, 122, .7); }
#toasts { position: absolute; left: 0; right: 0; bottom: 10px; display: flex; flex-direction: column; align-items: center; gap: 6px; pointer-events: none; } /* toasts sit under the route hint at the top, and drop below the action bar when that one is at the top (never behind it, never on the server) */
.toast { padding: 7px 14px; background: rgba(8, 13, 26, .94); border: 1px solid var(--line); border-radius: 10px; font-size: 14px; animation: toast 2.6s forwards; max-width: calc(100% - 24px); text-align: center; } #toasts { position: absolute; left: 0; right: 0; top: 46px; display: flex; flex-direction: column; align-items: center; gap: 6px; pointer-events: none; z-index: 5; }
#app[data-ui="compact"][data-bar="top"] #toasts { top: calc(var(--bar-h) + 18px); }
#app[data-ui="compact"][data-bar="top"][data-conf] #toasts { top: calc(var(--bar-h) + var(--nudge-h) + 18px); }
.toast { padding: 7px 14px; background: rgba(8, 13, 26, .96); border: 1px solid var(--line); border-radius: 10px; font-size: 14px; animation: toast 2.6s forwards; max-width: calc(100% - 24px); text-align: center; }
.toast.bad { border-color: #6a2336; color: #ffb3c1; } .toast.bad { border-color: #6a2336; color: #ffb3c1; }
.toast.good { border-color: #1c6a55; color: #aef5d6; } .toast.good { border-color: #1c6a55; color: #aef5d6; }
@keyframes toast { 0% { opacity: 0; transform: translateY(8px); } 8% { opacity: 1; transform: none; } 80% { opacity: 1; } 100% { opacity: 0; } } @keyframes toast { 0% { opacity: 0; transform: translateY(-8px); } 8% { opacity: 1; transform: none; } 80% { opacity: 1; } 100% { opacity: 0; } }
.confirm { position: absolute; left: 50%; bottom: 10px; transform: translateX(-50%); display: flex; gap: 8px; padding: 6px; border-radius: 14px; background: rgba(8, 13, 26, .94); border: 1px solid var(--line); z-index: 3; white-space: nowrap; } /* touch build bar: cancel, the route text (what the hint pill shows on desktop), and Build. Same slot and size as the tower action bar. */
.confirm.top { bottom: auto; top: 52px; } .confirm { position: absolute; left: 50%; bottom: 8px; transform: translateX(-50%); width: min(calc(100% - 16px), 480px); height: calc(var(--bar-h) + var(--nudge-h)); display: flex; flex-wrap: wrap; align-content: center; align-items: center; gap: 6px 8px; padding: 5px; border-radius: 14px; background: rgba(8, 13, 26, .96); border: 1px solid #2c4372; box-shadow: 0 6px 22px rgba(0, 0, 0, .5); z-index: 3; }
.confirm .primary.big { min-width: 120px; } .confirm.top { bottom: auto; top: 8px; }
.reconnect { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; gap: 12px; background: rgba(5, 8, 16, .72); z-index: 4; font-size: 16px; } .confirm button { min-height: 44px; flex: none; }
.spinner { width: 22px; height: 22px; border: 3px solid var(--line); border-top-color: var(--cyan); border-radius: 50%; animation: spin .8s linear infinite; } .confirm .primary.big { min-width: 112px; padding: 0 12px; font-size: 15px; }
.chint { flex: 1 1 0; min-width: 0; text-align: center; font-family: var(--mono); font-size: 12.5px; line-height: 1.2; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
/* nudge row: one cell left / up / down / right, for fine aim when a cell is only 12 to 20 px (the arrow is the up icon turned) */
.nudge { flex: 1 1 100%; display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; }
.nudge button { width: 100%; padding: 0; }
/* a stage wide enough for it (tablets, landscape phones) keeps the build bar one row: cancel, route text, arrows, Build */
#app[data-barrows="1"] { --nudge-h: 0px; }
#app[data-barrows="1"] .confirm { flex-wrap: nowrap; }
#app[data-barrows="1"] #confirmHint { order: 1; }
#app[data-barrows="1"] .nudge { order: 2; flex: 0 0 auto; grid-template-columns: repeat(4, 44px); gap: 4px; }
#app[data-barrows="1"] #btnConfirmBuild { order: 3; }
/* a stage too short for two rows (320x568): one row, no route text in the bar (it goes to the pill at the top) and a check-only Build, so the bar leaves the board free */
#app[data-barrows="0"] { --nudge-h: 0px; }
#app[data-barrows="0"] .confirm { flex-wrap: nowrap; gap: 4px; justify-content: space-between; }
#app[data-barrows="0"] #confirmHint, #app[data-barrows="0"] #confirmText { display: none; }
#app[data-barrows="0"] .nudge { order: 2; flex: 0 0 auto; grid-template-columns: repeat(4, 44px); gap: 4px; }
#app[data-barrows="0"] #btnConfirmBuild { order: 3; min-width: 44px; padding: 0; }
#app[data-barrows="0"][data-bar="top"] .hint { top: calc(var(--bar-h) + 16px); }
.nudge [data-dx="-1"] .ic { transform: rotate(-90deg); } .nudge [data-dx="1"] .ic { transform: rotate(90deg); } .nudge [data-dy="1"] .ic { transform: rotate(180deg); }
.chint.ok { color: var(--green); } .chint.bad { color: var(--red); } .chint.info { color: var(--cyan); }
#app[data-ui="compact"][data-bar="bottom"] #btnFit { bottom: auto; top: 8px; } /* keep the reset-zoom button out from under the bar */
.reconnect { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; gap: 12px; background: rgba(5, 8, 16, .78); z-index: 4; font-size: 16px; padding: 0 16px; text-align: center; }
.spinner { width: 22px; height: 22px; flex: none; border: 3px solid var(--line); border-top-color: var(--cyan); border-radius: 50%; animation: spin .8s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } } @keyframes spin { to { transform: rotate(360deg); } }
/* offline: the rest of the HUD looks dead too (only the menu and the room chip stay usable) */
#app.offline #side, #app.offline #topbar > :not(#btnMenu):not(#netChip) { opacity: .45; pointer-events: none; }
/* ---------------------------------------------------------------- side panel */ /* ---------------------------------------------------------------- side panel: palette */
#side h4 { margin: 0 0 6px; font-size: 11px; letter-spacing: .14em; color: var(--dim); text-transform: uppercase; font-weight: 600; } #side h4 { margin: 0 0 6px; font-size: 11px; letter-spacing: .14em; color: var(--dim); text-transform: uppercase; font-weight: 600; }
#palette { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; } #palette { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; }
.tbtn { position: relative; flex-direction: column; gap: 2px; padding: 6px 4px 5px; min-height: 66px; text-align: center; line-height: 1.15; } #palette.many { grid-template-columns: repeat(4, minmax(0, 1fr)); } /* more than 6 towers */
.tbtn { position: relative; flex-direction: column; gap: 2px; padding: 6px 4px 5px; min-height: var(--tile-h); text-align: center; line-height: 1.15; }
.tbtn canvas { width: 34px; height: 34px; pointer-events: none; } .tbtn canvas { width: 34px; height: 34px; pointer-events: none; }
.tbtn .nm { font-size: 11.5px; color: var(--text); } .tbtn .nm { font-size: 11.5px; color: var(--text); }
.tbtn .cost { font-family: var(--mono); font-size: 12px; color: var(--amber); } .tbtn .cost { font-family: var(--mono); font-size: 12px; color: var(--amber); }
.tbtn .key { position: absolute; top: 3px; left: 5px; font-family: var(--mono); font-size: 10px; color: var(--dim); } .tbtn .key { position: absolute; top: 3px; left: 5px; font-family: var(--mono); font-size: 11px; color: #9db4d8; }
.tbtn.sel { border-color: var(--cyan); background: #0f3550; box-shadow: inset 0 0 0 1px var(--cyan); } .tbtn.sel { border-color: var(--cyan); background: #0f3550; box-shadow: inset 0 0 0 1px var(--cyan); }
.tbtn.poor .cost { color: var(--red); } .tbtn.poor .nm { color: #9fb2d4; }
.tbtn.poor { opacity: .72; } .tbtn.poor .cost { color: #ff8fa3; }
.tbtn.poor canvas { opacity: .6; }
@media (pointer: coarse) { .tbtn .key { display: none; } } @media (pointer: coarse) { .tbtn .key { display: none; } }
/* scroll affordance: main.js sets data-more="start|end|both" on a palette that has hidden tiles; the edge fades out */
#palette[data-more="end"] { -webkit-mask-image: linear-gradient(var(--fade-dir, to right), #000 calc(100% - 30px), transparent); mask-image: linear-gradient(var(--fade-dir, to right), #000 calc(100% - 30px), transparent); }
#palette[data-more="start"] { -webkit-mask-image: linear-gradient(var(--fade-dir, to right), transparent, #000 30px); mask-image: linear-gradient(var(--fade-dir, to right), transparent, #000 30px); }
#palette[data-more="both"] { -webkit-mask-image: linear-gradient(var(--fade-dir, to right), transparent, #000 30px, #000 calc(100% - 30px), transparent); mask-image: linear-gradient(var(--fade-dir, to right), transparent, #000 30px, #000 calc(100% - 30px), transparent); }
/* stacked: one scrolling row of tiles pinned to the top of the side panel (thumb reach), wrapping grid when there is room */
@media (orientation: portrait), (max-width: 760px) and (min-height: 521px) { @media (orientation: portrait), (max-width: 760px) and (min-height: 521px) {
#palette { position: sticky; top: -8px; z-index: 2; margin: -8px -10px 0; padding: 8px 10px 6px; background: rgba(8, 13, 26, .97); } #palette { position: sticky; top: 0; z-index: 2; margin: 0 -10px; padding: 8px 10px 6px; background: #0a101f; display: flex; overflow-x: auto; gap: 6px; scrollbar-width: none; scroll-snap-type: x proximity; scroll-padding: 0 10px; overscroll-behavior-x: contain; }
#palette { display: flex; overflow-x: auto; gap: 6px; padding-bottom: 2px; scrollbar-width: none; scroll-snap-type: x proximity; scroll-padding: 0 10px; }
#palette::-webkit-scrollbar { display: none; } #palette::-webkit-scrollbar { display: none; }
.tbtn { flex: 0 0 76px; min-height: 72px; scroll-snap-align: start; } .tbtn { flex: 0 0 76px; min-height: 72px; scroll-snap-align: start; }
#palette.many { grid-template-columns: none; }
} }
@media (min-width: 640px) and (orientation: portrait), (min-width: 640px) and (max-width: 760px) and (min-height: 521px) {
#palette { display: grid; grid-template-columns: repeat(auto-fill, minmax(84px, 1fr)); overflow: visible; mask-image: none; -webkit-mask-image: none; }
#palette.many { grid-template-columns: repeat(auto-fill, minmax(84px, 1fr)); }
.tbtn { flex: none; }
}
/* short landscape: a few rows of tiles in the narrow column; a long palette scrolls vertically with a fade */
@media (orientation: landscape) and (max-height: 520px) { @media (orientation: landscape) and (max-height: 520px) {
#palette { grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 4px; } #palette { gap: 4px; max-height: calc(var(--tile-h) * 3.5 + 12px); overflow-y: auto; scrollbar-width: none; overscroll-behavior: contain; --fade-dir: to bottom; }
.tbtn { min-height: 58px; padding: 3px 2px; } #palette::-webkit-scrollbar { display: none; }
#palette.many { gap: 3px; }
.tbtn { padding: 3px 2px; }
.tbtn canvas { width: 26px; height: 26px; } .tbtn canvas { width: 26px; height: 26px; }
} }
/* ---------------------------------------------------------------- side panel: info, actions, wave, players */
.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 10px; } .panel { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 10px; }
#info:empty { display: none; } #info:empty { display: none; }
.info-head { display: flex; align-items: center; gap: 10px; margin-bottom: 6px; } .info-head { display: flex; align-items: center; gap: 10px; margin-bottom: 6px; }
@ -160,27 +229,62 @@ button.floating { position: absolute; right: 8px; bottom: 8px; background: rgba(
.kvp span:first-child { color: var(--dim); } .kvp span:first-child { color: var(--dim); }
.kv .up { color: var(--green); } .kv .up { color: var(--green); }
.actions { display: flex; flex-wrap: wrap; gap: 6px; } .actions { display: flex; flex-wrap: wrap; gap: 6px; }
.actions button { flex: 1 1 auto; font-size: 14px; } .actions button { flex: 1 1 auto; font-size: 14px; min-width: 0; white-space: nowrap; }
.actions .cost { font-family: var(--mono); color: var(--amber); } .actions .cost { font-family: var(--mono); color: var(--amber); }
.actions .mv { overflow: hidden; text-overflow: ellipsis; }
.actions [data-act="close"] { display: none; }
/* wide layout: the actions stay at the bottom edge of the side panel even when a tall palette pushes them down */
#app:not([data-ui="compact"]) .actions { position: sticky; bottom: 0; background: var(--panel); padding-top: 6px; margin-top: -2px; }
.byline { font-size: 11.5px; color: var(--dim); margin-top: 6px; display: flex; align-items: center; gap: 6px; } .byline { font-size: 11.5px; color: var(--dim); margin-top: 6px; display: flex; align-items: center; gap: 6px; }
.dot { width: 9px; height: 9px; border-radius: 50%; display: inline-block; flex: none; } .dot { width: 9px; height: 9px; border-radius: 50%; display: inline-block; flex: none; }
/* compact UI: the tower actions are a bar over the stage, on the half away from the tower (data-bar, set by main.js layoutBars) */
#app[data-ui="compact"] #info .actions {
position: fixed; z-index: 6; flex-wrap: nowrap; gap: 6px; padding: 5px; height: var(--bar-h);
left: calc(var(--st-l, 0px) + var(--st-w, 100vw) / 2); transform: translateX(-50%); width: min(calc(var(--st-w, 100vw) - 16px), 480px);
top: calc(var(--st-t, 0px) + var(--st-h, 120px) - var(--bar-h) - 8px);
border-radius: 14px; background: rgba(8, 13, 26, .96); border: 1px solid #2c4372; box-shadow: 0 6px 22px rgba(0, 0, 0, .5);
}
#app[data-ui="compact"][data-bar="top"] #info .actions { top: calc(var(--st-t, 0px) + 8px); }
#app[data-ui="compact"] #info .actions button { min-height: 44px; padding: 0 8px; gap: 5px; flex: 1 1 0; font-size: 14px; }
#app[data-ui="compact"] #info .actions [data-act="up"] { flex-grow: 1.1; }
#app[data-ui="compact"] #info .actions [data-act="mode"] { flex-grow: 1.4; }
#app[data-ui="compact"] #info .actions [data-act="close"] { display: inline-flex; flex: 0 0 44px; min-width: 44px; padding: 0; }
#app[data-ui="compact"][data-barw="s"] #info .actions [data-act="up"] .w, #app[data-ui="compact"][data-barw="s"] #info .actions [data-act="mode"] .w { display: none; }
#app[data-ui="compact"] #info .panel { padding: 8px 10px; }
#app[data-ui="compact"] .kv { display: flex; flex-wrap: wrap; gap: 2px 14px; margin-bottom: 4px; }
#app[data-ui="compact"] .kvp { display: inline-flex; gap: 6px; }
#app[data-ui="compact"] .info .desc { font-size: 12.5px; margin: 0 0 4px; }
#app[data-ui="compact"] .info-head { margin-bottom: 4px; }
#app[data-ui="compact"] .info-head canvas { width: 32px; height: 32px; }
#nextwave .panel { padding: 8px 10px; } #nextwave .panel { padding: 8px 10px; }
.wv { display: flex; flex-wrap: wrap; gap: 6px 10px; align-items: center; font-family: var(--mono); font-size: 12.5px; } .wv { display: flex; flex-wrap: wrap; gap: 6px 10px; align-items: center; font-family: var(--mono); font-size: 12.5px; }
.wv .e { display: inline-flex; align-items: center; gap: 4px; } .wv .e { display: inline-flex; align-items: center; gap: 4px; }
.wv .e i { width: 10px; height: 10px; border-radius: 3px; display: inline-block; } .wv .e i { width: 12px; height: 12px; display: inline-block; background: var(--c); flex: none; } /* shape per enemy kind, not just a colour (see .sh-*) */
.wv .e i.sh-ping, .wv .e i.sh-worm { border-radius: 50%; }
.wv .e i.sh-trojan { clip-path: polygon(25% 5%, 75% 5%, 100% 50%, 75% 95%, 25% 95%, 0 50%); }
.wv .e i.sh-spam { clip-path: polygon(0 20%, 60% 20%, 60% 0, 100% 50%, 60% 100%, 60% 80%, 0 80%); }
.wv .e i.sh-spoof { clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%); }
.wv .e i.sh-rootkit { clip-path: polygon(30% 0, 70% 0, 100% 30%, 100% 70%, 70% 100%, 30% 100%, 0 70%, 0 30%); width: 14px; height: 14px; }
.wv .tag { padding: 1px 6px; border-radius: 6px; font-size: 11px; border: 1px solid; } .wv .tag { padding: 1px 6px; border-radius: 6px; font-size: 11px; border: 1px solid; }
.wv .tag.air { color: #e29bff; border-color: #5b3a73; } .wv .tag.air { color: #e29bff; border-color: #5b3a73; }
.wv .tag.boss { color: var(--red); border-color: #6a2336; } .wv .tag.boss { color: var(--red); border-color: #6a2336; }
/* stacked / short: while a tower or build type is selected the wave panel makes room for its stats */
#app[data-ui="compact"] #info:not(:empty) ~ #nextwave { display: none; }
#players .pl { display: flex; align-items: center; gap: 8px; padding: 3px 0; font-size: 13.5px; } #players .pl { display: flex; align-items: center; gap: 8px; padding: 3px 0; font-size: 13.5px; }
#players .pl .off { color: var(--dim); font-size: 12px; } #players .pl .off { color: var(--dim); font-size: 12px; }
#players .pl .you { color: var(--dim); font-size: 12px; } #players .pl .you { color: var(--dim); font-size: 12px; }
#players .actions { margin-top: 6px; } #players .actions { margin-top: 6px; }
/* ---------------------------------------------------------------- overlays (menus) */ /* ---------------------------------------------------------------- overlays (menu, lobby, help, end)
.overlay { position: absolute; inset: 0; z-index: 10; display: flex; align-items: center; justify-content: center; padding: 14px; background: rgba(4, 7, 14, .78); backdrop-filter: blur(5px); -webkit-backdrop-filter: blur(5px); overflow-y: auto; } * .card is a flex column: .card-body scrolls, .card-foot (the primary buttons) is always visible. */
.card { width: min(560px, 100%); max-height: 100%; overflow-y: auto; margin: auto; padding: 20px 20px 16px; border-radius: 18px; background: linear-gradient(#0f1830, #0a1124); border: 1px solid #25396a; box-shadow: 0 20px 60px rgba(0, 0, 0, .6), 0 0 0 1px rgba(77, 227, 255, .06); } .overlay { position: absolute; inset: 0; z-index: 10; display: flex; align-items: center; justify-content: center; padding: max(14px, var(--safe-t)) max(14px, var(--safe-r)) max(14px, var(--safe-b)) max(14px, var(--safe-l)); background: rgba(4, 7, 14, .78); backdrop-filter: blur(5px); -webkit-backdrop-filter: blur(5px); overflow: hidden; }
.card { width: min(560px, 100%); max-height: 100%; min-height: 0; display: flex; flex-direction: column; overflow: hidden; border-radius: 18px; background: linear-gradient(#0f1830, #0a1124); border: 1px solid #25396a; box-shadow: 0 20px 60px rgba(0, 0, 0, .6), 0 0 0 1px rgba(77, 227, 255, .06); }
.card.wide { width: min(680px, 100%); } .card.wide { width: min(680px, 100%); }
.card-body { flex: 1 1 auto; min-height: 0; overflow-y: auto; overscroll-behavior: contain; padding: 20px 20px 10px; }
.card-foot { flex: none; padding: 10px 20px 14px; border-top: 1px solid #1a2a50; background: #0a1124; }
.card-foot > .row:first-child, .card-foot > .opts + .row { margin-top: 0; }
.card h1 { margin: 0; font-size: clamp(30px, 8vw, 46px); letter-spacing: .26em; font-weight: 800; color: #eaffff; text-shadow: 0 0 22px rgba(77, 227, 255, .55); } .card h1 { margin: 0; font-size: clamp(30px, 8vw, 46px); letter-spacing: .26em; font-weight: 800; color: #eaffff; text-shadow: 0 0 22px rgba(77, 227, 255, .55); }
.card h2 { margin: 0 0 8px; font-size: 24px; } .card h2 { margin: 0 0 8px; font-size: 24px; }
.card h3 { margin: 0 0 6px; font-size: 14px; letter-spacing: .08em; text-transform: uppercase; color: var(--dim); } .card h3 { margin: 0 0 6px; font-size: 14px; letter-spacing: .08em; text-transform: uppercase; color: var(--dim); }
@ -190,30 +294,41 @@ button.floating { position: absolute; right: 8px; bottom: 8px; background: rgba(
.muted { color: var(--dim); } .muted { color: var(--dim); }
.small { font-size: 13px; } .small { font-size: 13px; }
.row { display: flex; gap: 10px; justify-content: center; flex-wrap: wrap; margin-top: 12px; } .row { display: flex; gap: 10px; justify-content: center; flex-wrap: wrap; margin-top: 12px; }
.row.small { margin-top: 6px; } .row.small { margin-top: 4px; }
.row > .big { flex: 1 1 200px; } .row > .big { flex: 1 1 180px; }
.msg { min-height: 1.4em; text-align: center; color: var(--amber); margin: 8px 0 0; } .opts { display: flex; gap: 8px; justify-content: center; flex-wrap: wrap; margin-bottom: 10px; } /* difficulty selector goes here */
.opts:empty { display: none; }
.msg { min-height: 1.4em; text-align: center; color: var(--amber); margin: 0 0 4px; }
.msg.bad { color: var(--red); } .msg.bad { color: var(--red); }
.msg:empty { min-height: 0; margin: 0; }
.resume { width: 100%; margin-top: 10px; border-color: var(--cyan); color: var(--cyan); } .resume { width: 100%; margin-top: 10px; border-color: var(--cyan); color: var(--cyan); }
.maps { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; margin-bottom: 4px; } /* map picker: wrapping grid that copes with any number of maps (scrolls inside the card body) */
.maps { display: grid; grid-template-columns: repeat(auto-fill, minmax(96px, 1fr)); gap: 8px; margin-bottom: 4px; }
.mapcard { flex-direction: column; align-items: stretch; gap: 4px; padding: 8px; text-align: left; min-height: 0; border-radius: 12px; } .mapcard { flex-direction: column; align-items: stretch; gap: 4px; padding: 8px; text-align: left; min-height: 0; border-radius: 12px; }
.mapcard canvas { width: 100%; aspect-ratio: 26 / 16; border-radius: 6px; background: #060a14; } .mapcard canvas { width: 100%; aspect-ratio: 26 / 16; border-radius: 6px; background: #060a14; }
.mapcard .nm { font-weight: 700; font-size: 13.5px; min-height: 2.6em; } .mapcard .nm { font-weight: 700; font-size: 13.5px; min-height: 2.6em; }
.mapcard .df { font-size: 11px; color: var(--dim); letter-spacing: .06em; } .mapcard .df { font-size: 11px; color: #9db4d8; letter-spacing: .06em; }
.mapcard .df b { color: var(--amber); letter-spacing: 1px; } .mapcard .df b { color: var(--amber); letter-spacing: 1px; }
.mapcard[aria-checked="true"] { border-color: var(--cyan); background: #0f3550; box-shadow: inset 0 0 0 1px var(--cyan); } .mapcard[aria-checked="true"] { border-color: var(--cyan); background: #0f3550; box-shadow: inset 0 0 0 1px var(--cyan); }
.mapcard[aria-checked="true"] .nm::before { content: "\2713\00a0"; color: var(--cyan); }
.mapdesc { text-align: center; color: var(--dim); font-size: 13px; min-height: 2.6em; margin: 6px 0 4px; } .mapdesc { text-align: center; color: var(--dim); font-size: 13px; min-height: 2.6em; margin: 6px 0 4px; }
@media (max-width: 480px) { .mapcard .df { display: none; } .mapcard .nm { font-size: 12.5px; } .card { padding: 16px 14px 12px; } } @media (max-width: 480px) { .mapcard .df { display: none; } .mapcard .nm { font-size: 12.5px; min-height: 2.4em; } .card-body { padding: 14px 14px 8px; } .card-foot { padding: 8px 14px 12px; } }
.field { display: block; margin: 12px 0; } .field { display: block; margin: 12px 0; }
.field span { display: block; font-size: 12px; color: var(--dim); margin-bottom: 4px; letter-spacing: .06em; } .field span { display: block; font-size: 12px; color: var(--dim); margin-bottom: 4px; letter-spacing: .06em; }
input { width: 100%; min-height: var(--btn); border-radius: 10px; border: 1px solid var(--line); background: #070d1b; color: var(--text); padding: 0 12px; font: inherit; font-size: 16px; /* >=16px stops iOS zooming on focus */ } input { width: 100%; min-height: var(--btn); border-radius: 10px; border: 1px solid var(--line); background: #070d1b; color: var(--text); padding: 0 12px; font: inherit; font-size: 16px; /* >=16px stops iOS zooming on focus */ }
input.code { text-align: center; letter-spacing: .5em; font-family: var(--mono); font-size: 22px; text-transform: uppercase; padding-left: .5em; margin-bottom: 8px; } input::placeholder { color: #8397bb; }
input.code { text-align: center; letter-spacing: .5em; font-family: var(--mono); font-size: 22px; text-transform: uppercase; padding-left: .5em; }
.joinrow { display: flex; gap: 8px; margin-top: auto; }
.joinrow input { flex: 1 1 auto; min-width: 0; }
.joinrow button { flex: 0 0 auto; }
.split { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; } .split { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
.split .col { display: flex; flex-direction: column; gap: 6px; padding: 12px; border-radius: 12px; background: rgba(255, 255, 255, .02); border: 1px solid var(--line); } .split .col { display: flex; flex-direction: column; gap: 6px; padding: 12px; border-radius: 12px; background: rgba(255, 255, 255, .02); border: 1px solid var(--line); }
.split .col button { margin-top: auto; } .split .col > button { margin-top: auto; }
@media (max-width: 480px) { .split { grid-template-columns: 1fr; } } .roomlist { margin-top: 12px; }
@media (max-width: 480px) { .split { grid-template-columns: 1fr; gap: 10px; } }
@media (max-height: 640px) { .lead { display: none; } .field { margin: 8px 0; } .split .col { padding: 10px; } } /* small phones: the intro text makes way for the buttons */
.howto { padding-left: 18px; margin: 10px 0 0; display: grid; gap: 8px; } .howto { padding-left: 18px; margin: 10px 0 0; display: grid; gap: 8px; }
.howto li { color: #bcd3f5; } .howto li { color: #bcd3f5; }
@ -225,56 +340,87 @@ input.code { text-align: center; letter-spacing: .5em; font-family: var(--mono);
.stats div { display: flex; justify-content: space-between; padding: 4px 0; border-bottom: 1px solid var(--line); } .stats div { display: flex; justify-content: space-between; padding: 4px 0; border-bottom: 1px solid var(--line); }
.stats span { color: var(--dim); } .stats span { color: var(--dim); }
/* short landscape: compact menus so the title, a row of maps and the buttons all fit in 320px */
@media (orientation: landscape) and (max-height: 520px) {
.overlay { padding: max(6px, var(--safe-t)) max(8px, var(--safe-r)) max(6px, var(--safe-b)) max(8px, var(--safe-l)); }
.card-body { padding: 8px 16px 6px; }
.card-foot { padding: 6px 16px 8px; }
.card h1 { font-size: 24px; letter-spacing: .2em; }
.card h2 { font-size: 19px; margin-bottom: 4px; }
.logo { gap: 10px; } .logo-mark { width: 28px; height: 28px; }
.tag { margin: 2px 0 6px; font-size: 13px; }
.maps { display: flex; overflow-x: auto; scroll-snap-type: x proximity; scrollbar-width: none; padding-bottom: 2px; }
.maps::-webkit-scrollbar { display: none; }
.mapcard { flex: 0 0 118px; scroll-snap-align: start; padding: 5px; gap: 2px; }
.mapcard .nm { min-height: 0; font-size: 12px; }
.mapcard .df { display: none; }
.mapdesc { min-height: 0; margin: 4px 0 0; font-size: 12px; }
.row { margin-top: 6px; gap: 8px; } .row.small { margin-top: 0; }
.row > .big { flex: 1 1 140px; }
.lead { display: none; }
.field { margin: 6px 0; display: flex; align-items: center; gap: 10px; } .field span { margin: 0; flex: none; }
.split { gap: 8px; } .split .col { padding: 6px 8px; gap: 4px; } .split .col h3 { margin-bottom: 0; font-size: 12px; }
.split .col .small { display: none; }
.resume { margin-top: 6px; }
.stats { margin: 6px 0 2px; font-size: 13px; }
.stats div { padding: 2px 0; }
.howto { gap: 5px; font-size: 13.5px; }
button.link { min-height: 32px; }
}
/* the board gets the whole stage while a menu is shown behind blurred overlays; hide HUD chrome pre-game */ /* the board gets the whole stage while a menu is shown behind blurred overlays; hide HUD chrome pre-game */
#app[data-screen="menu"] #side, #app[data-screen="menu"] #side,
#app[data-screen="menu"] #topbar > :not(#btnMenu) { visibility: hidden; } #app[data-screen="menu"] #topbar > :not(#btnMenu) { visibility: hidden; }
@media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation-duration: .01ms !important; animation-iteration-count: 1 !important; transition-duration: .01ms !important; } } /* reduced motion: less movement, never less information (toasts and the low-integrity cue stay visible) */
@media (prefers-reduced-motion: reduce) {
/* compact info panel on stacked (portrait / narrow) layouts: must come after the base rules above */ .toast { animation: none; }
@media (orientation: portrait), (max-width: 760px) and (min-height: 521px) { #btnWave.attn, #statLives.low, .chip.waiting { animation: none; }
.kv { display: flex; flex-wrap: wrap; gap: 2px 14px; margin-bottom: 6px; } .banner { transition: none; }
.kvp { display: inline-flex; gap: 6px; } button { transition: none; }
.info .desc { font-size: 12.5px; margin: 0 0 4px; } .spinner { animation-duration: 2.4s; }
.info-head { margin-bottom: 4px; }
.info-head canvas { width: 32px; height: 32px; }
.panel { padding: 8px 10px; }
.actions button { min-height: 42px; }
} }
/* stacked layouts: keep the top bar to two rows even with the co-op chip */ /* narrow portrait phones: the room chip shrinks to its code + share icon, stats shrink so the bar stays two rows */
@media (orientation: portrait), (max-width: 760px) and (min-height: 521px) {
.chip { padding: 0 8px; font-size: 12.5px; }
.chip #netPing { display: none; }
#netChip { margin-left: auto; }
.spacer { display: none; }
#btnWave { flex: 1 1 130px; }
}
/* narrow portrait phones: the room chip moves into the players panel, stats shrink so the bar stays two rows */
@media (max-width: 420px) { @media (max-width: 420px) {
#netChip { display: none; } button.chip > svg:first-child { display: none; }
.stat { padding: 0 7px; gap: 4px; font-size: 14px; } .stat { padding: 0 7px; gap: 4px; font-size: 14px; }
.stat .lbl { font-size: 10px; letter-spacing: .06em; } .stat .lbl { font-size: 10px; letter-spacing: .06em; }
#topbar { gap: 5px 6px; padding: 5px 6px; } #topbar { gap: 5px 6px; padding: 5px 6px; }
} }
/* small landscape phones: one slim top bar, narrower side panel */ /* small landscape phones: one slim top bar, narrower side panel */
@media (orientation: landscape) and (max-height: 520px) and (max-width: 700px) { @media (orientation: landscape) and (max-height: 520px) and (max-width: 700px) {
:root { --side-w: 200px; --btn: 38px; } :root { --side-w: 200px; }
#netChip { display: none; }
.stat .lbl { display: none; } .stat .lbl { display: none; }
.stat { padding: 0 6px; font-size: 14px; } .stat { padding: 0 5px; font-size: 14px; }
button.icon { min-width: 36px; padding: 0 6px; } button.icon { min-width: 36px; padding: 0 6px; }
#topbar { gap: 4px; padding: 3px 6px; } #topbar { gap: 3px; padding: 3px 6px; }
#btnWave { padding: 0 8px; gap: 5px; }
.tbtn .nm { font-size: 10.5px; } .tbtn .nm { font-size: 10.5px; }
button.chip { padding: 0 6px; font-size: 12px; gap: 4px; } .chip #netPing { display: none; } button.chip > svg { display: none; }
} }
@media (orientation: landscape) and (max-height: 520px) and (min-width: 701px) { .chip #netPing { display: none; } }
/* very small phones (320px) */ /* very small phones (320px) */
@media (max-width: 340px) { @media (max-width: 340px) {
:root { --btn: 38px; }
.stat .lbl { display: none; } .stat .lbl { display: none; }
.stat { padding: 0 6px; } .stat { padding: 0 6px; }
#btnWave { flex: 1 1 80px; padding: 0 8px; } #btnWave { flex: 1 1 80px; padding: 0 8px; }
button.icon { min-width: 38px; padding: 0 4px; } button.icon { min-width: 38px; padding: 0 4px; }
#topbar { gap: 4px; padding: 4px; } #topbar { gap: 4px; padding: 4px; }
} }
/* touch: every target is at least 44px (declared last so no layout rule above can shrink it) */
@media (pointer: coarse) {
:root { --btn: 44px; }
button.icon { min-width: 44px; }
button.link { min-height: 44px; }
button.chip { min-width: 44px; }
}
/* Windows high contrast: selection must not depend on colours the UA replaces */
@media (forced-colors: active) {
.tbtn.sel, .mapcard[aria-checked="true"], button.toggle[aria-pressed="true"], button#btnPause[aria-pressed="true"] { outline: 3px solid Highlight; outline-offset: -3px; forced-color-adjust: none; background: Highlight; color: HighlightText; }
.tbtn.sel .nm, .tbtn.sel .cost, .mapcard[aria-checked="true"] .df, .mapcard[aria-checked="true"] .df b { color: HighlightText; }
.overlay { background: Canvas; }
#side { border-color: CanvasText; }
}

View file

@ -35,6 +35,7 @@
<symbol id="i-up" viewBox="0 0 24 24"><path d="M12 19V6M6 11.5L12 5.5l6 6" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"/></symbol> <symbol id="i-up" viewBox="0 0 24 24"><path d="M12 19V6M6 11.5L12 5.5l6 6" fill="none" stroke="currentColor" stroke-width="2.6" 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-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-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>
@ -46,12 +47,12 @@
<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></div>
<div id="netChip" class="chip" hidden title="Co-op room"><svg class="ic"><use href="#i-users"/></svg><span id="netRoom"></span><span id="netPing"></span></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>
<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>
<button id="btnAuto" class="icon toggle" aria-pressed="false" aria-label="Automatic waves" title="Automatic waves (A)"><span>AUTO</span></button> <button id="btnAuto" class="icon toggle" aria-pressed="false" aria-label="Automatic waves" title="Automatic waves (A)"><span>AUTO</span></button>
<button id="btnSpeed" class="icon" aria-label="Game speed" title="Speed (F)"><span id="speedText">1×</span></button> <button id="btnSpeed" class="icon" aria-label="Game speed" title="Speed (F)"><span id="speedText">1×</span></button>
<button id="btnPause" class="icon" aria-label="Pause" title="Pause (P)"><svg class="ic"><use href="#i-pause"/></svg></button> <button id="btnPause" class="icon" aria-label="Pause" aria-pressed="false" title="Pause (P)"><svg class="ic"><use href="#i-pause"/></svg></button>
<button id="btnSound" class="icon" aria-label="Sound" title="Sound (M)"><svg class="ic"><use href="#i-sound"/></svg></button> <button id="btnSound" class="icon" aria-label="Sound" title="Sound (M)"><svg class="ic"><use href="#i-sound"/></svg></button>
</header> </header>
@ -59,14 +60,21 @@
<canvas id="board" aria-label="Game board" role="img"></canvas> <canvas id="board" aria-label="Game board" role="img"></canvas>
<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>
<div id="pausedTag" class="paused-tag" hidden>PAUSED</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>
<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>
<button id="btnCancelBuild" class="icon danger" aria-label="Cancel"><svg class="ic"><use href="#i-x"/></svg></button> <button id="btnCancelBuild" class="icon danger" aria-label="Cancel"><svg class="ic"><use href="#i-x"/></svg></button>
<span id="confirmHint" class="chint" aria-live="polite"></span>
<button id="btnConfirmBuild" class="primary big"><svg class="ic"><use href="#i-check"/></svg><span id="confirmText">Build</span></button> <button id="btnConfirmBuild" class="primary big"><svg class="ic"><use href="#i-check"/></svg><span id="confirmText">Build</span></button>
<div id="nudge" class="nudge" role="group" aria-label="Move the build cell by one cell">
<button type="button" data-dx="-1" data-dy="0" aria-label="Move left"><svg class="ic"><use href="#i-up"/></svg></button>
<button type="button" data-dx="0" data-dy="-1" aria-label="Move up"><svg class="ic"><use href="#i-up"/></svg></button>
<button type="button" data-dx="0" data-dy="1" aria-label="Move down"><svg class="ic"><use href="#i-up"/></svg></button>
<button type="button" data-dx="1" data-dy="0" aria-label="Move right"><svg class="ic"><use href="#i-up"/></svg></button>
</div> </div>
<div id="reconnect" class="reconnect" hidden><div class="spinner"></div><span>Connection lost. Reconnecting&hellip;</span></div> </div>
<div id="reconnect" class="reconnect" hidden role="alert"><div class="spinner"></div><span>Connection lost. Reconnecting&hellip;</span></div>
</main> </main>
<aside id="side"> <aside id="side">
@ -76,15 +84,17 @@
<section id="players" hidden></section> <section id="players" hidden></section>
</aside> </aside>
<!-- ===== main menu ===== --> <!-- ===== main menu: .card-body scrolls, .card-foot (the primary buttons) is always visible ===== -->
<div id="menu" class="overlay"> <div id="menu" class="overlay">
<div class="card"> <div class="card">
<div class="card-body">
<div class="logo"><span class="logo-mark" aria-hidden="true"></span><h1>NETWALL</h1></div> <div class="logo"><span class="logo-mark" aria-hidden="true"></span><h1>NETWALL</h1></div>
<p class="tag">Build the firewall. Stretch the route. Protect the server.</p> <p class="tag">Build the firewall. Stretch the route. Protect the server.</p>
<div id="mapPick" class="maps" role="radiogroup" aria-label="Map"></div> <div id="mapPick" class="maps" role="radiogroup" aria-label="Map"></div>
<p id="mapDesc" class="mapdesc"></p> <p id="mapDesc" class="mapdesc"></p>
</div>
<div class="card-foot">
<div id="menuOpts" class="opts"></div><!-- room for the difficulty selector (Easy / Normal / Hard) -->
<div class="row"> <div class="row">
<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>
@ -97,12 +107,14 @@
</div> </div>
</div> </div>
</div> </div>
</div>
<!-- ===== co-op lobby ===== --> <!-- ===== co-op lobby ===== -->
<div id="lobby" class="overlay" hidden> <div id="lobby" class="overlay" hidden>
<div class="card"> <div class="card">
<div class="card-body">
<h2>Co-op online</h2> <h2>Co-op online</h2>
<p class="muted">Two players, one base, one pool of credits. Create a room and send the link, or enter a friend's code.</p> <p class="muted lead">Two players, one base, one pool of credits. Create a room and send the link, or enter a friend's code.</p>
<label class="field"><span>Your name</span><input id="inName" maxlength="16" autocomplete="nickname" autocapitalize="words" spellcheck="false" placeholder="Player"></label> <label class="field"><span>Your name</span><input id="inName" maxlength="16" autocomplete="nickname" autocapitalize="words" spellcheck="false" placeholder="Player"></label>
<div class="split"> <div class="split">
<div class="col"> <div class="col">
@ -112,38 +124,49 @@
</div> </div>
<div class="col"> <div class="col">
<h3>Join a game</h3> <h3>Join a game</h3>
<div class="joinrow">
<input id="inCode" class="code" maxlength="4" autocomplete="off" autocapitalize="characters" spellcheck="false" inputmode="text" placeholder="ABCD" aria-label="Room code"> <input id="inCode" class="code" maxlength="4" autocomplete="off" autocapitalize="characters" spellcheck="false" inputmode="text" placeholder="ABCD" aria-label="Room code">
<button id="btnJoin" class="big">Join</button> <button id="btnJoin" class="big">Join</button>
</div> </div>
</div> </div>
</div>
<div id="roomList" class="roomlist" hidden></div><!-- room for the list of open rooms -->
</div>
<div class="card-foot">
<p id="lobbyMsg" class="msg" role="status"></p> <p id="lobbyMsg" class="msg" role="status"></p>
<div class="row small"><button id="btnLobbyBack" class="link">&larr; Back</button></div> <div class="row small"><button id="btnLobbyBack" class="link">&larr; Back</button></div>
</div> </div>
</div> </div>
</div>
<!-- ===== help ===== --> <!-- ===== help ===== -->
<div id="help" class="overlay" hidden> <div id="help" class="overlay" hidden>
<div class="card wide"> <div class="card wide">
<div class="card-body">
<h2>How to play</h2> <h2>How to play</h2>
<ul class="howto"> <ul class="howto">
<li><b>Goal.</b> Packets pour in from the gateways (red). Don't let them reach the <b>server</b>. Each leak costs integrity (&hearts;).</li> <li><b>Goal.</b> Packets pour in from the gateways (red). Don't let them reach the <b>server</b>. Each leak costs integrity (&hearts;).</li>
<li><b>Maze.</b> The map is open: <b>Firewalls</b> are cheap walls. Packets always take the shortest open route, so walls make them walk further, past your turrets. You can lengthen the route but never seal it off completely. Hover to preview the new route.</li> <li><b>Maze.</b> The map is open: <b>Firewalls</b> are cheap walls. Packets always take the shortest open route, so walls make them walk further, past your turrets. You can lengthen the route but never seal it off completely. <span class="kbd-only">Hover</span><span class="touch-only">Tap</span> to preview the new route.</li>
<li><b>Turrets.</b> Filter (fast), IDS Sniper (long range, armour-piercing), Mortar (splash), Rate Limiter (slows), Router Arc (chain lightning). <b>Spoofed packets fly</b> over your maze, so keep some anti-air. Mortars can't hit flyers.</li> <li><b>Turrets.</b> Filter (fast), IDS Sniper (long range, armour-piercing), Mortar (splash), Rate Limiter (slows), Router Arc (chain lightning), and the very expensive late-game <b>Orbital Uplink</b> (a piercing beam that ignores armour, hits flyers and slows what it touches). <b>Spoofed packets fly</b> over your maze, so keep some anti-air. Mortars can't hit flyers.</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>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 1&ndash;6 pick a tower, Space starts a wave, U upgrades, X sells, T changes targeting, P pauses, F changes speed, 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, wheel zooms.</span>
<span class="touch-only">Tap a tower type, then tap the map to preview 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>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 class="row"><button id="btnHelpClose" class="primary big">Got it</button></div> </div>
<div class="card-foot"><div class="row"><button id="btnHelpClose" class="primary big">Got it</button></div></div>
</div> </div>
</div> </div>
<!-- ===== game over / victory ===== --> <!-- ===== game over / victory ===== -->
<div id="end" class="overlay" hidden> <div id="end" class="overlay" hidden>
<div class="card"> <div class="card">
<div class="card-body">
<h2 id="endTitle">Breach!</h2> <h2 id="endTitle">Breach!</h2>
<p id="endText" class="muted"></p> <p id="endText" class="muted"></p>
<div id="endStats" class="stats"></div> <div id="endStats" class="stats"></div>
</div>
<div class="card-foot">
<div class="row"> <div class="row">
<button id="btnAgain" class="primary big">Play again</button> <button id="btnAgain" class="primary big">Play again</button>
<button id="btnContinue" class="big" hidden>Keep going</button> <button id="btnContinue" class="big" hidden>Keep going</button>
@ -152,6 +175,7 @@
<p id="endWait" class="msg" hidden>Waiting for the host to start a new game&hellip;</p> <p id="endWait" class="msg" hidden>Waiting for the host to start a new game&hellip;</p>
</div> </div>
</div> </div>
</div>
</div> </div>

View file

@ -86,6 +86,8 @@
shot_filter: () => noise(0.03, 0.07, 'highpass', 5000), shot_filter: () => noise(0.03, 0.07, 'highpass', 5000),
shot_ids: () => { tone(1100, 0.14, 'sawtooth', 0.2, 180); noise(0.08, 0.12, 'highpass', 2500); }, shot_ids: () => { tone(1100, 0.14, 'sawtooth', 0.2, 180); noise(0.08, 0.12, 'highpass', 2500); },
shot_mortar: () => tone(150, 0.18, 'sine', 0.45, 60), shot_mortar: () => tone(150, 0.18, 'sine', 0.45, 60),
// Orbital Uplink: a falling laser sweep over a sub-bass thump and a hiss of ionised air
shot_uplink: () => { tone(2600, 0.45, 'sawtooth', 0.16, 140); tone(1300, 0.45, 'square', 0.07, 70, 0.02); tone(70, 0.55, 'sine', 0.5, 32); noise(0.4, 0.22, 'bandpass', 4200, 600); },
arc: () => { noise(0.1, 0.16, 'bandpass', 3500, 900); tone(900, 0.08, 'sawtooth', 0.1, 300); }, arc: () => { noise(0.1, 0.16, 'bandpass', 3500, 900); tone(900, 0.08, 'sawtooth', 0.1, 300); },
boom: () => noise(0.32, 0.5, 'lowpass', 1800, 90), boom: () => noise(0.32, 0.5, 'lowpass', 1800, 90),
kill: () => tone(820, 0.05, 'triangle', 0.1, 1200), kill: () => tone(820, 0.05, 'triangle', 0.1, 1200),
@ -96,7 +98,7 @@
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); },
}; };
const MIN_GAP = { 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 = { 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;

View file

@ -330,9 +330,11 @@
return this.board.trial(x, y, reserved, null, routes); return this.board.trial(x, y, reserved, null, routes);
} }
newGame(map) { this._send({ t: 'newgame', map }); } newGame(map) { this._send({ t: 'newgame', map }); }
sendCursor(x, y) { // Moves are throttled to one per 70 ms. A clear (x === null) or `force` always goes out, so the final position / the
// "cursor gone" message of a touch is never swallowed by the throttle (touch-9).
sendCursor(x, y, force) {
const now = performance.now(); const now = performance.now();
if (now - this.lastCursor < 70) return; if (x !== null && !force && now - this.lastCursor < 70) return;
this.lastCursor = now; this.lastCursor = now;
this._send({ t: 'cursor', x: x === null ? null : Math.round(x * 100) / 100, y: y === null ? null : Math.round(y * 100) / 100 }); this._send({ t: 'cursor', x: x === null ? null : Math.round(x * 100) / 100, y: y === null ? null : Math.round(y * 100) / 100 });
} }

View file

@ -72,15 +72,23 @@
clearTimeout(bannerT); clearTimeout(bannerT);
bannerT = setTimeout(() => { b.className = 'banner' + (boss ? ' boss' : ''); }, 1500); bannerT = setTimeout(() => { b.className = 'banner' + (boss ? ' boss' : ''); }, 1500);
} }
let hintText = '', hintKind = '';
function hint(text, kind) { function hint(text, kind) {
const h = $('hint'); const h = $('hint'), ch = $('confirmHint');
hintText = text || ''; hintKind = kind || 'info';
if (!$('confirm').hidden && $('app').dataset.barrows !== '0') { // the touch build bar carries the route text itself: one overlay on the board instead of two (not when it is too small for it)
h.hidden = true; h.textContent = hintText; ch.textContent = hintText; ch.className = 'chint ' + hintKind; return; // (#hint keeps the text, hidden, for readers and tests)
}
if (!text) { h.hidden = true; return; } if (!text) { h.hidden = true; return; }
h.hidden = false; h.textContent = text; h.className = 'hint ' + (kind || 'info'); h.hidden = false; h.textContent = text; h.className = 'hint ' + hintKind;
} }
const fmtLen = (v) => String(Math.round(v / Math.max(1, ui.spawns || 1))); const fmtLen = (v) => String(Math.round(v / Math.max(1, ui.spawns || 1)));
function showOverlay(id) { function showOverlay(id) {
for (const o of document.querySelectorAll('.overlay')) o.hidden = o.id !== id; for (const o of document.querySelectorAll('.overlay')) {
const wasHidden = o.hidden; o.hidden = o.id !== id;
if (wasHidden && !o.hidden) { const body = o.querySelector('.card-body'); if (body) body.scrollTop = 0; }
}
} }
function setScreen(name) { function setScreen(name) {
app.screen = name; app.screen = name;
@ -163,15 +171,20 @@
} }
} }
} }
let errSfxAt = -1e9;
function onReject(r) { function onReject(r) {
toast(REASONS[r.reason] || ('Not possible: ' + r.reason), 'bad'); toast(REASONS[r.reason] || ('Not possible: ' + r.reason), 'bad');
Audio.sfx('error'); // One buzzer per wall stroke (a stroke can reject dozens of cells), and never a burst: co-op rejects arrive after the finger has lifted (touch-16)
const now = performance.now();
if (now - errSfxAt > 450 && !(painting && strokeErr)) { errSfxAt = now; Audio.sfx('error'); }
if (painting) strokeErr = true;
} }
// ------------------------------------------------------------------ palette + info panel // ------------------------------------------------------------------ palette + info panel
function buildPalette() { function buildPalette() {
const pal = $('palette'); const pal = $('palette');
pal.textContent = ''; pal.textContent = '';
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];
const b = document.createElement('button'); const b = document.createElement('button');
@ -183,8 +196,28 @@
b.addEventListener('click', () => { Audio.sfx('click'); selectType(app.selType === type ? null : type); }); b.addEventListener('click', () => { Audio.sfx('click'); selectType(app.selType === type ? null : type); });
pal.appendChild(b); pal.appendChild(b);
} }
drawPaletteIcons(); drawPaletteIcons(); updatePaletteHint();
} }
// A palette that does not fit scrolls (sideways when stacked, down in the narrow landscape column). data-more says on which
// side more tiles are hidden; the CSS fades that edge so the player can see there is more.
function updatePaletteHint() {
const p = $('palette'); let more = '';
const edge = (pos, size, view) => { const a = pos > 2, b = pos < size - view - 2; return a && b ? 'both' : a ? 'start' : b ? 'end' : ''; };
if (p.scrollWidth > p.clientWidth + 2) more = edge(p.scrollLeft, p.scrollWidth, p.clientWidth);
else if (p.scrollHeight > p.clientHeight + 2) more = edge(p.scrollTop, p.scrollHeight, p.clientHeight);
if (more) { if (p.dataset.more !== more) p.dataset.more = more; } else if (p.dataset.more) delete p.dataset.more;
}
function revealTile(b) { // scroll the palette (only the palette, never the page) so this tile is fully in view
const p = $('palette'); if (!b) return;
const pr = p.getBoundingClientRect(), br = b.getBoundingClientRect(), m = 34; // keep clear of the edge fade
if (p.scrollWidth > p.clientWidth + 2) {
if (br.left < pr.left + m) p.scrollLeft -= pr.left + m - br.left; else if (br.right > pr.right - m) p.scrollLeft += br.right - (pr.right - m);
} else if (p.scrollHeight > p.clientHeight + 2) {
if (br.top < pr.top + m) p.scrollTop -= pr.top + m - br.top; else if (br.bottom > pr.bottom - m) p.scrollTop += br.bottom - (pr.bottom - m);
}
updatePaletteHint();
}
$('palette').addEventListener('scroll', updatePaletteHint, { passive: true });
function drawPaletteIcons() { function drawPaletteIcons() {
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);
} }
@ -193,6 +226,7 @@
const sel = b.dataset.type === app.selType; const sel = b.dataset.type === app.selType;
b.classList.toggle('sel', sel); b.classList.toggle('sel', sel);
b.setAttribute('aria-pressed', sel ? 'true' : 'false'); b.setAttribute('aria-pressed', sel ? 'true' : 'false');
if (sel) revealTile(b);
} }
} }
function selectType(type) { function selectType(type) {
@ -218,46 +252,40 @@
} }
function targetsText(def) { return def.ground && def.air ? 'ground + air' : def.ground ? 'ground only' : 'none'; } function targetsText(def) { return def.ground && def.air ? 'ground + air' : def.ground ? 'ground only' : 'none'; }
let infoSig = ''; // The info panel is built ONCE per selection (tower id + owner, or armed build type) and then updated in place, so a
// button is never replaced under a finger: partner actions bump view.rev constantly in co-op (code-2). A rebuild that
// would replace nodes is deferred while a pointer is down inside the panel.
const info = { shape: '', sig: '', lv: 0, pressed: false, dirty: false };
function renderInfo(force) { function renderInfo(force) {
const box = $('info'), ctrl = app.ctrl, view = ctrl.view; const box = $('info'), ctrl = app.ctrl, view = ctrl.view;
let sig, tower = null; let tower = null, ownerP = null, shape = '';
if (app.selTower) { if (app.selTower) {
tower = view.towers.find((t) => t.id === app.selTower); tower = view.towers.find((t) => t.id === app.selTower) || null;
if (!tower) { app.selTower = 0; } if (!tower) app.selTower = 0;
} }
if (tower) sig = 't' + tower.id + ':' + tower.level + ':' + tower.mode;
else if (app.selType) sig = 'b' + app.selType;
else sig = '';
if (!force && sig === infoSig) return;
infoSig = sig;
if (!sig) { box.textContent = ''; return; }
if (tower) { if (tower) {
const def = TD.TOWERS[tower.type], i = tower.level - 1; if (ctrl.kind === 'remote' && ctrl.players.length > 1) ownerP = ctrl.players.find((p) => p.slot === tower.owner) || null;
const cur = statsFor(tower.type, i), nxt = tower.level < def.levels.length ? statsFor(tower.type, i + 1) : null; shape = 't' + tower.id + tower.type + ':' + (ownerP ? ownerP.slot + ownerP.name : '');
let kv = ''; } else if (app.selType) shape = 'b' + app.selType;
cur.forEach((row, k) => { if (!force && shape === info.shape) { if (tower) syncInfo(); return; }
const n = nxt && nxt[k] && nxt[k][1] !== row[1] ? ' <span class="up">&rarr; ' + nxt[k][1] + '</span>' : ''; if (info.pressed) { info.dirty = true; return; } // never replace a node while a pointer is down on it
kv += '<div class="kvp"><span>' + row[0] + '</span><span>' + row[1] + n + '</span></div>'; info.shape = shape; info.sig = ''; info.lv = 0; info.dirty = false;
}); if (!shape) { box.textContent = ''; return; }
if (tower.type !== 'wall') kv += '<div class="kvp"><span>Targets</span><span>' + targetsText(def) + '</span></div>'; if (tower) {
const sellVal = def.refund ? tower.spent : Math.floor(tower.spent * TD.SELL_RATIO); const def = TD.TOWERS[tower.type], wall = tower.type === 'wall';
const upCost = tower.level < def.levels.length ? def.levels[tower.level].cost : null;
const owner = ctrl.kind === 'remote' && ctrl.players.length > 1;
const ownerP = owner ? ctrl.players.find((p) => p.slot === tower.owner) : null;
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">' + kv + '</div><div class="actions">' + '<div class="desc"></div><div class="kv"></div><div class="actions">' +
(tower.type === 'wall' ? '' : (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>') +
'<button type="button" data-act="up"' + (upCost === null ? ' disabled' : '') + '><svg class="ic"><use href="#i-up"/></svg>' + (upCost === null ? 'Max level' : 'Upgrade <span class="cost" id="upCost">' + 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>' +
'<button type="button" data-act="mode" title="Which packet to shoot"><span>Target: ' + MODE_NAMES[tower.mode] + '</span></button>') + (wall ? '' : '<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="sell" class="danger"><svg class="ic"><use href="#i-trash"/></svg>Sell <span class="cost">' + sellVal + '</span></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">' + (tower.type === 'wall' ? '' : '<span id="infoKills"></span>') + (ownerP ? '<span class="dot" style="background:' + NW.SLOT_COLORS[ownerP.slot] + '"></span><span id="infoOwner"></span>' : '') + '</div></div>'; '<div class="byline">' + (wall ? '' : '<span id="infoKills"></span>') + (ownerP ? '<span class="dot" style="background:' + NW.SLOT_COLORS[ownerP.slot] + '"></span><span id="infoOwner"></span>' : '') + '</div></div>';
box.querySelector('.nm').textContent = def.name; box.querySelector('.nm').textContent = def.name;
box.querySelector('.lv').textContent = tower.type === 'wall' ? '' : 'Level ' + tower.level + ' / ' + def.levels.length;
box.querySelector('.desc').textContent = def.desc; box.querySelector('.desc').textContent = def.desc;
if (ownerP) box.querySelector('#infoOwner').textContent = 'Built by ' + ownerP.name; if (ownerP) box.querySelector('#infoOwner').textContent = 'Built by ' + ownerP.name;
NW.drawIcon(box.querySelector('canvas'), tower.type, tower.level); syncInfo();
} else { } else {
const def = TD.TOWERS[app.selType]; const def = TD.TOWERS[app.selType];
let kv = ''; let kv = '';
@ -270,23 +298,65 @@
NW.drawIcon(box.querySelector('canvas'), app.selType, 1); NW.drawIcon(box.querySelector('canvas'), app.selType, 1);
} }
} }
function updateInfoDynamic() { // numbers of the selected tower: only text/disabled changes, never a replaced element
function syncInfo() {
if (!app.selTower) return; if (!app.selTower) return;
const t = app.ctrl.view.towers.find((x) => x.id === app.selTower); const box = $('info'), view = app.ctrl.view, t = view.towers.find((x) => x.id === app.selTower);
if (!t) return; if (!t || !box.firstChild) return;
const k = $('infoKills'); if (k) k.textContent = t.kills + (t.kills === 1 ? ' kill' : ' kills'); const def = TD.TOWERS[t.type], wall = t.type === 'wall', i = t.level - 1;
const def = TD.TOWERS[t.type]; const canUp = t.level < def.levels.length, upCost = canUp ? def.levels[t.level].cost : 0;
const up = $('info').querySelector('[data-act="up"]'); const affordable = canUp && view.gold >= upCost;
if (up && t.level < def.levels.length) up.disabled = app.ctrl.view.gold < def.levels[t.level].cost; const sellVal = def.refund ? t.spent : Math.floor(t.spent * TD.SELL_RATIO);
const sig = t.level + ':' + t.mode + ':' + sellVal + ':' + t.kills + ':' + (affordable ? 1 : 0);
if (sig === info.sig) return;
info.sig = sig;
const setText = (el, v) => { if (el && el.textContent !== v) el.textContent = v; };
if (info.lv !== t.level) { // level changed: stats table and icon
info.lv = t.level;
const cur = statsFor(t.type, i), nxt = canUp ? statsFor(t.type, i + 1) : null;
let kv = '';
cur.forEach((row, k) => {
const n = nxt && nxt[k] && nxt[k][1] !== row[1] ? ' <span class="up">&rarr; ' + nxt[k][1] + '</span>' : '';
kv += '<div class="kvp"><span>' + row[0] + '</span><span>' + row[1] + n + '</span></div>';
});
if (!wall) kv += '<div class="kvp"><span>Targets</span><span>' + targetsText(def) + '</span></div>';
box.querySelector('.kv').innerHTML = kv;
setText(box.querySelector('.lv'), wall ? '' : 'Level ' + t.level + ' / ' + def.levels.length);
NW.drawIcon(box.querySelector('canvas'), t.type, t.level);
} }
const up = box.querySelector('[data-act="up"]');
if (up) {
setText(up.querySelector('.w'), canUp ? 'Upgrade' : 'Max level');
setText(up.querySelector('.cost'), canUp ? String(upCost) : '');
up.disabled = !affordable;
up.setAttribute('aria-label', canUp ? 'Upgrade for ' + upCost + ' credits' : 'Max level');
}
const sell = box.querySelector('[data-act="sell"]');
setText(sell.querySelector('.cost'), String(sellVal));
sell.setAttribute('aria-label', 'Sell for ' + sellVal + ' credits');
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'); }
setText(box.querySelector('#infoKills'), t.kills + (t.kills === 1 ? ' kill' : ' kills'));
}
let infoTimer = 0;
$('info').addEventListener('pointerdown', () => { clearTimeout(infoTimer); info.pressed = true; }); // (a new press cancels the previous release timer)
const infoRelease = () => {
if (!info.pressed) return;
clearTimeout(infoTimer);
infoTimer = setTimeout(() => { info.pressed = false; if (info.dirty) renderInfo(false); }, 90); // after the click has been delivered
};
document.addEventListener('pointerup', infoRelease, true);
document.addEventListener('pointercancel', infoRelease, true);
$('info').addEventListener('click', (e) => { $('info').addEventListener('click', (e) => {
const btn = e.target.closest('button[data-act]'); if (!btn || !app.selTower) return; const btn = e.target.closest('button[data-act]'); if (!btn || !app.selTower) return;
info.pressed = false;
const ctrl = app.ctrl, tower = ctrl.view.towers.find((t) => t.id === app.selTower); const ctrl = app.ctrl, tower = ctrl.view.towers.find((t) => t.id === app.selTower);
if (!tower) return; if (!tower) return;
Audio.sfx('click'); Audio.sfx('click');
switch (btn.dataset.act) { switch (btn.dataset.act) {
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 '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;
@ -308,7 +378,7 @@
for (const g of sum) { for (const g of sum) {
const d = TD.ENEMIES[g.k]; const d = TD.ENEMIES[g.k];
if (d.air) air = true; if (d.air) air = true;
html += '<span class="e"><i style="background:' + d.color + '"></i>' + g.c + '&times; ' + d.name + '</span>'; html += '<span class="e" title="' + d.name + (d.air ? ' (flies)' : '') + '"><i class="sh-' + g.k + '" style="--c:' + d.color + '"></i>' + g.c + '&times; ' + d.name + '</span>';
} }
if (air) html += '<span class="tag air">AIR</span>'; if (air) html += '<span class="tag air">AIR</span>';
if (n % 10 === 0) html += '<span class="tag boss">BOSS</span>'; if (n % 10 === 0) html += '<span class="tag boss">BOSS</span>';
@ -328,7 +398,7 @@
} }
app.prevPlayers = list.map((p) => Object.assign({}, p)); app.prevPlayers = list.map((p) => Object.assign({}, p));
renderPlayers(); renderPlayers();
if (ctrl.kind === 'remote') renderInfo(true); if (ctrl.kind === 'remote') renderInfo(false); // the shape includes the owner, so only a changed roster rebuilds
} }
function renderPlayers() { function renderPlayers() {
const ctrl = app.ctrl, box = $('players'); const ctrl = app.ctrl, box = $('players');
@ -379,7 +449,12 @@
if (L.attn !== attn) { L.attn = attn; $('btnWave').classList.toggle('attn', attn); } if (L.attn !== attn) { L.attn = attn; $('btnWave').classList.toggle('attn', attn); }
if (L.auto !== view.auto) { L.auto = view.auto; $('btnAuto').setAttribute('aria-pressed', view.auto ? 'true' : 'false'); } if (L.auto !== view.auto) { L.auto = view.auto; $('btnAuto').setAttribute('aria-pressed', view.auto ? 'true' : 'false'); }
if (L.speed !== view.speed) { L.speed = view.speed; $('speedText').textContent = view.speed + '×'; } if (L.speed !== view.speed) { L.speed = view.speed; $('speedText').textContent = view.speed + '×'; }
if (L.paused !== view.paused) { L.paused = view.paused; $('pausedTag').hidden = !view.paused; $('btnPause').innerHTML = '<svg class="ic"><use href="#i-' + (view.paused ? 'play' : 'pause') + '"/></svg>'; $('btnPause').setAttribute('aria-label', view.paused ? 'Resume' : 'Pause'); } if (L.paused !== view.paused) { // paused: dimmed board, a resume pill, and an amber pressed pause button (not a second play triangle)
L.paused = view.paused; $('pausedTag').hidden = !view.paused; $('stage').classList.toggle('paused', !!view.paused);
$('btnPause').setAttribute('aria-pressed', view.paused ? 'true' : 'false'); $('btnPause').setAttribute('aria-label', view.paused ? 'Resume' : 'Pause');
}
const offline = !$('reconnect').hidden;
if (L.offline !== offline) { L.offline = offline; $('app').classList.toggle('offline', offline); }
if (L.muted !== Audio.muted) { L.muted = Audio.muted; $('btnSound').innerHTML = '<svg class="ic"><use href="#i-' + (Audio.muted ? 'mute' : 'sound') + '"/></svg>'; } if (L.muted !== Audio.muted) { L.muted = Audio.muted; $('btnSound').innerHTML = '<svg class="ic"><use href="#i-' + (Audio.muted ? 'mute' : 'sound') + '"/></svg>'; }
// palette affordability // palette affordability
const gold = view.gold; const gold = view.gold;
@ -391,11 +466,16 @@
const chip = $('netChip'); const chip = $('netChip');
chip.hidden = false; chip.hidden = false;
$('netRoom').textContent = ctrl.room || ''; $('netRoom').textContent = ctrl.room || '';
const alone = ctrl.players.length < 2;
if (L.alone !== alone || L.room !== ctrl.room) {
L.alone = alone; L.room = ctrl.room; chip.classList.toggle('waiting', alone);
chip.setAttribute('aria-label', 'Co-op room ' + (ctrl.room || '') + (alone ? '. Waiting for a partner: tap to invite them' : '. Tap to invite your partner'));
}
const p = ctrl.rtt ? ctrl.rtt + ' ms' : ''; const p = ctrl.rtt ? ctrl.rtt + ' ms' : '';
if (L.ping !== p) { L.ping = p; $('netPing').textContent = p; chip.classList.toggle('bad', ctrl.rtt > 220); const pp = $('plPing'); if (pp) pp.textContent = p ? '\u00b7 ' + p : ''; } if (L.ping !== p) { L.ping = p; $('netPing').textContent = p; chip.classList.toggle('bad', ctrl.rtt > 220); const pp = $('plPing'); if (pp) pp.textContent = p ? '\u00b7 ' + p : ''; }
} }
renderWavePanel(view); renderWavePanel(view);
updateInfoDynamic(); syncInfo();
} }
function endScreen(view) { function endScreen(view) {
@ -457,19 +537,62 @@
function updateConfirm() { function updateConfirm() {
const show = !!(app.pending && app.selType && app.selType !== 'wall'); const show = !!(app.pending && app.selType && app.selType !== 'wall');
$('confirm').hidden = !show; $('confirm').hidden = !show;
if (show) { if (show) { const cost = TD.TOWERS[app.selType].levels[0].cost; $('confirmText').textContent = 'Build · ' + cost; $('btnConfirmBuild').setAttribute('aria-label', 'Build for ' + cost + ' credits'); hint(hintText, hintKind); }
$('confirmText').textContent = 'Build · ' + TD.TOWERS[app.selType].levels[0].cost; else if (!ptrs.size) clearCursor(); // (no pending cell, no finger down: the partner's view of our touch cursor goes)
// keep the bar clear of the cell being placed: show it on the opposite half of the stage layoutBars(true);
const p = renderer.cellToScreen(app.pending.x, app.pending.y);
$('confirm').classList.toggle('top', p.y > $('stage').clientHeight * 0.5);
} }
// Where the floating bars go (the touch confirm bar and the selected-tower action bar): on the half of the stage away from the
// cell they act on, so they never cover it. Runs every frame (cheap, writes only on change) so rotation, resize, pan and zoom
// keep it right (touch-14). The stage rectangle goes into CSS variables because the tower bar is position:fixed.
// The bar does not hop to the other half while the same cell is being worked on (nudging across the middle must not move the buttons
// out from under the thumb): it flips only when the cell would end up under it.
let barKey = '', barSide = '', barSubject = '';
function layoutBars(force) {
const r = $('stage').getBoundingClientRect(), a = $('app'), conf = !$('confirm').hidden && !!app.pending;
let cell = null;
if (conf) cell = app.pending;
else if (app.selTower && app.ctrl) cell = app.ctrl.view.towers.find((t) => t.id === app.selTower) || null;
let side = '';
if (cell) {
const sp = renderer.cellToScreen(cell.x, cell.y), bar = conf ? $('confirm') : $('info').querySelector('.actions');
const guard = (bar ? bar.offsetHeight : 54) + 8 + renderer.cellSizePx() / 2 + 8; // the strip a bar there would cover, plus the cell itself
const hit = (s) => (s === 'top' ? sp.y < guard : sp.y > r.height - guard);
const subject = conf ? 'pending' : 'tower' + app.selTower;
const mid = sp.y > r.height * 0.5 ? 'top' : 'bottom', other = mid === 'top' ? 'bottom' : 'top';
side = subject === barSubject && barSide && !hit(barSide) ? barSide : hit(mid) && !hit(other) ? other : mid;
barSubject = subject; barSide = side;
} else { barSubject = ''; barSide = ''; }
const key = side + '|' + (conf ? 1 : 0) + '|' + Math.round(r.left) + ',' + Math.round(r.top) + ',' + Math.round(r.width) + ',' + Math.round(r.height);
if (!force && key === barKey) return;
barKey = key;
const st = a.style;
st.setProperty('--st-l', r.left.toFixed(1) + 'px'); st.setProperty('--st-t', r.top.toFixed(1) + 'px');
st.setProperty('--st-w', r.width.toFixed(1) + 'px'); st.setProperty('--st-h', r.height.toFixed(1) + 'px');
if (side) a.dataset.bar = side; else delete a.dataset.bar;
if (conf) a.dataset.conf = '1'; else delete a.dataset.conf; // the build bar is taller than the tower bar (it has the nudge row)
a.dataset.barrows = r.width >= 484 ? '1' : r.height >= 262 ? '2' : '0'; // build bar: nudge buttons in the bar's row on a wide stage, a second row on a phone, no text at all on a tiny one
a.dataset.barw = r.width < 440 ? 's' : 'm'; // narrow stage: the bar drops the words, keeps icons + numbers
$('confirm').classList.toggle('top', side === 'top');
} }
$('btnConfirmBuild').addEventListener('click', () => { if (app.pending && placeAt(app.pending)) { app.pending = null; updateConfirm(); } }); $('btnConfirmBuild').addEventListener('click', () => { if (app.pending && placeAt(app.pending)) setPending(null); });
$('btnCancelBuild').addEventListener('click', () => { selectType(null); }); $('btnCancelBuild').addEventListener('click', () => { selectType(null); });
// ------------------------------------------------------------------ pointer input // ------------------------------------------------------------------ pointer input
// Touch rules. pointerdown never builds and never selects: every pinch starts with one finger down. A TAP (the finger stays within
// TAP_SLOP of where it landed and lifts before the long press) acts on the cell it LANDED on, when it lifts. A DRAG acts as soon as it
// passes the slop: it paints a Firewall line, aims the pending turret, or pans a zoomed board. A second finger turns the whole gesture
// into pinch/pan and undoes whatever the first finger had begun; extra fingers (a palm) are ignored. A long press pings the map,
// whatever is armed, and never builds. Cells are only 12 to 20 px on a phone, which is why the build bar also has nudge buttons.
const TAP_SLOP = 10, MOUSE_SLOP = 8, LONG_MS = 520;
const ptrs = new Map(); const ptrs = new Map();
let painting = false, paintCell = null, panning = false, longT = 0, longFired = false, rightDown = null, prevPending = null, pinch = null; let painting = false, paintCell = null, panning = false, longT = 0, longFired = false, rightDown = null, pinch = null;
let multi = false; // a second finger landed: pinch/pan owns the gesture until every finger is up
let tg = null; // the one-finger touch gesture in progress: { id, cell (where it landed), pend (pending cell then), hover0, dragged }
let tapSelectOnUp = false;
let tapTowerId = 0; // a wall stroke that began on a turret: a stationary click or tap selects that turret instead (touch-17)
let pendFree = true; // the pending cell held no tower when it was chosen (a tower appearing there later is the partner's, coop-7)
let curSent = false; // a touch cursor is showing on the partner's board
let strokeErr = false; // this wall stroke already played its error sound (touch-16)
function cancelLong() { clearTimeout(longT); longT = 0; } function cancelLong() { clearTimeout(longT); longT = 0; }
function setHover(cell) { function setHover(cell) {
@ -478,6 +601,50 @@
if (c && app.hover && c.x === app.hover.x && c.y === app.hover.y) return; if (c && app.hover && c.x === app.hover.x && c.y === app.hover.y) return;
app.hover = c; app.previewDirty = true; app.hover = c; app.previewDirty = true;
} }
// The partner's view of where this touch is aiming. `force` skips the 70 ms throttle (the last position must get through).
function touchCursor(cell, force) {
if (!cell || !app.ctrl.board.inBounds(cell.x, cell.y)) return;
app.ctrl.sendCursor(cell.x + 0.5, cell.y + 0.5, force); curSent = true;
}
function clearCursor() { if (curSent) { curSent = false; app.ctrl.sendCursor(null, null); } }
// The only way the touch-pending build cell changes. An off-board cell is no cell (code-23).
function setPending(cell, commit) {
const c = cell && app.ctrl.board.inBounds(cell.x, cell.y) ? { x: cell.x, y: cell.y } : null;
app.pending = c; pendFree = !c || !towerAtCell(c); app.previewDirty = true;
if (c) { setHover(c); touchCursor(c, commit); }
updateConfirm();
}
// the finger-down preview ends without a commit (long press, second finger, cancel): hover goes back, the touch cursor goes away
function unaim() {
if (tg) { app.hover = tg.hover0; app.previewDirty = true; }
if (!app.pending) clearCursor();
}
function abortTouch() { // forget what the first finger began: a second finger landed, or the touch was cancelled
cancelLong(); painting = false; paintCell = null; tapSelectOnUp = false; tapTowerId = 0; longFired = false;
if (tg) { if (tg.dragged) setPending(tg.pend); unaim(); tg = null; }
}
function startStroke(cell) { painting = true; paintCell = cell; strokeErr = false; }
function seedPinch() { // pinch/pan between the first two fingers only; the pair is re-seeded when one of them lifts
const ids = [...ptrs.keys()].slice(0, 2), a = ptrs.get(ids[0]), b = ptrs.get(ids[1]);
pinch = { ids, d: Math.hypot(a.x - b.x, a.y - b.y) || 1, mx: (a.x + b.x) / 2, my: (a.y + b.y) / 2 };
}
// nudge buttons: move the pending cell one cell in a screen direction (rotation-safe), and keep it in view when zoomed in
function nudge(dx, dy) {
const p = app.pending; if (!p) return;
const c = renderer.stepCell(p.x, p.y, dx, dy);
if (!app.ctrl.board.inBounds(c.x, c.y)) return; // the edge of the board: stay put
setPending(c, true);
if (renderer.zoom > 1.01) {
const s = renderer.cellToScreen(c.x, c.y), m = renderer.cellSizePx() * 1.5;
const mx = s.x < m ? m - s.x : s.x > renderer.W - m ? renderer.W - m - s.x : 0, my = s.y < m ? m - s.y : s.y > renderer.H - m ? renderer.H - m - s.y : 0;
if (mx || my) { renderer.panBy(mx, my); updateFit(); }
}
}
$('nudge').addEventListener('click', (e) => {
const b = e.target.closest('button[data-dx]'); if (!b) return;
Audio.sfx('click'); nudge(+b.dataset.dx, +b.dataset.dy);
});
function paintLine(from, to) { // place on every cell crossed by a fast drag (Bresenham) function paintLine(from, to) { // place on every cell crossed by a fast drag (Bresenham)
let x0 = from.x, y0 = from.y; const x1 = to.x, y1 = to.y; let x0 = from.x, y0 = from.y; const x1 = to.x, y1 = to.y;
const dx = Math.abs(x1 - x0), dy = -Math.abs(y1 - y0), sx = x0 < x1 ? 1 : -1, sy = y0 < y1 ? 1 : -1; const dx = Math.abs(x1 - x0), dy = -Math.abs(y1 - y0), sx = x0 < x1 ? 1 : -1, sy = y0 < y1 ? 1 : -1;
@ -511,47 +678,42 @@
e.preventDefault(); e.preventDefault();
try { canvas.setPointerCapture(e.pointerId); } catch (err) { /* ignore */ } try { canvas.setPointerCapture(e.pointerId); } catch (err) { /* ignore */ }
Audio.unlock(); Audio.unlock();
const touch = e.pointerType !== 'mouse';
if (touch && e.isPrimary) { ptrs.clear(); abortTouch(); multi = false; pinch = null; } // (a lost pointerup must never leave half a gesture behind)
const r = canvas.getBoundingClientRect(), sx = e.clientX - r.left, sy = e.clientY - r.top; const r = canvas.getBoundingClientRect(), sx = e.clientX - r.left, sy = e.clientY - r.top;
ptrs.set(e.pointerId, { x: sx, y: sy, sx, sy, type: e.pointerType, moved: false, btn: e.button }); ptrs.set(e.pointerId, { x: sx, y: sy, sx, sy, type: e.pointerType, moved: false, btn: e.button });
if (ptrs.size === 2) { // second finger: pinch/pan, abandon whatever the first finger started if (ptrs.size >= 2) { // second finger: pinch/pan; whatever the first finger had begun is undone, a third finger is ignored
cancelLong(); painting = false; tapSelectOnUp = false; if (!multi) { multi = true; abortTouch(); }
const [a, b] = [...ptrs.values()]; if (!pinch) seedPinch();
pinch = { d: Math.hypot(a.x - b.x, a.y - b.y) || 1, mx: (a.x + b.x) / 2, my: (a.y + b.y) / 2 };
return; return;
} }
if (ptrs.size > 2) return;
const cell = renderer.screenToCell(sx, sy); const cell = renderer.screenToCell(sx, sy);
longFired = false; longFired = false;
if (e.pointerType === 'mouse') { if (!touch) {
if (e.button === 2) { rightDown = { x: sx, y: sy, moved: false }; return; } if (e.button === 2) { rightDown = { x: sx, y: sy, moved: false }; return; }
if (e.button === 1) { panning = true; return; } if (e.button === 1) { panning = true; return; }
if (e.altKey) { markAt(cell); return; } if (e.altKey) { markAt(cell); return; }
const ex = towerAtCell(cell); const ex = towerAtCell(cell);
if (app.selType && ex && !(app.selType === 'wall' && ex.type === 'wall')) { selectTower(ex.id); Audio.sfx('click'); } if (app.selType === 'wall' && ex && ex.type !== 'wall') { setHover(cell); startStroke(cell); tapTowerId = ex.id; } // a Firewall stroke may start on a turret; a plain click selects it
else if (app.selType && ex && !(app.selType === 'wall' && ex.type === 'wall')) { selectTower(ex.id); Audio.sfx('click'); }
else if (app.selType) { else if (app.selType) {
setHover(cell); setHover(cell);
if (!ex) placeAt(cell); if (!ex) placeAt(cell);
if (app.selType === 'wall') { painting = true; paintCell = cell; } if (app.selType === 'wall') startStroke(cell);
} else { } else {
tapSelectOnUp = true; panning = renderer.zoom > 1.01; tapSelectOnUp = true; panning = renderer.zoom > 1.01;
} }
return; return;
} }
// touch / pen // touch / pen: remember what is under the finger and preview it; commit nothing until the finger lifts or drags
prevPending = app.pending ? { x: app.pending.x, y: app.pending.y } : null; tg = { id: e.pointerId, cell, pend: app.pending ? { x: app.pending.x, y: app.pending.y } : null, hover0: app.hover, dragged: false };
const ex = towerAtCell(cell); if (app.selType) { setHover(cell); touchCursor(cell); }
if (app.selType && ex && !(app.selType === 'wall' && ex.type === 'wall')) { tapSelectOnUp = !app.selType;
selectTower(ex.id); Audio.sfx('click'); longT = setTimeout(() => { // a long press pings the map, whatever is armed
} else if (app.selType === 'wall') { longT = 0; if (!tg || multi || tg.id !== e.pointerId) return;
setHover(cell); if (!ex) placeAt(cell); painting = true; paintCell = cell; longFired = true; tapSelectOnUp = false; unaim(); markAt(tg.cell);
} else if (app.selType) { }, LONG_MS);
app.pending = { x: cell.x, y: cell.y }; setHover(cell); updateConfirm();
} else {
tapSelectOnUp = true;
longT = setTimeout(() => { longFired = true; tapSelectOnUp = false; markAt(cell); }, 520);
}
}); });
let tapSelectOnUp = false;
canvas.addEventListener('pointermove', (e) => { canvas.addEventListener('pointermove', (e) => {
const r = canvas.getBoundingClientRect(), sx = e.clientX - r.left, sy = e.clientY - r.top; const r = canvas.getBoundingClientRect(), sx = e.clientX - r.left, sy = e.clientY - r.top;
@ -567,9 +729,10 @@
} }
const dx = sx - p.x, dy = sy - p.y; const dx = sx - p.x, dy = sy - p.y;
p.x = sx; p.y = sy; p.x = sx; p.y = sy;
if (Math.hypot(sx - p.sx, sy - p.sy) > 8) p.moved = true; if (Math.hypot(sx - p.sx, sy - p.sy) > (e.pointerType === 'mouse' ? MOUSE_SLOP : TAP_SLOP)) p.moved = true;
if (ptrs.size === 2 && pinch) { if (pinch) {
const [a, b] = [...ptrs.values()]; if (!pinch.ids.includes(e.pointerId)) return; // a third finger (palm) neither pans nor zooms
const a = ptrs.get(pinch.ids[0]), b = ptrs.get(pinch.ids[1]); if (!a || !b) return;
const d = Math.hypot(a.x - b.x, a.y - b.y) || 1, mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2; const d = Math.hypot(a.x - b.x, a.y - b.y) || 1, mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2;
renderer.panBy(mx - pinch.mx, my - pinch.my); renderer.panBy(mx - pinch.mx, my - pinch.my);
renderer.setZoom(renderer.zoom * d / pinch.d, mx, my); renderer.setZoom(renderer.zoom * d / pinch.d, mx, my);
@ -577,50 +740,76 @@
updateFit(); updateFit();
return; return;
} }
if (multi) return; // one finger of a pinch is still down: it must not paint, aim or pan
const cell = renderer.screenToCell(sx, sy); const cell = renderer.screenToCell(sx, sy);
if (e.pointerType === 'mouse') { if (e.pointerType === 'mouse') {
if (rightDown) { if (Math.hypot(sx - rightDown.x, sy - rightDown.y) > 5) rightDown.moved = true; if (rightDown.moved) { renderer.panBy(dx, dy); updateFit(); } rightDown.x = rightDown.moved ? sx : rightDown.x; return; } if (rightDown) { if (Math.hypot(sx - rightDown.x, sy - rightDown.y) > 5) rightDown.moved = true; if (rightDown.moved) { renderer.panBy(dx, dy); updateFit(); } rightDown.x = rightDown.moved ? sx : rightDown.x; return; }
if (panning && p.moved) { renderer.panBy(dx, dy); updateFit(); tapSelectOnUp = false; return; } if (panning && p.moved) { renderer.panBy(dx, dy); updateFit(); tapSelectOnUp = false; return; }
setHover(cell); setHover(cell);
app.ctrl.sendCursor(cell.fx, cell.fy); app.ctrl.sendCursor(cell.fx, cell.fy);
if (painting && app.selType === 'wall' && paintCell && (cell.x !== paintCell.x || cell.y !== paintCell.y)) { paintLine(paintCell, cell); paintCell = cell; } if (painting && app.selType === 'wall' && paintCell && (cell.x !== paintCell.x || cell.y !== paintCell.y)) { tapTowerId = 0; paintLine(paintCell, cell); paintCell = cell; }
return; return;
} }
// touch / pen // touch / pen
if (p.moved) { cancelLong(); tapSelectOnUp = tapSelectOnUp && !p.moved; } if (!tg || tg.id !== e.pointerId || !p.moved) return; // inside the tap slop it is still a tap: nothing moves
if (painting && app.selType === 'wall') { cancelLong(); tapSelectOnUp = false;
if (app.selType === 'wall') {
if (!painting) { // the stroke starts here; paintLine skips its first cell, so the origin goes in now (unless a tower is on it)
startStroke(tg.cell);
if (!towerAtCell(tg.cell)) placeAt(tg.cell);
}
setHover(cell); setHover(cell);
if (paintCell && (cell.x !== paintCell.x || cell.y !== paintCell.y)) { paintLine(paintCell, cell); paintCell = cell; } if (cell.x !== paintCell.x || cell.y !== paintCell.y) { paintLine(paintCell, cell); paintCell = cell; }
} else if (app.selType) { } else if (app.selType) { // aim: the pending cell follows the finger (off the board it stays on the last cell)
app.pending = { x: cell.x, y: cell.y }; setHover(cell); updateConfirm(); if (app.ctrl.board.inBounds(cell.x, cell.y)) { tg.dragged = true; setPending(cell); }
app.ctrl.sendCursor(cell.fx, cell.fy); } else if (renderer.zoom > 1.01) {
} else if (p.moved && renderer.zoom > 1.01) {
renderer.panBy(dx, dy); updateFit(); renderer.panBy(dx, dy); updateFit();
} }
}); });
function endPointer(e) { function endPointer(e) {
const p = ptrs.get(e.pointerId); const p = ptrs.get(e.pointerId), cancelled = e.type === 'pointercancel';
ptrs.delete(e.pointerId); ptrs.delete(e.pointerId);
try { canvas.releasePointerCapture(e.pointerId); } catch (err) { /* ignore */ } try { canvas.releasePointerCapture(e.pointerId); } catch (err) { /* ignore */ }
if (!p || !app.inGame) return; if (!p || !app.inGame) { if (!ptrs.size) { multi = false; pinch = null; } return; }
cancelLong(); cancelLong();
if (ptrs.size < 2) pinch = null;
const r = canvas.getBoundingClientRect(), cell = renderer.screenToCell(e.clientX - r.left, e.clientY - r.top);
if (e.pointerType === 'mouse') { if (e.pointerType === 'mouse') {
const r = canvas.getBoundingClientRect(), cell = renderer.screenToCell(e.clientX - r.left, e.clientY - r.top);
if (e.button === 2 && rightDown) { if (!rightDown.moved) { selectType(null); selectTower(0); } rightDown = null; return; } if (e.button === 2 && rightDown) { if (!rightDown.moved) { selectType(null); selectTower(0); } rightDown = null; return; }
if (e.button === 1) { panning = false; return; } if (e.button === 1) { panning = false; return; }
if (tapSelectOnUp && !p.moved && e.type === 'pointerup') tapSelect(cell); if (tapSelectOnUp && !p.moved && e.type === 'pointerup') tapSelect(cell);
tapSelectOnUp = false; painting = false; panning = false; if (tapTowerId && !p.moved && e.type === 'pointerup') { selectTower(tapTowerId); Audio.sfx('click'); }
tapSelectOnUp = false; tapTowerId = 0; painting = false; panning = false;
return; return;
} }
if (e.type === 'pointercancel') { painting = false; tapSelectOnUp = false; return; } // touch / pen
if (painting) { painting = false; return; } if (pinch && pinch.ids.includes(e.pointerId)) { if (ptrs.size >= 2) seedPinch(); else pinch = null; }
if (ptrs.size > 0) return; // lifted one finger of a pinch const wasMulti = multi;
if (app.selType && app.pending && !p.moved && prevPending && prevPending.x === app.pending.x && prevPending.y === app.pending.y) { if (!ptrs.size) multi = false;
if (placeAt(app.pending)) { app.pending = null; updateConfirm(); } // tapping the previewed cell again builds if (wasMulti) return; // the end of a pinch/pan is never a tap
} else if (!app.selType && tapSelectOnUp && !p.moved && !longFired) tapSelect(cell); const g = tg;
if (!g || g.id !== e.pointerId) return;
if (cancelled) { abortTouch(); return; } // pointercancel: no action, nothing half done
tg = null;
const wasPainting = painting; painting = false; paintCell = null;
if (wasPainting || p.moved || longFired) { // a stroke, an aim drag, a pan or a long press: lifting the finger adds nothing
tapSelectOnUp = false; tapSelectOnUp = false;
if (longFired) unaim(); else if (!app.pending) clearCursor();
return;
}
// a tap, on the cell the finger landed on (not wherever it drifted to)
const cell = g.cell, ex = towerAtCell(cell);
if (app.selType === 'wall') {
if (ex && ex.type !== 'wall') { selectTower(ex.id); Audio.sfx('click'); } // (a drag that starts on a turret is a stroke: it keeps the tool)
else if (!ex) placeAt(cell);
} else if (app.selType) {
if (ex) { selectTower(ex.id); Audio.sfx('click'); }
else if (!app.ctrl.board.inBounds(cell.x, cell.y)) setPending(null);
else if (g.pend && g.pend.x === cell.x && g.pend.y === cell.y) { if (placeAt(cell)) setPending(null); } // tapping the previewed cell again builds
else setPending(cell, true);
} else if (tapSelectOnUp) tapSelect(cell);
tapSelectOnUp = false;
if (!app.pending) clearCursor();
} }
canvas.addEventListener('pointerup', endPointer); canvas.addEventListener('pointerup', endPointer);
canvas.addEventListener('pointercancel', endPointer); canvas.addEventListener('pointercancel', endPointer);
@ -629,9 +818,13 @@
if (!app.inGame) return; if (!app.inGame) return;
e.preventDefault(); e.preventDefault();
const r = canvas.getBoundingClientRect(); const r = canvas.getBoundingClientRect();
renderer.setZoom(renderer.zoom * (e.deltaY < 0 ? 1.15 : 1 / 1.15), e.clientX - r.left, e.clientY - r.top); // proportional to the scroll distance (a mouse notch is about the old 1.15x; a trackpad glides). ctrl+wheel is a trackpad pinch: much smaller deltas.
const dy = clamp(e.deltaY * (e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? 400 : 1), -300, 300);
renderer.setZoom(renderer.zoom * Math.exp(-dy * (e.ctrlKey ? 0.01 : 0.0015)), e.clientX - r.left, e.clientY - r.top);
updateFit(); updateFit();
}, { passive: false }); }, { passive: false });
// (the window lost focus mid-gesture: the pointerup may never arrive)
root.addEventListener('blur', () => { ptrs.clear(); abortTouch(); multi = false; pinch = null; rightDown = null; panning = false; });
function updateFit() { function updateFit() {
const z = renderer.zoom > 1.02; const z = renderer.zoom > 1.02;
@ -643,12 +836,15 @@
root.addEventListener('keydown', (e) => { root.addEventListener('keydown', (e) => {
if (e.target && (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA')) return; if (e.target && (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA')) return;
if (e.ctrlKey || e.metaKey) return; if (e.ctrlKey || e.metaKey) return;
if (e.repeat) return; // holding a key is one press: Space must not start 20 waves (code-6)
if (!app.inGame) return; if (!app.inGame) return;
if (document.querySelector('.overlay:not([hidden])')) { if (e.key === 'Escape') { closeOverlayToGame(); } return; } if (document.querySelector('.overlay:not([hidden])')) { if (e.key === 'Escape') { closeOverlayToGame(); } return; }
const ctrl = app.ctrl, view = ctrl.view; const ctrl = app.ctrl, view = ctrl.view;
const k = e.key.toLowerCase(); const k = e.key.toLowerCase();
const idx = '123456'.indexOf(k); // Space / Enter on a focused button or link press THAT control (keyboard users), not the next-wave hotkey (code-8)
if (idx >= 0 && k.length === 1) { selectType(app.selType === TD.TOWER_ORDER[idx] ? null : TD.TOWER_ORDER[idx]); Audio.sfx('click'); e.preventDefault(); return; } if ((k === ' ' || k === 'enter') && e.target && e.target.closest && e.target.closest('button, a, select, [role="button"]')) return;
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; }
switch (k) { switch (k) {
case 'escape': case 'q': selectType(null); selectTower(0); app.pending = null; updateConfirm(); break; case 'escape': case 'q': selectType(null); selectTower(0); app.pending = null; updateConfirm(); break;
case ' ': case 'enter': ctrl.send({ c: 'wave' }); e.preventDefault(); break; case ' ': case 'enter': ctrl.send({ c: 'wave' }); e.preventDefault(); break;
@ -673,6 +869,8 @@
$('btnPause').addEventListener('click', () => { Audio.sfx('click'); app.ctrl.ctl('pause', !app.ctrl.view.paused); }); $('btnPause').addEventListener('click', () => { Audio.sfx('click'); app.ctrl.ctl('pause', !app.ctrl.view.paused); });
$('btnSound').addEventListener('click', () => { Audio.unlock(); Audio.toggleMuted(); Audio.sfx('click'); }); $('btnSound').addEventListener('click', () => { Audio.unlock(); Audio.toggleMuted(); Audio.sfx('click'); });
$('btnMenu').addEventListener('click', () => { Audio.sfx('click'); openMenu(); }); $('btnMenu').addEventListener('click', () => { Audio.sfx('click'); openMenu(); });
$('pausedTag').addEventListener('click', () => { Audio.sfx('click'); app.ctrl.ctl('pause', false); });
$('netChip').addEventListener('click', () => { if (app.ctrl && app.ctrl.kind === 'remote') { Audio.sfx('click'); invite(); } }); // room code chip: tap to invite
// ------------------------------------------------------------------ menu / lobby // ------------------------------------------------------------------ menu / lobby
function buildMapPicker() { function buildMapPicker() {
@ -818,13 +1016,45 @@
} }
document.addEventListener('visibilitychange', () => { if (!document.hidden && app.inGame) requestWakeLock(); }); document.addEventListener('visibilitychange', () => { if (!document.hidden && app.inGame) requestWakeLock(); });
// ------------------------------------------------------------------ app layout (the JS half of the layout modes in style.css)
const mq = (q) => (root.matchMedia ? root.matchMedia(q) : { matches: false, addEventListener() {} });
const mqStacked = mq('(orientation: portrait), (max-width: 760px) and (min-height: 521px)');
const mqCompact = mq('(pointer: coarse), (orientation: portrait), (max-width: 760px) and (min-height: 521px), (orientation: landscape) and (max-height: 520px)');
// Stacked (portrait / narrow) layout: the stage hugs the board, so there is no dead band above and below it and the side panel gets
// everything else. The board is drawn turned 90 degrees when that makes the cells clearly bigger (tall phones), otherwise upright
// and short (small phones: the freed height goes to the palette and info panel). Inputs are the viewport and top bar only (never
// the stage's own size), so this cannot feed back into the ResizeObserver.
function layoutApp() {
const a = $('app'), b = app.ctrl && app.ctrl.board;
a.dataset.ui = mqCompact.matches ? 'compact' : 'wide';
if (!mqStacked.matches || !b) { a.style.removeProperty('--stage-h'); app.rotate = null; return; }
const cs = root.getComputedStyle(a);
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 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 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 rot = sR > sU * 1.08;
const bh = rot ? dw : dh, bw = rot ? dh : dw;
const stageH = Math.round(Math.min(maxStage, Math.ceil(bh * ((W - pad) / bw) + pad)));
app.rotate = rot;
if (a.style.getPropertyValue('--stage-h') !== stageH + 'px') a.style.setProperty('--stage-h', stageH + 'px');
}
function resizeCanvas() { function resizeCanvas() {
layoutApp();
const st = $('stage'), r = st.getBoundingClientRect(); const st = $('stage'), r = st.getBoundingClientRect();
renderer.setRotation(r.height > r.width * 1.05); // portrait: draw the board turned 90 degrees (bigger cells) renderer.setRotation(app.rotate !== null && app.rotate !== undefined ? app.rotate : r.height > r.width * 1.05); // portrait: board turned 90 degrees (bigger cells)
const dpr = Math.min(root.devicePixelRatio || 1, root.matchMedia && root.matchMedia('(pointer: coarse)').matches ? 2 : 2.5); const dpr = Math.min(root.devicePixelRatio || 1, root.matchMedia && root.matchMedia('(pointer: coarse)').matches ? 2 : 2.5);
renderer.resize(r.width, r.height, dpr); renderer.resize(r.width, r.height, dpr);
updatePaletteHint(); layoutBars(true); updateFit(); // (a rotation or board swap resets the camera: hide a stale Reset-zoom button)
} }
if (root.ResizeObserver) new ResizeObserver(resizeCanvas).observe($('stage')); else root.addEventListener('resize', resizeCanvas); let resizeRaf = 0;
function scheduleResize() { if (!resizeRaf) resizeRaf = root.requestAnimationFrame(() => { resizeRaf = 0; resizeCanvas(); }); } // (a frame later: never resize inside the observer callback)
if (root.ResizeObserver) { const ro = new ResizeObserver(scheduleResize); ro.observe($('stage')); ro.observe($('topbar')); ro.observe($('palette')); }
root.addEventListener('resize', scheduleResize);
mqStacked.addEventListener && mqStacked.addEventListener('change', scheduleResize);
mqCompact.addEventListener && mqCompact.addEventListener('change', scheduleResize);
root.addEventListener('orientationchange', () => setTimeout(() => { resizeCanvas(); drawPaletteIcons(); }, 250)); root.addEventListener('orientationchange', () => setTimeout(() => { resizeCanvas(); drawPaletteIcons(); }, 250));
// keep the page from scrolling/bouncing or zooming on iOS // keep the page from scrolling/bouncing or zooming on iOS
document.addEventListener('gesturestart', (e) => e.preventDefault()); document.addEventListener('gesturestart', (e) => e.preventDefault());
@ -843,8 +1073,13 @@
else if (app.endShown) { app.endShown = false; $('end').hidden = true; } else if (app.endShown) { app.endShown = false; $('end').hidden = true; }
} }
if (app.selTower && !view.towers.some((t) => t.id === app.selTower)) { app.selTower = 0; renderInfo(true); } if (app.selTower && !view.towers.some((t) => t.id === app.selTower)) { app.selTower = 0; renderInfo(true); }
if (app.last.rev !== view.rev) { app.last.rev = view.rev; app.previewDirty = true; if (app.selTower) renderInfo(true); } if (app.pending && pendFree) { // the partner built on the cell being previewed: drop it and say so (coop-7)
const t = towerAtCell(app.pending);
if (t) { setPending(null); toast(((ui.names && ui.names[t.owner]) || 'Someone') + ' just built there', 'bad'); }
}
if (app.last.rev !== view.rev) { app.last.rev = view.rev; app.previewDirty = true; if (app.selTower) renderInfo(false); }
updateHud(view); updateHud(view);
layoutBars(false);
if (now - app.lastBossCheck > 600 && view.state === 'playing') { if (now - app.lastBossCheck > 600 && view.state === 'playing') {
app.lastBossCheck = now; app.lastBossCheck = now;
const boss = view.monsters.some((m) => m.kind === 'rootkit'); const boss = view.monsters.some((m) => m.kind === 'rootkit');
@ -861,6 +1096,7 @@
// ------------------------------------------------------------------ boot // ------------------------------------------------------------------ boot
function boot() { function boot() {
buildPalette(); buildMapPicker(); buildPalette(); buildMapPicker();
{ const keys = TD.TOWER_ORDER.map((t) => TD.TOWERS[t].key); $('helpKeys').textContent = keys[0] + '\u2013' + keys[keys.length - 1]; }
previewMap(app.mapId); previewMap(app.mapId);
setScreen('menu'); showOverlay('menu'); setScreen('menu'); showOverlay('menu');
$('btnCloseMenu').hidden = true; $('btnCloseMenu').hidden = true;

View file

@ -10,6 +10,7 @@
const TAU = Math.PI * 2; const TAU = Math.PI * 2;
const SLOT_COLORS = ['#4de3ff', '#ffd24d']; const SLOT_COLORS = ['#4de3ff', '#ffd24d'];
const BG = '#050810', BOARD = '#09101f'; const BG = '#050810', BOARD = '#09101f';
const MARGIN = 10; // world px kept free on every side of the board so the gateway / server rings are never cut off
const clamp = (v, a, b) => Math.min(b, Math.max(a, v)); const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
const lerpAngle = (a, b, k) => { let d = ((b - a + Math.PI * 3) % TAU) - Math.PI; return a + d * k; }; const lerpAngle = (a, b, k) => { let d = ((b - a + Math.PI * 3) % TAU) - Math.PI; return a + d * k; };
@ -55,6 +56,7 @@
ctx.restore(); return; ctx.restore(); return;
} }
ctx.fillStyle = '#0c1426'; rr(ctx, -h, -h, h * 2, h * 2, S * 0.12); ctx.fill(); ctx.fillStyle = '#0c1426'; rr(ctx, -h, -h, h * 2, h * 2, S * 0.12); ctx.fill();
if (level >= 2) { ctx.fillStyle = rgba(col, level >= 3 ? 0.3 : 0.16); ctx.fill(); } // upgraded towers are tinted (level 3 clearly)
ctx.lineWidth = S * (level >= 3 ? 0.075 : 0.05); ctx.strokeStyle = col; ctx.stroke(); ctx.lineWidth = S * (level >= 3 ? 0.075 : 0.05); ctx.strokeStyle = col; ctx.stroke();
ctx.lineCap = 'round'; ctx.lineJoin = 'round'; ctx.lineCap = 'round'; ctx.lineJoin = 'round';
switch (type) { switch (type) {
@ -100,11 +102,29 @@
ctx.lineTo(-S * 0.07, S * 0.27); ctx.lineTo(S * 0.15, -S * 0.07); ctx.lineTo(S * 0.02, -S * 0.07); ctx.lineTo(S * 0.11, -S * 0.26); ctx.lineTo(-S * 0.07, S * 0.27); ctx.lineTo(S * 0.15, -S * 0.07); ctx.lineTo(S * 0.02, -S * 0.07); ctx.lineTo(S * 0.11, -S * 0.26);
ctx.closePath(); ctx.fill(); ctx.closePath(); ctx.fill();
break; break;
case 'uplink': {
// satellite dish with a feed horn and two pulsing signal arcs
const pulse = (t * 0.8) % 1;
ctx.lineWidth = S * 0.07; ctx.strokeStyle = col;
ctx.beginPath(); ctx.arc(0, S * 0.07, S * 0.23, Math.PI * 0.12, Math.PI * 0.88); ctx.stroke();
ctx.lineWidth = S * 0.045;
ctx.beginPath(); ctx.moveTo(0, S * 0.07); ctx.lineTo(0, -S * 0.15); ctx.stroke();
ctx.fillStyle = col; ctx.beginPath(); ctx.arc(0, -S * 0.17, S * 0.05, 0, TAU); ctx.fill();
for (let i = 0; i < 2; i++) {
const k = (pulse + i * 0.5) % 1;
ctx.strokeStyle = rgba(col, 1 - k); ctx.lineWidth = S * 0.035;
ctx.beginPath(); ctx.arc(0, -S * 0.17, S * (0.1 + 0.2 * k), -Math.PI * 0.85, -Math.PI * 0.15); ctx.stroke();
}
break;
}
default: break; default: break;
} }
// level pips // level pips: big enough to read at 14 px cells, with a dark halo so they show on any tile colour
ctx.fillStyle = '#ffffff'; for (let i = 0; i < level; i++) {
for (let i = 0; i < level; i++) { ctx.beginPath(); ctx.arc((i - (level - 1) / 2) * S * 0.13, h - S * 0.08, S * 0.035, 0, TAU); ctx.fill(); } const px = (i - (level - 1) / 2) * S * 0.25, py = h - S * 0.11;
ctx.fillStyle = '#04101a'; ctx.beginPath(); ctx.arc(px, py, S * 0.125, 0, TAU); ctx.fill();
ctx.fillStyle = '#ffffff'; ctx.beginPath(); ctx.arc(px, py, S * 0.085, 0, TAU); ctx.fill();
}
ctx.restore(); ctx.restore();
} }
@ -229,7 +249,7 @@
_layout() { _layout() {
const b = this.board; if (!b) return; const b = this.board; if (!b) return;
const d = this._dims(), pad = 4; const d = this._dims(), pad = 4;
this.fit = Math.min((this.W - pad * 2) / d.w, (this.H - pad * 2) / d.h); this.fit = Math.min((this.W - pad * 2) / (d.w + MARGIN * 2), (this.H - pad * 2) / (d.h + MARGIN * 2));
this.scale = this.fit * this.cam.zoom; this.scale = this.fit * this.cam.zoom;
const sw = d.w * this.scale, sh = d.h * this.scale; const sw = d.w * this.scale, sh = d.h * this.scale;
const mx = sw > this.W ? (sw - this.W) / 2 + 24 : 0, my = sh > this.H ? (sh - this.H) / 2 + 24 : 0; const mx = sw > this.W ? (sw - this.W) / 2 + 24 : 0, my = sh > this.H ? (sh - this.H) / 2 + 24 : 0;
@ -261,6 +281,9 @@
return { x: Math.floor(fx), y: Math.floor(fy), fx, fy }; return { x: Math.floor(fx), y: Math.floor(fy), fx, fy };
} }
cellToScreen(cx, cy) { return this._w2s((cx + 0.5) * C, (cy + 0.5) * C); } cellToScreen(cx, cy) { return this._w2s((cx + 0.5) * C, (cy + 0.5) * C); }
// The cell one step away in a SCREEN direction (dx, dy each -1, 0 or 1). The board is drawn turned 90 degrees on tall screens,
// so screen right is not world +x there: this is what the touch nudge buttons use.
stepCell(cx, cy, dx, dy) { return this.rot ? { x: cx + dy, y: cy - dx } : { x: cx + dx, y: cy + dy }; }
cellSizePx() { return C * this.scale; } cellSizePx() { return C * this.scale; }
// ---------------------------------------------------------------- effects // ---------------------------------------------------------------- effects
@ -296,6 +319,17 @@
else if (e.k === 'filter') this._burst(e.x * C + Math.cos(e.a) * 14, e.y * C + Math.sin(e.a) * 14, '#35e0a1', 1, 30, 0.12); else if (e.k === 'filter') this._burst(e.x * C + Math.cos(e.a) * 14, e.y * C + Math.sin(e.a) * 14, '#35e0a1', 1, 30, 0.12);
else if (e.k === 'mortar') this._burst(e.x * C + Math.cos(e.a) * 16, e.y * C + Math.sin(e.a) * 16, '#d4f04a', 3, 40, 0.25); else if (e.k === 'mortar') this._burst(e.x * C + Math.cos(e.a) * 16, e.y * C + Math.sin(e.a) * 16, '#d4f04a', 3, 40, 0.25);
break; break;
case 'beam': {
const x1 = e.x * C, y1 = e.y * C, x2 = e.tx * C, y2 = e.ty * C, wpx = (e.w || 0.5) * C;
this.lines.push({ pts: [[x1, y1], [x2, y2]], col: 'rgba(255,226,122,.35)', w: wpx * 2.6, life: 0.42, max: 0.42, jit: 0 });
this.lines.push({ pts: [[x1, y1], [x2, y2]], col: '#ffe27a', w: wpx * 1.1, life: 0.34, max: 0.34, jit: 0 });
this.lines.push({ pts: [[x1, y1], [x2, y2]], col: '#ffffff', w: wpx * 0.45, life: 0.26, max: 0.26, jit: 0 });
this._ring(e.bx * C, e.by * C, 6, (e.br || 1.3) * C, '#ffe27a', 0.45, 4);
this._burst(e.bx * C, e.by * C, '#ffe27a', 10, 130, 0.45);
this._ring(x1, y1, 4, 30, '#ffffff', 0.25, 3);
this.shake = Math.min(2, this.shake + 0.35);
break;
}
case 'arc': this.lines.push({ pts: e.pts.map((p) => [p[0] * C, p[1] * C]), col: '#ff7ad9', w: 2.4, life: 0.18, max: 0.18, jit: 5 }); break; case 'arc': this.lines.push({ pts: e.pts.map((p) => [p[0] * C, p[1] * C]), col: '#ff7ad9', w: 2.4, life: 0.18, max: 0.18, jit: 5 }); break;
case 'place': { const d = TD.TOWERS[e.type]; this._ring((e.x + 0.5) * C, (e.y + 0.5) * C, 6, 34, d ? d.color : '#fff', 0.35, 2.5); this._burst((e.x + 0.5) * C, (e.y + 0.5) * C, d ? d.color : '#fff', 5, 60, 0.35); break; } case 'place': { const d = TD.TOWERS[e.type]; this._ring((e.x + 0.5) * C, (e.y + 0.5) * C, 6, 34, d ? d.color : '#fff', 0.35, 2.5); this._burst((e.x + 0.5) * C, (e.y + 0.5) * C, d ? d.color : '#fff', 5, 60, 0.35); break; }
case 'sell': this._burst((e.x + 0.5) * C, (e.y + 0.5) * C, '#9db4d8', 6, 70, 0.35); break; case 'sell': this._burst((e.x + 0.5) * C, (e.y + 0.5) * C, '#9db4d8', 6, 70, 0.35); break;
@ -388,9 +422,11 @@
if (tg) { ang = lerpAngle(ang, Math.atan2(tg.y - (tw.y + 0.5), tg.x - (tw.x + 0.5)), 0.35); this.aim.set(tw.id, ang); } if (tg) { ang = lerpAngle(ang, Math.atan2(tg.y - (tw.y + 0.5), tg.x - (tw.x + 0.5)), 0.35); this.aim.set(tw.id, ang); }
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;
drawGlyph(ctx, tw.type, tw.level, cx, cy, C, ang, t, 1, rot); drawGlyph(ctx, tw.type, tw.level, cx, cy, C, ang, t, 1, rot);
if (coop && tw.type !== 'wall') { 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
ctx.fillStyle = SLOT_COLORS[tw.owner] || '#fff'; const k = Math.max(12, 5.5 / sc), x0 = cx - C * 0.46, y0 = cy - C * 0.46;
ctx.beginPath(); ctx.moveTo(cx - C * 0.43, cy - C * 0.43); ctx.lineTo(cx - C * 0.43 + 8, cy - C * 0.43); ctx.lineTo(cx - C * 0.43, cy - C * 0.43 + 8); ctx.closePath(); ctx.fill(); ctx.beginPath(); ctx.moveTo(x0, y0); ctx.lineTo(x0 + k, y0); ctx.lineTo(x0, y0 + k); ctx.closePath();
ctx.fillStyle = SLOT_COLORS[tw.owner] || '#fff'; ctx.fill();
ctx.lineWidth = 1.5 / sc; ctx.strokeStyle = '#04101a'; ctx.stroke();
} }
} }
if (this.aim.size > towers.length + 40) { const live = new Set(towers.map((x) => x.id)); for (const k of this.aim.keys()) if (!live.has(k)) this.aim.delete(k); } if (this.aim.size > towers.length + 40) { const live = new Set(towers.map((x) => x.id)); for (const k of this.aim.keys()) if (!live.has(k)) this.aim.delete(k); }
@ -445,18 +481,12 @@
} }
// partner cursors and pings // partner cursors and pings
ctx.font = '600 ' + (11 / sc) + 'px system-ui, sans-serif'; ctx.textBaseline = 'middle'; const labels = []; // the cell frame is drawn on the board, the name label later in screen space (clamped to the stage)
for (const cu of view.cursors || []) { for (const cu of view.cursors || []) {
const col = SLOT_COLORS[cu.slot] || '#fff', gx = Math.floor(cu.x), gy = Math.floor(cu.y); const col = SLOT_COLORS[cu.slot] || '#fff', gx = Math.floor(cu.x), gy = Math.floor(cu.y);
ctx.strokeStyle = col; ctx.lineWidth = 2; ctx.strokeRect(gx * C + 1, gy * C + 1, C - 2, C - 2); ctx.strokeStyle = col; ctx.lineWidth = 2; ctx.strokeRect(gx * C + 1, gy * C + 1, C - 2, C - 2);
const nm = (ui.names && ui.names[cu.slot]) || 'Partner'; labels.push({ nm: (ui.names && ui.names[cu.slot]) || 'Partner', col, gx, gy });
const tw = ctx.measureText(nm).width + 10 / sc;
ctx.save(); ctx.translate((gx + 0.5) * C, (gy + 0.5) * C); if (rot) ctx.rotate(-rot);
ctx.fillStyle = col; ctx.fillRect(-tw / 2, -C / 2 - 17 / sc, tw, 15 / sc);
ctx.fillStyle = '#04101a'; ctx.textAlign = 'center'; ctx.fillText(nm, 0, -C / 2 - 9.5 / sc);
ctx.restore();
} }
ctx.textAlign = 'start';
for (let i = this.marks.length - 1; i >= 0; i--) { for (let i = this.marks.length - 1; i >= 0; i--) {
const m = this.marks[i]; m.life -= dt; const m = this.marks[i]; m.life -= dt;
if (m.life <= 0) { this.marks.splice(i, 1); continue; } if (m.life <= 0) { this.marks.splice(i, 1); continue; }
@ -469,6 +499,7 @@
ctx.globalAlpha = 1; ctx.globalAlpha = 1;
ctx.fillStyle = col; ctx.beginPath(); ctx.arc((m.x + 0.5) * C, (m.y + 0.5) * C, 5, 0, TAU); ctx.fill(); ctx.fillStyle = col; ctx.beginPath(); ctx.arc((m.x + 0.5) * C, (m.y + 0.5) * C, 5, 0, TAU); ctx.fill();
} }
if (labels.length) this._cursorLabels(ctx, labels);
} }
_rangeRing(ctx, cx, cy, r, col) { _rangeRing(ctx, cx, cy, r, col) {
@ -589,6 +620,22 @@
ctx.globalAlpha = 1; ctx.textAlign = 'start'; ctx.globalAlpha = 1; ctx.textAlign = 'start';
} }
} }
// partner name labels: screen space, kept inside the stage, flipped below the cell when there is no room above it
_cursorLabels(ctx, labels) {
ctx.setTransform(this.dpr, 0, 0, this.dpr, 0, 0);
ctx.font = '600 11px system-ui, sans-serif'; ctx.textBaseline = 'middle'; ctx.textAlign = 'center';
const half = C * this.scale / 2;
for (const l of labels) {
const p = this.cellToScreen(l.gx, l.gy), w = ctx.measureText(l.nm).width + 10;
const x = clamp(p.x - w / 2, 2, Math.max(2, this.W - 2 - w));
let y = p.y - half - 17; if (y < 2) y = p.y + half + 2;
y = clamp(y, 2, Math.max(2, this.H - 17));
ctx.fillStyle = l.col; ctx.fillRect(x, y, w, 15);
ctx.fillStyle = '#04101a'; ctx.fillText(l.nm, x + w / 2, y + 7.5);
}
ctx.textAlign = 'start';
}
} }
// Draw a tower icon into a small canvas (palette buttons, info panel) // Draw a tower icon into a small canvas (palette buttons, info panel)
@ -606,4 +653,5 @@
NW.drawGlyph = drawGlyph; NW.drawGlyph = drawGlyph;
NW.SLOT_COLORS = SLOT_COLORS; NW.SLOT_COLORS = SLOT_COLORS;
NW.CELL = C; NW.CELL = C;
NW.BOARD_MARGIN = MARGIN;
})(typeof self !== 'undefined' ? self : this); })(typeof self !== 'undefined' ? self : this);

View file

@ -91,8 +91,96 @@
'..........................', '..........................',
], ],
}, },
canyon: {
id: 'canyon', name: 'The Canyon', difficulty: 1,
desc: 'Three ridges force a natural S-bend. Great for learning where to stack turrets.',
rows: [
'.......#.........#........',
'.......#.........#........',
'.......#.........#........',
'.......#.........#........',
'.......#.........#........',
'.......#....#....#........',
'.......#....#....#........',
'S......#....#....#........',
'.......#....#....#.......C',
'.......#....#....#........',
'.......#....#....#........',
'............#.............',
'............#.............',
'............#.............',
'............#.............',
'............#.............',
],
},
archipelago: {
id: 'archipelago', name: 'Archipelago', difficulty: 2,
desc: 'Islands of dead nodes everywhere and two gateways. Mind the gaps between them.',
rows: [
'..........................',
'..........................',
'S...##........##......##..',
'....##........##......##..',
'...................##.....',
'.........##........##.....',
'.........##...............',
'..........................',
'...............##........C',
'.....##........##.........',
'.....##...................',
'..........................',
'..........##.......##.....',
'S.........##.......##.##..',
'......................##..',
'..........................',
],
},
fortress: {
id: 'fortress', name: 'Fortress', difficulty: 2,
desc: 'The server sits inside a ring with three entrances. Wall off two, defend the third.',
rows: [
'..........................',
'..........................',
'..........................',
'S.........................',
'..........................',
'..................###.###.',
'..................#.....#.',
'..................#.....#.',
'.....................C..#.',
'..................#.....#.',
'..................#.....#.',
'..................###.###.',
'S.........................',
'..........................',
'..........................',
'..........................',
],
},
pinwheel: {
id: 'pinwheel', name: 'Pinwheel', difficulty: 3,
desc: 'Four gateways, one server in the middle, bars that twist every route.',
rows: [
'.............S............',
'..........................',
'..........................',
'................#.........',
'................#.........',
'........#####...#.........',
'................#.........',
'................#........S',
'S............C............',
'.........#................',
'.........#................',
'.........#....#####.......',
'.........#................',
'.........#................',
'..........................',
'............S.............',
],
},
}; };
const MAP_ORDER = ['open', 'twin', 'hub']; const MAP_ORDER = ['open', 'canyon', 'twin', 'archipelago', 'fortress', 'hub', 'pinwheel'];
function parseMap(m) { function parseMap(m) {
const rows = m.rows.length, cols = m.rows[0].length; const rows = m.rows.length, cols = m.rows[0].length;
@ -113,7 +201,7 @@
} }
// ---------------------------------------------------------------- definitions // ---------------------------------------------------------------- definitions
const TOWER_ORDER = ['wall', 'filter', 'ids', 'mortar', 'throttle', 'arc']; const TOWER_ORDER = ['wall', 'filter', 'ids', 'mortar', 'throttle', 'arc', 'uplink'];
const TARGET_MODES = ['first', 'last', 'strong', 'close']; const TARGET_MODES = ['first', 'last', 'strong', 'close'];
const TOWERS = { const TOWERS = {
wall: { wall: {
@ -168,6 +256,16 @@
{ cost: 120, dmg: 36, range: 4.2, rate: 1.4, chains: 4, chainRange: 2.2, falloff: 0.75 }, { cost: 120, dmg: 36, range: 4.2, rate: 1.4, chains: 4, chainRange: 2.2, falloff: 0.75 },
], ],
}, },
uplink: {
name: 'Orbital Uplink', key: '7', color: '#ffe27a', air: true, ground: true,
desc: 'Endgame weapon. A piercing orbital beam that ignores armour, scorches everything in its line, blasts and slows the rest around the target, and reaches across most of the map. Very expensive to build and to upgrade.',
levels: [
{ cost: 450, dmg: 260, range: 11, rate: 0.45, width: 0.5, splash: 1.3, slowOnHit: 0.4, slowFor: 1.5 },
{ cost: 500, dmg: 400, range: 12, rate: 0.5, width: 0.55, splash: 1.5, slowOnHit: 0.45, slowFor: 1.75 },
{ cost: 800, dmg: 640, range: 13, rate: 0.55, width: 0.6, splash: 1.7, slowOnHit: 0.5, slowFor: 2.0 },
{ cost: 1200, dmg: 1000, range: 14, rate: 0.6, width: 0.7, splash: 2.0, slowOnHit: 0.6, slowFor: 2.5 },
],
},
}; };
const ENEMY_ORDER = ['ping', 'worm', 'trojan', 'spam', 'ghost', 'rootkit']; const ENEMY_ORDER = ['ping', 'worm', 'trojan', 'spam', 'ghost', 'rootkit'];
@ -554,7 +652,7 @@
x: s.x + 0.5, y: s.y + 0.5, cx: s.x, cy: s.y, tx: -1, ty: -1, 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, speed: def.speed, hp, maxhp: hp, armor: def.armor, speed: def.speed,
reward: Math.max(1, Math.round(def.reward * rewardScale(q.wave))), reward: Math.max(1, Math.round(def.reward * rewardScale(q.wave))),
leak: def.leak, slow: 0, rem: 0, dead: false, wave: q.wave, leak: def.leak, slow: 0, slowT: 0, slowAmt: 0, rem: 0, dead: false, wave: q.wave,
}; };
m.rem = m.air m.rem = m.air
? Math.hypot(b.core.x - s.x, b.core.y - s.y) ? Math.hypot(b.core.x - s.x, b.core.y - s.y)
@ -572,7 +670,9 @@
} }
while (this.spawnQ.length && this.spawnQ[0].t <= this.time) this.spawnMonster(this.spawnQ.shift()); while (this.spawnQ.length && this.spawnQ[0].t <= this.time) this.spawnMonster(this.spawnQ.shift());
for (const m of this.monsters) m.slow = 0; for (const m of this.monsters) { // slow = lingering slow (Orbital Uplink) unless a Rate Limiter says more
if (m.slowT > 0) { m.slow = m.slowAmt; m.slowT -= dt; } else m.slow = 0;
}
for (const t of this.towers) this.updateTower(t, dt); for (const t of this.towers) this.updateTower(t, dt);
this.updateBullets(dt); this.updateBullets(dt);
for (const m of this.monsters) if (!m.dead) this.moveMonster(m, dt); for (const m of this.monsters) if (!m.dead) this.moveMonster(m, dt);
@ -645,9 +745,9 @@
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) { damage(m, raw, src, ignoreArmor) {
if (m.dead) return; if (m.dead) return;
const d = Math.max(raw - m.armor, raw * 0.25); const d = ignoreArmor ? raw : Math.max(raw - m.armor, raw * 0.25);
m.hp -= d; m.hp -= d;
if (src) src.dealt += d; if (src) src.dealt += d;
if (m.hp <= 0) { if (m.hp <= 0) {
@ -727,6 +827,35 @@
this.emit({ e: 'shot', k: 'mortar', x: cx, y: cy, a: Math.atan2(gy - cy, gx - cx) }); this.emit({ e: 'shot', k: 'mortar', x: cx, y: cy, a: Math.atan2(gy - cy, gx - cx) });
break; break;
} }
case 'uplink': {
// A beam from the tower through the target out to full range: everything in the line takes full damage
// (armour ignored), then everything near the target is blasted for half and everything hit is slowed for a moment.
const ex = m.x - cx, ey = m.y - cy, el = Math.hypot(ex, ey) || 1, ux = ex / el, uy = ey / el;
const hit = new Set();
for (const o of this.monsters) {
if (o.dead || (o.air ? !def.air : !def.ground)) continue;
const ox = o.x - cx, oy = o.y - cy, along = ox * ux + oy * uy;
if (along < 0 || along > st.range) continue;
if (Math.abs(ox * uy - oy * ux) <= st.width) hit.add(o);
}
const r2 = st.splash * st.splash;
const blast = [];
for (const o of this.monsters) {
if (o.dead || hit.has(o) || (o.air ? !def.air : !def.ground)) continue;
const dx = o.x - m.x, dy = o.y - m.y;
if (dx * dx + dy * dy <= r2) blast.push(o);
}
const slowFor = (o) => {
const eff = Math.min(0.6, st.slowOnHit * (1 - (ENEMIES[o.kind].slowRes || 0)));
if (eff >= o.slowAmt || o.slowT <= 0) o.slowAmt = eff;
o.slowT = Math.max(o.slowT, st.slowFor);
};
for (const o of hit) { this.damage(o, st.dmg, t, true); slowFor(o); }
for (const o of blast) { this.damage(o, st.dmg * 0.5, t, true); slowFor(o); }
this.emit({ e: 'shot', k: 'uplink', x: cx, y: cy, tx: round2(m.x), ty: round2(m.y) });
this.emit({ e: 'beam', x: round2(cx), y: round2(cy), tx: round2(cx + ux * st.range), ty: round2(cy + uy * st.range), w: st.width, bx: round2(m.x), by: round2(m.y), br: st.splash });
break;
}
case 'arc': { case 'arc': {
const pts = [[cx, cy], [m.x, m.y]]; const pts = [[cx, cy], [m.x, m.y]];
const hit = new Set([m]); const hit = new Set([m]);

View file

@ -9,6 +9,18 @@ self.addEventListener('install', (e) => {
self.addEventListener('activate', (e) => { self.addEventListener('activate', (e) => {
e.waitUntil(caches.keys().then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))).then(() => self.clients.claim())); e.waitUntil(caches.keys().then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))).then(() => self.clients.claim()));
}); });
// An error page from the proxy in front of the app (nginx answers 502/503/504 while the Node process restarts or is
// down) is a "network failure" for our purposes: serve the cached copy instead of the proxy's error page.
const GATEWAY_ERRORS = [502, 503, 504];
// The cached copy of this request; a navigation (also /?room=ABCD, which has no cache entry of its own) falls back to the
// cached app shell. `res` is the proxy's error response, still better than nothing for a file that was never cached.
function offline(req, res) {
return caches.match(req)
.then((r) => r || (req.mode === 'navigate' ? caches.match('index.html') : null))
.then((r) => r || res || Response.error());
}
self.addEventListener('fetch', (e) => { self.addEventListener('fetch', (e) => {
const req = e.request; const req = e.request;
if (req.method !== 'GET') return; if (req.method !== 'GET') return;
@ -17,9 +29,11 @@ self.addEventListener('fetch', (e) => {
e.respondWith( e.respondWith(
fetch(req) fetch(req)
.then((res) => { .then((res) => {
if (res.ok && res.type === 'basic') { const copy = res.clone(); caches.open(CACHE).then((c) => c.put(req, copy)).catch(() => {}); } if (GATEWAY_ERRORS.includes(res.status)) return offline(req, res);
// Only complete responses: a 206 (a range request for audio) is ok but is not the whole file.
if (res.status === 200 && res.type === 'basic') { const copy = res.clone(); caches.open(CACHE).then((c) => c.put(req, copy)).catch(() => {}); }
return res; return res;
}) })
.catch(() => caches.match(req).then((r) => r || caches.match('index.html'))), .catch(() => offline(req)),
); );
}); });

View file

@ -6,7 +6,7 @@
* const { createServer } = require('./server'); * const { createServer } = require('./server');
* const srv = await createServer({ port: 8080 }); // srv.port, srv.addresses, srv.close(), srv.rooms * const srv = await createServer({ port: 8080 }); // srv.port, srv.addresses, srv.close(), srv.rooms
* *
* Run directly: PORT=8080 HOST=:: TRUST_PROXY=auto ALLOWED_ORIGINS=https://game.example.com node server/index.js * Run directly: PORT=8080 HOST=:: TRUST_PROXY=auto TRUSTED_PROXIES=100.64.0.0/10 ALLOWED_ORIGINS=https://game.example.com node server/index.js
*/ */
const http = require('http'); const http = require('http');
const path = require('path'); const path = require('path');
@ -14,7 +14,7 @@ const { WebSocketServer } = require('ws');
const TD = require('../public/js/sim.js'); const TD = require('../public/js/sim.js');
const { RoomManager } = require('./room'); const { RoomManager } = require('./room');
const { createStaticHandler, applySecurityHeaders, CSP } = require('./static'); const { createStaticHandler, applySecurityHeaders, CSP } = require('./static');
const { parseTrustProxy, clientIp, originAllowed, TokenBucket, listenDual, listUrls } = require('./net'); const { parseTrustProxy, parseTrustedProxies, isTrustedPeer, clientIp, originAllowed, TokenBucket, listenDual, listUrls } = require('./net');
const MAX_PAYLOAD = 2048; // bytes per client frame const MAX_PAYLOAD = 2048; // bytes per client frame
const RATE_PER_SEC = 60, RATE_BURST = 120; const RATE_PER_SEC = 60, RATE_BURST = 120;
@ -40,11 +40,12 @@ async function createServer(userOpts) {
const o = { const o = {
port: 8080, host: '::', publicDir: path.join(__dirname, '..', 'public'), port: 8080, host: '::', publicDir: path.join(__dirname, '..', 'public'),
graceMs: 60000, snapshotHz: 20, maxRooms: 50, graceMs: 60000, snapshotHz: 20, maxRooms: 50,
trustProxy: 'auto', 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
}; };
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);
o.trustedProxies = parseTrustedProxies(o.trustedProxies); // null, or { list, has(ip) }: extra proxy addresses for 'auto'
o.allowedOrigins = (o.allowedOrigins || []).map(String).filter(Boolean); o.allowedOrigins = (o.allowedOrigins || []).map(String).filter(Boolean);
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;
@ -96,11 +97,13 @@ async function createServer(userOpts) {
if (closing) return refuse(socket, 503, 'Service Unavailable'); if (closing) return refuse(socket, 503, 'Service Unavailable');
if ((req.url || '').split('?')[0] !== '/ws') return refuse(socket, 404, 'Not Found'); if ((req.url || '').split('?')[0] !== '/ws') return refuse(socket, 404, 'Not Found');
if (!originAllowed(req, o)) { if (!originAllowed(req, o)) {
log('refused websocket from ' + clientIp(req, o.trustProxy) + ': Origin ' + JSON.stringify(req.headers.origin) + log('refused websocket from ' + clientIp(req, o.trustProxy, o.trustedProxies) + ': Origin ' + JSON.stringify(req.headers.origin) +
' does not match Host ' + JSON.stringify(req.headers.host) + ' (see ALLOWED_ORIGINS)'); ' does not match Host ' + JSON.stringify(req.headers.host) + (isTrustedPeer(req, o.trustProxy, o.trustedProxies)
? ' (see ALLOWED_ORIGINS)'
: ' (this connection is not from a trusted proxy: see TRUST_PROXY, TRUSTED_PROXIES and ALLOWED_ORIGINS)'));
return refuse(socket, 403, 'Forbidden'); return refuse(socket, 403, 'Forbidden');
} }
const ip = clientIp(req, o.trustProxy); const ip = clientIp(req, o.trustProxy, o.trustedProxies);
if (o.maxConnPerIp > 0 && (ipCount.get(ip) || 0) >= o.maxConnPerIp) { if (o.maxConnPerIp > 0 && (ipCount.get(ip) || 0) >= o.maxConnPerIp) {
log('refused websocket from ' + ip + ': too many connections'); log('refused websocket from ' + ip + ': too many connections');
return refuse(socket, 429, 'Too Many Requests'); return refuse(socket, 429, 'Too Many Requests');
@ -280,6 +283,7 @@ async function main() {
port: envInt('PORT', 8080), port: envInt('PORT', 8080),
host: process.env.HOST || '::', host: process.env.HOST || '::',
trustProxy: process.env.TRUST_PROXY || 'auto', trustProxy: process.env.TRUST_PROXY || 'auto',
trustedProxies: process.env.TRUSTED_PROXIES || '',
allowedOrigins: (process.env.ALLOWED_ORIGINS || '').split(',').map((s) => s.trim()).filter(Boolean), allowedOrigins: (process.env.ALLOWED_ORIGINS || '').split(',').map((s) => s.trim()).filter(Boolean),
}; };
if (process.env.MAX_CONN_PER_IP) opts.maxConnPerIp = envInt('MAX_CONN_PER_IP', 40); if (process.env.MAX_CONN_PER_IP) opts.maxConnPerIp = envInt('MAX_CONN_PER_IP', 40);
@ -288,7 +292,9 @@ async function main() {
const shownProxy = parseTrustProxy(opts.trustProxy); const shownProxy = parseTrustProxy(opts.trustProxy);
console.log('Netwall is listening on ' + (srv.host.includes(':') ? '[' + srv.host + ']' : srv.host) + ':' + srv.port + console.log('Netwall is listening on ' + (srv.host.includes(':') ? '[' + srv.host + ']' : srv.host) + ':' + srv.port +
(srv.host === '::' ? ' (dual stack: IPv4 + IPv6)' : srv.host === '0.0.0.0' ? ' (IPv4 only)' : '')); (srv.host === '::' ? ' (dual stack: IPv4 + IPv6)' : srv.host === '0.0.0.0' ? ' (IPv4 only)' : ''));
console.log(' trust proxy: ' + shownProxy + ', extra allowed origins: ' + (opts.allowedOrigins.join(', ') || '(none)')); console.log(' trust proxy: ' + shownProxy + (srv.options.trustedProxies && shownProxy === 'auto'
? ' + ' + srv.options.trustedProxies.list.join(', ') : '') +
', extra allowed origins: ' + (opts.allowedOrigins.join(', ') || '(none)'));
console.log('Open:'); console.log('Open:');
for (const u of listUrls(srv.host, srv.port)) console.log(' ' + u); for (const u of listUrls(srv.host, srv.port)) console.log(' ' + u);

View file

@ -54,11 +54,44 @@ function peerIp(req) {
return normalizeIp(req.socket && req.socket.remoteAddress) || 'unknown'; return normalizeIp(req.socket && req.socket.remoteAddress) || 'unknown';
} }
// Does this request come from a proxy whose X-Forwarded-* headers we believe? // TRUSTED_PROXIES: extra proxy addresses believed under TRUST_PROXY=auto, on top of the private ranges. The built-in
function isTrustedPeer(req, trustProxy) { // "private" list misses a proxy that reaches the game over a global IPv6 address, Tailscale / CGNAT (100.64.0.0/10) or
// any other routable address. Accepts an array or a comma separated string of IPs and CIDRs, IPv4 or IPv6
// ("100.64.0.0/10, 2001:db8::6, 2001:db8:1::/48"). Returns null for an empty list, throws on a malformed entry (a
// typo must stop the start-up, not silently leave the proxy untrusted). The result has .has(ip) and .list.
function parseTrustedProxies(v) {
const items = Array.isArray(v) ? v : String(v === undefined || v === null ? '' : v).split(',');
const list = items.map((s) => String(s).trim()).filter(Boolean);
if (!list.length) return null;
const bl = new net.BlockList();
for (const item of list) {
const slash = item.indexOf('/');
const addr = normalizeIp(slash < 0 ? item : item.slice(0, slash));
const type = net.isIPv4(addr) ? 'ipv4' : net.isIPv6(addr) ? 'ipv6' : null;
const max = type === 'ipv4' ? 32 : 128;
const prefixText = slash < 0 ? null : item.slice(slash + 1);
const prefix = prefixText === null ? max : (/^\d{1,3}$/.test(prefixText) ? Number(prefixText) : NaN);
if (!type || !(prefix >= 0 && prefix <= max) ||
(item.startsWith('::ffff:') && slash >= 0)) { // a v4-mapped prefix would need its own arithmetic: write the IPv4 form
throw new Error('invalid TRUSTED_PROXIES entry ' + JSON.stringify(item) + ' (use an IP or CIDR such as 100.64.0.0/10 or 2001:db8::6)');
}
if (prefixText === null) bl.addAddress(addr, type); else bl.addSubnet(addr, prefix, type);
}
return {
list,
has(ip) {
const a = normalizeIp(ip);
return net.isIPv4(a) ? bl.check(a, 'ipv4') : net.isIPv6(a) ? bl.check(a, 'ipv6') : false;
},
};
}
// Does this request come from a proxy whose X-Forwarded-* headers we believe? `trusted` = parseTrustedProxies() result.
function isTrustedPeer(req, trustProxy, trusted) {
if (trustProxy === true) return true; if (trustProxy === true) return true;
if (trustProxy === false) return false; if (trustProxy === false) return false;
return isPrivateIp(peerIp(req)); const ip = peerIp(req);
return isPrivateIp(ip) || !!(trusted && trusted.has(ip));
} }
// One entry of a forwarding header ("203.0.113.9", "[2001:db8::5]:443", "1.2.3.4:5555") -> bare IP or null. // One entry of a forwarding header ("203.0.113.9", "[2001:db8::5]:443", "1.2.3.4:5555") -> bare IP or null.
@ -95,17 +128,17 @@ function forwardedClientIp(value) {
} }
// The address used for logging and the per-IP socket cap. // The address used for logging and the per-IP socket cap.
function clientIp(req, trustProxy) { function clientIp(req, trustProxy, trusted) {
const peer = peerIp(req); const peer = peerIp(req);
if (!isTrustedPeer(req, trustProxy)) return peer; if (!isTrustedPeer(req, trustProxy, trusted)) return peer;
return forwardedClientIp(req.headers['x-forwarded-for']) || return forwardedClientIp(req.headers['x-forwarded-for']) ||
firstForwardedIp(req.headers['x-real-ip']) || peer; firstForwardedIp(req.headers['x-real-ip']) || peer;
} }
// ---------------------------------------------------------------- Origin check // ---------------------------------------------------------------- Origin check
// Scheme-less, lower-case "host[:port]" with the default ports 80 / 443 dropped. // Scheme-less, lower-case host name and port of a bare host ("Game.Example.com:443"), a Host header or a full origin
// Accepts a bare host ("Game.Example.com:443"), a Host header, or a full origin ("https://x.example"). // ("https://x.example"): { name, port }, with port '' for none or for the default ports 80 / 443. null if unusable.
function normalizeHost(s) { function hostParts(s) {
if (typeof s !== 'string') return null; if (typeof s !== 'string') return null;
let v = s.trim(); let v = s.trim();
if (!v) return null; if (!v) return null;
@ -117,27 +150,43 @@ function normalizeHost(s) {
try { u = new URL(v); } catch (e) { return null; } try { u = new URL(v); } catch (e) { return null; }
if (!u.hostname) return null; if (!u.hostname) return null;
const port = u.port; // '' for the scheme's own default const port = u.port; // '' for the scheme's own default
const h = u.hostname.toLowerCase(); // IPv6 keeps its brackets return { name: u.hostname.toLowerCase(), port: port && port !== '80' && port !== '443' ? port : '' }; // IPv6 keeps its brackets
return port && port !== '80' && port !== '443' ? h + ':' + port : h; }
// "host[:port]" form of hostParts().
function normalizeHost(s) {
const p = hostParts(s);
return p ? (p.port ? p.name + ':' + p.port : p.name) : null;
} }
// Returns true when a WebSocket upgrade with this Origin may proceed. // Returns true when a WebSocket upgrade with this Origin may proceed.
// no Origin header -> true (non-browser clients) // no Origin header -> true (non-browser clients)
// Origin host == Host -> true // Origin host == Host -> true
// Origin host == X-Forwarded-Host (first) -> true, only when the peer is a trusted proxy // Origin host == X-Forwarded-Host (first) -> true, only when the peer is a trusted proxy
// Origin host name == Host name, Host without a port -> true, only when the peer is a trusted proxy (see below)
// Origin host in allowedOrigins -> true // Origin host in allowedOrigins -> true
// opts: { trustProxy, trustedProxies (parseTrustedProxies() result), allowedOrigins }.
function originAllowed(req, opts) { function originAllowed(req, opts) {
const origin = req.headers.origin; const origin = req.headers.origin;
if (origin === undefined) return true; if (origin === undefined) return true;
const o = (typeof origin === 'string' && origin.toLowerCase() !== 'null' && /^[a-z][a-z0-9+.-]*:\/\//i.test(origin)) const o = (typeof origin === 'string' && origin.toLowerCase() !== 'null' && /^[a-z][a-z0-9+.-]*:\/\//i.test(origin))
? normalizeHost(origin) : null; ? hostParts(origin) : null;
if (!o) return false; if (!o) return false;
if (o === normalizeHost(req.headers.host)) return true; const h = hostParts(req.headers.host);
if (isTrustedPeer(req, opts.trustProxy)) { if (h && o.name === h.name && o.port === h.port) return true;
if (isTrustedPeer(req, opts.trustProxy, opts.trustedProxies)) {
const xfh = req.headers['x-forwarded-host']; const xfh = req.headers['x-forwarded-host'];
if (typeof xfh === 'string' && o === normalizeHost(xfh.split(',')[0])) return true; if (typeof xfh === 'string' && normalizeHost(xfh.split(',')[0]) === normalizeHost(origin)) return true;
// Published on a port other than 80/443 (https://game.example.com:8443) behind nginx / nginx Proxy Manager: their
// "proxy_set_header Host $host" drops the port, so Host is "game.example.com" while the browser's Origin keeps
// ":8443", and neither the X-Forwarded-Host nor an ALLOWED_ORIGINS entry written without the port helps. A browser that
// talks to this server directly on its port (8080 by default, never 80/443 unless you chose that) puts the port in
// Host, so a Host WITHOUT one from a trusted proxy is what a stripped port looks like: accept the same host name on
// any port. Another name still fails.
if (h && !h.port && o.name === h.name) return true;
} }
for (const a of opts.allowedOrigins || []) if (o === normalizeHost(a)) return true; const on = normalizeHost(origin);
for (const a of opts.allowedOrigins || []) if (on === normalizeHost(a)) return true;
return false; return false;
} }
@ -220,6 +269,6 @@ function listUrls(bound, port, ifaces) {
} }
module.exports = { module.exports = {
normalizeIp, isPrivateIp, parseTrustProxy, peerIp, isTrustedPeer, firstForwardedIp, forwardedClientIp, clientIp, normalizeIp, isPrivateIp, parseTrustProxy, parseTrustedProxies, peerIp, isTrustedPeer, firstForwardedIp, forwardedClientIp, clientIp,
normalizeHost, originAllowed, TokenBucket, listenDual, listUrls, fmtUrl, hostParts, normalizeHost, originAllowed, TokenBucket, listenDual, listUrls, fmtUrl,
}; };

101
test/camera.test.js Normal file
View file

@ -0,0 +1,101 @@
'use strict';
// The camera math of the renderer (cell <-> screen under rotation, zoom and pan) is what turns a fingertip into a cell. It runs in Node
// here with a stub canvas: randomised round trips, so a rotated board, a zoomed board and a panned board all pick the same cell the
// player sees. (public/js/render.js assigns to `this` when there is no `self`, i.e. to module.exports in Node.)
const test = require('node:test');
const assert = require('node:assert/strict');
const TD = require('../public/js/sim.js');
const NW = require('../public/js/render.js').NW;
function rng(seed) { let s = seed >>> 0; return () => { s = (s * 1664525 + 1013904223) >>> 0; return s / 4294967296; }; }
const stubCanvas = { getContext() { return {}; }, width: 0, height: 0 };
function makeRenderer(mapId, rot, W, H) {
const r = new NW.Renderer(stubCanvas);
r.setBoard(new TD.Board(mapId));
r.setRotation(rot);
r.resize(W, H, 1);
return r;
}
function randomCamera(r, rand) {
r.setZoom(1 + rand() * 3, rand() * r.W, rand() * r.H); // zoom about a random point ...
r.panBy((rand() - 0.5) * r.W * 1.5, (rand() - 0.5) * r.H * 1.5); // ... then pan (the camera clamps what is too far)
}
const DIRS = [[-1, 0], [1, 0], [0, -1], [0, 1]];
test('every cell round-trips through the screen, and a point anywhere inside a cell picks it (rotated or not, zoomed, panned)', () => {
const rand = rng(20261010);
let checked = 0;
for (const mapId of TD.MAP_ORDER) {
for (const rot of [false, true]) {
for (let run = 0; run < 6; run++) {
const W = 280 + Math.floor(rand() * 700), H = 200 + Math.floor(rand() * 700);
const r = makeRenderer(mapId, rot, W, H);
if (run) randomCamera(r, rand);
const cs = r.cellSizePx(), b = r.board;
for (let y = 0; y < b.rows; y++) for (let x = 0; x < b.cols; x++) {
const s = r.cellToScreen(x, y);
const c = r.screenToCell(s.x, s.y);
assert.deepEqual([c.x, c.y], [x, y], `${mapId} rot=${rot} ${W}x${H} zoom=${r.zoom.toFixed(2)}: cell ${x},${y} came back as ${c.x},${c.y}`);
for (let k = 0; k < 3; k++) {
const o = r.screenToCell(s.x + (rand() - 0.5) * 0.9 * cs, s.y + (rand() - 0.5) * 0.9 * cs);
assert.deepEqual([o.x, o.y], [x, y], `${mapId} rot=${rot}: a point inside cell ${x},${y} picked ${o.x},${o.y}`);
}
checked++;
}
}
}
}
assert.ok(checked > 3000);
});
test('zooming keeps the point under the finger fixed', () => {
const rand = rng(7);
let checked = 0;
for (const rot of [false, true]) {
for (let run = 0; run < 120; run++) {
const r = makeRenderer('open', rot, 300 + rand() * 500, 300 + rand() * 500);
randomCamera(r, rand);
const ax = rand() * r.W, ay = rand() * r.H, before = r._s2w(ax, ay);
r.setZoom(r.zoom * (0.6 + rand() * 1.6), ax, ay);
const after = r._s2w(ax, ay);
// The camera refuses to keep it exactly where it clamps the pan: a board smaller than the canvas is centred, and a big one may
// not be dragged more than 24 px past its edge. Only the free case is checked.
const d = r._dims(), sw = d.w * r.scale, sh = d.h * r.scale;
const free = sw > r.W && sh > r.H && Math.abs(r.cam.px) < (sw - r.W) / 2 + 23.9 && Math.abs(r.cam.py) < (sh - r.H) / 2 + 23.9;
if (!free) continue;
checked++;
assert.ok(Math.hypot(after.x - before.x, after.y - before.y) < 0.01, `rot=${rot}: the world point under (${ax.toFixed(1)},${ay.toFixed(1)}) moved by ${Math.hypot(after.x - before.x, after.y - before.y).toFixed(3)}`);
}
}
assert.ok(checked > 40, 'only ' + checked + ' unclamped runs');
});
test('stepCell moves exactly one cell in a SCREEN direction, also when the board is drawn turned 90 degrees', () => {
const rand = rng(99);
for (const rot of [false, true]) {
for (let run = 0; run < 10; run++) {
const r = makeRenderer('open', rot, 320 + rand() * 400, 320 + rand() * 400);
if (run % 2) randomCamera(r, rand);
const b = r.board, cs = r.cellSizePx();
for (let k = 0; k < 40; k++) {
const x = 1 + Math.floor(rand() * (b.cols - 2)), y = 1 + Math.floor(rand() * (b.rows - 2));
const s0 = r.cellToScreen(x, y);
for (const [dx, dy] of DIRS) {
const n = r.stepCell(x, y, dx, dy), s1 = r.cellToScreen(n.x, n.y);
assert.ok(Math.abs(s1.x - s0.x - dx * cs) < 1e-6 && Math.abs(s1.y - s0.y - dy * cs) < 1e-6, `rot=${rot}: step (${dx},${dy}) from ${x},${y} moved the cell by (${(s1.x - s0.x).toFixed(2)},${(s1.y - s0.y).toFixed(2)}) instead of (${dx * cs},${dy * cs})`);
}
}
}
}
});
test('at zoom 1 the whole board, with its margin, is inside the canvas (a tap on any edge cell is on screen)', () => {
const rand = rng(5);
for (const mapId of TD.MAP_ORDER) for (const rot of [false, true]) {
const W = 300 + Math.floor(rand() * 600), H = 300 + Math.floor(rand() * 600), r = makeRenderer(mapId, rot, W, H), b = r.board, h = r.cellSizePx() / 2;
for (const [x, y] of [[0, 0], [b.cols - 1, 0], [0, b.rows - 1], [b.cols - 1, b.rows - 1]]) {
const s = r.cellToScreen(x, y);
assert.ok(s.x - h >= -0.01 && s.y - h >= -0.01 && s.x + h <= W + 0.01 && s.y + h <= H + 0.01, `${mapId} rot=${rot} ${W}x${H}: corner cell ${x},${y} is cut off`);
}
}
});

View file

@ -1156,6 +1156,143 @@ test('per-IP socket cap uses X-Forwarded-For behind a private/loopback peer; 429
}); });
}); });
// ================================================================ proxy findings (docs/review-2026-10-09, proxy-*)
test('Origin check: a trusted proxy that drops the port from Host (nginx $host, nginx Proxy Manager) on a non-default public port', () => {
const req = (h, peer) => ({ headers: h, socket: { remoteAddress: peer || '10.0.0.2' } });
const o = { trustProxy: 'auto', allowedOrigins: [] };
// https://game.example.com:8443 -> proxy -> Host: game.example.com (no port), Origin keeps :8443
const stripped = { host: 'game.example.com', origin: 'https://game.example.com:8443' };
assert.equal(netx.originAllowed(req(stripped), o), true, 'private proxy peer');
assert.equal(netx.originAllowed(req(stripped, '::ffff:127.0.0.1'), o), true, 'loopback proxy peer');
assert.equal(netx.originAllowed(req({ host: 'game.example.com', origin: 'http://GAME.example.com:8080' }), o), true, 'http on 8080');
assert.equal(netx.originAllowed(req({ host: 'game.example.com', origin: 'https://game.example.com' }), o), true, 'default port still works');
// ...and must stay closed everywhere else
assert.equal(netx.originAllowed(req(stripped, '203.0.113.9'), o), false, 'public peer is not a proxy: Host must match exactly');
assert.equal(netx.originAllowed(req(stripped), { trustProxy: false, allowedOrigins: [] }), false, 'TRUST_PROXY=0');
assert.equal(netx.originAllowed(req(stripped, '203.0.113.9'), { trustProxy: true, allowedOrigins: [] }), true, 'TRUST_PROXY=1 believes any peer');
assert.equal(netx.originAllowed(req({ host: 'game.example.com', origin: 'https://evil.example.com:8443' }), o), false, 'another host name');
assert.equal(netx.originAllowed(req({ host: 'game.example.com', origin: 'https://game.example.com.evil.net:8443' }), o), false, 'name suffix trick');
assert.equal(netx.originAllowed(req({ host: 'game.example.com:8080', origin: 'https://game.example.com:8443' }), o), false,
'Host WITH a port (a direct connection, or a proxy that keeps it) must match exactly');
assert.equal(netx.originAllowed(req({ host: '127.0.0.1:8080', origin: 'http://127.0.0.1:9999' }, '127.0.0.1'), o), false, 'direct loopback, other port');
assert.equal(netx.originAllowed(req({ host: 'game.example.com' }), o), true, 'no Origin');
assert.equal(netx.originAllowed(req({ host: '[2001:db8::7]', origin: 'https://[2001:db8::7]:8443' }), o), true, 'IPv6 literal');
assert.equal(netx.originAllowed(req({ host: '[2001:db8::7]', origin: 'https://[2001:db8::8]:8443' }), o), false, 'other IPv6 literal');
assert.equal(netx.hostParts('Game.Example.com:8443').port, '8443');
assert.equal(netx.hostParts('https://game.example.com:443').port, '');
assert.equal(netx.hostParts('a b'), null);
});
test('Origin check over a real upgrade: Host without port + Origin with port is accepted from a trusted proxy peer only', async () => {
await withServer({}, async (S) => { // the test peer is loopback = a trusted proxy under auto
const ok = (host, origin) => probe(S.url, { headers: { Host: host }, origin });
assert.equal((await ok('highport.test', 'https://highport.test:8332')).ok, true);
assert.equal((await ok('highport.test', 'http://highport.test:8330')).ok, true);
assert.equal((await ok('highport.test', 'https://evil.test:8332')).status, 403);
assert.equal((await ok('highport.test:8330', 'https://highport.test:8332')).status, 403, 'Host has a port: exact match only');
});
await withServer({ trustProxy: false }, async (S) => {
assert.equal((await probe(S.url, { headers: { Host: 'highport.test' }, origin: 'https://highport.test:8332' })).status, 403);
});
});
test('TRUSTED_PROXIES: parseTrustedProxies accepts IPs and CIDRs (v4 + v6) and rejects typos', () => {
const t = netx.parseTrustedProxies(' 100.64.0.0/10, 2001:db8::6 ,2001:db8:1::/48,,192.0.2.1 ');
assert.deepEqual(t.list, ['100.64.0.0/10', '2001:db8::6', '2001:db8:1::/48', '192.0.2.1']);
for (const ip of ['100.64.1.1', '100.127.255.254', '::ffff:100.64.0.1', '2001:db8::6', '2001:DB8::6', '2001:db8:1:ffff::9', '192.0.2.1'])
assert.equal(t.has(ip), true, ip);
for (const ip of ['100.63.255.255', '100.128.0.1', '2001:db8::7', '2001:db8:2::1', '192.0.2.2', '8.8.8.8', 'junk', ''])
assert.equal(t.has(ip), false, ip);
assert.deepEqual(netx.parseTrustedProxies(['10.1.1.1', '2001:db8::/32']).list, ['10.1.1.1', '2001:db8::/32']);
for (const v of [undefined, null, '', ' , ', []]) assert.equal(netx.parseTrustedProxies(v), null);
for (const bad of ['nonsense', '100.64.0.0/33', '2001:db8::/129', '1.2.3.4/', '1.2.3.4/x', '1.2.3', '::ffff:10.0.0.0/104', '100.64.0.0/10, oops'])
assert.throws(() => netx.parseTrustedProxies(bad), /invalid TRUSTED_PROXIES entry/, bad);
});
test('TRUSTED_PROXIES: a proxy on a global IPv6 / CGNAT address is believed (isTrustedPeer, clientIp, Origin) once it is listed', async () => {
const req = (peer, h) => ({ headers: h || {}, socket: { remoteAddress: peer } });
const xff = { 'x-forwarded-for': '198.51.100.7' };
const t = netx.parseTrustedProxies('100.64.0.0/10,2001:db8::6');
// before: the built-in private list does not know these addresses, every player is "the proxy"
assert.equal(netx.clientIp(req('2001:db8::6', xff), 'auto'), '2001:db8::6');
assert.equal(netx.clientIp(req('100.64.1.1', xff), 'auto'), '100.64.1.1');
assert.equal(netx.isTrustedPeer(req('2001:db8::6'), 'auto'), false);
// after
assert.equal(netx.clientIp(req('2001:db8::6', xff), 'auto', t), '198.51.100.7');
assert.equal(netx.clientIp(req('::ffff:100.64.1.1', xff), 'auto', t), '198.51.100.7');
assert.equal(netx.isTrustedPeer(req('2001:db8::6'), 'auto', t), true);
assert.equal(netx.clientIp(req('2001:db8::7', xff), 'auto', t), '2001:db8::7', 'an unlisted neighbour is still not believed');
assert.equal(netx.clientIp(req('203.0.113.5', xff), 'auto', t), '203.0.113.5');
assert.equal(netx.clientIp(req('10.0.0.2', xff), 'auto', t), '198.51.100.7', 'the private ranges stay trusted: the list is an addition');
assert.equal(netx.clientIp(req('2001:db8::6', xff), false, t), '2001:db8::6', 'TRUST_PROXY=0 wins over the list');
assert.equal(netx.clientIp(req('2001:db8::6', xff), true), '198.51.100.7');
const o = { trustProxy: 'auto', allowedOrigins: [], trustedProxies: t };
const fwd = { host: 'x', origin: 'https://c.d', 'x-forwarded-host': 'c.d' };
assert.equal(netx.originAllowed(req('2001:db8::6', fwd), { trustProxy: 'auto', allowedOrigins: [] }), false);
assert.equal(netx.originAllowed(req('2001:db8::6', fwd), o), true, 'X-Forwarded-Host from a listed proxy');
assert.equal(netx.originAllowed(req('2001:db8::6', { host: 'game.example.com', origin: 'https://game.example.com:8443' }), o), true);
assert.equal(netx.originAllowed(req('2001:db8::7', { host: 'game.example.com', origin: 'https://game.example.com:8443' }), o), false);
// the server option: bad list stops the start, a good one is kept
await assert.rejects(createServer({ port: 0, host: '127.0.0.1', log: noop, trustedProxies: '100.64.0.0/40' }), /invalid TRUSTED_PROXIES entry/);
await withServer({ trustedProxies: '100.64.0.0/10, 2001:db8::6' }, async (S) => {
assert.deepEqual(S.srv.options.trustedProxies.list, ['100.64.0.0/10', '2001:db8::6']);
assert.equal((await probe(S.url, { headers: { 'X-Forwarded-For': '198.51.100.7' } })).ok, true);
});
});
// public/sw.js run in a vm with a fake Cache Storage, to see what a navigation gets while nginx answers 502 for a stopped app
function loadServiceWorker(net) {
const vm = require('vm');
const src = fs.readFileSync(path.join(__dirname, '..', 'public', 'sw.js'), 'utf8');
const BASE = 'https://game.test/';
const handlers = {}, store = new Map(), puts = [];
store.set(BASE, R(200, 'cached game')); store.set(BASE + 'index.html', R(200, 'cached shell'));
store.set(BASE + 'js/main.js', R(200, 'cached main.js'));
const caches = {
match: async (r) => store.get(typeof r === 'string' ? new URL(r, BASE + 'sw.js').href : r.url),
open: async () => ({ put: async (r, res) => { puts.push(r.url + ' ' + res.status); store.set(r.url, res); }, addAll: async () => {} }),
keys: async () => [], delete: async () => true,
};
const self = { location: new URL(BASE + 'sw.js'), skipWaiting() {}, clients: { claim() {} }, addEventListener: (t, f) => { handlers[t] = f; } };
vm.runInNewContext(src, { self, caches, fetch: net, URL, Response, Promise, Set, console });
return {
BASE, puts,
async get(url, mode) {
let out; const request = { method: 'GET', url, mode: mode || 'no-cors' };
handlers.fetch({ request, respondWith: (p) => { out = p; } });
const res = await out;
await new Promise((r) => setImmediate(r)); // the cache.put is fire-and-forget
return res;
},
};
}
function R(status, body) { return { status, body, ok: status >= 200 && status < 300, type: 'basic', clone() { return R(status, body); } }; }
test('service worker: 502/503/504 from the proxy fall back to the cache instead of showing nginx\'s error page', async () => {
for (const code of [502, 503, 504]) {
const sw = loadServiceWorker(async () => R(code, 'nginx error page'));
const B = sw.BASE;
assert.equal((await sw.get(B, 'navigate')).body, 'cached game', code + ': cached page, not the proxy error page');
assert.equal((await sw.get(B + '?room=ABCD', 'navigate')).body, 'cached shell', code + ': invite link -> cached app shell');
assert.equal((await sw.get(B + 'js/main.js')).body, 'cached main.js', code + ': cached script');
assert.equal((await sw.get(B + 'assets/music/battle.mp3')).status, code, code + ': never cached -> the real error, not index.html');
assert.deepEqual(sw.puts, [], code + ': an error response is never stored');
}
const down = loadServiceWorker(async () => { throw new TypeError('Failed to fetch'); });
assert.equal((await down.get(down.BASE, 'navigate')).body, 'cached game', 'network failure: cached page (unchanged behaviour)');
assert.equal((await down.get(down.BASE + '?room=ABCD', 'navigate')).body, 'cached shell');
assert.equal((await down.get(down.BASE + 'assets/music/battle.mp3')).type, 'error', 'a missing file is a network error, not index.html');
});
test('service worker: only complete 200 responses are cached (not a 206 range response, not a 404)', async () => {
const sw = loadServiceWorker(async (r) => R(r.url.endsWith('/range.mp3') ? 206 : r.url.endsWith('/missing.png') ? 404 : 200, 'fresh'));
const B = sw.BASE;
assert.equal((await sw.get(B + 'js/main.js')).body, 'fresh', 'healthy upstream: network first');
assert.equal((await sw.get(B + 'assets/range.mp3')).status, 206, 'a range response is passed through');
assert.equal((await sw.get(B + 'missing.png')).status, 404, 'a 404 is the upstream\'s answer');
assert.deepEqual(sw.puts, [B + 'js/main.js 200'], 'only the complete 200 is cached (not 206, not 404)');
});
// ================================================================ dual stack // ================================================================ dual stack
test('listenDual: IPv6 fallback logic (stub server)', async () => { test('listenDual: IPv6 fallback logic (stub server)', async () => {
const stub = (failWith) => { const stub = (failWith) => {

View file

@ -313,7 +313,7 @@ test('fuzz: garbage commands never throw', () => {
}); });
test('balance tables keep the shape the client and server rely on', () => { test('balance tables keep the shape the client and server rely on', () => {
assert.deepEqual(TD.TOWER_ORDER, ['wall', 'filter', 'ids', 'mortar', 'throttle', 'arc']); assert.deepEqual(TD.TOWER_ORDER, ['wall', 'filter', 'ids', 'mortar', 'throttle', 'arc', 'uplink']);
assert.deepEqual(TD.ENEMY_ORDER, ['ping', 'worm', 'trojan', 'spam', 'ghost', 'rootkit']); assert.deepEqual(TD.ENEMY_ORDER, ['ping', 'worm', 'trojan', 'spam', 'ghost', 'rootkit']);
assert.equal(TOWERS.wall.levels.length, 1); assert.equal(TOWERS.wall.levels.length, 1);
assert.ok(TOWERS.wall.refund, 'walls refund in full'); assert.ok(TOWERS.wall.refund, 'walls refund in full');
@ -321,13 +321,14 @@ test('balance tables keep the shape the client and server rely on', () => {
const t = TOWERS[k]; const t = TOWERS[k];
assert.ok(t.name && t.color && t.key && t.desc, k + ' has display fields'); assert.ok(t.name && t.color && t.key && t.desc, k + ' has display fields');
if (k === 'wall') continue; if (k === 'wall') continue;
assert.equal(t.levels.length, 3, k + ' has exactly 3 levels'); assert.equal(t.levels.length, k === 'uplink' ? 4 : 3, k + ' has the expected number of levels');
t.levels.forEach((lv, i) => { t.levels.forEach((lv, i) => {
assert.ok(lv.cost > 0 && lv.range > 0, k + ' L' + (i + 1) + ' cost/range'); assert.ok(lv.cost > 0 && lv.range > 0, k + ' L' + (i + 1) + ' cost/range');
if (k === 'throttle') assert.ok(lv.slow > 0 && lv.slow <= 0.6, 'slow is capped at 0.6 by the sim'); if (k === 'throttle') assert.ok(lv.slow > 0 && lv.slow <= 0.6, 'slow is capped at 0.6 by the sim');
else assert.ok(lv.dmg > 0 && lv.rate > 0, k + ' L' + (i + 1) + ' dmg/rate'); else assert.ok(lv.dmg > 0 && lv.rate > 0, k + ' L' + (i + 1) + ' dmg/rate');
if (k === 'mortar') assert.ok(lv.splash > 0); if (k === 'mortar') assert.ok(lv.splash > 0);
if (k === 'arc') assert.ok(lv.chains >= 1 && lv.chainRange > 0 && lv.falloff > 0 && lv.falloff < 1); if (k === 'arc') assert.ok(lv.chains >= 1 && lv.chainRange > 0 && lv.falloff > 0 && lv.falloff < 1);
if (k === 'uplink') assert.ok(lv.width > 0 && lv.splash > 0 && lv.slowOnHit > 0 && lv.slowOnHit <= 0.6 && lv.slowFor > 0);
if (i > 0) assert.ok(lv.range >= t.levels[i - 1].range, 'range never shrinks on upgrade'); if (i > 0) assert.ok(lv.range >= t.levels[i - 1].range, 'range never shrinks on upgrade');
}); });
} }
@ -347,3 +348,39 @@ test('balance tables keep the shape the client and server rely on', () => {
for (let n = 2; n <= 60; n++) assert.ok(TD.hpScale(n) > TD.hpScale(n - 1)); for (let n = 2; n <= 60; n++) assert.ok(TD.hpScale(n) > TD.hpScale(n - 1));
for (let n = 2; n <= 60; n++) assert.ok(TD.rewardScale(n) >= TD.rewardScale(n - 1)); for (let n = 2; n <= 60; n++) assert.ok(TD.rewardScale(n) >= TD.rewardScale(n - 1));
}); });
test('Orbital Uplink: expensive endgame beam that pierces, ignores armour, blasts, slows and hits flyers', () => {
const s = new Sim({ map: 'open', gold: 100000 });
const r = s.place('uplink', 5, 7);
assert.ok(r.ok);
const t = s.towerById(r.id), st = TOWERS.uplink.levels[0];
const idsTotal = TOWERS.ids.levels.reduce((a, l) => a + l.cost, 0);
const upTotal = TOWERS.uplink.levels.reduce((a, l) => a + l.cost, 0);
assert.ok(TOWERS.uplink.levels[0].cost >= 5 * TOWERS.ids.levels[0].cost, 'buying it costs several times an IDS Sniper');
assert.ok(upTotal >= 8 * idsTotal, 'a fully upgraded Uplink costs many times a fully upgraded IDS');
assert.ok(st.range > TOWERS.ids.levels[2].range, 'it out-ranges even a level 3 IDS');
assert.ok(st.dmg > TOWERS.ids.levels[2].dmg, 'and hits harder than a level 3 IDS from the start');
const mk = (id, x, y, extra) => Object.assign({ id, kind: 'trojan', air: false, x, y, cx: 0, cy: 0, tx: -1, ty: -1, hp: 5000, maxhp: 5000, armor: 50, speed: 1, slow: 0, slowT: 0, slowAmt: 0, rem: 10, dead: false }, extra);
// tower centre is (5.5, 7.5): three monsters on the horizontal line, one flyer on it, one far off the line, one beside the first target
const a = mk(201, 8.5, 7.5), b = mk(202, 11.5, 7.5), c = mk(203, 14.5, 7.5), air = mk(204, 12.5, 7.5, { air: true, kind: 'ghost' });
const off = mk(205, 9.5, 12.5), near = mk(206, 8.5, 8.6);
s.monsters = [a, b, c, air, off, near];
t.mode = 'close'; t.cd = 0;
s.updateTower(t, TD.STEP);
for (const o of [a, b, c, air]) assert.equal(o.hp, 5000 - st.dmg, 'on-line monster took full beam damage ignoring armour (armour 50)');
assert.equal(off.hp, 5000, 'a monster off the line is untouched');
assert.equal(near.hp, 5000 - st.dmg * 0.5, 'a monster beside the target takes half from the blast, also ignoring armour');
assert.ok(a.slowT > 0 && a.slowAmt > 0, 'hit monsters are slowed');
assert.equal(off.slowT, 0);
// slow lingers after the shot and then wears off
t.cd = 1e9; // stop it re-firing so we can watch the slow wear off
s.tick(TD.STEP); assert.ok(a.slow > 0, 'slow is applied on the next tick');
for (let i = 0; i < 60 * 3; i++) s.tick(TD.STEP);
assert.equal(a.slow, 0, 'slow wears off after a couple of seconds');
// upgrades to level 4 and refunds 70% of everything spent
assert.ok(s.upgrade(t.id).ok); assert.ok(s.upgrade(t.id).ok); assert.ok(s.upgrade(t.id).ok);
assert.equal(s.upgrade(t.id).reason, 'max');
assert.equal(t.level, 4);
const g = s.gold; s.sell(t.id);
assert.equal(s.gold, g + Math.floor(upTotal * TD.SELL_RATIO));
});