towerdef/README.md
Claude b4ae6cb57d Difficulty picker (Easy/Normal/Hard) and a balance pass
Difficulty:
- TD.DIFFICULTIES (starting credits, lives, enemy hp/shield, kill reward), validated
  create-room / newgame option, state carries it; solo menu picker and co-op lobby
  picker (44px segmented control, reachable on every layout), HUD/room/end-screen
  labels, best-wave record per map AND difficulty (Normal keeps the legacy key),
  Play again keeps the running game's difficulty for host and guest

Balance (12 bot runs, deterministic, 48/48 games replay identically in QA):
- Normal ~71% bot wins at wave 30 (was 94%), Easy 100%, Hard 25% on open
- credits tamed: reward growth 3% -> 2% per wave, clear bonus 10+2n -> 10+n, hp scaling
  eased, Rootkit pays 60 (was 100) but is tougher, flyers slower; unspent credits at
  wave 30: 1309 -> 335
- IDS Sniper is now a slow heavy hitter (essential, no longer sufficient: IDS-only
  dies by wave 7); Mortar, Arc and Filter buffed
- Orbital Uplink price step per owned unit 30% (buy and upgrade)
- remaining imbalances documented in docs/BALANCE.md

Tests: difficulty (19) and balance (8) unit suites, 14-difficulty e2e, layout matrix
reachability of the picker. 156 unit tests, 17 e2e scenarios.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
2026-10-10 23:41:21 +00:00

14 KiB

NETWALL

Build the firewall. Stretch the route. Protect the server.

An open-map, maze-building tower defence game for the browser, with two-player co-op. Hostile packets (pings, worms, trojans, spam, spoofed flyers and the odd rootkit boss) pour in from internet gateways and head for your server along the shortest open route. You can't walk them off the map, but you can make that route long: cheap Firewall walls, placed anywhere, force them on a detour past your turrets. You may never seal the route completely, so every wall is a decision.

  • Plays in any modern browser, desktop and mobile (portrait and landscape, touch, pinch-zoom).
  • Solo works straight from the files (no server needed).
  • Co-op online: two players, one shared map, one base and one pot of credits, building at the same time, with live partner cursors and map pings. Needs the small Node server in this repo.
  • No build step, no framework, no external requests. Vanilla JS + canvas.

Status: playable and playtested on desktop and phones. A review pass found more polish issues (mostly phone layout and touch precision) that are being worked through; see docs/NEXT.md.

Run it

# Debian / Ubuntu: sudo apt install nodejs npm
npm install            # one dependency: ws
npm start              # http://localhost:8080  (prints your LAN URLs too)

Open the printed URL on any device on your network. Pick a map and press Play solo, or Co-op online to create a 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 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, TRUSTED_PROXIES, ALLOWED_ORIGINS, MAX_CONN_PER_IP, GRACE_MS. Full reference and troubleshooting: docs/DEPLOY.md.

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 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.

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)

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):

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):

git clone ssh://forgejo@int.git.vanvikinternet.no/jvanvik/towerdef.git /opt/netwall

Then, in the LXC:

cd /opt/netwall && npm install --omit=dev          # only "ws"

useradd --system --home-dir /opt/netwall --shell /usr/sbin/nologin netwall
install -m 0644 deploy/netwall.service /etc/systemd/system/netwall.service
systemctl daemon-reload && systemctl enable --now netwall

curl http://127.0.0.1:8080/healthz                 # -> ok
curl -g 'http://[::1]:8080/healthz'                # -> ok (the server listens on IPv4 and IPv6 at once)
journalctl -u netwall -f                           # live log

The service listens on [::]:8080 (dual stack) and runs as the unprivileged netwall user. Change PORT, HOST, 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, 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

Hosts > Proxy Hosts > Add Proxy Host (labels as in NPM v2.16.0)

