commit 107ef60ec64eeaf14178992d862d2911b7aca0f5 Author: Claude Date: Fri Oct 9 19:14:35 2026 +0000 Add Netwall solo client, shared simulation core and protocol spec - public/js/sim.js: pure game rules shared by browser and server (flow-field pathing with no corner cutting, placement validation that can never seal the route, towers, enemies, waves, economy, snapshots) - Responsive canvas client: desktop, landscape and portrait phones (board rotates 90 degrees in portrait), mouse + touch input, pinch zoom/pan, tap-to-preview placement, route preview, effects, synth sfx + music - Local and Remote controllers behind one interface (remote: snapshot interpolation, auto-reconnect, seat resume) - docs/PROTOCOL.md: co-op wire protocol and server requirements - README, PWA manifest and icons, 20 sim unit tests Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea918a3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +node_modules/ +*.log +.DS_Store +.env +# local scratch +/tmp/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..c795684 --- /dev/null +++ b/README.md @@ -0,0 +1,98 @@ +# 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. + +## Run it + +```bash +# 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. + +Environment variables: `PORT` (8080), `HOST` (`::`, dual-stack IPv4 + IPv6), `TRUST_PROXY`, `ALLOWED_ORIGINS`, +`MAX_CONN_PER_IP`, `GRACE_MS`. Deployment in a Debian LXC behind nginx Proxy Manager (WebSockets, TLS, IPv6, systemd) +is in [docs/DEPLOY.md](docs/DEPLOY.md). + +## How to play + +| | | +|---|---| +| **Goal** | Survive 30 waves (then keep going in endless mode). 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. | +| **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. | +| **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%). | + +Controls, desktop: click to build, drag to paint walls, right-click cancels, `1`-`6` 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), tap the check mark (or the same cell +again) to build. Walls paint as you drag. Two fingers pan and zoom; long-press pings your partner. In portrait the board +turns 90 degrees so the cells stay big. + +## 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`: + +```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 + +```bash +npm test +``` + +Covers the rules (placement validation, route sealing, corner cutting, targeting, waves, economy) and the server +(protocol, rooms, reconnects, security checks, static files, dual stack). diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md new file mode 100644 index 0000000..6cad108 --- /dev/null +++ b/docs/PROTOCOL.md @@ -0,0 +1,153 @@ +# Netwall multiplayer protocol (v1) + +Two people play **the same map together**: one shared base, one shared credit pool, one shared set of lives. +The Node server runs the game (the same `public/js/sim.js` the browser uses for solo play) and is the +single source of truth. Clients send *commands*; the server steps the simulation and broadcasts *snapshots*. +Clients never simulate in multiplayer; they render (with interpolation) what the server says. + +Transport: one WebSocket per player at `ws(s):///ws`, JSON text frames, one object per frame, field `t` += message type. Client -> server frames are capped at **2048 bytes** (`maxPayload`). + +## Server + +`server/index.js` exports `createServer(opts)` and, when run directly (`node server/index.js`), starts it. + +``` +createServer({ port = 8080, host = '::', publicDir = /public, + graceMs = 60000, snapshotHz = 20, maxRooms = 50, + trustProxy = 'auto', allowedOrigins = [], maxConnPerIp = 40, pingMs = 25000, log = console.log }) + -> Promise<{ port, addresses: string[], close(): Promise, rooms: Map }> +``` +Env when run directly: `PORT` (8080), `HOST` (`::`), `TRUST_PROXY` (`auto`|`1`|`0`), `ALLOWED_ORIGINS` +(comma separated, e.g. `https://game.example.com`), `MAX_CONN_PER_IP`, `GRACE_MS`. +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::`). +Handles SIGINT/SIGTERM by closing sockets and exiting 0. + +### Dual stack +Default `host` is `::` and the listen call must pass `ipv6Only: false` so that one socket serves **IPv4 and +IPv6** (IPv4 arrives as `::ffff:a.b.c.d`; normalise it for logs). If binding `::` fails with `EAFNOSUPPORT`, +`EADDRNOTAVAIL` or similar (IPv6 disabled in the container), fall back to `0.0.0.0` and log that. Any explicit +`host` (e.g. `127.0.0.1` in tests, or `HOST=0.0.0.0`) is honoured as given. `addresses` lists what is bound. + +### 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 +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` + the server sends a WebSocket *protocol* ping to each socket and terminates sockets that did not pong since the + previous round (so a dead mobile client is noticed within ~2 rounds and goes into the grace period). +* **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 first address of + `X-Forwarded-For` (else `X-Real-IP`) as the client IP; 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. +* **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 + (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 + 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). +* `HEAD`/`GET /healthz` returns `200 ok` for proxy health checks. +* Do **not** trust `X-Forwarded-Proto` for anything security relevant. +* Disable `ws` per-message-deflate (default for the server) - snapshots are small and CPU is better spent elsewhere. + +### HTTP +* `GET|HEAD` of files under `public/` only. `/` -> `index.html`. Correct MIME (html, js, css, json, svg, + png, jpg, ico, woff2, mp3, ogg, wav, txt). `Cache-Control: no-cache`. +* Path traversal (`..`, `%2e%2e`, `%2f`, backslash, NUL, absolute paths, dotfiles) -> 400/404, never a file + outside `public/`. Other methods -> 405. +* `GET /healthz` -> `200 ok`. +* Headers on every response: `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer`, + `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 +* Only on path `/ws`. If the request has an `Origin` header, its host must equal the `Host` header, + 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). +* 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. + +## Handshake + +Client's first message: + +``` +{ t:'join', pid, name, room?, map? } +``` +* `pid` `^[A-Za-z0-9_-]{8,40}$` - random, generated by the client, kept in `sessionStorage` (stable across reloads). +* `name` any string; server trims, strips control chars, caps at 16 chars, default `"Player"`. +* `room` absent -> **create** a room. `map` must be a key of `TD.MAPS` (default `'open'`). + Server generates a 4 character code from `ABCDEFGHJKLMNPQRSTUVWXYZ23456789`, unique among rooms. +* `room` present (`^[A-Za-z0-9]{4}$`, case-insensitive -> upper-cased) -> **join**. + +Failure: `{ t:'error', code, msg }` then the server closes the socket (code 4000+). +Codes: `bad_request`, `no_room`, `full` (two *other* pids already hold the slots), `too_many_rooms`, `bad_map`. + +Success: reply to the joiner + +``` +{ t:'joined', room, resumed, you:{ pid, slot, host }, + players:[ { pid, slot, name, host, online } ], // everyone incl. you + state: , snap: , speed, paused } +``` +then broadcast `{ t:'players', players:[...] }` to all *other* players. + +* A player owns a **slot** (0 or 1), the lowest free one, kept until they leave for good. +* **Host** = creator; if the host leaves for good the other player becomes host. +* **Reconnect**: a `join` whose `pid` already holds a slot in that room re-binds to it (`resumed:true`); the old + socket, if still open, is closed with 4001. No `full` error for the pid that owns the slot. +* **Grace**: when a socket closes the player stays in the room with `online:false` for `graceMs`, then is removed + (and `players` re-broadcast). A player who sent `{t:'leave'}` is removed immediately. +* The simulation **only ticks while at least one player is online**. A room with no one left is deleted. + +## Client -> server (after joining) + +| message | meaning | +|---|---| +| `{t:'cmd', c:'place', type, x, y}` | build. Server calls `sim.cmd({...msg, by: slot})` (never trust a `by` from the client) | +| `{t:'cmd', c:'sell', id}` / `'upgrade'` `id` / `'target'` `id,mode` / `'wave'` / `'auto'` `v` / `'continue'` | other sim commands, same path | +| `{t:'ctl', c:'pause', v:bool}` / `{t:'ctl', c:'speed', v:1\|2\|3}` | room-level; reflected in `snap.pa` / `snap.sp` | +| `{t:'cursor', x, y}` | hover position in cell units (floats) or `x:null` to hide; clamp to board, round to 2 dp | +| `{t:'mark', x, y}` | map ping; at most 1 per 400 ms per player; server broadcasts `mark` (below) | +| `{t:'rtt', ts}` | latency probe; reply immediately with the same `ts` | +| `{t:'sync'}` | ask for a full state resend | +| `{t:'newgame', map}` | **host only**: replace the sim with a fresh `new Sim({map})`; resets pause/speed | +| `{t:'leave'}` | leave now | + +Command validation is the server's job: `t:'cmd'` must carry a string `c` in the whitelist above; unknown +`c`, non-object, etc. count as malformed. A command the sim refuses (`{ok:false, reason}`) gets +`{ t:'reject', c, reason, x?, y?, id? }` sent **to the sender only** (echo `x,y`/`id` when present). +Successful commands send nothing extra; the effect arrives via `snap`. +`newgame` from a non-host -> `reject` with `reason:'not_host'`; `newgame` with a bad map -> `reject` `bad_map`. + +## Server -> client + +``` +{ t:'snap', seq, ...sim.snapshot(), ev:[ ...sim.drainEvents() ], + cur:[ [slot, x, y], ... ], // other players' cursors (only those currently set), all players included + pa:0|1, sp:1|2|3, + tw?: sim.towerList() } // ONLY when sim.rev changed since the previous snap was sent to the room +{ t:'state', state:, snap:, speed, paused, newgame?:true } // reply to sync / newgame +{ t:'players', players:[...] } +{ t:'mark', slot, x, y } // to everyone in the room, including the sender +{ t:'rtt', ts } +{ t:'reject', c, reason, ... } +{ t:'error', code, msg } +``` +* `seq` increments by 1 per snapshot per room. +* Snapshots are sent every `1000/snapshotHz` ms **whether or not** the sim advanced (paused rooms still send, so + cursors keep moving) but only to online players, and only if at least one player is online. +* `ev` events are drained from the sim once per snapshot, so every client sees every event exactly once. +* Because WebSocket is reliable and ordered, `tw` deltas cannot be lost; `snap.rev` lets a client detect a + bug/desync (`rev` differs from the `rev` it last applied and no `tw` came along) and ask for `sync`. + +## Tick loop + +Fixed step `TD.STEP` (1/60 s) with an accumulator driven by `process.hrtime.bigint()`; real time elapsed is +multiplied by `speed` (1-3) and ignored while `paused`; clamp elapsed per iteration to 250 ms so a stalled event +loop does not fast-forward the game. Drive it with a `setInterval` of ~8 ms (or setTimeout chain) per room, or one +global loop for all rooms. Must keep working with several rooms at once. + +## Events (`ev`), produced by the sim + +`place`, `sell`, `up`, `shot`, `arc`, `boom`, `kill`, `leak`, `wave`, `clear`, `win`, `lose` (see `sim.js`). +Treat them as opaque JSON. diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..0a35fb2 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,39 @@ +{ + "name": "netwall", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "netwall", + "version": "1.0.0", + "dependencies": { + "ws": "^8.18.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/ws": { + "version": "8.22.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz", + "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..9c898b3 --- /dev/null +++ b/package.json @@ -0,0 +1,15 @@ +{ + "name": "netwall", + "version": "1.0.0", + "description": "Netwall: an open-map, maze-building tower defence game with two-player co-op", + "private": true, + "main": "server/index.js", + "scripts": { + "start": "node server/index.js", + "test": "node --test" + }, + "engines": { "node": ">=18" }, + "dependencies": { + "ws": "^8.18.0" + } +} diff --git a/public/assets/music/README.md b/public/assets/music/README.md new file mode 100644 index 0000000..be2bd3c --- /dev/null +++ b/public/assets/music/README.md @@ -0,0 +1,33 @@ +# Music + +Netwall plays a built-in synth melody. To use your own tracks (for example from Suno), put the files in this folder and +name them in `tracks.json`: + +```json +{ "theme": "menu.mp3", "battle": "battle.mp3", "boss": "boss.mp3", "win": "win.mp3", "lose": "lose.mp3" } +``` + +* `theme`: main menu. `battle`: in game (loops). `boss`: plays while a Rootkit boss is on the board (loops). +* `win` / `lose`: short one-shot stingers on the end screens. +* Formats: mp3, ogg, m4a or wav. Anything left `null` keeps the synth version. +* Loops are played with the browser's `loop` flag, so crop the track to a whole number of bars for a clean seam. +* Keep files small (a few MB) so phones start playing quickly. + +## Suno prompts + +Style: `instrumental, cyberpunk synthwave, dark ambient electronica, driving arpeggiated synth, pulsing sub bass, 110 bpm, A minor, tense but hypnotic, digital glitch percussion, retro sci-fi, seamless loop, no vocals` + +Exclude: `vocals, rap, acoustic guitar, orchestral, fade out, long intro, spoken word` + +Lyrics box: `[Instrumental]` + +| Track | Style tweak | +|---|---| +| theme | `slow 80 bpm, atmospheric pads, minimal, curious, wide reverb` | +| battle | the prompt above, plus `[Loop-friendly: steady energy, no big breakdown]` | +| boss | `140 bpm, aggressive, distorted bass, heavy industrial, urgent, pounding kick` | +| win | `short victory fanfare, 8 seconds` | +| lose | `short descending glitch, system failure, 6 seconds` | + +Words that fit the game: data stream, packet traffic, firewall, mainframe, server room, neon grid, circuit board, binary, +handshake, encrypted, modem blips, bitcrushed snares, FM bells, filtered saw lead, sidechained pads. diff --git a/public/assets/music/tracks.json b/public/assets/music/tracks.json new file mode 100644 index 0000000..0aca0d7 --- /dev/null +++ b/public/assets/music/tracks.json @@ -0,0 +1,8 @@ +{ + "_help": "Put your music files in this folder and name them here, for example \"battle\": \"my-song.mp3\". Leave a track as null to use the built-in synth melody.", + "theme": null, + "battle": null, + "boss": null, + "win": null, + "lose": null +} diff --git a/public/css/style.css b/public/css/style.css new file mode 100644 index 0000000..31a375c --- /dev/null +++ b/public/css/style.css @@ -0,0 +1,251 @@ +/* Netwall - styles. Dark "network operations" theme. Mobile-first: portrait phones, landscape phones, desktop. */ +:root { + --bg: #070b16; + --panel: #0c1322; + --panel2: #111b30; + --line: #1d2c4c; + --text: #d3e6ff; + --dim: #7f97bd; + --cyan: #4de3ff; + --amber: #ffd24d; + --red: #ff5c7a; + --green: #35e0a1; + --side-w: 320px; + --safe-t: env(safe-area-inset-top, 0px); + --safe-r: env(safe-area-inset-right, 0px); + --safe-b: env(safe-area-inset-bottom, 0px); + --safe-l: env(safe-area-inset-left, 0px); + --btn: 40px; + --aspect: 26 / 16; + --font: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + --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; } +html, body { + margin: 0; height: 100%; background: var(--bg); color: var(--text); font: 15px/1.35 var(--font); + overflow: hidden; overscroll-behavior: none; -webkit-text-size-adjust: 100%; + -webkit-user-select: none; user-select: none; -webkit-touch-callout: none; +} +input { -webkit-user-select: text; user-select: text; } +button { font: inherit; color: inherit; cursor: pointer; } +[hidden] { display: none !important; } +svg.ic { width: 1.25em; height: 1.25em; flex: none; } + +/* ---------------------------------------------------------------- layout */ +#app { + position: fixed; inset: 0; height: 100dvh; + display: grid; + grid-template-columns: minmax(0, 1fr) var(--side-w); + grid-template-rows: auto minmax(0, 1fr); + grid-template-areas: "top top" "stage side"; + padding: var(--safe-t) var(--safe-r) var(--safe-b) var(--safe-l); + background: + radial-gradient(1200px 600px at 20% -10%, #0f1f3d 0%, transparent 60%), + radial-gradient(900px 500px at 100% 110%, #1b1035 0%, transparent 55%), var(--bg); +} +#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; } +#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; } +#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 */ +@media (orientation: portrait), (max-width: 760px) { + #app { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto auto minmax(0, 1fr); grid-template-areas: "top" "stage" "side"; } + #stage { aspect-ratio: var(--aspect-p, 16 / 26); max-height: 58dvh; width: 100%; } + #side { border-left: 0; border-top: 1px solid var(--line); padding: 8px 10px calc(8px + var(--safe-b)); gap: 8px; } +} +/* landscape phones: short viewport, narrow side panel */ +@media (orientation: landscape) and (max-height: 520px) { + :root { --side-w: 236px; --btn: 40px; } + #topbar { padding: 3px 8px; gap: 4px 6px; flex-wrap: nowrap; } + #side { gap: 6px; padding: 6px; } +} +@media (orientation: landscape) and (min-width: 761px) and (max-width: 1000px) and (min-height: 521px) { :root { --side-w: 270px; } } + +/* ---------------------------------------------------------------- top bar */ +.stat { display: flex; align-items: center; gap: 6px; padding: 0 10px; height: var(--btn); background: var(--panel); border: 1px solid var(--line); border-radius: 10px; font-family: var(--mono); font-size: 16px; white-space: nowrap; } +.stat b { font-weight: 700; letter-spacing: .02em; } +.stat small { color: var(--dim); } +.stat .lbl { color: var(--dim); font-size: 11px; letter-spacing: .12em; } +#statLives { color: var(--red); } +#statGold { color: var(--amber); } +#statLives.low { animation: pulse 0.8s infinite; } +@keyframes pulse { 50% { background: #3a1020; } } +.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); } +.chip #netPing { color: var(--dim); } +.chip.bad #netPing { color: var(--red); } + +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:active { transform: translateY(1px); } +button:disabled { opacity: .4; cursor: default; } +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.toggle[aria-pressed="true"] { background: #0f3550; border-color: var(--cyan); color: var(--cyan); } +button.primary { background: linear-gradient(#1b7a96, #135872); border-color: #2fb4d6; color: #eaffff; font-weight: 600; } +button.primary:hover { background: linear-gradient(#2290b0, #176b8a); } +button.danger { color: var(--red); } +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:hover { color: var(--text); background: none; } +button.floating { position: absolute; right: 8px; bottom: 8px; background: rgba(12, 19, 34, .85); } +#btnWave.attn { animation: glow 1.4s infinite; } +@keyframes glow { 50% { box-shadow: 0 0 0 4px rgba(77, 227, 255, .25); } } + +@media (orientation: portrait), (max-width: 760px) { + #topbar { padding: 6px 8px; } + .stat { padding: 0 8px; font-size: 15px; } + #btnWave { flex: 1 1 auto; } + .spacer { flex: 0 0 0; } +} + +/* ---------------------------------------------------------------- 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.ok { color: var(--green); border-color: #1c6a55; } +.hint.bad { color: var(--red); border-color: #6a2336; } +.hint.info { color: var(--cyan); } +.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.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; } +.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; } +.toast.bad { border-color: #6a2336; color: #ffb3c1; } +.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; } } +.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; } +.confirm.top { bottom: auto; top: 52px; } +.confirm .primary.big { min-width: 120px; } +.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; } +.spinner { width: 22px; height: 22px; border: 3px solid var(--line); border-top-color: var(--cyan); border-radius: 50%; animation: spin .8s linear infinite; } +@keyframes spin { to { transform: rotate(360deg); } } + +/* ---------------------------------------------------------------- side panel */ +#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; } +.tbtn { position: relative; flex-direction: column; gap: 2px; padding: 6px 4px 5px; min-height: 66px; text-align: center; line-height: 1.15; } +.tbtn canvas { width: 34px; height: 34px; pointer-events: none; } +.tbtn .nm { font-size: 11.5px; color: var(--text); } +.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.sel { border-color: var(--cyan); background: #0f3550; box-shadow: inset 0 0 0 1px var(--cyan); } +.tbtn.poor .cost { color: var(--red); } +.tbtn.poor { opacity: .72; } +@media (pointer: coarse) { .tbtn .key { display: none; } } +@media (orientation: portrait), (max-width: 760px) { + #palette { position: sticky; top: -8px; z-index: 2; margin: -8px -10px 0; padding: 8px 10px 6px; background: rgba(8, 13, 26, .97); } + #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; } + .tbtn { flex: 0 0 76px; min-height: 72px; scroll-snap-align: start; } +} +@media (orientation: landscape) and (max-height: 520px) { + #palette { grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 4px; } + .tbtn { min-height: 58px; padding: 3px 2px; } + .tbtn canvas { width: 26px; height: 26px; } +} + +.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 10px; } +#info:empty { display: none; } +.info-head { display: flex; align-items: center; gap: 10px; margin-bottom: 6px; } +.info-head canvas { width: 38px; height: 38px; flex: none; } +.info-head .nm { font-weight: 700; } +.info-head .lv { color: var(--dim); font-size: 12px; font-family: var(--mono); } +.info .desc { color: var(--dim); font-size: 13px; margin: 2px 0 6px; } +.kv { display: grid; grid-template-columns: auto 1fr; gap: 2px 10px; font-family: var(--mono); font-size: 12.5px; margin-bottom: 8px; } +.kvp { display: contents; } +.kvp span:first-child { color: var(--dim); } +.kv .up { color: var(--green); } +.actions { display: flex; flex-wrap: wrap; gap: 6px; } +.actions button { flex: 1 1 auto; font-size: 14px; } +.actions .cost { font-family: var(--mono); color: var(--amber); } +.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; } + +#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 .e { display: inline-flex; align-items: center; gap: 4px; } +.wv .e i { width: 10px; height: 10px; border-radius: 3px; display: inline-block; } +.wv .tag { padding: 1px 6px; border-radius: 6px; font-size: 11px; border: 1px solid; } +.wv .tag.air { color: #e29bff; border-color: #5b3a73; } +.wv .tag.boss { color: var(--red); border-color: #6a2336; } +#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 .you { color: var(--dim); font-size: 12px; } +#players .actions { margin-top: 6px; } + +/* ---------------------------------------------------------------- overlays (menus) */ +.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 { 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); } +.card.wide { width: min(680px, 100%); } +.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 h3 { margin: 0 0 6px; font-size: 14px; letter-spacing: .08em; text-transform: uppercase; color: var(--dim); } +.logo { display: flex; align-items: center; gap: 14px; justify-content: center; } +.logo-mark { width: 44px; height: 44px; flex: none; background: url("../icons/icon.svg") center/contain no-repeat; filter: drop-shadow(0 0 10px rgba(77, 227, 255, .5)); } +.tag { text-align: center; color: var(--dim); margin: 6px 0 14px; } +.muted { color: var(--dim); } +.small { font-size: 13px; } +.row { display: flex; gap: 10px; justify-content: center; flex-wrap: wrap; margin-top: 12px; } +.row.small { margin-top: 6px; } +.row > .big { flex: 1 1 200px; } +.msg { min-height: 1.4em; text-align: center; color: var(--amber); margin: 8px 0 0; } +.msg.bad { color: var(--red); } +.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; } +.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 .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 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); } +.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; } } + +.field { display: block; margin: 12px 0; } +.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.code { text-align: center; letter-spacing: .5em; font-family: var(--mono); font-size: 22px; text-transform: uppercase; padding-left: .5em; margin-bottom: 8px; } +.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 button { margin-top: auto; } +@media (max-width: 480px) { .split { grid-template-columns: 1fr; } } + +.howto { padding-left: 18px; margin: 10px 0 0; display: grid; gap: 8px; } +.howto li { color: #bcd3f5; } +.howto b { color: var(--text); } +.kbd-only { display: inline; } .touch-only { display: none; } +@media (pointer: coarse) { .kbd-only { display: none; } .touch-only { display: inline; } } + +.stats { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px 14px; margin: 10px 0 4px; font-family: var(--mono); font-size: 14px; } +.stats div { display: flex; justify-content: space-between; padding: 4px 0; border-bottom: 1px solid var(--line); } +.stats span { color: var(--dim); } + +/* 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"] #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; } } + +/* compact info panel on stacked (portrait / narrow) layouts: must come after the base rules above */ +@media (orientation: portrait), (max-width: 760px) { + .kv { display: flex; flex-wrap: wrap; gap: 2px 14px; margin-bottom: 6px; } + .kvp { display: inline-flex; gap: 6px; } + .info .desc { font-size: 12.5px; margin: 0 0 4px; } + .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 */ +@media (orientation: portrait), (max-width: 760px) { + .chip { padding: 0 8px; font-size: 12.5px; } + .chip #netPing { display: none; } + #netChip { margin-left: auto; } + .spacer { display: none; } + #btnWave { flex: 1 1 130px; } +} diff --git a/public/icons/icon-192.png b/public/icons/icon-192.png new file mode 100644 index 0000000..b077faf Binary files /dev/null and b/public/icons/icon-192.png differ diff --git a/public/icons/icon-512.png b/public/icons/icon-512.png new file mode 100644 index 0000000..e336af1 Binary files /dev/null and b/public/icons/icon-512.png differ diff --git a/public/icons/icon-maskable-512.png b/public/icons/icon-maskable-512.png new file mode 100644 index 0000000..410b049 Binary files /dev/null and b/public/icons/icon-maskable-512.png differ diff --git a/public/icons/icon.svg b/public/icons/icon.svg new file mode 100644 index 0000000..4a14515 --- /dev/null +++ b/public/icons/icon.svg @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..95f6d7d --- /dev/null +++ b/public/index.html @@ -0,0 +1,163 @@ + + + + + + + + + + + +Netwall + + + + + + + + + + +
+ +
+ +
WAVE0
+
20
+
0
+ +
+ + + + + +
+ +
+ + + +
+ + + +
+ + + + + + + + + + + + + + + +
+ + + + + + + + diff --git a/public/js/audio.js b/public/js/audio.js new file mode 100644 index 0000000..bef0452 --- /dev/null +++ b/public/js/audio.js @@ -0,0 +1,318 @@ +/* + * NETWALL audio: synthesised sound effects + background music. + * + * Music: looks for assets/music/.mp3 (or .ogg) - tracks: theme (menu), battle, boss - plus one-shot + * stingers win / lose. Any track that is missing falls back to a small generative synth melody, so the game + * has music out of the box and a Suno-made file simply replaces it when you drop it in. + */ +(function (root) { + 'use strict'; + const NW = root.NW = root.NW || {}; + + const MUSIC_DIR = 'assets/music/'; + const STORE = 'nw.audio'; + + let ctx = null, master = null, sfxBus = null, musBus = null, delayNode = null; + let muted = false, musicVol = 0.55, sfxVol = 0.8; + let unlocked = false; + let wanted = null; // music track the game currently wants ('theme' | 'battle' | 'boss' | null) + let current = null; // { name, kind:'file'|'synth', el?, stop() } + const fileState = {}; // name -> 'unknown' | 'ok' | 'missing' + const lastPlay = {}; + const files = {}; // name -> HTMLAudioElement + + try { + const s = JSON.parse(localStorage.getItem(STORE) || '{}'); + if (typeof s.muted === 'boolean') muted = s.muted; + if (typeof s.music === 'number') musicVol = Math.min(1, Math.max(0, s.music)); + } catch (e) { /* storage unavailable */ } + function save() { try { localStorage.setItem(STORE, JSON.stringify({ muted, music: musicVol })); } catch (e) { /* ignore */ } } + + function ensureCtx() { + if (ctx) return ctx; + const AC = root.AudioContext || root.webkitAudioContext; + if (!AC) return null; + try { ctx = new AC(); } catch (e) { return null; } + master = ctx.createGain(); master.gain.value = muted ? 0 : 0.9; + master.connect(ctx.destination); + sfxBus = ctx.createGain(); sfxBus.gain.value = 0.32 * sfxVol; sfxBus.connect(master); + musBus = ctx.createGain(); musBus.gain.value = 0.3 * musicVol; musBus.connect(master); + return ctx; + } + + // ---------------------------------------------------------------- sfx + function tone(freq, dur, type, vol, slideTo, when) { + if (!ctx || muted) return; + const t0 = ctx.currentTime + (when || 0); + const o = ctx.createOscillator(), g = ctx.createGain(); + o.type = type || 'square'; + o.frequency.setValueAtTime(freq, t0); + if (slideTo) o.frequency.exponentialRampToValueAtTime(Math.max(20, slideTo), t0 + dur); + g.gain.setValueAtTime(0.0001, t0); + g.gain.exponentialRampToValueAtTime(vol, t0 + 0.008); + g.gain.exponentialRampToValueAtTime(0.0001, t0 + dur); + o.connect(g); g.connect(sfxBus); + o.start(t0); o.stop(t0 + dur + 0.02); + } + let noiseBuf = null; + function noiseBuffer() { + if (noiseBuf) return noiseBuf; + noiseBuf = ctx.createBuffer(1, ctx.sampleRate, ctx.sampleRate); + const d = noiseBuf.getChannelData(0); + for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1; + return noiseBuf; + } + function noise(dur, vol, filterType, f0, f1, when, bus) { + if (!ctx || muted) return; + const t0 = ctx.currentTime + (when || 0); + const s = ctx.createBufferSource(); s.buffer = noiseBuffer(); + const f = ctx.createBiquadFilter(); f.type = filterType || 'lowpass'; + f.frequency.setValueAtTime(f0, t0); + if (f1) f.frequency.exponentialRampToValueAtTime(f1, t0 + dur); + const g = ctx.createGain(); + g.gain.setValueAtTime(vol, t0); + g.gain.exponentialRampToValueAtTime(0.0001, t0 + dur); + s.connect(f); f.connect(g); g.connect(bus || sfxBus); + s.start(t0, Math.random() * 0.5); s.stop(t0 + dur + 0.02); + } + + const SFX = { + click: () => tone(660, 0.04, 'square', 0.12), + place: () => { tone(420, 0.07, 'square', 0.22, 700); noise(0.05, 0.12, 'highpass', 3000); }, + wall: () => tone(240, 0.05, 'square', 0.16, 330), + sell: () => tone(560, 0.12, 'triangle', 0.22, 220), + up: () => { tone(520, 0.08, 'square', 0.18); tone(780, 0.08, 'square', 0.18, 0, 0.07); tone(1040, 0.14, 'square', 0.18, 0, 0.14); }, + error: () => { tone(190, 0.1, 'square', 0.2); tone(150, 0.12, 'square', 0.2, 0, 0.09); }, + 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_mortar: () => tone(150, 0.18, 'sine', 0.45, 60), + 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), + kill: () => tone(820, 0.05, 'triangle', 0.1, 1200), + leak: () => { tone(320, 0.35, 'sawtooth', 0.3, 70); noise(0.25, 0.25, 'lowpass', 900, 100); }, + wave: () => { tone(220, 0.35, 'sawtooth', 0.14, 330); tone(330, 0.35, 'sawtooth', 0.12, 495, 0.05); tone(440, 0.45, 'sawtooth', 0.1, 660, 0.1); }, + boss: () => { tone(110, 0.8, 'sawtooth', 0.28, 55); tone(116, 0.8, 'sawtooth', 0.22, 58); noise(0.6, 0.2, 'lowpass', 600, 80); }, + clear: () => { tone(660, 0.09, 'triangle', 0.2); tone(880, 0.09, 'triangle', 0.2, 0, 0.09); tone(1320, 0.2, 'triangle', 0.2, 0, 0.18); }, + ping: () => { tone(1320, 0.18, 'sine', 0.25, 1760); tone(1760, 0.3, 'sine', 0.12, 0, 0.12); }, + 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 }; + + function sfx(name) { + if (muted || !unlocked || !ctx || !SFX[name]) return; + const now = ctx.currentTime, gap = MIN_GAP[name] || 0; + if (gap && lastPlay[name] && now - lastPlay[name] < gap) return; + lastPlay[name] = now; + SFX[name](); + } + + // ---------------------------------------------------------------- generative music (fallback) + const NOTE = (n) => 440 * Math.pow(2, (n - 69) / 12); // midi -> Hz + const PROGS = { + theme: { bpm: 76, chords: [[57, 60, 64], [53, 57, 60], [48, 52, 55], [55, 59, 62]], bass: [45, 41, 36, 43] }, + battle: { bpm: 112, chords: [[57, 60, 64], [53, 57, 60], [48, 52, 55], [55, 59, 62]], bass: [45, 41, 36, 43] }, + boss: { bpm: 138, chords: [[57, 60, 64], [57, 60, 64], [53, 57, 60], [52, 56, 59]], bass: [45, 45, 41, 40] }, + }; + const ARP = [0, 1, 2, 1, 2, 1, 2, 0, 1, 2, 1, 2, 1, 0, 2, 1]; // chord-tone index per 16th + + function startSynth(name) { + const p = PROGS[name] || PROGS.battle; + const out = ctx.createGain(); out.gain.value = 0.0001; out.connect(musBus); + out.gain.exponentialRampToValueAtTime(1, ctx.currentTime + 1.5); + const delay = ctx.createDelay(1.0); delay.delayTime.value = 60 / p.bpm * 0.75; + const fb = ctx.createGain(); fb.gain.value = 0.38; delay.connect(fb); fb.connect(delay); + const wet = ctx.createGain(); wet.gain.value = 0.5; delay.connect(wet); wet.connect(out); + const sixteenth = 60 / p.bpm / 4; + let step = 0, next = ctx.currentTime + 0.1, timer = 0, dead = false; + + function note(type, freq, t, dur, vol, cutoff, dest) { + const o = ctx.createOscillator(), f = ctx.createBiquadFilter(), g = ctx.createGain(); + o.type = type; o.frequency.value = freq; + f.type = 'lowpass'; f.frequency.value = cutoff; f.Q.value = 2; + g.gain.setValueAtTime(0.0001, t); + g.gain.exponentialRampToValueAtTime(vol, t + Math.min(0.02, dur / 3)); + g.gain.exponentialRampToValueAtTime(0.0001, t + dur); + o.connect(f); f.connect(g); g.connect(dest || out); + o.start(t); o.stop(t + dur + 0.05); + } + function pad(chord, t, dur) { + for (const n of chord) { + for (const det of [-7, 7]) { + const o = ctx.createOscillator(), f = ctx.createBiquadFilter(), g = ctx.createGain(); + o.type = 'sawtooth'; o.frequency.value = NOTE(n + 12); o.detune.value = det; + f.type = 'lowpass'; f.frequency.setValueAtTime(500, t); f.frequency.linearRampToValueAtTime(1400, t + dur * 0.5); f.frequency.linearRampToValueAtTime(600, t + dur); + g.gain.setValueAtTime(0.0001, t); + g.gain.linearRampToValueAtTime(0.05, t + dur * 0.3); + g.gain.linearRampToValueAtTime(0.0001, t + dur); + o.connect(f); f.connect(g); g.connect(out); + o.start(t); o.stop(t + dur + 0.05); + } + } + } + function kick(t) { + const o = ctx.createOscillator(), g = ctx.createGain(); + o.type = 'sine'; o.frequency.setValueAtTime(140, t); o.frequency.exponentialRampToValueAtTime(42, t + 0.12); + g.gain.setValueAtTime(0.9, t); g.gain.exponentialRampToValueAtTime(0.0001, t + 0.22); + o.connect(g); g.connect(out); o.start(t); o.stop(t + 0.25); + } + + function schedule() { + if (dead) return; + while (next < ctx.currentTime + 0.25) { + const bar = Math.floor(step / 16) % p.chords.length, s = step % 16; + const chord = p.chords[bar], t = next; + if (s === 0) pad(chord, t, sixteenth * 16 * 1.02); + if (name !== 'theme' || s % 4 === 0) { + // arpeggio, quieter and sparser for the menu theme + const idx = ARP[s], n = chord[idx % 3] + 12 * (idx === 2 ? 1 : 0) + 12; + const pat = name === 'theme' ? (s % 8 === 0) : (name === 'boss' ? true : (s % 2 === 0 || s % 16 === 15)); + if (pat) note('square', NOTE(n), t, sixteenth * 1.6, name === 'theme' ? 0.05 : 0.06, 2600, delay); + if (pat) note('square', NOTE(n), t, sixteenth * 1.6, 0.03, 2600); + } + if (name !== 'theme') { + if (s % 2 === 0) note('sawtooth', NOTE(p.bass[bar] + (s % 8 === 6 ? 12 : 0)), t, sixteenth * 1.7, 0.16, 420); + if (s % 4 === 0) kick(t); + if (s % 4 === 2) noise(0.05, 0.12, 'highpass', 7000, 0, t - ctx.currentTime, out); + if (name === 'boss' && s % 8 === 4) noise(0.12, 0.2, 'bandpass', 1800, 900, t - ctx.currentTime, out); + } else if (s === 0) { + note('sine', NOTE(p.bass[bar]), t, sixteenth * 14, 0.22, 300); + } + step++; next += sixteenth; + } + } + timer = setInterval(schedule, 40); + schedule(); + return { + name, kind: 'synth', + stop(fade) { + dead = true; clearInterval(timer); + const t = ctx.currentTime; + out.gain.cancelScheduledValues(t); + out.gain.setValueAtTime(Math.max(0.0001, out.gain.value), t); + out.gain.exponentialRampToValueAtTime(0.0001, t + (fade || 0.8)); + setTimeout(() => { try { out.disconnect(); } catch (e) { /* ignore */ } }, ((fade || 0.8) + 0.2) * 1000); + }, + }; + } + + // ---------------------------------------------------------------- file music + // assets/music/tracks.json maps track names to file names, e.g. {"battle": "my-song.mp3"}; null = use the synth. + // Reading one small manifest (instead of probing for files) keeps the console free of 404s. + let manifestP = null; + function manifest() { + if (!manifestP) { + manifestP = (typeof fetch === 'function' && root.location && /^https?:/.test(root.location.protocol)) + ? fetch(MUSIC_DIR + 'tracks.json', { cache: 'no-cache' }).then((r) => (r.ok ? r.json() : {})).catch(() => ({})) + : Promise.resolve({}); + } + return manifestP; + } + function fileFor(name, cb) { + if (fileState[name] === 'missing') { cb(null); return; } + if (files[name]) { cb(files[name]); return; } + manifest().then((m) => { + const f = m && typeof m[name] === 'string' && /^[\w .()-]+\.(mp3|ogg|m4a|wav)$/i.test(m[name]) ? m[name] : null; + if (!f) { fileState[name] = 'missing'; cb(null); return; } + const el = new Audio(); + el.preload = 'auto'; + el.loop = name !== 'win' && name !== 'lose'; + el.addEventListener('canplay', () => { fileState[name] = 'ok'; files[name] = el; cb(el); }, { once: true }); + el.addEventListener('error', () => { fileState[name] = 'missing'; cb(null); }, { once: true }); + el.src = MUSIC_DIR + encodeURIComponent(f).replace(/%2F/g, '/'); + el.load(); + }); + } + + function fadeEl(el, to, ms, done) { + const from = el.volume, t0 = performance.now(); + const step = () => { + const k = Math.min(1, (performance.now() - t0) / ms); + try { el.volume = Math.max(0, Math.min(1, from + (to - from) * k)); } catch (e) { /* ignore */ } + if (k < 1) requestAnimationFrame(step); else if (done) done(); + }; + step(); + } + + function stopCurrent(fade) { + const c = current; current = null; + if (!c || c.kind === 'pending') return; + if (c.kind === 'synth') c.stop(fade); + else fadeEl(c.el, 0, (fade || 0.8) * 1000, () => { try { c.el.pause(); } catch (e) { /* ignore */ } }); + } + + function applyMusic() { + if (!unlocked) return; + if (!wanted || muted) { stopCurrent(0.4); return; } + if (current && current.name === wanted) return; + const name = wanted; + stopCurrent(0.9); + // placeholder so that rapid calls do not stack + const token = current = { name, kind: 'pending', stop() {} }; + fileFor(name, (el) => { + if (current !== token) return; // superseded while loading + if (el) { + el.currentTime = 0; el.volume = 0; + const pr = el.play(); + if (pr && pr.catch) pr.catch(() => { /* blocked: will retry on next gesture */ current = null; }); + current = { name, kind: 'file', el, stop() {} }; + fadeEl(el, 0.8 * musicVol, 1200); + } else { + const c = ensureCtx(); + current = c ? startSynth(name) : null; + if (current) current.name = name; + } + }); + } + + function stinger(name) { + if (muted || !unlocked) return; + fileFor(name, (el) => { + if (el) { try { el.currentTime = 0; el.volume = Math.min(1, 0.9 * Math.max(0.3, musicVol)); el.play().catch(() => {}); } catch (e) { /* ignore */ } return; } + if (name === 'win') { [0, 4, 7, 12, 16, 19, 24].forEach((n, i) => tone(NOTE(69 + n), 0.3, 'triangle', 0.22, 0, i * 0.11)); } + else { [0, -3, -7, -12, -17].forEach((n, i) => tone(NOTE(60 + n), 0.5, 'sawtooth', 0.2, NOTE(58 + n), i * 0.22)); } + }); + } + + // ---------------------------------------------------------------- public + function unlock() { + if (unlocked) return; + const c = ensureCtx(); + if (c && c.state === 'suspended') c.resume(); + unlocked = true; + applyMusic(); + } + + root.addEventListener('pointerdown', unlock, { passive: true }); + root.addEventListener('keydown', unlock, { passive: true }); + document.addEventListener('visibilitychange', () => { + if (!ctx) return; + if (document.hidden) { + ctx.suspend && ctx.suspend(); + if (current && current.kind === 'file') current.el.pause(); + } else { + ctx.resume && ctx.resume(); + if (current && current.kind === 'file' && !muted) current.el.play().catch(() => {}); + } + }); + + NW.Audio = { + sfx, + unlock, + stinger, + get muted() { return muted; }, + setMuted(m) { + muted = !!m; save(); + if (master) master.gain.value = muted ? 0 : 0.9; + if (muted) stopCurrent(0.2); else applyMusic(); + }, + toggleMuted() { this.setMuted(!muted); return muted; }, + // Which music the game wants right now: 'theme' | 'battle' | 'boss' | null + music(name) { wanted = name; applyMusic(); }, + get musicVolume() { return musicVol; }, + setMusicVolume(v) { + musicVol = Math.min(1, Math.max(0, v)); save(); + if (musBus) musBus.gain.value = 0.3 * musicVol; + if (current && current.kind === 'file') current.el.volume = 0.8 * musicVol; + }, + }; +})(typeof self !== 'undefined' ? self : this); diff --git a/public/js/controllers.js b/public/js/controllers.js new file mode 100644 index 0000000..e64dd11 --- /dev/null +++ b/public/js/controllers.js @@ -0,0 +1,353 @@ +/* + * NETWALL controllers. The UI and renderer talk to a "controller" and do not care whether the game runs + * in this tab (LocalController, solo, works from file://) or on the server (RemoteController, co-op). + * + * ctrl.kind 'local' | 'remote' + * ctrl.board TD.Board (own for local, a mirror for remote: used for route previews) + * ctrl.view render state, refreshed by ctrl.update(nowMs): + * gold lives maxLives wave state auto nextWaveIn kills winWave rev queued speed paused + * towers[{id,type,x,y,level,mode,spent,owner,tgt,kills}] + * monsters[{id,kind,x,y,hp,maxhp,slow,air}] bullets[{id,k,x,y}] cursors[{slot,x,y}] + * ctrl.send(cmd) place / sell / upgrade / target / wave / auto / continue + * ctrl.ctl(c, v) 'pause' | 'speed' + * ctrl.preview(x,y,routes) would a block there be legal, and what does it do to the route? + * events ctrl.on('events', list) | 'reject' | 'mark' | 'players' | 'status' | 'joined' | 'newgame' | 'fatal' | 'rtt' + */ +(function (root) { + 'use strict'; + const NW = root.NW = root.NW || {}; + const TD = root.TD; + const clamp = (v, a, b) => Math.min(b, Math.max(a, v)); + + class Emitter { + constructor() { this._h = {}; } + on(ev, fn) { (this._h[ev] = this._h[ev] || []).push(fn); return this; } + emit(ev, a, b) { + const l = this._h[ev]; + if (!l) return; + for (const fn of l.slice()) { try { fn(a, b); } catch (e) { console.error(e); } } + } + } + + // ws(s):///ws, relative to the page so it also works under a proxy path prefix + function wsUrl() { + const u = new URL('ws', root.location.href); + u.protocol = u.protocol === 'https:' ? 'wss:' : 'ws:'; + u.search = ''; u.hash = ''; + return u.toString(); + } + + // ================================================================= local (solo) + class LocalController extends Emitter { + constructor(opts) { + super(); + this.kind = 'local'; + this.mapId = (opts && opts.map) || 'open'; + this.speed = 1; this.paused = false; + this.players = [{ slot: 0, name: 'You', online: true, host: true }]; + this.you = { slot: 0, host: true }; + this._fresh(); + } + _fresh() { + this.sim = new TD.Sim({ map: this.mapId }); + this.board = this.sim.board; + this.acc = 0; this.last = 0; + this.view = { + gold: 0, lives: 0, maxLives: 0, wave: 0, state: 'playing', auto: false, nextWaveIn: -1, kills: 0, winWave: 0, rev: 0, queued: 0, + speed: this.speed, paused: this.paused, time: 0, + towers: this.sim.towers, monsters: this.sim.monsters, bullets: this.sim.bullets, cursors: [], + }; + this._sync(); + } + _sync() { + const s = this.sim, v = this.view; + v.gold = s.gold; v.lives = s.lives; v.maxLives = s.maxLives; v.wave = s.wave; v.state = s.state; + v.auto = s.autoWaves; v.nextWaveIn = s.autoWaves ? s.nextWaveIn : -1; v.kills = s.kills; + v.winWave = isFinite(s.winWave) ? s.winWave : 0; v.rev = s.rev; v.queued = s.spawnQ.length; + v.speed = this.speed; v.paused = this.paused; v.time = s.time; + v.towers = s.towers; v.monsters = s.monsters; v.bullets = s.bullets; + } + update(now) { + if (!this.last) this.last = now; + const dt = Math.min(0.25, Math.max(0, (now - this.last) / 1000)); + this.last = now; + if (!this.paused) { + this.acc = Math.min(0.6, this.acc + dt * this.speed); + while (this.acc >= TD.STEP) { this.sim.tick(TD.STEP); this.acc -= TD.STEP; } + } + const ev = this.sim.drainEvents(); + this._sync(); + if (ev.length) this.emit('events', ev); + } + send(cmd) { + const res = this.sim.cmd(Object.assign({}, cmd, { by: 0 })); + if (!res.ok) this.emit('reject', { c: cmd.c, reason: res.reason, x: cmd.x, y: cmd.y, id: cmd.id }); + return res; + } + ctl(c, v) { + if (c === 'pause') this.paused = !!v; + else if (c === 'speed') this.speed = clamp(v | 0, 1, 3); + this._sync(); + } + preview(x, y, routes) { return this.sim.preview(x, y, routes); } + newGame(map) { if (map) this.mapId = map; this._fresh(); this.emit('newgame'); } + sendCursor() {} + sendMark(x, y) { this.emit('mark', { slot: 0, x, y }); } + requestSync() {} + close() {} + } + + // ================================================================= remote (co-op) + class RemoteController extends Emitter { + constructor(opts) { + super(); + this.kind = 'remote'; + this.url = opts.url || wsUrl(); + this.pid = opts.pid; this.name = opts.name || 'Player'; + this.room = opts.room || null; // null => create a room on first connect + this.mapId = opts.map || 'open'; + this.status = 'idle'; // idle | connecting | joined | reconnecting | closed + this.ws = null; this.players = []; this.you = null; this.board = null; + this.buf = []; this.delay = 120; + this.rev = -1; this.recvRev = -1; this.towers = []; + this.monCache = new Map(); this.bulCache = new Map(); this._gen = 0; + this.rtt = 0; + this.retry = 0; this.intentional = false; this.fatal = false; + this.lastMsg = 0; this.lastSync = 0; this.lastCursor = 0; + this.speed = 1; this.paused = false; + this.view = { + gold: 0, lives: 0, maxLives: 0, wave: 0, state: 'playing', auto: false, nextWaveIn: -1, kills: 0, winWave: 0, rev: 0, queued: 0, + speed: 1, paused: false, time: 0, towers: [], monsters: [], bullets: [], cursors: [], + }; + this._onVis = () => { if (!document.hidden) this._wake(); }; + document.addEventListener('visibilitychange', this._onVis); + root.addEventListener('online', this._onVis); + this._timers = []; + } + + connect() { + if (this.intentional || this.fatal) return; + if (this.ws && (this.ws.readyState === 0 || this.ws.readyState === 1)) return; + this._setStatus(this.status === 'joined' || this.status === 'reconnecting' ? 'reconnecting' : 'connecting'); + let ws; + try { ws = new WebSocket(this.url); } catch (e) { this._failed(); return; } + this.ws = ws; + ws.onopen = () => { + const j = { t: 'join', pid: this.pid, name: this.name }; + if (this.room) j.room = this.room; else j.map = this.mapId; + this._send(j); + }; + ws.onmessage = (e) => { this.lastMsg = performance.now(); this._onMsg(e.data); }; + ws.onclose = (e) => { if (this.ws === ws) this._onClose(e); }; + ws.onerror = () => { /* onclose follows */ }; + } + + _setStatus(s) { if (this.status !== s) { this.status = s; this.emit('status', s); } } + + _failed() { + if (this.status === 'connecting') { this._die('connect', 'Could not reach the game server.'); return; } + this.retry++; + if (this.retry > 14) { this._die('lost', 'Lost connection to the server.'); return; } + this._setStatus('reconnecting'); + const wait = Math.min(5000, 350 * Math.pow(1.7, this.retry - 1)); + const id = setTimeout(() => this.connect(), wait); + this._timers.push(id); + } + _die(code, msg) { + this.fatal = true; this._setStatus('closed'); + this._stopTimers(); + this.emit('fatal', { code, msg }); + } + _onClose(e) { + this.ws = null; + this._stopRtt(); + if (this.intentional || this.fatal) { this._setStatus('closed'); return; } + if (e && e.code === 4001) { this._die('replaced', 'This game was opened in another tab or device.'); return; } + this._failed(); + } + _wake() { + // back from sleep / background / network switch: a socket that looks open may be dead, so reconnect quickly + if (this.intentional || this.fatal || this.status === 'connecting') return; + const stale = performance.now() - this.lastMsg > 2500; + if (!this.ws || this.ws.readyState > 1) { this.retry = 0; this.connect(); } + else if (this.status === 'joined' && stale) { try { this.ws.close(); } catch (e) { /* ignore */ } } + } + _stopTimers() { for (const t of this._timers) clearTimeout(t); this._timers.length = 0; this._stopRtt(); } + _stopRtt() { if (this._rttT) { clearInterval(this._rttT); this._rttT = 0; } if (this._wdT) { clearInterval(this._wdT); this._wdT = 0; } } + _startRtt() { + this._stopRtt(); + this._rttT = setInterval(() => this._send({ t: 'rtt', ts: performance.now() }), 2000); + this._wdT = setInterval(() => { // snapshots flow at 20 Hz even when paused: silence means a dead socket + if (this.status === 'joined' && this.ws && performance.now() - this.lastMsg > 5000) { try { this.ws.close(); } catch (e) { /* ignore */ } } + }, 1000); + } + _send(o) { if (this.ws && this.ws.readyState === 1) this.ws.send(JSON.stringify(o)); } + + _onMsg(raw) { + let m; + try { m = JSON.parse(raw); } catch (e) { return; } + if (!m || typeof m.t !== 'string') return; + switch (m.t) { + case 'snap': this._onSnap(m); break; + case 'joined': + this.room = m.room; this.you = m.you; this.players = m.players || []; + this.retry = 0; this.speed = m.speed || 1; this.paused = !!m.paused; + this._applyState(m.state, m.snap); + this._setStatus('joined'); + this._startRtt(); + this.emit('joined', m); + this.emit('players', this.players); + break; + case 'state': + this.speed = m.speed || 1; this.paused = !!m.paused; + this._applyState(m.state, m.snap); + if (m.newgame) this.emit('newgame'); + break; + case 'players': + this.players = m.players || []; + { const me = this.players.find((p) => this.you && p.pid === this.you.pid); if (me) this.you = Object.assign({}, this.you, { host: me.host, slot: me.slot }); } + this.emit('players', this.players); + break; + case 'reject': this.emit('reject', m); break; + case 'mark': this.emit('mark', m); break; + case 'rtt': + { const s = performance.now() - m.ts; this.rtt = this.rtt ? Math.round(this.rtt * 0.7 + s * 0.3) : Math.round(s); this.emit('rtt', this.rtt); } + break; + case 'error': { + const msgs = { no_room: 'That room does not exist (any more).', full: 'That room already has two players.', bad_request: 'The server did not understand the request.', too_many_rooms: 'The server is full right now. Try again in a minute.', bad_map: 'Unknown map.' }; + this._die(m.code || 'error', msgs[m.code] || m.msg || 'Server error.'); + break; + } + default: break; + } + } + + _setTowers(list) { + const b = this.board; + b.solid.set(b.obst); + this.towers = list.map((a) => { + b.setSolid(a[2], a[3], 1); + return { id: a[0], type: a[1], x: a[2], y: a[3], level: a[4], mode: a[5], spent: a[6], owner: a[7], tgt: 0, kills: 0 }; + }); + b.recompute(); + } + _applyState(state, snap) { + if (!this.board || this.board.mapId !== state.map) { this.board = new TD.Board(state.map); this.mapId = state.map; } + this._setTowers(state.towers); + this.rev = this.recvRev = state.rev; + this.maxLives = state.maxLives; this.winWave = state.winWave; + this.buf.length = 0; this.monCache.clear(); this.bulCache.clear(); + if (snap) this._push(snap, true); + } + _push(snap, first) { + const mo = new Map(), bu = new Map(), tt = new Map(); + for (const a of snap.mo || []) mo.set(a[0], a); + for (const a of snap.bu || []) bu.set(a[0], a); + for (const a of snap.tt || []) tt.set(a[0], a); + const e = { t: performance.now(), snap, mo, bu, tt, rel: !!first }; + this.buf.push(e); + if (this.buf.length > 10) this.buf.shift(); + } + // Towers ride along with the snapshot that changed them and are applied when that snapshot is *displayed* + // (see update), so a new tower and the credits it cost appear on screen together. + _onSnap(m) { + if (m.tw) this.recvRev = m.rev; + else if (m.rev !== this.recvRev) this.requestSync(); + this._push(m, false); + } + requestSync() { + const now = performance.now(); + if (now - this.lastSync < 1000) return; + this.lastSync = now; + this._send({ t: 'sync' }); + } + + update(now) { + const buf = this.buf; + if (!buf.length || !this.board) return; + const rt = now - this.delay; + for (const e of buf) { + if (!e.rel && e.t <= rt) { e.rel = true; if (e.snap.ev && e.snap.ev.length) this.emit('events', e.snap.ev); } + } + let i = buf.length - 1; + while (i > 0 && buf[i].t > rt) i--; + const a = buf[i], b = buf[Math.min(i + 1, buf.length - 1)]; + const alpha = a === b ? 1 : clamp((rt - a.t) / (b.t - a.t), 0, 1); + let lastTw = null; + for (let k = 0; k <= i; k++) { if (buf[k].snap.tw && !buf[k].twDone) { lastTw = buf[k]; } buf[k].twDone = true; } + if (lastTw) { this._setTowers(lastTw.snap.tw); this.rev = lastTw.snap.rev; } + const s = a.snap, v = this.view; + v.gold = s.g; v.lives = s.l; v.wave = s.w; v.state = s.s; v.auto = !!s.au; v.nextWaveIn = s.nw; v.kills = s.k; + v.rev = s.rev; v.queued = s.q || 0; v.time = s.time; + v.maxLives = this.maxLives; v.winWave = this.winWave; + v.speed = s.sp || 1; v.paused = !!s.pa; + + const gen = ++this._gen; + const kinds = TD.ENEMY_ORDER; + const mons = v.monsters; mons.length = 0; + for (const mb of b.mo.values()) { + const ma = a !== b ? a.mo.get(mb[0]) : null; + let o = this.monCache.get(mb[0]); + if (!o) { o = { id: mb[0], kind: kinds[mb[1]], air: !!TD.ENEMIES[kinds[mb[1]]].air }; this.monCache.set(mb[0], o); } + o.x = ma ? ma[2] + (mb[2] - ma[2]) * alpha : mb[2]; + o.y = ma ? ma[3] + (mb[3] - ma[3]) * alpha : mb[3]; + o.hp = mb[4]; o.maxhp = mb[5]; o.slow = mb[6]; o.gen = gen; + mons.push(o); + } + for (const [id, o] of this.monCache) if (o.gen !== gen) this.monCache.delete(id); + + const buls = v.bullets; buls.length = 0; + for (const bb of b.bu.values()) { + const ba = a !== b ? a.bu.get(bb[0]) : null; + let o = this.bulCache.get(bb[0]); + if (!o) { o = { id: bb[0], k: bb[1] === 1 ? 'mortar' : 'filter' }; this.bulCache.set(bb[0], o); } + o.x = ba ? ba[2] + (bb[2] - ba[2]) * alpha : bb[2]; + o.y = ba ? ba[3] + (bb[3] - ba[3]) * alpha : bb[3]; + o.gen = gen; + buls.push(o); + } + for (const [id, o] of this.bulCache) if (o.gen !== gen) this.bulCache.delete(id); + + for (const t of this.towers) { + const r = a.tt.get(t.id); + t.tgt = r ? r[1] : 0; t.kills = r ? r[2] : 0; + } + v.towers = this.towers; + const mySlot = this.you ? this.you.slot : -1; + v.cursors = (b.snap.cur || []).filter((c) => c[0] !== mySlot).map((c) => ({ slot: c[0], x: c[1], y: c[2] })); + } + + send(cmd) { + const c = Object.assign({}, cmd); delete c.by; + this._send(Object.assign({ t: 'cmd' }, c)); + return { ok: true, pending: true }; + } + ctl(c, v) { this._send({ t: 'ctl', c, v }); } + preview(x, y, routes) { + if (!this.board) return { ok: false, reason: 'bounds' }; + const reserved = new Set(); + for (const m of this.view.monsters) if (!m.air) reserved.add(Math.floor(m.y) * this.board.cols + Math.floor(m.x)); + return this.board.trial(x, y, reserved, null, routes); + } + newGame(map) { this._send({ t: 'newgame', map }); } + sendCursor(x, y) { + const now = performance.now(); + if (now - this.lastCursor < 70) return; + 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 }); + } + sendMark(x, y) { this._send({ t: 'mark', x: Math.round(x * 100) / 100, y: Math.round(y * 100) / 100 }); } + close() { + this.intentional = true; + this._stopTimers(); + document.removeEventListener('visibilitychange', this._onVis); + root.removeEventListener('online', this._onVis); + if (this.ws) { try { this._send({ t: 'leave' }); this.ws.close(); } catch (e) { /* ignore */ } } + this._setStatus('closed'); + } + } + + NW.LocalController = LocalController; + NW.RemoteController = RemoteController; + NW.wsUrl = wsUrl; +})(typeof self !== 'undefined' ? self : this); diff --git a/public/js/main.js b/public/js/main.js new file mode 100644 index 0000000..308376e --- /dev/null +++ b/public/js/main.js @@ -0,0 +1,888 @@ +/* + * NETWALL main: screens, HUD, input (mouse + touch), lobby, glue between controllers, renderer and audio. + */ +(function (root) { + 'use strict'; + const TD = root.TD, NW = root.NW, Audio = NW.Audio; + const $ = (id) => document.getElementById(id); + const clamp = (v, a, b) => Math.min(b, Math.max(a, v)); + + // ------------------------------------------------------------------ storage (every access guarded) + const store = { + get(k, d) { try { const v = root.localStorage.getItem(k); return v === null ? d : JSON.parse(v); } catch (e) { return d; } }, + set(k, v) { try { root.localStorage.setItem(k, JSON.stringify(v)); } catch (e) { /* ignore */ } }, + del(k) { try { root.localStorage.removeItem(k); } catch (e) { /* ignore */ } }, + }; + const sess = { + get(k) { try { return root.sessionStorage.getItem(k); } catch (e) { return null; } }, + set(k, v) { try { root.sessionStorage.setItem(k, v); } catch (e) { /* ignore */ } }, + del(k) { try { root.sessionStorage.removeItem(k); } catch (e) { /* ignore */ } }, + }; + function randomId(n) { + const abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-'; + let out = ''; + const buf = new Uint8Array(n); + if (root.crypto && root.crypto.getRandomValues) root.crypto.getRandomValues(buf); else for (let i = 0; i < n; i++) buf[i] = Math.random() * 256; + for (let i = 0; i < n; i++) out += abc[buf[i] & 63]; + return out; + } + function getPid() { let p = sess.get('nw.pid'); if (!p || !/^[A-Za-z0-9_-]{8,40}$/.test(p)) { p = randomId(22); sess.set('nw.pid', p); } return p; } + + const REASONS = { + bounds: 'Out of bounds', obstacle: 'That node is dead. Pick another cell', occupied: 'Something is already there', spawn: "Can't build on a gateway", + core: "Can't build on the server", monster: 'A packet is in the way', blocks: 'That would seal the route. Leave a path!', gold: 'Not enough credits', + over: 'The game is over', no_tower: 'That tower no longer exists', max: 'Already at max level', not_host: 'Only the host can do that', + bad_map: 'Unknown map', bad_type: 'Unknown tower', bad_cmd: 'Invalid command', not_won: 'Nothing to continue', + }; + const MODE_NAMES = { first: 'First', last: 'Last', strong: 'Strongest', close: 'Closest' }; + + // ------------------------------------------------------------------ app state + const app = { + ctrl: null, renderer: null, screen: 'menu', inGame: false, + mapId: store.get('nw.map', 'open'), + selType: null, selTower: 0, + hover: null, pending: null, preview: null, valid: true, previewDirty: true, lastPreviewAt: 0, + zoomed: false, last: {}, names: {}, started: false, lastBossCheck: 0, bossMusic: false, + endShown: false, prevPlayers: null, + }; + const ui = { hover: null, selType: null, selTower: 0, preview: null, valid: true, coop: false, names: {} }; + + const canvas = $('board'); + const renderer = new NW.Renderer(canvas); + app.renderer = renderer; + if (!TD.MAPS[app.mapId]) app.mapId = 'open'; + + // ------------------------------------------------------------------ small UI helpers + let lastToast = '', lastToastAt = 0; + function toast(text, kind) { + const now = performance.now(); + if (text === lastToast && now - lastToastAt < 900) return; + lastToast = text; lastToastAt = now; + const d = document.createElement('div'); + d.className = 'toast' + (kind ? ' ' + kind : ''); + d.textContent = text; + $('toasts').appendChild(d); + setTimeout(() => d.remove(), 2700); + while ($('toasts').children.length > 3) $('toasts').firstChild.remove(); + } + let bannerT = 0; + function banner(text, boss) { + const b = $('banner'); + b.textContent = text; b.className = 'banner show' + (boss ? ' boss' : ''); + clearTimeout(bannerT); + bannerT = setTimeout(() => { b.className = 'banner' + (boss ? ' boss' : ''); }, 1500); + } + function hint(text, kind) { + const h = $('hint'); + if (!text) { h.hidden = true; return; } + h.hidden = false; h.textContent = text; h.className = 'hint ' + (kind || 'info'); + } + const fmtLen = (v) => String(Math.round(v / Math.max(1, ui.spawns || 1))); + + function showOverlay(id) { + for (const o of document.querySelectorAll('.overlay')) o.hidden = o.id !== id; + } + function setScreen(name) { + app.screen = name; + $('app').dataset.screen = name; + } + + // ------------------------------------------------------------------ controller switching + function useController(ctrl) { + if (app.ctrl && app.ctrl !== ctrl && app.ctrl.kind === 'remote') { /* closed by caller */ } + app.ctrl = ctrl; + ctrl.on('events', onEvents); + ctrl.on('reject', onReject); + ctrl.on('mark', (m) => { renderer.addMark(m.x, m.y, m.slot); Audio.sfx('ping'); }); + ctrl.on('players', onPlayers); + ctrl.on('newgame', () => { resetSelection(); app.endShown = false; app.last.state = 'playing'; adoptBoard(); $('end').hidden = true; }); + adoptBoard(true); + } + function adoptBoard(force) { + const b = app.ctrl.board; + if (b && (force || renderer.board !== b)) { + renderer.setBoard(b); + $('app').style.setProperty('--aspect', b.cols + ' / ' + b.rows); + $('app').style.setProperty('--aspect-p', b.rows + ' / ' + b.cols); + ui.spawns = b.spawns.length; + resizeCanvas(); + } + } + function resetSelection() { + app.selType = null; app.selTower = 0; app.pending = null; app.hover = null; app.preview = null; app.previewDirty = true; + syncPalette(); renderInfo(true); updateConfirm(); + } + + function startSolo(mapId) { + leaveRemote(true); + app.mapId = mapId; store.set('nw.map', mapId); + const c = new NW.LocalController({ map: mapId }); + useController(c); + app.inGame = true; app.started = true; app.endShown = false; app.last = {}; + resetSelection(); setScreen('playing'); showOverlay(null); + $('players').hidden = true; $('netChip').hidden = true; $('reconnect').hidden = true; + renderInfo(true); + Audio.music('battle'); + requestWakeLock(); + if (!store.get('nw.helped', false)) { store.set('nw.helped', true); showOverlay('help'); } + } + function previewMap(mapId) { + const c = new NW.LocalController({ map: mapId }); + c.paused = true; + useController(c); + app.inGame = false; + } + + function leaveRemote(silent) { + const c = app.ctrl; + if (c && c.kind === 'remote') { c.close(); } + sess.del('nw.room'); store.del('nw.session'); + clearRoomFromUrl(); + if (!silent) { /* caller handles screens */ } + } + function clearRoomFromUrl() { + try { if (root.location.search) root.history.replaceState(null, '', root.location.pathname); } catch (e) { /* ignore */ } + } + + // ------------------------------------------------------------------ events from the controller + function onEvents(evs) { + renderer.addEvents(evs); + for (const e of evs) { + switch (e.e) { + case 'place': Audio.sfx(e.type === 'wall' ? 'wall' : 'place'); break; + case 'sell': Audio.sfx('sell'); break; + case 'up': Audio.sfx('up'); break; + case 'shot': Audio.sfx('shot_' + e.k); break; + case 'arc': Audio.sfx('arc'); break; + case 'boom': Audio.sfx('boom'); break; + case 'kill': Audio.sfx('kill'); break; + case 'leak': Audio.sfx('leak'); break; + case 'wave': banner(e.boss ? 'BOSS WAVE ' + e.n : 'WAVE ' + e.n, e.boss); Audio.sfx(e.boss ? 'boss' : 'wave'); break; + case 'clear': toast('Wave ' + e.n + ' cleared +' + e.bonus + ' credits', 'good'); Audio.sfx('clear'); break; + default: break; + } + } + } + function onReject(r) { + toast(REASONS[r.reason] || ('Not possible: ' + r.reason), 'bad'); + Audio.sfx('error'); + } + + // ------------------------------------------------------------------ palette + info panel + function buildPalette() { + const pal = $('palette'); + pal.textContent = ''; + for (const type of TD.TOWER_ORDER) { + const def = TD.TOWERS[type]; + const b = document.createElement('button'); + b.className = 'tbtn'; b.dataset.type = type; b.type = 'button'; + b.setAttribute('aria-label', def.name + ', ' + def.levels[0].cost + ' credits'); + b.innerHTML = '' + def.key + ''; + b.querySelector('.nm').textContent = def.name; + b.querySelector('.cost').textContent = String(def.levels[0].cost); + b.addEventListener('click', () => { Audio.sfx('click'); selectType(app.selType === type ? null : type); }); + pal.appendChild(b); + } + drawPaletteIcons(); + } + function drawPaletteIcons() { + for (const b of $('palette').children) NW.drawIcon(b.querySelector('canvas'), b.dataset.type, 1); + } + function syncPalette() { + for (const b of $('palette').children) { + const sel = b.dataset.type === app.selType; + b.classList.toggle('sel', sel); + b.setAttribute('aria-pressed', sel ? 'true' : 'false'); + } + } + function selectType(type) { + app.selType = type; app.selTower = 0; app.pending = null; app.previewDirty = true; + syncPalette(); renderInfo(true); updateConfirm(); + if (!type) { ui.preview = null; hint(null); } + } + function selectTower(id) { + app.selTower = id; app.selType = null; app.pending = null; app.preview = null; ui.preview = null; + syncPalette(); renderInfo(true); updateConfirm(); hint(null); + } + + function statsFor(type, lv) { + const L = TD.TOWERS[type].levels[lv], out = []; + if (L.dmg) out.push(['Damage', String(Math.round(L.dmg))]); + if (L.rate) out.push(['Fire rate', L.rate.toFixed(1) + '/s']); + if (L.dmg && L.rate) out.push(['DPS', String(Math.round(L.dmg * L.rate))]); + if (L.range) out.push(['Range', L.range.toFixed(1)]); + if (L.splash) out.push(['Splash', L.splash.toFixed(1)]); + if (L.slow) out.push(['Slows', Math.round(L.slow * 100) + '%']); + if (L.chains) out.push(['Chains', String(L.chains)]); + return out; + } + function targetsText(def) { return def.ground && def.air ? 'ground + air' : def.ground ? 'ground only' : 'none'; } + + let infoSig = ''; + function renderInfo(force) { + const box = $('info'), ctrl = app.ctrl, view = ctrl.view; + let sig, tower = null; + if (app.selTower) { + tower = view.towers.find((t) => t.id === app.selTower); + 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) { + const def = TD.TOWERS[tower.type], i = tower.level - 1; + const cur = statsFor(tower.type, i), nxt = tower.level < 3 ? statsFor(tower.type, i + 1) : null; + let kv = ''; + cur.forEach((row, k) => { + const n = nxt && nxt[k] && nxt[k][1] !== row[1] ? ' → ' + nxt[k][1] + '' : ''; + kv += '
' + row[0] + '' + row[1] + n + '
'; + }); + if (tower.type !== 'wall') kv += '
Targets' + targetsText(def) + '
'; + const sellVal = def.refund ? tower.spent : Math.floor(tower.spent * TD.SELL_RATIO); + const upCost = tower.level < 3 ? 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 = + '
' + + '
' + kv + '
' + + (tower.type === 'wall' ? '' : + '' + + '') + + '
' + + '
'; + box.querySelector('.nm').textContent = def.name; + box.querySelector('.lv').textContent = tower.type === 'wall' ? '' : 'Level ' + tower.level + ' / 3'; + box.querySelector('.desc').textContent = def.desc; + if (ownerP) box.querySelector('#infoOwner').textContent = 'Built by ' + ownerP.name; + NW.drawIcon(box.querySelector('canvas'), tower.type, tower.level); + } else { + const def = TD.TOWERS[app.selType]; + let kv = ''; + for (const row of statsFor(app.selType, 0)) kv += '
' + row[0] + '' + row[1] + '
'; + if (app.selType !== 'wall') kv += '
Targets' + targetsText(def) + '
'; + box.innerHTML = '
' + kv + '
'; + box.querySelector('.nm').textContent = def.name; + box.querySelector('.lv').textContent = def.levels[0].cost + ' credits'; + box.querySelector('.desc').textContent = def.desc; + NW.drawIcon(box.querySelector('canvas'), app.selType, 1); + } + } + function updateInfoDynamic() { + if (!app.selTower) return; + const t = app.ctrl.view.towers.find((x) => x.id === app.selTower); + if (!t) return; + const k = $('infoKills'); if (k) k.textContent = t.kills + (t.kills === 1 ? ' kill' : ' kills'); + const def = TD.TOWERS[t.type]; + const up = $('info').querySelector('[data-act="up"]'); + if (up && t.level < 3) up.disabled = app.ctrl.view.gold < def.levels[t.level].cost; + } + $('info').addEventListener('click', (e) => { + const btn = e.target.closest('button[data-act]'); if (!btn || !app.selTower) return; + const ctrl = app.ctrl, tower = ctrl.view.towers.find((t) => t.id === app.selTower); + if (!tower) return; + Audio.sfx('click'); + switch (btn.dataset.act) { + 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 'mode': { + const modes = TD.TARGET_MODES; ctrl.send({ c: 'target', id: tower.id, mode: modes[(modes.indexOf(tower.mode) + 1) % modes.length] }); + break; + } + default: break; + } + }); + + function renderWavePanel(view) { + const n = view.wave + 1; + const key = n + ':' + view.state; + if (app.last.waveKey === key) return; + app.last.waveKey = key; + const box = $('nextwave'); + if (view.state !== 'playing') { box.textContent = ''; return; } + const sum = TD.waveSummary(n); + let html = '

Next · wave ' + n + '

'; + let air = false; + for (const g of sum) { + const d = TD.ENEMIES[g.k]; + if (d.air) air = true; + html += '' + g.c + '× ' + d.name + ''; + } + if (air) html += 'AIR'; + if (n % 10 === 0) html += 'BOSS'; + html += '
'; + box.innerHTML = html; + } + + function onPlayers(list) { + const ctrl = app.ctrl; + ui.names = {}; for (const p of list) ui.names[p.slot] = p.name; + ui.coop = list.length > 1; + // join / leave toasts + if (app.prevPlayers) { + for (const p of list) if (!app.prevPlayers.find((q) => q.pid === p.pid)) { toast(p.name + ' joined', 'good'); Audio.sfx('join'); } + for (const q of app.prevPlayers) if (!list.find((p) => p.pid === q.pid)) toast(q.name + ' left'); + for (const p of list) { const q = app.prevPlayers.find((x) => x.pid === p.pid); if (q && q.online && !p.online) toast(p.name + ' lost connection'); if (q && !q.online && p.online) toast(p.name + ' is back', 'good'); } + } + app.prevPlayers = list.map((p) => Object.assign({}, p)); + renderPlayers(); + if (ctrl.kind === 'remote') renderInfo(true); + } + function renderPlayers() { + const ctrl = app.ctrl, box = $('players'); + if (!ctrl || ctrl.kind !== 'remote') { box.hidden = true; return; } + box.hidden = false; + let html = '

Room ' + (ctrl.room || '') + '

'; + for (const p of ctrl.players) { + html += '
' + + (ctrl.you && p.pid === ctrl.you.pid ? '(you)' : '') + (p.host ? 'host' : '') + (p.online ? '' : 'offline') + '
'; + } + if (ctrl.players.length < 2) html += '
Waiting for a partner… share the invite link.
'; + html += '
'; + box.innerHTML = html; + const names = box.querySelectorAll('.pn'); + ctrl.players.forEach((p, i) => { names[i].textContent = p.name; }); + } + $('players').addEventListener('click', (e) => { + const b = e.target.closest('button[data-act]'); if (!b) return; + if (b.dataset.act === 'invite') invite(); + if (b.dataset.act === 'leave') { leaveToMenu(); } + }); + function inviteUrl() { return root.location.origin + root.location.pathname + '?room=' + app.ctrl.room; } + function invite() { + const url = inviteUrl(), text = 'Join my Netwall game (room ' + app.ctrl.room + ')'; + if (root.navigator.share) { root.navigator.share({ title: 'Netwall', text, url }).catch(() => {}); return; } + const done = () => toast('Invite link copied', 'good'); + if (root.navigator.clipboard && root.navigator.clipboard.writeText) root.navigator.clipboard.writeText(url).then(done, () => root.prompt('Copy this link', url)); + else root.prompt('Copy this link', url); + } + + // ------------------------------------------------------------------ HUD + function updateHud(view) { + const L = app.last, ctrl = app.ctrl; + if (L.gold !== view.gold) { L.gold = view.gold; $('vGold').textContent = String(view.gold); } + if (L.lives !== view.lives) { + L.lives = view.lives; $('vLives').textContent = String(view.lives); + $('statLives').classList.toggle('low', view.maxLives > 0 && view.lives <= view.maxLives * 0.25); + } + if (L.wave !== view.wave) { L.wave = view.wave; $('vWave').textContent = String(view.wave); } + if (L.winWave !== view.winWave) { L.winWave = view.winWave; $('vWaveMax').textContent = view.winWave ? '/' + view.winWave : ''; } + const idle = view.queued === 0 && view.monsters.length === 0; + const timer = view.auto && view.nextWaveIn >= 0 ? ' · ' + Math.ceil(view.nextWaveIn) + 's' : ''; + const wtxt = 'Wave ' + (view.wave + 1) + timer; + if (L.wtxt !== wtxt) { L.wtxt = wtxt; $('btnWaveText').textContent = wtxt; } + const wdis = view.state !== 'playing'; + if (L.wdis !== wdis) { L.wdis = wdis; $('btnWave').disabled = wdis; } + const attn = idle && view.wave === 0 && view.state === 'playing'; + 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.speed !== view.speed) { L.speed = view.speed; $('speedText').textContent = view.speed + '×'; } + if (L.paused !== view.paused) { L.paused = view.paused; $('btnPause').innerHTML = ''; $('btnPause').setAttribute('aria-label', view.paused ? 'Resume' : 'Pause'); } + if (L.muted !== Audio.muted) { L.muted = Audio.muted; $('btnSound').innerHTML = ''; } + // palette affordability + const gold = view.gold; + if (L.palGold !== gold) { + L.palGold = gold; + for (const b of $('palette').children) b.classList.toggle('poor', gold < TD.TOWERS[b.dataset.type].levels[0].cost); + } + if (ctrl.kind === 'remote') { + const chip = $('netChip'); + chip.hidden = false; + $('netRoom').textContent = ctrl.room || ''; + const p = ctrl.rtt ? ctrl.rtt + ' ms' : ''; + if (L.ping !== p) { L.ping = p; $('netPing').textContent = p; chip.classList.toggle('bad', ctrl.rtt > 220); } + } + renderWavePanel(view); + updateInfoDynamic(); + } + + function endScreen(view) { + const ctrl = app.ctrl; + const won = view.state === 'won'; + $('endTitle').textContent = won ? 'Server secured!' : 'Breach!'; + $('endTitle').style.color = won ? 'var(--green)' : 'var(--red)'; + const best = store.get('nw.best.' + ctrl.board.mapId, 0); + if (!won && view.wave > best) store.set('nw.best.' + ctrl.board.mapId, view.wave); + $('endText').textContent = won ? 'You held the line through wave ' + view.wave + '. Every packet was filtered.' : 'The server fell on wave ' + view.wave + '.'; + const walls = view.towers.filter((t) => t.type === 'wall').length; + const rows = [['Wave', view.wave], ['Packets killed', view.kills], ['Turrets', view.towers.length - walls], ['Firewalls', walls], ['Integrity left', view.lives], ['Best (map)', Math.max(best, view.wave)]]; + $('endStats').innerHTML = rows.map((r) => '
' + r[0] + '' + r[1] + '
').join(''); + const remoteGuest = ctrl.kind === 'remote' && !(ctrl.you && ctrl.you.host); + $('btnAgain').hidden = remoteGuest; $('endWait').hidden = !remoteGuest; + $('btnContinue').hidden = !won; + showOverlay('end'); + Audio.music(null); Audio.stinger(won ? 'win' : 'lose'); + } + + // ------------------------------------------------------------------ placement + previews + function cellFromEvent(e) { + const r = canvas.getBoundingClientRect(); + return renderer.screenToCell(e.clientX - r.left, e.clientY - r.top); + } + function placeAt(cell) { + const ctrl = app.ctrl; + if (!app.selType || !cell || !ctrl.board.inBounds(cell.x, cell.y)) return false; + const cost = TD.TOWERS[app.selType].levels[0].cost; + if (ctrl.view.gold < cost) { onReject({ reason: 'gold' }); return false; } + ctrl.send({ c: 'place', type: app.selType, x: cell.x, y: cell.y }); + app.previewDirty = true; + return true; + } + function refreshPreview(force) { + const ctrl = app.ctrl, now = performance.now(); + const cell = app.pending || app.hover; + if (cell && app.selType && ui.noGhost) { if (ui.preview || !$('hint').hidden) { ui.preview = null; ui.valid = true; hint(null); } return; } + if (!app.selType || !cell || !ctrl.board.inBounds(cell.x, cell.y)) { + if (ui.preview || !$('hint').hidden) { ui.preview = null; ui.valid = true; hint(null); } + return; + } + if (!force && !app.previewDirty && now - app.lastPreviewAt < 250) return; + app.previewDirty = false; app.lastPreviewAt = now; + const pv = ctrl.preview(cell.x, cell.y, true); + const cost = TD.TOWERS[app.selType].levels[0].cost; + const poor = ctrl.view.gold < cost; + ui.preview = pv; ui.valid = pv.ok && !poor; + if (!pv.ok) hint('✕ ' + (REASONS[pv.reason] || pv.reason), 'bad'); + else if (poor) hint('Need ' + cost + ' credits (have ' + ctrl.view.gold + ')', 'bad'); + else { + const d = Math.round(pv.after - pv.before) / 1; + const a = Math.round(pv.before / (ui.spawns || 1)), b = Math.round(pv.after / (ui.spawns || 1)); + hint(b === a ? 'Route ' + a : 'Route ' + a + ' → ' + b + (b > a ? ' (+' + (b - a) + ')' : ' (' + (b - a) + ')'), d > 0.5 ? 'ok' : 'info'); + } + } + + // touch placement bar + function updateConfirm() { + const show = !!(app.pending && app.selType && app.selType !== 'wall'); + $('confirm').hidden = !show; + if (show) { + $('confirmText').textContent = 'Build · ' + TD.TOWERS[app.selType].levels[0].cost; + // keep the bar clear of the cell being placed: show it on the opposite half of the stage + const p = renderer.cellToScreen(app.pending.x, app.pending.y); + $('confirm').classList.toggle('top', p.y > $('stage').clientHeight * 0.5); + } + } + $('btnConfirmBuild').addEventListener('click', () => { if (app.pending && placeAt(app.pending)) { app.pending = null; updateConfirm(); } }); + $('btnCancelBuild').addEventListener('click', () => { selectType(null); }); + + // ------------------------------------------------------------------ pointer input + const ptrs = new Map(); + let painting = false, paintCell = null, panning = false, longT = 0, longFired = false, rightDown = null, prevPending = null, pinch = null; + + function cancelLong() { clearTimeout(longT); longT = 0; } + function setHover(cell) { + const c = cell && app.ctrl.board.inBounds(cell.x, cell.y) ? { x: cell.x, y: cell.y } : null; + if (!c && !app.hover) return; + if (c && app.hover && c.x === app.hover.x && c.y === app.hover.y) return; + app.hover = c; app.previewDirty = true; + } + 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; + const dx = Math.abs(x1 - x0), dy = -Math.abs(y1 - y0), sx = x0 < x1 ? 1 : -1, sy = y0 < y1 ? 1 : -1; + let err = dx + dy; + for (let guard = 0; guard < 80; guard++) { + if (x0 !== from.x || y0 !== from.y) placeAt({ x: x0, y: y0 }); + if (x0 === x1 && y0 === y1) break; + const e2 = 2 * err; + if (e2 >= dy) { err += dy; x0 += sx; } + if (e2 <= dx) { err += dx; y0 += sy; } + } + } + function markAt(cell) { + if (!cell || !app.ctrl.board.inBounds(cell.x, cell.y)) return; + app.ctrl.sendMark(cell.x, cell.y); + if (navigator.vibrate) try { navigator.vibrate(15); } catch (e) { /* ignore */ } + } + function towerAtCell(cell) { + return app.ctrl.view.towers.find((x) => x.x === cell.x && x.y === cell.y) || null; + } + function tapSelect(cell) { + const ctrl = app.ctrl; + if (!ctrl.board.inBounds(cell.x, cell.y)) { selectTower(0); return; } + const t = ctrl.view.towers.find((x) => x.x === cell.x && x.y === cell.y); + if (t) { selectTower(t.id); Audio.sfx('click'); } else selectTower(0); + } + + canvas.addEventListener('contextmenu', (e) => e.preventDefault()); + canvas.addEventListener('pointerdown', (e) => { + if (!app.inGame) return; + e.preventDefault(); + try { canvas.setPointerCapture(e.pointerId); } catch (err) { /* ignore */ } + Audio.unlock(); + 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 }); + if (ptrs.size === 2) { // second finger: pinch/pan, abandon whatever the first finger started + cancelLong(); painting = false; tapSelectOnUp = false; + const [a, b] = [...ptrs.values()]; + 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; + } + if (ptrs.size > 2) return; + const cell = renderer.screenToCell(sx, sy); + longFired = false; + if (e.pointerType === 'mouse') { + if (e.button === 2) { rightDown = { x: sx, y: sy, moved: false }; return; } + if (e.button === 1) { panning = true; return; } + if (e.altKey) { markAt(cell); return; } + const ex = towerAtCell(cell); + if (app.selType && ex && !(app.selType === 'wall' && ex.type === 'wall')) { selectTower(ex.id); Audio.sfx('click'); } + else if (app.selType) { + setHover(cell); + if (!ex) placeAt(cell); + if (app.selType === 'wall') { painting = true; paintCell = cell; } + } else { + tapSelectOnUp = true; panning = renderer.zoom > 1.01; + } + return; + } + // touch / pen + prevPending = app.pending ? { x: app.pending.x, y: app.pending.y } : null; + const ex = towerAtCell(cell); + if (app.selType && ex && !(app.selType === 'wall' && ex.type === 'wall')) { + selectTower(ex.id); Audio.sfx('click'); + } else if (app.selType === 'wall') { + setHover(cell); if (!ex) placeAt(cell); painting = true; paintCell = cell; + } else if (app.selType) { + 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) => { + const r = canvas.getBoundingClientRect(), sx = e.clientX - r.left, sy = e.clientY - r.top; + const p = ptrs.get(e.pointerId); + if (!app.inGame) return; + if (!p) { // hovering mouse + if (e.pointerType === 'mouse') { + const cell = renderer.screenToCell(sx, sy); + setHover(cell); + app.ctrl.sendCursor(cell.fx, cell.fy); + } + return; + } + const dx = sx - p.x, dy = sy - p.y; + p.x = sx; p.y = sy; + if (Math.hypot(sx - p.sx, sy - p.sy) > 8) p.moved = true; + if (ptrs.size === 2 && pinch) { + const [a, b] = [...ptrs.values()]; + 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.setZoom(renderer.zoom * d / pinch.d, mx, my); + pinch.d = d; pinch.mx = mx; pinch.my = my; + updateFit(); + return; + } + const cell = renderer.screenToCell(sx, sy); + 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 (panning && p.moved) { renderer.panBy(dx, dy); updateFit(); tapSelectOnUp = false; return; } + setHover(cell); + 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; } + return; + } + // touch / pen + if (p.moved) { cancelLong(); tapSelectOnUp = tapSelectOnUp && !p.moved; } + if (painting && app.selType === 'wall') { + setHover(cell); + if (paintCell && (cell.x !== paintCell.x || cell.y !== paintCell.y)) { paintLine(paintCell, cell); paintCell = cell; } + } else if (app.selType) { + app.pending = { x: cell.x, y: cell.y }; setHover(cell); updateConfirm(); + app.ctrl.sendCursor(cell.fx, cell.fy); + } else if (p.moved && renderer.zoom > 1.01) { + renderer.panBy(dx, dy); updateFit(); + } + }); + + function endPointer(e) { + const p = ptrs.get(e.pointerId); + ptrs.delete(e.pointerId); + try { canvas.releasePointerCapture(e.pointerId); } catch (err) { /* ignore */ } + if (!p || !app.inGame) return; + 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.button === 2 && rightDown) { if (!rightDown.moved) { selectType(null); selectTower(0); } rightDown = null; return; } + if (e.button === 1) { panning = false; return; } + if (tapSelectOnUp && !p.moved && e.type === 'pointerup') tapSelect(cell); + tapSelectOnUp = false; painting = false; panning = false; + return; + } + if (e.type === 'pointercancel') { painting = false; tapSelectOnUp = false; return; } + if (painting) { painting = false; return; } + if (ptrs.size > 0) return; // lifted one finger of a pinch + if (app.selType && app.pending && !p.moved && prevPending && prevPending.x === app.pending.x && prevPending.y === app.pending.y) { + if (placeAt(app.pending)) { app.pending = null; updateConfirm(); } // tapping the previewed cell again builds + } else if (!app.selType && tapSelectOnUp && !p.moved && !longFired) tapSelect(cell); + tapSelectOnUp = false; + } + canvas.addEventListener('pointerup', endPointer); + canvas.addEventListener('pointercancel', endPointer); + canvas.addEventListener('pointerleave', (e) => { if (e.pointerType === 'mouse' && !ptrs.size) { app.hover = null; app.previewDirty = true; app.ctrl.sendCursor(null, null); } }); + canvas.addEventListener('wheel', (e) => { + if (!app.inGame) return; + e.preventDefault(); + const r = canvas.getBoundingClientRect(); + renderer.setZoom(renderer.zoom * (e.deltaY < 0 ? 1.15 : 1 / 1.15), e.clientX - r.left, e.clientY - r.top); + updateFit(); + }, { passive: false }); + + function updateFit() { + const z = renderer.zoom > 1.02; + if (z !== app.zoomed) { app.zoomed = z; $('btnFit').hidden = !z; } + } + $('btnFit').addEventListener('click', () => { renderer.resetCamera(); updateFit(); }); + + // ------------------------------------------------------------------ keyboard + root.addEventListener('keydown', (e) => { + if (e.target && (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA')) return; + if (e.ctrlKey || e.metaKey) return; + if (!app.inGame) return; + if (document.querySelector('.overlay:not([hidden])')) { if (e.key === 'Escape') { closeOverlayToGame(); } return; } + const ctrl = app.ctrl, view = ctrl.view; + const k = e.key.toLowerCase(); + const idx = '123456'.indexOf(k); + if (idx >= 0 && k.length === 1) { selectType(app.selType === TD.TOWER_ORDER[idx] ? null : TD.TOWER_ORDER[idx]); Audio.sfx('click'); e.preventDefault(); return; } + switch (k) { + case 'escape': case 'q': selectType(null); selectTower(0); app.pending = null; updateConfirm(); break; + case ' ': case 'enter': ctrl.send({ c: 'wave' }); e.preventDefault(); break; + case 'p': ctrl.ctl('pause', !view.paused); break; + case 'f': ctrl.ctl('speed', view.speed % 3 + 1); break; + case 'a': ctrl.send({ c: 'auto', v: !view.auto }); break; + case 'm': Audio.toggleMuted(); break; + case 'u': if (app.selTower) $('info').querySelector('[data-act="up"]') && $('info').querySelector('[data-act="up"]').click(); break; + case 'x': case 'delete': case 'backspace': if (app.selTower) { $('info').querySelector('[data-act="sell"]') && $('info').querySelector('[data-act="sell"]').click(); e.preventDefault(); } break; + case 't': if (app.selTower) $('info').querySelector('[data-act="mode"]') && $('info').querySelector('[data-act="mode"]').click(); break; + case '?': case 'h': showOverlay('help'); break; + default: break; + } + }); + + document.addEventListener('click', (e) => { const b = e.target.closest && e.target.closest('button'); if (b && e.detail > 0) b.blur(); }); + + // ------------------------------------------------------------------ top bar buttons + $('btnWave').addEventListener('click', () => { Audio.sfx('click'); app.ctrl.send({ c: 'wave' }); }); + $('btnAuto').addEventListener('click', () => { Audio.sfx('click'); app.ctrl.send({ c: 'auto', v: !app.ctrl.view.auto }); }); + $('btnSpeed').addEventListener('click', () => { Audio.sfx('click'); app.ctrl.ctl('speed', app.ctrl.view.speed % 3 + 1); }); + $('btnPause').addEventListener('click', () => { Audio.sfx('click'); app.ctrl.ctl('pause', !app.ctrl.view.paused); }); + $('btnSound').addEventListener('click', () => { Audio.unlock(); Audio.toggleMuted(); Audio.sfx('click'); }); + $('btnMenu').addEventListener('click', () => { Audio.sfx('click'); openMenu(); }); + + // ------------------------------------------------------------------ menu / lobby + function buildMapPicker() { + const box = $('mapPick'); box.textContent = ''; + for (const id of TD.MAP_ORDER) { + const def = TD.MAPS[id]; + const b = document.createElement('button'); + b.type = 'button'; b.className = 'mapcard'; b.dataset.map = id; b.setAttribute('role', 'radio'); + b.innerHTML = 'DIFFICULTY '; + b.querySelector('.nm').textContent = def.name; + b.querySelector('.df b').textContent = '●'.repeat(def.difficulty) + '○'.repeat(3 - def.difficulty); + drawMapPreview(b.querySelector('canvas'), def); + b.addEventListener('click', () => { Audio.sfx('click'); chooseMap(id); }); + box.appendChild(b); + } + chooseMap(app.mapId, true); + } + function drawMapPreview(cv, def) { + const p = TD.parseMap(def), ctx = cv.getContext('2d'), w = cv.width / p.cols, h = cv.height / p.rows; + ctx.fillStyle = '#09101f'; ctx.fillRect(0, 0, cv.width, cv.height); + ctx.fillStyle = '#26304f'; + for (let y = 0; y < p.rows; y++) for (let x = 0; x < p.cols; x++) if (p.obst[y * p.cols + x]) ctx.fillRect(x * w + 1, y * h + 1, w - 2, h - 2); + ctx.fillStyle = '#ff5c7a'; for (const s of p.spawns) { ctx.beginPath(); ctx.arc((s.x + 0.5) * w, (s.y + 0.5) * h, h * 0.6, 0, Math.PI * 2); ctx.fill(); } + ctx.fillStyle = '#4de3ff'; ctx.fillRect(p.core.x * w - 2, p.core.y * h - 2, w + 4, h + 4); + } + function chooseMap(id, silent) { + app.mapId = id; store.set('nw.map', id); + for (const b of $('mapPick').children) b.setAttribute('aria-checked', b.dataset.map === id ? 'true' : 'false'); + $('mapDesc').textContent = TD.MAPS[id].desc; + $('lobbyMapName').textContent = 'Map: ' + TD.MAPS[id].name; + if (!silent && !app.inGame) previewMap(id); + } + + function openMenu() { + if (app.inGame && app.ctrl.kind === 'local') app.ctrl.ctl('pause', true); + setScreen(app.inGame ? 'playing' : 'menu'); + $('btnCloseMenu').hidden = !app.inGame; + $('btnSolo').lastChild.textContent = app.inGame ? 'New solo game' : 'Play solo'; + showOverlay('menu'); + if (!app.inGame) Audio.music('theme'); + updateResumeButton(); + } + function closeOverlayToGame() { + if (!app.inGame) return; + showOverlay(null); + if (app.ctrl.kind === 'local' && app.ctrl.view.paused) app.ctrl.ctl('pause', false); + } + function leaveToMenu() { + leaveRemote(true); + app.prevPlayers = null; + app.inGame = false; + $('reconnect').hidden = true; $('players').hidden = true; $('netChip').hidden = true; + previewMap(app.mapId); + setScreen('menu'); openMenu(); + } + + $('btnSolo').addEventListener('click', () => { Audio.unlock(); startSolo(app.mapId); }); + $('btnCloseMenu').addEventListener('click', closeOverlayToGame); + $('btnHelp').addEventListener('click', () => showOverlay('help')); + $('btnHelpClose').addEventListener('click', () => { if (app.inGame) closeOverlayToGame(); else showOverlay('menu'); }); + $('btnFullscreen').addEventListener('click', () => { + const d = document, el = d.documentElement; + if (d.fullscreenElement) d.exitFullscreen(); else if (el.requestFullscreen) el.requestFullscreen().catch(() => {}); + }); + if (!document.documentElement.requestFullscreen || (root.matchMedia && root.matchMedia('(display-mode: standalone)').matches)) $('btnFullscreen').hidden = true; else $('btnFullscreen').hidden = false; + + $('btnAgain').addEventListener('click', () => { + Audio.sfx('click'); + if (app.ctrl.kind === 'local') { app.ctrl.newGame(app.ctrl.mapId); Audio.music('battle'); } + else { app.ctrl.newGame(app.ctrl.board.mapId); } + }); + $('btnContinue').addEventListener('click', () => { app.ctrl.send({ c: 'continue' }); $('end').hidden = true; app.endShown = false; Audio.music('battle'); }); + $('btnEndMenu').addEventListener('click', () => { if (app.ctrl.kind === 'remote') leaveToMenu(); else { app.inGame = false; previewMap(app.mapId); setScreen('menu'); openMenu(); } }); + + // lobby + function lobbyMsg(text, bad) { const m = $('lobbyMsg'); m.textContent = text || ''; m.className = 'msg' + (bad ? ' bad' : ''); } + function openLobby(code) { + showOverlay('lobby'); setScreen(app.inGame ? 'playing' : 'menu'); + $('inName').value = store.get('nw.name', '') || ''; + if (code) $('inCode').value = code; + lobbyMsg(root.location.protocol === 'file:' ? 'Co-op needs the Netwall server: run "npm start" and open its address (the page is currently opened as a file).' : '', root.location.protocol === 'file:'); + } + $('btnCoop').addEventListener('click', () => { Audio.unlock(); openLobby(); }); + $('btnLobbyBack').addEventListener('click', () => { if (app.inGame) closeOverlayToGame(); else openMenu(); }); + $('inCode').addEventListener('input', (e) => { e.target.value = e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 4); }); + $('btnCreate').addEventListener('click', () => connectRemote({ room: null, map: app.mapId })); + $('btnJoin').addEventListener('click', () => { + const code = $('inCode').value.trim().toUpperCase(); + if (!/^[A-Z0-9]{4}$/.test(code)) { lobbyMsg('Enter the 4 character room code.', true); return; } + connectRemote({ room: code }); + }); + $('inCode').addEventListener('keydown', (e) => { if (e.key === 'Enter') $('btnJoin').click(); }); + + function connectRemote(opts) { + if (root.location.protocol === 'file:') { lobbyMsg('Open the game through the Netwall server to play online.', true); return; } + const name = ($('inName').value || store.get('nw.name', '') || '').trim().slice(0, 16) || 'Player'; + store.set('nw.name', name); + if (app.ctrl && app.ctrl.kind === 'remote') app.ctrl.close(); + lobbyMsg('Connecting…'); + const rc = new NW.RemoteController({ pid: getPid(), name, room: opts.room, map: opts.map }); + let first = true; + rc.on('joined', () => { + sess.set('nw.room', rc.room); store.set('nw.session', { pid: getPid(), room: rc.room, name, ts: Date.now() }); + $('reconnect').hidden = true; + if (first) { + first = false; + useController(rc); + app.inGame = true; app.started = true; app.last = {}; app.endShown = false; app.prevPlayers = null; + resetSelection(); setScreen('playing'); showOverlay(null); + onPlayers(rc.players); + try { root.history.replaceState(null, '', root.location.pathname + '?room=' + rc.room); } catch (e) { /* ignore */ } + toast('Room ' + rc.room + (rc.players.length < 2 ? '. Send the invite link to your partner!' : ''), 'good'); + Audio.music('battle'); requestWakeLock(); + } else { toast('Reconnected', 'good'); adoptBoard(); } + lobbyMsg(''); + }); + rc.on('status', (s) => { if (app.ctrl === rc && app.inGame) $('reconnect').hidden = s !== 'reconnecting'; }); + rc.on('fatal', (f) => { + sess.del('nw.room'); store.del('nw.session'); + if (app.ctrl === rc && app.inGame) { toast(f.msg, 'bad'); leaveToMenu(); openLobby(); lobbyMsg(f.msg, true); } + else lobbyMsg(f.msg, true); + }); + rc.connect(); + } + + function updateResumeButton() { + const s = store.get('nw.session', null), b = $('btnResume'); + const fresh = s && s.room && Date.now() - s.ts < 15 * 60 * 1000 && !(app.ctrl && app.ctrl.kind === 'remote'); + b.hidden = !fresh || root.location.protocol === 'file:'; + if (fresh) b.textContent = 'Resume co-op game · room ' + s.room; + } + $('btnResume').addEventListener('click', () => { + const s = store.get('nw.session', null); if (!s) return; + sess.set('nw.pid', s.pid); + $('inName').value = s.name || ''; + connectRemote({ room: s.room }); + }); + + // ------------------------------------------------------------------ misc platform bits + let wakeLock = null; + function requestWakeLock() { + try { if (navigator.wakeLock && !wakeLock) navigator.wakeLock.request('screen').then((l) => { wakeLock = l; l.addEventListener('release', () => { wakeLock = null; }); }).catch(() => {}); } catch (e) { /* ignore */ } + } + document.addEventListener('visibilitychange', () => { if (!document.hidden && app.inGame) requestWakeLock(); }); + + function resizeCanvas() { + const st = $('stage'), r = st.getBoundingClientRect(); + renderer.setRotation(r.height > r.width * 1.05); // portrait: draw the board turned 90 degrees (bigger cells) + const dpr = Math.min(root.devicePixelRatio || 1, root.matchMedia && root.matchMedia('(pointer: coarse)').matches ? 2 : 2.5); + renderer.resize(r.width, r.height, dpr); + } + if (root.ResizeObserver) new ResizeObserver(resizeCanvas).observe($('stage')); else root.addEventListener('resize', resizeCanvas); + root.addEventListener('orientationchange', () => setTimeout(() => { resizeCanvas(); drawPaletteIcons(); }, 250)); + // keep the page from scrolling/bouncing or zooming on iOS + document.addEventListener('gesturestart', (e) => e.preventDefault()); + document.addEventListener('touchmove', (e) => { if (e.target === canvas || e.target.closest('#stage')) e.preventDefault(); }, { passive: false }); + + // ------------------------------------------------------------------ main loop + function frame(now) { + root.requestAnimationFrame(frame); + const ctrl = app.ctrl; if (!ctrl) return; + ctrl.update(now); + const view = ctrl.view; + if (app.inGame) { + if (app.last.state !== view.state) { + app.last.state = view.state; + if (view.state === 'won' || view.state === 'lost') { if (!app.endShown) { app.endShown = true; endScreen(view); } } + 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.last.rev !== view.rev) { app.last.rev = view.rev; app.previewDirty = true; if (app.selTower) renderInfo(true); } + updateHud(view); + if (now - app.lastBossCheck > 600 && view.state === 'playing') { + app.lastBossCheck = now; + const boss = view.monsters.some((m) => m.kind === 'rootkit'); + if (boss !== app.bossMusic) { app.bossMusic = boss; if (!app.endShown) Audio.music(boss ? 'boss' : 'battle'); } + } + } + ui.hover = app.pending || app.hover; ui.selType = app.selType; ui.selTower = app.selTower; + // hovering an existing tower while a build type is active: a click selects it, so show no ghost + ui.noGhost = !!(ui.hover && app.selType && view.towers.some((t) => t.x === ui.hover.x && t.y === ui.hover.y)); + refreshPreview(false); + renderer.frame(now, view, ui); + } + + // ------------------------------------------------------------------ boot + function boot() { + buildPalette(); buildMapPicker(); + previewMap(app.mapId); + setScreen('menu'); showOverlay('menu'); + $('btnCloseMenu').hidden = true; + resizeCanvas(); drawPaletteIcons(); + root.requestAnimationFrame(frame); + + const q = new URLSearchParams(root.location.search), codeParam = (q.get('room') || '').toUpperCase(); + const savedRoom = sess.get('nw.room'); + if (savedRoom && /^[A-Z0-9]{4}$/.test(savedRoom) && root.location.protocol !== 'file:' && (!codeParam || codeParam === savedRoom)) { + // page reload in the same tab: slip straight back into the room + $('inName').value = store.get('nw.name', '') || ''; + connectRemote({ room: savedRoom }); + } else if (/^[A-Z0-9]{4}$/.test(codeParam)) { + openLobby(codeParam); + lobbyMsg('Enter your name and press Join.'); + } else { + updateResumeButton(); + Audio.music('theme'); + } + if (root.navigator.serviceWorker && root.location.protocol.startsWith('http')) { /* reserved for offline support */ } + } + if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot); else boot(); + + NW.app = app; // handy for debugging and automated tests +})(typeof self !== 'undefined' ? self : this); diff --git a/public/js/render.js b/public/js/render.js new file mode 100644 index 0000000..46f9ffc --- /dev/null +++ b/public/js/render.js @@ -0,0 +1,609 @@ +/* + * NETWALL renderer: canvas 2D, world units = 40 px per cell, camera (zoom + pan) maps world -> CSS px. + * No shadowBlur / per-frame gradients so it stays smooth on phones. + */ +(function (root) { + 'use strict'; + const NW = root.NW = root.NW || {}; + const TD = root.TD; + const C = 40; // world px per cell + const TAU = Math.PI * 2; + const SLOT_COLORS = ['#4de3ff', '#ffd24d']; + const BG = '#050810', BOARD = '#09101f'; + 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; }; + + function rr(ctx, x, y, w, h, r) { + ctx.beginPath(); + ctx.moveTo(x + r, y); + ctx.arcTo(x + w, y, x + w, y + h, r); + ctx.arcTo(x + w, y + h, x, y + h, r); + ctx.arcTo(x, y + h, x, y, r); + ctx.arcTo(x, y, x + w, y, r); + ctx.closePath(); + } + function poly(ctx, n, r, rot) { + ctx.beginPath(); + for (let i = 0; i < n; i++) { + const a = rot + (i / n) * TAU; + i ? ctx.lineTo(Math.cos(a) * r, Math.sin(a) * r) : ctx.moveTo(Math.cos(a) * r, Math.sin(a) * r); + } + ctx.closePath(); + } + function rgba(hex, a) { + const n = parseInt(hex.slice(1), 16); + return 'rgba(' + (n >> 16) + ',' + ((n >> 8) & 255) + ',' + (n & 255) + ',' + a + ')'; + } + + // ------------------------------------------------------------------ tower glyphs (also used for UI icons) + // S = tile size, (cx,cy) = centre, ang = barrel angle (radians), t = seconds (animation) + function drawGlyph(ctx, type, level, cx, cy, S, ang, t, alpha, rot) { + const def = TD.TOWERS[type]; if (!def) return; + const col = def.color; + ctx.save(); + ctx.globalAlpha *= alpha === undefined ? 1 : alpha; + ctx.translate(cx, cy); + if (rot) { ctx.rotate(-rot); ang = (ang || 0) + rot; } // board is drawn rotated: keep glyphs upright + const h = S * 0.43; + if (type === 'wall') { + ctx.fillStyle = '#10305f'; rr(ctx, -h * 0.92, -h * 0.92, h * 1.84, h * 1.84, S * 0.09); ctx.fill(); + ctx.lineWidth = S * 0.05; ctx.strokeStyle = col; ctx.stroke(); + ctx.fillStyle = 'rgba(90,169,255,.28)'; + ctx.fillRect(-h * 0.55, -h * 0.55, h * 1.1, h * 0.5); + ctx.fillRect(-h * 0.55, h * 0.05, h * 0.5, h * 0.5); + ctx.fillRect(h * 0.05, h * 0.05, h * 0.5, h * 0.5); + ctx.restore(); return; + } + ctx.fillStyle = '#0c1426'; rr(ctx, -h, -h, h * 2, h * 2, S * 0.12); ctx.fill(); + ctx.lineWidth = S * (level >= 3 ? 0.075 : 0.05); ctx.strokeStyle = col; ctx.stroke(); + ctx.lineCap = 'round'; ctx.lineJoin = 'round'; + switch (type) { + case 'filter': + ctx.fillStyle = rgba(col, 0.22); ctx.beginPath(); ctx.arc(0, 0, S * 0.2, 0, TAU); ctx.fill(); + ctx.lineWidth = S * 0.04; ctx.stroke(); + ctx.save(); ctx.rotate(ang); ctx.fillStyle = col; ctx.fillRect(0, -S * 0.05, S * 0.34, S * 0.1); ctx.restore(); + ctx.fillStyle = col; ctx.beginPath(); ctx.arc(0, 0, S * 0.07, 0, TAU); ctx.fill(); + break; + case 'ids': + ctx.lineWidth = S * 0.035; + ctx.beginPath(); ctx.arc(0, 0, S * 0.19, 0, TAU); ctx.stroke(); + ctx.save(); ctx.rotate(ang); + ctx.fillStyle = col; ctx.fillRect(0, -S * 0.03, S * 0.46, S * 0.06); + ctx.fillRect(S * 0.36, -S * 0.07, S * 0.05, S * 0.14); + ctx.restore(); + ctx.beginPath(); ctx.moveTo(-S * 0.26, 0); ctx.lineTo(-S * 0.12, 0); ctx.moveTo(0, -S * 0.26); ctx.lineTo(0, -S * 0.12); ctx.moveTo(0, S * 0.26); ctx.lineTo(0, S * 0.12); ctx.stroke(); + ctx.fillStyle = col; ctx.beginPath(); ctx.arc(0, 0, S * 0.05, 0, TAU); ctx.fill(); + break; + case 'mortar': + ctx.fillStyle = rgba(col, 0.25); ctx.beginPath(); ctx.arc(0, 0, S * 0.22, 0, TAU); ctx.fill(); + ctx.lineWidth = S * 0.04; ctx.stroke(); + ctx.save(); ctx.rotate(ang); ctx.fillStyle = col; rr(ctx, -S * 0.02, -S * 0.1, S * 0.3, S * 0.2, S * 0.04); ctx.fill(); ctx.restore(); + ctx.fillStyle = '#0c1426'; ctx.beginPath(); ctx.arc(0, 0, S * 0.08, 0, TAU); ctx.fill(); + break; + case 'throttle': { + const pulse = ((t * 0.9) % 1); + ctx.lineWidth = S * 0.04; + for (let i = 0; i < 3; i++) { + const r = S * (0.08 + 0.085 * i) + (i === 2 ? pulse * S * 0.05 : 0); + ctx.strokeStyle = rgba(col, 1 - i * 0.28 - (i === 2 ? pulse * 0.3 : 0)); + ctx.beginPath(); ctx.arc(0, 0, r, -2.3, -0.84); ctx.stroke(); + ctx.beginPath(); ctx.arc(0, 0, r, 0.84, 2.3); ctx.stroke(); + } + ctx.fillStyle = col; ctx.beginPath(); ctx.arc(0, 0, S * 0.05, 0, TAU); ctx.fill(); + ctx.strokeStyle = col; + break; + } + case 'arc': + ctx.fillStyle = col; + ctx.beginPath(); + ctx.moveTo(-S * 0.03, -S * 0.26); ctx.lineTo(-S * 0.14, S * 0.02); ctx.lineTo(-S * 0.01, S * 0.02); + 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(); + break; + default: break; + } + // level pips + ctx.fillStyle = '#ffffff'; + 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(); } + ctx.restore(); + } + + // ------------------------------------------------------------------ monsters + function drawMonster(ctx, m, ang, t, flash, rot) { + const def = TD.ENEMIES[m.kind], r = def.r * C, col = def.color; + ctx.save(); + ctx.translate(m.x * C, m.y * C); + if (rot) { ctx.rotate(-rot); ang += rot; } + ctx.lineJoin = 'round'; ctx.lineCap = 'round'; + switch (m.kind) { + case 'ping': + ctx.fillStyle = '#2a0b16'; ctx.beginPath(); ctx.arc(0, 0, r, 0, TAU); ctx.fill(); + ctx.lineWidth = 2.4; ctx.strokeStyle = col; ctx.stroke(); + ctx.fillStyle = col; ctx.beginPath(); ctx.arc(Math.cos(ang) * r * 0.35, Math.sin(ang) * r * 0.35, r * 0.38, 0, TAU); ctx.fill(); + break; + case 'worm': { + ctx.fillStyle = col; + for (let i = 2; i >= 0; i--) { + const k = i * r * 1.05, w = Math.sin(t * 11 + m.id + i * 1.3) * r * 0.35; + const px = -Math.cos(ang) * k - Math.sin(ang) * w, py = -Math.sin(ang) * k + Math.cos(ang) * w; + ctx.globalAlpha = 1 - i * 0.22; + ctx.beginPath(); ctx.arc(px, py, r * (1 - i * 0.18), 0, TAU); ctx.fill(); + } + ctx.globalAlpha = 1; + ctx.fillStyle = '#2a1204'; ctx.beginPath(); ctx.arc(Math.cos(ang) * r * 0.3, Math.sin(ang) * r * 0.3, r * 0.28, 0, TAU); ctx.fill(); + break; + } + case 'trojan': + poly(ctx, 6, r, ang); ctx.fillStyle = '#2a0e1a'; ctx.fill(); + ctx.lineWidth = 3; ctx.strokeStyle = col; ctx.stroke(); + ctx.fillStyle = col; rr(ctx, -r * 0.32, -r * 0.1, r * 0.64, r * 0.5, 2); ctx.fill(); + ctx.lineWidth = 2.2; ctx.strokeStyle = col; ctx.beginPath(); ctx.arc(0, -r * 0.1, r * 0.22, Math.PI, 0); ctx.stroke(); + break; + case 'spam': + ctx.save(); ctx.rotate(ang); + ctx.beginPath(); ctx.moveTo(r * 1.25, 0); ctx.lineTo(-r, r * 0.9); ctx.lineTo(-r, -r * 0.9); ctx.closePath(); + ctx.fillStyle = col; ctx.fill(); ctx.restore(); + break; + case 'ghost': { + const bob = Math.sin(t * 5 + m.id) * 2; + ctx.translate(0, -7 + bob); + ctx.globalAlpha = 0.72 + Math.sin(t * 9 + m.id) * 0.18; + poly(ctx, 4, r * 1.25, Math.PI / 4); ctx.fillStyle = rgba(col, 0.28); ctx.fill(); + ctx.lineWidth = 2.2; ctx.strokeStyle = col; ctx.stroke(); + ctx.beginPath(); ctx.arc(0, 0, r * 0.42, 0, TAU); ctx.fillStyle = col; ctx.fill(); + ctx.globalAlpha = 1; + break; + } + case 'rootkit': { + ctx.save(); ctx.rotate(t * 0.6); + ctx.fillStyle = col; + for (let i = 0; i < 8; i++) { + ctx.rotate(TAU / 8); + ctx.beginPath(); ctx.moveTo(r * 0.8, -r * 0.18); ctx.lineTo(r * 1.28, 0); ctx.lineTo(r * 0.8, r * 0.18); ctx.closePath(); ctx.fill(); + } + ctx.restore(); + poly(ctx, 8, r, 0.39); ctx.fillStyle = '#240609'; ctx.fill(); + ctx.lineWidth = 3.2; ctx.strokeStyle = col; ctx.stroke(); + ctx.fillStyle = rgba('#ff3b3b', 0.55 + Math.sin(t * 4) * 0.3); ctx.beginPath(); ctx.arc(0, 0, r * 0.45, 0, TAU); ctx.fill(); + break; + } + default: + ctx.fillStyle = col; ctx.beginPath(); ctx.arc(0, 0, r, 0, TAU); ctx.fill(); + } + if (flash > 0) { ctx.globalAlpha = Math.min(0.85, flash * 9); ctx.fillStyle = '#fff'; ctx.beginPath(); ctx.arc(0, m.kind === 'ghost' ? -7 : 0, r * 1.05, 0, TAU); ctx.fill(); ctx.globalAlpha = 1; } + if (m.slow > 0) { ctx.lineWidth = 1.6; ctx.strokeStyle = 'rgba(77,227,255,.85)'; ctx.beginPath(); ctx.arc(0, m.kind === 'ghost' ? -7 : 0, r + 3.5, 0, TAU); ctx.stroke(); } + ctx.restore(); + // health bar + if (m.hp < m.maxhp) { + const w = Math.max(15, r * 2.3), y = -r - (m.kind === 'ghost' ? 16 : 9), x = -w / 2; + const f = clamp(m.hp / m.maxhp, 0, 1); + ctx.save(); ctx.translate(m.x * C, m.y * C); if (rot) ctx.rotate(-rot); + ctx.fillStyle = 'rgba(0,0,0,.65)'; ctx.fillRect(x - 1, y - 1, w + 2, 5); + ctx.fillStyle = f > 0.5 ? '#35e0a1' : f > 0.25 ? '#ffd24d' : '#ff5c7a'; + ctx.fillRect(x, y, w * f, 3); + ctx.restore(); + } + } + + // ------------------------------------------------------------------ renderer + class Renderer { + constructor(canvas) { + this.cv = canvas; + this.ctx = canvas.getContext('2d', { alpha: false }); + this.W = 300; this.H = 200; this.dpr = 1; + this.cam = { zoom: 1, px: 0, py: 0 }; + this.board = null; + this.parts = []; this.rings = []; this.lines = []; this.texts = []; this.marks = []; + this.aim = new Map(); this.trk = new Map(); + this.wallGrid = null; + this.shake = 0; this.flashCore = 0; this.lastNow = 0; + this.rot = 0; // 0, or PI/2 when the board is drawn rotated for portrait screens + this.fx = (root.matchMedia && root.matchMedia('(pointer: coarse)').matches) ? 0.55 : 1; // fewer particles on phones + this.names = {}; + } + + setBoard(board) { + this.board = board; + this.wallGrid = new Uint8Array(board.cols * board.rows); + this.parts.length = 0; this.rings.length = 0; this.lines.length = 0; this.texts.length = 0; this.marks.length = 0; + this.aim.clear(); this.trk.clear(); + this.resetCamera(); + } + resize(w, h, dpr) { + this.W = Math.max(50, w); this.H = Math.max(50, h); this.dpr = dpr || 1; + this.cv.width = Math.round(this.W * this.dpr); this.cv.height = Math.round(this.H * this.dpr); + this._layout(); + } + resetCamera() { this.cam.zoom = 1; this.cam.px = 0; this.cam.py = 0; this._layout(); } + get zoom() { return this.cam.zoom; } + + setRotation(on) { + const r = on ? Math.PI / 2 : 0; + if (r === this.rot) return; + this.rot = r; this.cam.zoom = 1; this.cam.px = 0; this.cam.py = 0; this._layout(); + } + _dims() { + const b = this.board; + return this.rot ? { w: b.rows * C, h: b.cols * C } : { w: b.cols * C, h: b.rows * C }; + } + _layout() { + const b = this.board; if (!b) return; + const d = this._dims(), pad = 4; + this.fit = Math.min((this.W - pad * 2) / d.w, (this.H - pad * 2) / d.h); + this.scale = this.fit * this.cam.zoom; + 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; + this.cam.px = clamp(this.cam.px, -mx, mx); this.cam.py = clamp(this.cam.py, -my, my); + this.ox = (this.W - sw) / 2 + this.cam.px; this.oy = (this.H - sh) / 2 + this.cam.py; + } + // CSS px <-> world px (world is always unrotated: 40 px per cell) + _s2w(sx, sy) { + const u = (sx - this.ox) / this.scale, v = (sy - this.oy) / this.scale; + return this.rot ? { x: v, y: this.board.rows * C - u } : { x: u, y: v }; + } + _w2s(wx, wy) { + return this.rot + ? { x: this.ox + (this.board.rows * C - wy) * this.scale, y: this.oy + wx * this.scale } + : { x: this.ox + wx * this.scale, y: this.oy + wy * this.scale }; + } + setZoom(z, ax, ay) { + z = clamp(z, 1, 4); + const w = this._s2w(ax, ay); + this.cam.zoom = z; this._layout(); + const s = this._w2s(w.x, w.y); + this.cam.px += ax - s.x; this.cam.py += ay - s.y; + this._layout(); + } + panBy(dx, dy) { this.cam.px += dx; this.cam.py += dy; this._layout(); } + // CSS px (relative to the canvas) -> cell coordinates + screenToCell(sx, sy) { + const w = this._s2w(sx, sy), fx = w.x / C, fy = w.y / C; + 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); } + cellSizePx() { return C * this.scale; } + + // ---------------------------------------------------------------- effects + _burst(x, y, col, n, speed, life) { + n = Math.max(1, Math.round(n * this.fx)); + if (this.parts.length > 260) return; + for (let i = 0; i < n; i++) { + const a = Math.random() * TAU, s = (0.4 + Math.random()) * speed; + this.parts.push({ x, y, vx: Math.cos(a) * s, vy: Math.sin(a) * s, life: life * (0.6 + Math.random() * 0.6), max: life, s: 2 + Math.random() * 2.5, c: col }); + } + } + _ring(x, y, r0, r1, col, life, w) { if (this.rings.length < 40) this.rings.push({ x, y, r0, r1, col, life, max: life, w: w || 2 }); } + _text(x, y, txt, col) { if (this.texts.length < 24) this.texts.push({ x, y, txt, col, life: 0.9, max: 0.9 }); } + addMark(x, y, slot) { this.marks.push({ x, y, slot: slot | 0, life: 1.6, max: 1.6 }); if (this.marks.length > 12) this.marks.shift(); } + addEvents(evs) { + for (const e of evs) { + switch (e.e) { + case 'kill': { + const d = TD.ENEMIES[e.k]; + this._burst(e.x * C, e.y * C, d ? d.color : '#fff', e.k === 'rootkit' ? 26 : 6, 90, 0.5); + if (e.rw >= 3) this._text(e.x * C, e.y * C - 8, '+' + e.rw, '#ffd24d'); + break; + } + case 'leak': { + const b = this.board; + this.flashCore = 1; this.shake = Math.min(2, this.shake + 0.9); + if (b) this._ring((b.core.x + 0.5) * C, (b.core.y + 0.5) * C, 10, 48, '#ff5c7a', 0.5, 3); + break; + } + case 'boom': this._ring(e.x * C, e.y * C, 4, e.r * C, '#d4f04a', 0.32, 3); this._burst(e.x * C, e.y * C, '#d4f04a', 8, 110, 0.4); break; + case 'shot': + if (e.k === 'ids') this.lines.push({ pts: [[e.x * C, e.y * C], [e.tx * C, e.ty * C]], col: '#b78cff', w: 2.5, life: 0.16, max: 0.16, jit: 0 }); + 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); + 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 'sell': this._burst((e.x + 0.5) * C, (e.y + 0.5) * C, '#9db4d8', 6, 70, 0.35); break; + case 'up': this._ring((e.x + 0.5) * C, (e.y + 0.5) * C, 6, 38, '#ffffff', 0.4, 2.5); break; + default: break; + } + } + } + + // ---------------------------------------------------------------- frame + // ui: { hover:{x,y}|null, selType, selTower, preview, valid, coop, mySlot, names:{slot:name} } + frame(now, view, ui) { + const b = this.board; if (!b) return; + const ctx = this.ctx, dpr = this.dpr; + const t = now / 1000; + const dt = clamp((now - (this.lastNow || now)) / 1000, 0, 0.1); this.lastNow = now; + const sc = this.scale; + + ctx.setTransform(dpr, 0, 0, dpr, 0, 0); + ctx.fillStyle = BG; ctx.fillRect(0, 0, this.W, this.H); + + let shx = 0, shy = 0; + if (this.shake > 0.02) { shx = (Math.random() - 0.5) * this.shake * 5; shy = (Math.random() - 0.5) * this.shake * 5; this.shake *= Math.pow(0.02, dt); } + const rot = this.rot; + if (rot) ctx.setTransform(0, dpr * sc, -dpr * sc, 0, dpr * (this.ox + shx + b.rows * C * sc), dpr * (this.oy + shy)); + else ctx.setTransform(dpr * sc, 0, 0, dpr * sc, dpr * (this.ox + shx), dpr * (this.oy + shy)); + + const cols = b.cols, rows = b.rows; + // board plate + ctx.fillStyle = BOARD; ctx.fillRect(0, 0, cols * C, rows * C); + ctx.lineWidth = 1 / sc * 1.5; ctx.strokeStyle = 'rgba(77,227,255,.35)'; ctx.strokeRect(0, 0, cols * C, rows * C); + // grid + ctx.lineWidth = 1 / sc; ctx.strokeStyle = 'rgba(80,150,255,.10)'; + ctx.beginPath(); + for (let x = 1; x < cols; x++) { ctx.moveTo(x * C, 0); ctx.lineTo(x * C, rows * C); } + for (let y = 1; y < rows; y++) { ctx.moveTo(0, y * C); ctx.lineTo(cols * C, y * C); } + ctx.stroke(); + ctx.fillStyle = 'rgba(120,200,255,.22)'; + ctx.beginPath(); + for (let y = 0; y <= rows; y++) for (let x = 0; x <= cols; x++) ctx.rect(x * C - 1.2, y * C - 1.2, 2.4, 2.4); + ctx.fill(); + + // dead nodes + for (let y = 0; y < rows; y++) for (let x = 0; x < cols; x++) { + if (!b.obst[y * cols + x]) continue; + const px = x * C, py = y * C; + ctx.fillStyle = '#121828'; rr(ctx, px + 4, py + 4, C - 8, C - 8, 6); ctx.fill(); + ctx.lineWidth = 1.5; ctx.strokeStyle = '#2b3556'; ctx.stroke(); + ctx.strokeStyle = 'rgba(255,92,122,.32)'; ctx.lineWidth = 2; + ctx.beginPath(); ctx.moveTo(px + 12, py + 12); ctx.lineTo(px + C - 12, py + C - 12); ctx.moveTo(px + C - 12, py + 12); ctx.lineTo(px + 12, py + C - 12); ctx.stroke(); + } + + this._drawRoutes(ctx, b, ui, t); + this._drawEndpoints(ctx, b, view, t, dt, rot); + + // walls (with trace links) then turrets + const wg = this.wallGrid; wg.fill(0); + const towers = view.towers; + for (let i = 0; i < towers.length; i++) if (towers[i].type === 'wall') wg[towers[i].y * cols + towers[i].x] = 1; + ctx.lineCap = 'round'; + ctx.strokeStyle = 'rgba(90,169,255,.55)'; ctx.lineWidth = 3.2; + ctx.beginPath(); + for (let i = 0; i < towers.length; i++) { + const w = towers[i]; if (w.type !== 'wall') continue; + const cx = (w.x + 0.5) * C, cy = (w.y + 0.5) * C; + if (w.x + 1 < cols && wg[w.y * cols + w.x + 1]) { ctx.moveTo(cx, cy); ctx.lineTo(cx + C, cy); } + if (w.y + 1 < rows && wg[(w.y + 1) * cols + w.x]) { ctx.moveTo(cx, cy); ctx.lineTo(cx, cy + C); } + } + ctx.stroke(); + ctx.strokeStyle = 'rgba(90,169,255,.32)'; ctx.lineWidth = 2; + ctx.beginPath(); + for (let i = 0; i < towers.length; i++) { + const w = towers[i]; if (w.type !== 'wall') continue; + const cx = (w.x + 0.5) * C, cy = (w.y + 0.5) * C; + if (w.x + 1 < cols && w.y + 1 < rows && wg[(w.y + 1) * cols + w.x + 1]) { ctx.moveTo(cx, cy); ctx.lineTo(cx + C, cy + C); } + if (w.x > 0 && w.y + 1 < rows && wg[(w.y + 1) * cols + w.x - 1]) { ctx.moveTo(cx, cy); ctx.lineTo(cx - C, cy + C); } + } + ctx.stroke(); + + // monster lookup for aiming + const monById = new Map(); + for (let i = 0; i < view.monsters.length; i++) monById.set(view.monsters[i].id, view.monsters[i]); + + const coop = ui.coop; + for (let i = 0; i < towers.length; i++) { + const tw = towers[i]; + let ang = this.aim.get(tw.id); + if (ang === undefined) ang = -Math.PI / 2; + const tg = tw.tgt ? monById.get(tw.tgt) : null; + 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; + drawGlyph(ctx, tw.type, tw.level, cx, cy, C, ang, t, 1, rot); + if (coop && tw.type !== 'wall') { + ctx.fillStyle = SLOT_COLORS[tw.owner] || '#fff'; + 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(); + } + } + 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); } + + // selection and ranges + if (ui.selTower) { + const st = towers.find((x) => x.id === ui.selTower); + if (st) { + const def = TD.TOWERS[st.type], lv = def.levels[st.level - 1]; + const cx = (st.x + 0.5) * C, cy = (st.y + 0.5) * C; + if (lv.range) this._rangeRing(ctx, cx, cy, lv.range * C, def.color); + ctx.strokeStyle = '#fff'; ctx.lineWidth = 2; const k = 3 + Math.sin(t * 5) * 1.2, h = C / 2 + k; + ctx.beginPath(); + for (const [sx, sy] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) { ctx.moveTo(cx + sx * h, cy + sy * (h - 9)); ctx.lineTo(cx + sx * h, cy + sy * h); ctx.lineTo(cx + sx * (h - 9), cy + sy * h); } + ctx.stroke(); + } + } + + // ground monsters, then flyers on top + this._drawMonsters(ctx, view, t, dt, false, rot); + this._drawMonsters(ctx, view, t, dt, true, rot); + + // bullets + for (const bu of view.bullets) { + if (bu.k === 'mortar') { + ctx.fillStyle = 'rgba(0,0,0,.35)'; ctx.beginPath(); ctx.arc(bu.x * C, bu.y * C + 5, 4, 0, TAU); ctx.fill(); + ctx.fillStyle = '#d4f04a'; ctx.beginPath(); ctx.arc(bu.x * C, bu.y * C - 2, 4.5, 0, TAU); ctx.fill(); + } else { + ctx.fillStyle = 'rgba(53,224,161,.3)'; ctx.beginPath(); ctx.arc(bu.x * C, bu.y * C, 6, 0, TAU); ctx.fill(); + ctx.fillStyle = '#d6fff0'; ctx.beginPath(); ctx.arc(bu.x * C, bu.y * C, 2.6, 0, TAU); ctx.fill(); + } + } + + this._drawFx(ctx, dt, sc, rot); + + // placement ghost + if (ui.hover && ui.selType && !ui.noGhost && b.inBounds(ui.hover.x, ui.hover.y)) { + const def = TD.TOWERS[ui.selType], lv = def.levels[0]; + const cx = (ui.hover.x + 0.5) * C, cy = (ui.hover.y + 0.5) * C; + const ok = ui.valid !== false; + if (lv.range) this._rangeRing(ctx, cx, cy, lv.range * C, ok ? def.color : '#ff5c7a'); + drawGlyph(ctx, ui.selType, 1, cx, cy, C, -Math.PI / 2 - rot, t, ok ? 0.7 : 0.4, rot); + if (!ok) { + ctx.fillStyle = 'rgba(255,60,90,.28)'; ctx.fillRect(ui.hover.x * C + 2, ui.hover.y * C + 2, C - 4, C - 4); + ctx.strokeStyle = '#ff5c7a'; ctx.lineWidth = 3; ctx.beginPath(); + ctx.moveTo(cx - 9, cy - 9); ctx.lineTo(cx + 9, cy + 9); ctx.moveTo(cx + 9, cy - 9); ctx.lineTo(cx - 9, cy + 9); ctx.stroke(); + } else { + ctx.strokeStyle = rgba(def.color, 0.9); ctx.lineWidth = 2; rr(ctx, ui.hover.x * C + 2, ui.hover.y * C + 2, C - 4, C - 4, 6); ctx.stroke(); + } + } else if (ui.hover && (!ui.selType || ui.noGhost) && b.inBounds(ui.hover.x, ui.hover.y)) { + ctx.strokeStyle = 'rgba(255,255,255,.22)'; ctx.lineWidth = 1.5; ctx.strokeRect(ui.hover.x * C + 1, ui.hover.y * C + 1, C - 2, C - 2); + } + + // partner cursors and pings + ctx.font = '600 ' + (11 / sc) + 'px system-ui, sans-serif'; ctx.textBaseline = 'middle'; + for (const cu of view.cursors || []) { + 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); + const nm = (ui.names && ui.names[cu.slot]) || 'Partner'; + 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--) { + const m = this.marks[i]; m.life -= dt; + if (m.life <= 0) { this.marks.splice(i, 1); continue; } + const k = 1 - m.life / m.max, col = SLOT_COLORS[m.slot] || '#fff'; + ctx.strokeStyle = col; ctx.lineWidth = 3; + for (let j = 0; j < 3; j++) { + const kk = k - j * 0.16; if (kk <= 0) continue; + ctx.globalAlpha = (1 - kk) * 0.9; ctx.beginPath(); ctx.arc((m.x + 0.5) * C, (m.y + 0.5) * C, 6 + kk * 46, 0, TAU); ctx.stroke(); + } + 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(); + } + } + + _rangeRing(ctx, cx, cy, r, col) { + ctx.fillStyle = rgba(col, 0.07); ctx.beginPath(); ctx.arc(cx, cy, r, 0, TAU); ctx.fill(); + ctx.strokeStyle = rgba(col, 0.55); ctx.lineWidth = 1.5; ctx.stroke(); + } + + _drawRoutes(ctx, b, ui, t) { + const pv = ui && ui.preview && ui.preview.ok && ui.preview.routes; + const dash = (col, w, speed) => { ctx.strokeStyle = col; ctx.lineWidth = w; ctx.setLineDash([9, 9]); ctx.lineDashOffset = -t * speed; }; + ctx.lineJoin = 'round'; ctx.lineCap = 'round'; + dash(pv ? 'rgba(77,227,255,.10)' : 'rgba(77,227,255,.34)', 3, 34); + for (const r of b.routes) { + ctx.beginPath(); + for (let i = 0; i < r.length; i++) { const px = (r[i][0] + 0.5) * C, py = (r[i][1] + 0.5) * C; i ? ctx.lineTo(px, py) : ctx.moveTo(px, py); } + ctx.stroke(); + } + if (pv) { + dash('rgba(255,210,77,.85)', 3.6, 60); + for (const r of ui.preview.routes) { + ctx.beginPath(); + for (let i = 0; i < r.length; i++) { const px = (r[i][0] + 0.5) * C, py = (r[i][1] + 0.5) * C; i ? ctx.lineTo(px, py) : ctx.moveTo(px, py); } + ctx.stroke(); + } + } + ctx.setLineDash([]); + } + + _drawEndpoints(ctx, b, view, t, dt, rot) { + // spawns: red gateways + for (const sp of b.spawns) { + const p = (t * 0.7) % 1; + ctx.save(); ctx.translate((sp.x + 0.5) * C, (sp.y + 0.5) * C); if (rot) ctx.rotate(-rot); + ctx.strokeStyle = rgba('#ff5c7a', 0.5 * (1 - p)); ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(0, 0, 12 + p * 16, 0, TAU); ctx.stroke(); + ctx.fillStyle = '#2a0c18'; ctx.beginPath(); ctx.arc(0, 0, 13, 0, TAU); ctx.fill(); + ctx.strokeStyle = '#ff5c7a'; ctx.lineWidth = 2; ctx.stroke(); + ctx.lineWidth = 1.3; ctx.beginPath(); ctx.ellipse(0, 0, 5.5, 13, 0, 0, TAU); ctx.moveTo(-13, 0); ctx.lineTo(13, 0); ctx.stroke(); + ctx.restore(); + } + // core: server rack with an integrity ring + const c = b.core; + const frac = view.maxLives ? clamp(view.lives / view.maxLives, 0, 1) : 1; + const col = frac > 0.5 ? '#35e0a1' : frac > 0.25 ? '#ffd24d' : '#ff5c7a'; + this.flashCore = Math.max(0, this.flashCore - dt * 2.2); + ctx.save(); ctx.translate((c.x + 0.5) * C, (c.y + 0.5) * C); if (rot) ctx.rotate(-rot); + ctx.strokeStyle = 'rgba(255,255,255,.08)'; ctx.lineWidth = 4; ctx.beginPath(); ctx.arc(0, 0, 25, 0, TAU); ctx.stroke(); + ctx.strokeStyle = col; ctx.lineWidth = 4; ctx.beginPath(); ctx.arc(0, 0, 25, -Math.PI / 2, -Math.PI / 2 + TAU * frac); ctx.stroke(); + if (this.flashCore > 0) { ctx.fillStyle = 'rgba(255,60,90,' + (this.flashCore * 0.4) + ')'; ctx.beginPath(); ctx.arc(0, 0, 29, 0, TAU); ctx.fill(); } + ctx.fillStyle = '#0d2038'; rr(ctx, -13, -16, 26, 32, 5); ctx.fill(); + ctx.strokeStyle = '#4de3ff'; ctx.lineWidth = 2; ctx.stroke(); + ctx.lineWidth = 1.5; ctx.beginPath(); + for (let i = 0; i < 3; i++) { ctx.moveTo(-9, -9 + i * 8); ctx.lineTo(3, -9 + i * 8); } + ctx.stroke(); + for (let i = 0; i < 3; i++) { ctx.fillStyle = (Math.floor(t * 3 + i * 1.7) % 2) ? col : rgba(col, 0.35); ctx.beginPath(); ctx.arc(8, -9 + i * 8, 2, 0, TAU); ctx.fill(); } + ctx.restore(); + } + + _drawMonsters(ctx, view, t, dt, air, rot) { + const trk = this.trk; + for (const m of view.monsters) { + if (!!m.air !== air) continue; + let k = trk.get(m.id); + if (!k) { k = { x: m.x, y: m.y, ang: 0, hp: m.hp, flash: 0 }; trk.set(m.id, k); } + const dx = m.x - k.x, dy = m.y - k.y; + if (dx * dx + dy * dy > 1e-6) k.ang = lerpAngle(k.ang, Math.atan2(dy, dx), 0.35); + k.x = m.x; k.y = m.y; + if (m.hp < k.hp) k.flash = 0.1; + k.hp = m.hp; k.flash = Math.max(0, k.flash - dt); + if (air) { const er = TD.ENEMIES[m.kind].r * C; ctx.fillStyle = 'rgba(0,0,0,.28)'; ctx.save(); ctx.translate(m.x * C, m.y * C); if (rot) ctx.rotate(-rot); ctx.beginPath(); ctx.ellipse(0, 5, er, er * 0.45, 0, 0, TAU); ctx.fill(); ctx.restore(); } + drawMonster(ctx, m, k.ang, t, k.flash, rot); + } + if (air && trk.size > view.monsters.length + 60) { // drop stale trackers + const live = new Set(view.monsters.map((x) => x.id)); + for (const id of trk.keys()) if (!live.has(id)) trk.delete(id); + } + } + + _drawFx(ctx, dt, sc, rot) { + // lines (tracers, arcs) + ctx.lineCap = 'round'; ctx.lineJoin = 'round'; + for (let i = this.lines.length - 1; i >= 0; i--) { + const l = this.lines[i]; l.life -= dt; + if (l.life <= 0) { this.lines.splice(i, 1); continue; } + ctx.globalAlpha = l.life / l.max; ctx.strokeStyle = l.col; ctx.lineWidth = l.w; + ctx.beginPath(); + for (let j = 0; j < l.pts.length; j++) { + const jx = l.jit && j > 0 ? (Math.random() - 0.5) * l.jit * 2 : 0, jy = l.jit && j > 0 ? (Math.random() - 0.5) * l.jit * 2 : 0; + j ? ctx.lineTo(l.pts[j][0] + jx, l.pts[j][1] + jy) : ctx.moveTo(l.pts[j][0], l.pts[j][1]); + } + ctx.stroke(); + } + ctx.globalAlpha = 1; + for (let i = this.rings.length - 1; i >= 0; i--) { + const r = this.rings[i]; r.life -= dt; + if (r.life <= 0) { this.rings.splice(i, 1); continue; } + const k = 1 - r.life / r.max; + ctx.globalAlpha = 1 - k; ctx.strokeStyle = r.col; ctx.lineWidth = r.w; + ctx.beginPath(); ctx.arc(r.x, r.y, r.r0 + (r.r1 - r.r0) * k, 0, TAU); ctx.stroke(); + } + ctx.globalAlpha = 1; + for (let i = this.parts.length - 1; i >= 0; i--) { + const p = this.parts[i]; p.life -= dt; + if (p.life <= 0) { this.parts.splice(i, 1); continue; } + p.x += p.vx * dt; p.y += p.vy * dt; p.vx *= 0.94; p.vy *= 0.94; + ctx.globalAlpha = Math.min(1, p.life / p.max * 1.4); ctx.fillStyle = p.c; + ctx.fillRect(p.x - p.s / 2, p.y - p.s / 2, p.s, p.s); + } + ctx.globalAlpha = 1; + if (this.texts.length) { + ctx.font = '700 ' + (12 / sc) + 'px ui-monospace, monospace'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + for (let i = this.texts.length - 1; i >= 0; i--) { + const x = this.texts[i]; x.life -= dt; + if (x.life <= 0) { this.texts.splice(i, 1); continue; } + if (rot) x.x -= 22 * dt; else x.y -= 22 * dt; // drift towards the top of the screen + ctx.globalAlpha = Math.min(1, x.life / x.max * 1.6); ctx.fillStyle = x.col; + ctx.save(); ctx.translate(x.x, x.y); if (rot) ctx.rotate(-rot); ctx.fillText(x.txt, 0, 0); ctx.restore(); + } + ctx.globalAlpha = 1; ctx.textAlign = 'start'; + } + } + } + + // Draw a tower icon into a small canvas (palette buttons, info panel) + function drawIcon(canvas, type, level) { + const dpr = Math.min(2, root.devicePixelRatio || 1), size = canvas.clientWidth || 34; + canvas.width = canvas.height = Math.round(size * dpr); + const ctx = canvas.getContext('2d'); + ctx.setTransform(dpr, 0, 0, dpr, 0, 0); + ctx.clearRect(0, 0, size, size); + drawGlyph(ctx, type, level || 1, size / 2, size / 2, size * 1.1, -0.6, 0.3, 1); + } + + NW.Renderer = Renderer; + NW.drawIcon = drawIcon; + NW.drawGlyph = drawGlyph; + NW.SLOT_COLORS = SLOT_COLORS; + NW.CELL = C; +})(typeof self !== 'undefined' ? self : this); diff --git a/public/js/sim.js b/public/js/sim.js new file mode 100644 index 0000000..a08c33f --- /dev/null +++ b/public/js/sim.js @@ -0,0 +1,819 @@ +/* + * NETWALL - shared simulation core. + * + * Pure game logic, no DOM, no timers. Loaded as a classic