Tab / field Value
Details: Domain Names game.example.com (your name for it)
Details: Scheme http
Details: Forward Hostname / IP the LXC's IP address (192.168.1.50), not 127.0.0.1
Details: Forward Port 8080
Details: Cache Assets off
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
Advanced (the gear icon) nothing needed (NPM's default 90 s timeouts are fine: a joined game streams data all the time)

On the standard ports (80/443) that is all: NPM sends the public name as Host, which is what the server's WebSocket origin check expects. If you publish NPM on another port (for example https://game.example.com:8443): NPM drops the 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)

The server side is already dual stack. Publish an AAAA record for the game name after your proxy really answers on IPv6 (curl -6 -I https://game.example.com/); a published but broken AAAA breaks IPv6 visitors and certificate issuance. The proxy-to-LXC hop can stay IPv4.

4. Check it, play it

curl -i https://game.example.com/healthz           # 200 ok

Open https://game.example.com/ on two phones, press Co-op online, create a room on one and tap the invite link (or type the 4-letter code) on the other. On a phone, "Add to Home Screen" gives a full-screen app.

Lock the LXC down so that only the proxy can reach port 8080 (firewall example in docs/DEPLOY.md).

5. Update

If you cloned it: cd /opt/netwall && git pull && npm install --omit=dev && systemctl restart netwall. If you copied it 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).

Under a path prefix such as https://example.com/netwall/, the proxy must strip the prefix; see section 7 of 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

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.
Packet Filter Fast and cheap. Weak against armour.
IDS Sniper Long range, hits hard, slow. The answer to armour and bosses, but a poor answer to swarms of weak packets (use Filters, Mortars and Arcs for those).
Flood Mortar Splash damage on ground swarms. Cannot hit flyers.
Rate Limiter Slows everything in range. Rootkits resist it.
Router Arc Chain lightning between nearby packets.
Sandbox Control tower, no damage: pulses a stun on every packet in range (bosses are stunned half as long).
Load Balancer Support tower, no attack: nearby attack turrets fire 15 / 25 / 35% faster (the best balancer in range applies, they do not stack).
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. Extremely expensive: 1500 credits, upgrades 1200 / 2000 / 3200 (4 levels), and every Uplink you already own makes the next one 30% dearer, to buy and to upgrade (1500, 1950, 2540, 3300, ...), so kill rewards cannot buy a carpet of them.
Spoofed packets Fly straight over your maze: keep some anti-air. Botnet drones are fast flying swarms.
Daemons Healers: they restore nearby packets (up to 12% of max health per second), so kill them first.
Proxies Shielded packets: the shield soaks damage first and regrows after 3 s without being hit.
Credits From kills and cleared waves. Upgrade turrets (3 levels, 4 for the Uplink); selling returns 70% (walls 100%).
Difficulty Easy / Normal / Hard, picked in the menu (solo) or by the host when creating a co-op room, and shown next to the next-wave list and on the end screen. It scales the starting credits and integrity, the hit points of every packet and what a kill pays (the table is DIFFICULTIES in public/js/sim.js). Normal uses the base tables of the game with every multiplier at 1. Your best wave is kept per map and difficulty.

Controls, desktop: click to build, drag to paint walls, right-click cancels, 1-9 pick a tower, Space next wave, U upgrade, X sell, T change targeting, P pause, F speed, A auto-waves, M mute, wheel zoom, Alt+click pings.

Controls, touch: tap a tower type, tap the map to preview (the new route is drawn), nudge the preview with the arrow 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 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

The game has a built-in synth melody, and plays your own tracks if you add them. Drop files in public/assets/music/ and name them in public/assets/music/tracks.json:

{ "theme": "menu.mp3", "battle": "battle.mp3", "boss": "boss.mp3", "win": "win.mp3", "lose": "lose.mp3" }

Any entry left null keeps the synth version. See public/assets/music/README.md for prompt ideas for Suno.

How it works

public/              static client (also the web root)
  index.html, css/   layout: grid that reflows for desktop / landscape phone / portrait phone
  js/sim.js          the whole game rules: pure, deterministic, no DOM. Runs in the browser (solo) AND in Node (co-op)
  js/controllers.js  LocalController (runs sim in the tab) | RemoteController (WebSocket, snapshot interpolation, reconnect)
  js/render.js       canvas renderer: camera, zoom/pan, portrait rotation, effects
  js/main.js         screens, HUD, mouse + touch input, lobby
  js/audio.js        sfx + music
server/              Node: static files + authoritative co-op rooms over WebSocket
docs/PROTOCOL.md     wire protocol and server requirements
test/                node:test suites (sim rules, server)
tools/bot.js         headless bot used to balance the game

Pathing. Every placement is checked against a flow field (Dijkstra from the server, 8-way movement, no corner cutting so two diagonal walls really are a wall). A wall is refused if it would seal any gateway or trap any packet already on the board. The browser keeps a mirror of the maze so it can preview a placement and the resulting route instantly, even in co-op.

Co-op. The server owns the one true simulation per room and ticks it at a fixed 60 Hz. Clients send commands (place, sell, upgrade, ...); the server broadcasts compact 20 Hz snapshots, and clients render them slightly in the past, interpolating. Nothing is simulated twice, so nothing can drift. A dropped connection (phone locked, wifi switch) reconnects automatically and resumes the same seat for a minute.

Tests

npm test          # rules + server: placement validation, route sealing, corner cutting, targeting, waves, economy,
                  # 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,
                  # two-browser co-op incl. reconnect and chaos (stalls, half-open sockets, races), audio, keyboard / a11y, and a
                  # layout matrix (many phone, tablet, foldable and desktop sizes, thumb reach of every control)

npm run e2e drives Chromium through Playwright (a devDependency). Install the browser once with npx playwright-core install chromium-headless-shell (on a minimal Debian also npx playwright-core install-deps as root). It starts its own server on a random port and writes screenshots to e2e/out/.