Wrap up: review findings, balance baseline, bot tool and next-session notes
- docs/NEXT.md: where to pick up, prioritised, with the known wall-selling bug and its two-line fix - docs/review-2026-10-09/: 85 reviewer findings (touch, co-op, client code, visual, reverse proxy) with verification status, repro scripts archive and the review workflow script; nothing fixed yet by design - docs/BALANCE.md + tools/bot.js: headless balance bot and the untuned baseline (IDS Sniper dominates, maze is a near-guaranteed win, credits snowball) - test/sim.test.js derives tunable numbers from the tables, plus a shape test - README status note Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
This commit is contained in:
parent
45dea022ae
commit
72c49eee1f
8 changed files with 2187 additions and 9 deletions
|
|
@ -14,6 +14,10 @@ a decision.
|
|||
partner cursors and map pings. Needs the small Node server in this repo.
|
||||
* No build step, no framework, no external requests. Vanilla JS + canvas.
|
||||
|
||||
> **Status:** playable, but a review pass found bugs that are not fixed yet (for example, a placed Firewall cannot be
|
||||
> sold because selecting it throws). The full list, balance analysis and the plan for the next session are in
|
||||
> [docs/NEXT.md](docs/NEXT.md).
|
||||
|
||||
## Run it
|
||||
|
||||
```bash
|
||||
|
|
|
|||
64
docs/BALANCE.md
Normal file
64
docs/BALANCE.md
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
# Balance notes (baseline measured 2026-10-09, nothing tuned yet)
|
||||
|
||||
`public/js/sim.js` still holds my first-guess numbers. A balance engineer agent built `tools/bot.js` (a headless player that
|
||||
drives the sim through `sim.cmd()` / `sim.preview()`) and measured the untouched numbers; it was stopped before it applied any
|
||||
tuning. `test/sim.test.js` was already updated by it so that no test hard-codes a tunable number (they derive values from
|
||||
the `TOWERS` / `ENEMIES` tables), plus one test that pins the table *shape* the client and server depend on.
|
||||
|
||||
## Re-running the measurement
|
||||
|
||||
```bash
|
||||
node tools/bot.js --maps open,twin,hub \
|
||||
--strategies maze,nomaze,spam-filter,spam-ids,spam-mortar,spam-arc,lazy,maze-no-ids,maze-no-filter,maze-no-mortar,maze-no-throttle,maze-no-arc \
|
||||
--seeds 8 --max 45
|
||||
```
|
||||
(runs on all cores; `--sim other/sim.js` measures another copy; `--json out.json --detail` for raw games.) Strategies: `maze`
|
||||
(the mixed build), `nomaze`, `spam-<type>` (maze + one turret type), `maze-no-<type>` (ablation), `lazy`.
|
||||
|
||||
## Baseline results (8 seeds, waves up to 45; "win" = survived to wave 45)
|
||||
|
||||
| strategy | open | twin | hub |
|
||||
|---|---|---|---|
|
||||
| maze (mixed) | 8/8 win | 6/8 | 8/8 |
|
||||
| nomaze | 7/8 (dies ~wave 29-43) | 0/8 (wave 29-30) | 0/8 (wave 29) |
|
||||
| spam-ids | **8/8 win** | **8/8 win** | **8/8 win** |
|
||||
| spam-filter | 0/8 (wave 14-28) | 0/8 | 0/8 |
|
||||
| spam-mortar | 0/8 (wave 8) | 0/8 (wave 6-8) | 0/8 (wave 6-7) |
|
||||
| spam-arc | 0/8 (wave 14-22) | 0/8 | 0/8 |
|
||||
| maze without IDS | 0/8 (wave 14-29) | 0/8 | 0/8 |
|
||||
| maze without filter / throttle / arc | still wins (7-8 of 8) | still wins (7-8 of 8) | still wins (7-8 of 8) |
|
||||
| lazy | dies wave 8-9 | wave 3-4 | wave 6 |
|
||||
|
||||
Route length at wave 30 with the maze strategy, per gateway: about 150 cells on open, ~165 on twin and ~136 on hub, versus
|
||||
roughly 25 for the unobstructed path (the bot reports the sum over gateways: 150 / 330 / 409). Credits at wave 30: about 280 unspent.
|
||||
|
||||
## What the numbers say
|
||||
|
||||
1. **IDS Sniper is mandatory and sufficient.** Every build without it collapses around wave 15-28; a maze + IDS-only
|
||||
build wins everything on every map. That breaks the design goal that no single tower dominates and that flyers/armour
|
||||
force a mixed defence. IDS needs a cost/damage/range nerf, or the other towers need real roles (Mortar and Arc are
|
||||
far too weak on their own: they die by wave 8 / 15-22).
|
||||
2. **The maze is a near-guaranteed win.** Cheap 5-credit walls stretch routes about 5 to 6 times, and the game is too easy
|
||||
once you do it. Mazing should be rewarding but not a solved game. Candidate levers (a design decision, see NEXT.md):
|
||||
escalating wall price (for example +1 credit per 10 walls), a wall cap, faster late waves, or armour/regen that punishes
|
||||
long exposure.
|
||||
3. **No-maze is too viable on open** (reaches wave 29-43). Early waves are too gentle, or turrets too strong without a maze.
|
||||
4. **Economy snowballs** (about 280 credits unspent at wave 30) while the early game is tight (about 30-45 credits spare
|
||||
around waves 5-10). Cut late-game rewards or add sinks (upgrade costs, escalating prices).
|
||||
5. Throttle, Filter and Arc individually add little (removing any one still wins): either buff their roles or accept they
|
||||
are support pieces.
|
||||
|
||||
## Targets the tuning should hit (from the original brief)
|
||||
|
||||
* Maze clearly beats no-maze; no-maze still survives the first 8-10 waves; lazy dies early.
|
||||
* On `open`, a good maze build wins wave 30 in most seeds with a few lives to spare but not with a perfect record; no leaks
|
||||
in waves 1-5.
|
||||
* `twin` harder than `open`; `hub` hardest (maze build reaching roughly waves 24-30).
|
||||
* Every single-tower spam strategy loses before wave 30 on `open`; every tower type is part of the best mixed build at least
|
||||
sometimes. Flyer waves must punish a defence without anti-air, boss/Trojan waves must punish pure Filter spam.
|
||||
* Credits neither snowball nor starve.
|
||||
|
||||
Only constants and tables in `sim.js` should need to change (costs, damage, range, rates, enemy hp/speed/armor/reward,
|
||||
`waveGroups` counts, `hpScale`, `rewardScale`, `START_GOLD`, `SELL_RATIO`). Keep every table key, the 3-entry `levels`
|
||||
arrays and the field names: the client UI and the server read them. A wall price escalation would be a logic change in
|
||||
`Sim.place` and in the client's cost display.
|
||||
79
docs/NEXT.md
Normal file
79
docs/NEXT.md
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
# Where to pick up (written 2026-10-09)
|
||||
|
||||
Netwall is playable and pushed: solo (desktop + phone), two-player co-op through the Node server, music, PWA, deploy docs.
|
||||
Development was paused on purpose before the fix stage. This file is the entry point for the next session.
|
||||
|
||||
## State of the repo
|
||||
|
||||
| Area | State |
|
||||
|---|---|
|
||||
| `public/js/sim.js` | Shared rules. 20 unit tests. **Balance not tuned yet** (see `docs/BALANCE.md`). |
|
||||
| `server/` | Done and reviewed by an independent adversarial pass (5 real issues found and fixed: pid leak/slot hijack, room-flood lockout, spoofable X-Forwarded-For, startup crash in restricted sandboxes, clock-step in rate limiter). 59 tests. |
|
||||
| `public/` client | Works, but a second review pass found many issues. **None fixed yet.** See `docs/review-2026-10-09/findings.md`. |
|
||||
| `e2e/` | `npm run e2e`: smoke, touch, end flow, co-op (two browsers incl. reconnect), 14-size layout matrix. All passed at the last run. |
|
||||
| `tools/bot.js` | Headless balance bot (dev tool). Complete; its results are summarised in `docs/BALANCE.md`. |
|
||||
| Deploy | `docs/DEPLOY.md`, `deploy/netwall.service`, README setup guide. Never run against a real nginx Proxy Manager or on a phone yet (an NPM-style review found doc inaccuracies, listed in the findings). |
|
||||
|
||||
`npm test` = 80 passing (20 sim + 59 server + 1 balance-table shape test). Verified from a fresh `git clone`.
|
||||
|
||||
## KNOWN BUG in the pushed build (fix first, it is two lines)
|
||||
|
||||
**Selecting a placed Firewall throws a TypeError, so walls cannot be sold** (finding `visual-1`, confirmed).
|
||||
Cause: `renderInfo()` in `public/js/main.js` assumes every tower has 3 levels (`tower.level < 3`), but a wall has one
|
||||
level, so `statsFor(type, i + 1)` and `def.levels[tower.level].cost` read `levels[1]`, which is `undefined`. Use
|
||||
`tower.level < def.levels.length` in both places (and for the `up` button / `updateInfoDynamic`). Add an e2e assertion:
|
||||
build a wall, tap it, tap Sell, check the credits.
|
||||
|
||||
## Suggested order of work
|
||||
|
||||
1. **The wall bug above**, then the other confirmed high/medium client bugs:
|
||||
* `code-2`: the info panel is rebuilt with `innerHTML` on every `view.rev` change, so an Upgrade/Sell/Target tap that
|
||||
lands during a rebuild is lost (worse in co-op, where the partner's actions bump `rev`). Update in place or rebuild
|
||||
only when this tower's signature changes.
|
||||
* `coop-1` / `code-1`: `RemoteController` keeps only the last 10 snapshots; a render stall of ~0.5 to 1 s drops snapshots
|
||||
that carry `tw` (tower list) before they are displayed, so the partner's new towers are lost until a resync. Never
|
||||
discard an entry whose `tw` has not been applied (or apply `tw` to the mirror on arrival and only delay the drawn list).
|
||||
* `touch-1`, `touch-2`: with a wall armed, the first finger of a pinch builds a wall immediately; with a turret armed
|
||||
it moves the pending placement. Defer the first placement to pointerup/first real move and cancel on a second pointer.
|
||||
* Phone layout: after tapping a tower the Upgrade/Sell/Target buttons are below the fold (`visual-2`, `touch-3`); on small
|
||||
phones the first-run Help has no visible "Got it" (`visual-3`) and the co-op room code and Invite button are not
|
||||
visible while waiting for a partner (`visual-4`, `touch-8`). Likely fix: show the selected-tower panel as a bottom
|
||||
sheet over the palette, put room code/invite in the top bar or a toast, make overlays scroll with a sticky button row.
|
||||
* `coop-2`: after a half-open connection (Wi-Fi/cell switch) the UI looks alive but frozen for 47 to 65 s; show the
|
||||
reconnect overlay as soon as the watchdog fires and open a new socket without waiting for the old one to close.
|
||||
2. **Co-op correctness**: simultaneous Upgrade / Next Wave from both players are applied twice (`coop-5`: make upgrade
|
||||
idempotent, e.g. send the expected level; ignore a wave command within ~1 s of another), host-leaves-while-end-screen
|
||||
(`coop-3`, `code-11`), failed join from the menu kills the live game (`coop-4`), controller races (`code-3`, `code-4`).
|
||||
3. **Smaller UX/a11y**: reduced-motion hides every toast (`touch-5`, `visual-6`), Space held launches ~20 waves
|
||||
(`code-6`: ignore `e.repeat`), co-op music/stinger after Play again (`code-5`, `code-7`, `code-12`), touch target sizes,
|
||||
safe-area double padding, contrast, colour-only enemy legend, pause not obvious.
|
||||
4. **Proxy docs/behaviour** (`proxy-*` in the findings): 403 when the public URL has a non-default port (Origin vs Host
|
||||
port handling), DEPLOY.md claims NPM can send `X-Forwarded-Host` from the Advanced tab (it cannot), NPM's default read
|
||||
timeout is 90 s not 60 s, service worker serves nginx's 502 page instead of the cached app, path-prefix instructions for NPM.
|
||||
5. **Balance** (`docs/BALANCE.md`): the baseline shows the game is currently too easy and IDS Sniper dominates.
|
||||
6. Real-world checks that were never possible in the sandbox: a real phone (iOS Safari audio unlock, safe areas, wake
|
||||
lock), real nginx Proxy Manager with Let's Encrypt, a Proxmox LXC with the systemd unit.
|
||||
|
||||
Findings marked UNVERIFIED were reported with a reproduction but not yet independently re-checked (the verification
|
||||
stage was stopped); re-run the repro from `docs/review-2026-10-09/repro-scripts.tgz` before fixing.
|
||||
|
||||
## Decisions waiting for the user
|
||||
|
||||
* **Maze exploit.** A long serpentine of cheap walls (5 credits) makes routes about 5 to 6 times longer than the direct path.
|
||||
Options: escalating wall price, a wall cap, or faster/tougher waves. See `docs/BALANCE.md`.
|
||||
* **Room codes** are 4 characters (about 1M); a stranger could guess an open room. Options: 6 characters, an optional
|
||||
room password, per-IP rate limit on failed joins.
|
||||
* **Music size.** battle/boss/menu are 3 to 8 MB each and downloaded whole on first use; fine on Wi-Fi, heavy on mobile
|
||||
data. Could re-encode to mono ~48 kbps.
|
||||
|
||||
## Dev environment (what the session used, none of it is in the repo)
|
||||
|
||||
* The sandbox had no Node and no root. The user's machine can install anything: `apt install nodejs npm`, `npm install`,
|
||||
`npx playwright-core install chromium-headless-shell` (plus `npx playwright-core install-deps` as root) and `npm run e2e` is all that is needed.
|
||||
* The review pipeline (5 reviewers, a verifier per finding, one fixer, a final QA) was a Workflow script; a copy is in
|
||||
`docs/review-2026-10-09/phase2-workflow.js` and can be re-run (re-point its scratch paths) to verify the UNVERIFIED
|
||||
findings and to run the fix stage.
|
||||
* Conventions: `public/js/sim.js` must stay pure and DOM-free (it runs in the browser for solo and in Node for co-op); `ws` is the only
|
||||
runtime dependency; the client uses only relative URLs (works under a proxy path prefix); `test/` may only hold real test files
|
||||
(plain `node --test` runs everything there).
|
||||
* Git: commit and push at milestones is pre-authorised for this project.
|
||||
926
docs/review-2026-10-09/findings.md
Normal file
926
docs/review-2026-10-09/findings.md
Normal file
|
|
@ -0,0 +1,926 @@
|
|||
# Review findings, 2026-10-09
|
||||
|
||||
Five independent reviewers probed the running game in real browsers (Chromium via Playwright, CDP touch events) and against
|
||||
the real server; a second set of agents then tried to *refute* each finding. The pipeline was stopped before the fix stage,
|
||||
**so nothing below has been fixed yet** (except where noted). Status per finding:
|
||||
|
||||
* **CONFIRMED**: an independent verifier reproduced it.
|
||||
* **REFUTED**: a verifier could not reproduce it / judged it intended.
|
||||
* **UNVERIFIED**: reported by a reviewer with a repro, verification had not run yet (treat as likely, re-check before fixing).
|
||||
|
||||
Reviewer repro scripts (throwaway Playwright/ws scripts, with the hard-coded scratch paths they were written for) are in
|
||||
`repro-scripts.tgz` next to this file: `tar xzf repro-scripts.tgz` gives one folder per reviewer.
|
||||
|
||||
|
||||
## Summary
|
||||
|
||||
| Area | Confirmed | Refuted | Unverified |
|
||||
|---|---|---|---|
|
||||
| Touch UX on phones/tablets | 18 | 0 | 0 |
|
||||
| Co-op chaos / protocol races | 0 | 0 | 8 |
|
||||
| Client code review | 0 | 0 | 28 |
|
||||
| Visual / UX QA | 7 | 1 | 14 |
|
||||
| Reverse proxy (nginx / NPM) | 0 | 0 | 9 |
|
||||
|
||||
## Touch UX on phones/tablets (18 findings)
|
||||
|
||||
*Coverage:* Tested with real Chromium 156 (Playwright, --no-sandbox), real server on port 8210 (killed afterwards), CDP Input.dispatchTouchEvent touch plus isMobile/hasTouch emulation, pointer:coarse matched. Viewports: 375x667, 390x844, 412x915, 360x640, 320x568, 667x375, 844x390, 915x412, 768x1024, 1024x768, plus width/height sweeps 560-920 wide for the landscape top bar. Covered and OK: tap-preview then confirm bar, tap-same-cell-again and Cancel for all 6 types on 390x844 and 667x375 (all pass); wall drag painting (fast single-jump line, diagonal, dense stroke leaving the board and re-entering: only crossed cells get walls, gold exhaustion, route-seal rejection, pointercancel mid-paint and mid-pinch then fresh tap, pointercancel cancels long-press timer); cellToScreen/screenToCell round trips (0 wrong of 2080 per variant for zoom 1/2.3/3/4 with extreme pan, rotated and unrotated) and 30 real tap [...]
|
||||
|
||||
### touch-1 [HIGH] Firewall armed: any two-finger pinch/pan drops a wall under the first finger (5 credits)
|
||||
*Status:* **CONFIRMED** (verifier severity: medium)
|
||||
|
||||
- **Repro:** R=/tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/touch-ux ; start server on 8210 (PORT=8210 HOST=127.0.0.1 node server/index.js); source pwenv.sh; node $R/gestures.js i14 (first test). Manual: iPhone 14 390x844, Play solo, tap Firewall in palette, touchStart finger 1 on cell (8,6), 30 ms later add finger 2 on (12,6), spread both outward, lift.
|
||||
- **Observed:** walls 0 -> 1 and gold 140 -> 135 although the gesture was a pinch (zoom ended 1.47). Cause: canvas pointerdown (main.js ~L545) calls placeAt() for the first touch immediately when selType==='wall'; the ptrs.size===2 branch only sets painting=false afterwards, it cannot undo the placement. Every zoom/pan gesture with the main maze tool armed builds a stray wall (can lengthen/alter the route, and in co-op the partner sees it).
|
||||
- **Expected:** A two-finger gesture never builds. Walls should be committed on first move/pointerup (or after a ~60-80 ms delay that is cancelled when a 2nd pointer lands), like the long-press timer already is.
|
||||
- **Suggested fix:** For pointerType touch/pen with a wall armed: defer the first placeAt() to pointerup (if not moved and ptrs.size stayed 1) or to the first pointermove beyond slop; start painting only then. Cancel the deferral in the ptrs.size===2 branch.
|
||||
- **Verifier:** Reproduced with my own scripts (reviews/verify-touch/v1.js, v2.js, v3.js; server on 8210). Code: main.js pointerdown (L545-546) calls placeAt(cell) synchronously for the first touch when selType==='wall'. The ptrs.size===2 branch (L516-520) only does cancelLong(); painting=false; tapSelectOnUp=false and returns, so it cannot undo the placement.
|
||||
|
||||
Steps and results (iPhone 14 390x844 dpr3, Play solo, tap Firewall, CDP touch events):
|
||||
- Finger 1 down on cell (8,6), 30 ms later finger 2 on (12,6), spread 10 steps, lift. Before: walls [], gold 140, zoom 1. After: walls ["8,6"], gold 135, zoom 1.47. [...]
|
||||
- **Verifier's better fix:** The suggested direction is right, but two details need care:
|
||||
1. paintLine() deliberately skips its `from` cell. If the first placement is deferred to the first move past the slop, the origin cell must be placed explicitly at that moment, then paintLine(origin, current) run, or the first cell of every drag stroke is lost.
|
||||
2. A timer-only deferral (~60-80 ms, cancelled when a 2nd pointer lands) is NOT enough. My 80 ms test shows two-finger landings can be that far apart, and a quick tap with a ~40 ms hold would need flushing on pointerup anyway.
|
||||
|
||||
Simplest robust version, touch/pen with wall arme [...]
|
||||
|
||||
### touch-2 [MEDIUM] Turret armed: pinch/pan relocates the pending build to the cell under finger 1
|
||||
*Status:* **CONFIRMED** (verifier severity: low)
|
||||
|
||||
- **Repro:** node $R/gestures.js i14 (tests 2 and 3); also $R/rotate.js and $R/offscreen.js. Manual: arm Packet Filter, tap cell (10,8) (preview + Build bar), then pinch with finger 1 landing on (6,5).
|
||||
- **Observed:** pending {x:10,y:8} -> {x:6,y:5} at pinch start (gestures.js FAIL line 2); rotate.js: pending (15,4) became (15,6) after a pinch, and after three two-finger pans it ended at (8,6). Same root cause as the wall bug: pointerdown for the first finger runs the 'app.pending = cell' branch before the second finger lands. The Build bar (and hint/route preview) now refer to a cell the user never chose, and the bar's .top class is not recomputed (see stale confirm bar finding). Also after lifting one finger of a pinch the remaining finger drags the pending cell around (pointermove single-finger branch).
|
||||
- **Expected:** Pending stays on the chosen cell while the camera is panned/zoomed; only a deliberate one-finger tap or drag moves it.
|
||||
- **Suggested fix:** Defer the pending update to pointermove-beyond-slop or pointerup for touch; ignore single-finger moves for a pointer that was part of a multi-touch gesture (track a 'gestureUsed' flag until all pointers are up).
|
||||
- **Verifier:** Reproduced from scratch with my own scripts (verify-touch/v4.js, v5.js, v6.js, v7.js) against the real server (port 8211), headless Chromium, isMobile + hasTouch, CDP Input.dispatchTouchEvent, iPhone-14 portrait (390x844) and Pixel-7 landscape. Code cause: public/js/main.js pointerdown touch branch (line ~547) runs `app.pending = cell` for finger 1 before finger 2 exists. The ptrs.size===2 branch only cancels long-press/paint and starts the pinch, so it never undoes that. The single-finger pointermove branch (~594) also keeps moving pending. Nothing handles this elsewhere.
|
||||
|
||||
Observed:
|
||||
(1) Filte [...]
|
||||
- **Verifier's better fix:** Deferring the pending update to pointerup, as suggested, would break the drag-to-aim ghost and the tap-again-to-build logic, which relies on prevPending and pending at pointerup. A smaller fix is to keep immediate feedback and undo it when the second finger arrives.
|
||||
|
||||
1. Add a `multi` flag. Inside the `ptrs.size === 2` branch of pointerdown, set `multi = true`. If `app.selType && app.selType !== 'wall'`, restore `app.pending = prevPending ? {...prevPending} : null`, set `app.previewDirty = true` and call `updateConfirm()`. prevPending was already snapshotted at finger 1's pointerdown, before pe [...]
|
||||
|
||||
### touch-3 [MEDIUM] After tapping a tower, Upgrade/Sell/Target are below the fold on most phones (portrait and landscape)
|
||||
*Status:* **CONFIRMED** (verifier severity: medium)
|
||||
|
||||
- **Repro:** node $R/layout.js and node $R/sidescroll.js (screens in $R/shots/layout-*.png, sidescroll-se-bottom.png). Manual: Play solo, build any turret, tap it.
|
||||
- **Observed:** Sell button bottom edge vs viewport height: 375x667 y=826 (vh 667), 390x844 y=929 (vh 844), 360x640 y=810 (vh 640), 320x568 y=754 (vh 568), landscape 667x375 y=569, 844x390 y=548, 915x412 y=548. Only 412x915 (Upgrade/Sell row just fits) and iPad fit. #side scrolls (touch swipe works: scrollTop 0->81) but the portrait palette is sticky and 101 px tall, so the scroll window left is 59 px (360x640), 71 px (375x667), 145 px (390x844). Nothing scrolls #info into view on selection (scrollTop stayed 0). In landscape the info panel starts below the 156-160 px palette grid.
|
||||
- **Expected:** Tower actions reachable without hunting: visible after selection (auto-scroll, compact action bar in the stage, or collapse the palette while a tower is selected).
|
||||
- **Suggested fix:** On selectTower() call info.scrollIntoView({block:'nearest'}) / side.scrollTop reset, collapse the palette to one row (or un-stick it) while a tower is selected, and fix the root cause in the next finding.
|
||||
- **Verifier:** Reproduced from scratch with my own scripts (repro.js, scroll.js, window.js, fix.js in .../scratchpad/reviews/verify-touch/, server on 8210, mobile+touch contexts, real CDP touch swipes). Steps: Play solo, select Packet Filter, tap cell (10,8), tap the check button to build, tap the tower, then read the geometry. Nothing in the repo is edited.
|
||||
|
||||
1. The claim's numbers reproduce exactly. Sell bottom edge against viewport height after selecting the tower, with scrollTop 0 in every case:
|
||||
- Portrait: 375x667 gives 826 (vh 667). 390x844 gives 929. 360x640 gives 810. 320x568 gives 754.
|
||||
- Landsc [...]
|
||||
- **Verifier's better fix:** The suggested fix is flawed. I simulated each variant in the page with injected JS and CSS (no repo edits), checking the Upgrade and Sell buttons.
|
||||
|
||||
- scrollIntoView on #info with block:'nearest' leaves Sell 0/42 px visible on 375x667, 360x640 and 320x568. #info is 251 px tall against a window of about 59 to 70 px, and the sticky palette covers the top of the scroll port.
|
||||
- scrollIntoView on .actions leaves Sell visible but Upgrade and Target cut off (22/42, 11/42 and 0/42 px on the three small phones).
|
||||
- Hiding the palette while a tower is selected (a [data-sel] attribute or class on #app) giv [...]
|
||||
|
||||
### touch-4 [MEDIUM] Small portrait phones: stage wastes ~140-160 px of dead bands, board drawn at 12-14 px cells, side panel starved
|
||||
*Status:* **CONFIRMED** (verifier severity: low)
|
||||
|
||||
- **Repro:** node $R/offboard2.js (second half) and node $R/roundtrip.js se,i14,seL; screen $R/shots/layout-se.png
|
||||
- **Observed:** stage vs drawn board: 320x568 stage 320x329, board 312x192, dead 137 px vertical, cell 12.0 px, side 145 px; 360x640 stage 360x371, board 352x217, dead 155 px, cell 13.5 px, side 161 px; 375x667 stage 375x387, board 367x226, dead 161 px (about 80 px black above and below), cell 14.1 px, side 172 px. 390x844: cell 18.5, 412x915: 20.1. Cause: #stage aspect-ratio uses the rotated ratio (--aspect-p 16/26) but is clamped by max-height:58dvh; the stage then measures ~1.03 tall:wide, the rotation test (height > width*1.05) fails so the board is drawn UNrotated inside a tall box. The dead band is almost exactly the height missing from the side panel. Hit-testing itself is exact (0 wrong of 2080 roun [...]
|
||||
- **Expected:** Stage sized to the board's drawn aspect when unrotated (or rotation chosen when it gives larger cells), giving the freed 140-160 px to the palette/info panel; cells >= ~18 px at 360-375 px width if possible.
|
||||
- **Suggested fix:** When the board will be drawn unrotated, set the stage height to fit the board (aspect-ratio var(--aspect)) instead of the 58dvh box; or raise the cap for narrow phones. Consider an offset/magnifier for the preview.
|
||||
- **Verifier:** REPRODUCED the layout numbers from scratch (own script /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/verify-touch/m1.js, real server on 8212, Playwright mobile emulation, solo game started). Stage WxH / board drawn / cell / dead band / #side height: 320x568 -> 320x329.4, 312x192, 12.0px, 137, 145. 360x640 -> 360x371, 352x217, 13.5, 155, 161. 375x667 -> 375x386.9, 367x226, 14.1, 161, 172 (screenshot shows ~80px black above and below the board). 390x844 -> cell 18.5 (rotated, dead 8), 412x915 -> 20.1. Cause confirmed: computed #stage aspect-r [...]
|
||||
- **Verifier's better fix:** Do not simply fit the stage to the board, because the hint pill and the confirm bar then cover about 45% of it at 375x667. Either (a) move the confirm bar and the route hint out of the stage (for example a sticky action row at the top of #side, or into the freed band), then size the stage to the board aspect; or (b) keep a fixed overlay allowance, e.g. stage height = board height + about 75px for the bar at the bottom, which still frees about 85px of the 161px for #side. For the CSS condition, the unrotated regime is exactly when 58dvh < 1.05*W, i.e. viewport W/H > ~0.55. A media query like @m [...]
|
||||
|
||||
### touch-5 [MEDIUM] prefers-reduced-motion hides every toast
|
||||
*Status:* **CONFIRMED** (verifier severity: low)
|
||||
|
||||
- **Repro:** node $R/reduced.js (Playwright reducedMotion 'reduce'; screens shots/toast-*.png). Manual: OS 'Reduce motion' on, arm a tower with too few credits and tap twice.
|
||||
- **Observed:** no-preference: toast opacity 0.976, animationDuration 2.6s. reduce: opacity 0, animationDuration 1e-05s, fill 'forwards'. The global reduced-motion rule sets animation-duration .01ms with iteration-count 1, and the toast keyframes end at opacity:0 with fill-mode forwards, so the toast is invisible immediately. That removes reject reasons ('Not enough credits', 'That would seal the route'), 'Wave N cleared +credits', co-op join/leave/lost-connection notices and the 'Room XXXX. Send the invite link' toast. iOS 'Reduce Motion' is common.
|
||||
- **Expected:** Reduced motion shortens/removes the movement, not the information; toasts stay visible for their lifetime.
|
||||
- **Suggested fix:** In the reduced-motion block give .toast animation:none and remove it via the existing setTimeout (or a non-forwards opacity-only animation). Also gate renderer screen shake / core flash on matchMedia('(prefers-reduced-motion: reduce)') (render.js L289/L321 ignore it).
|
||||
- **Verifier:** Reproduced from scratch with my own Playwright script (/tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/verify-touch/v2.js, server on port 8210). The script uses the real UI with no sim tampering. In solo play it picks Packet Filter, places filters until credits run out, then taps again to get the "Not enough credits" toast. I ran it on desktop (1280x800, mouse) and a phone (390x844, isMobile, touch), each with reducedMotion 'no-preference' and 'reduce'.
|
||||
|
||||
Results, measured 120ms after the toast appears:
|
||||
- no-preference, desktop and phone: opac [...]
|
||||
- **Verifier's better fix:** Add one rule after the global reduced-motion rule in public/css/style.css: `@media (prefers-reduced-motion: reduce) { .toast { animation: none; } }`. I verified it. The toast stays at full opacity until the existing 2700ms setTimeout in main.js removes it, and no JS change is needed. For the shake, gate it in render.js with a single `const reduceMotion = root.matchMedia && root.matchMedia('(prefers-reduced-motion: reduce)').matches` check around `this.shake` and `this.flashCore`. Keep a brief non-movement indicator, such as the core ring or flash, so the leak is still signalled. The global rul [...]
|
||||
|
||||
### touch-6 [MEDIUM] Landscape phone main menu: Play solo / Co-op buttons cut by the bottom edge
|
||||
*Status:* **CONFIRMED** (verifier severity: medium)
|
||||
|
||||
- **Repro:** node $R/menu.js (screens shots/menu-seL.png, menu-i14L.png). Manual: open on 667x375 or 844x390, nothing tapped.
|
||||
- **Observed:** 667x375: #btnSolo/#btnCoop top 357, bottom 401 (viewport 375) so only 18 px of the 44 px primary button is visible; 844x390: 357-403 (vh 390). Map picker (137-305) plus description push the buttons off; the card is overflow-y:auto but there is no scroll cue. overlays.js also shows the menu and help cards are scrollable in all landscape sizes.
|
||||
- **Expected:** The primary action visible on first paint (smaller map cards or two-column layout in short landscape).
|
||||
- **Suggested fix:** In (orientation:landscape) and (max-height:520px) lay the menu out as two columns (maps left, buttons right) or shrink .mapcard canvas height.
|
||||
- **Verifier:** Reproduced with my own scripts (menu_v.js, menu_scroll.js, menu_fix.js under scratchpad/reviews/verify-touch/). I used a fresh real server on port 8216, because 8210 was already in use by another agent. The menu was untouched and the viewport was mobile with touch.
|
||||
|
||||
Measured with getBoundingClientRect and elementFromPoint:
|
||||
- 667x375: #btnSolo/#btnCoop span 357-401, the card spans 14-361, and the card's scrollHeight is 444 against a clientHeight of 345. The reviewer's "18 px visible" is generous. The card's own overflow clip at y=361 leaves only about 4 px of the button hit-testable (elementFro [...]
|
||||
- **Verifier's better fix:** Add a compact variant of the menu card inside the existing short-landscape query, with no markup changes:
|
||||
|
||||
@media (orientation: landscape) and (max-height: 520px) {
|
||||
#menu .card { padding: 8px 14px; }
|
||||
#menu .logo-mark { width: 30px; height: 30px; }
|
||||
#menu .card h1 { font-size: 26px; }
|
||||
#menu .tag { margin: 2px 0 6px; }
|
||||
#menu .mapcard { flex-direction: row; align-items: center; padding: 6px; }
|
||||
#menu .mapcard canvas { width: 44%; flex: none; }
|
||||
#menu .mapcard .nm { min-height: 0; font-size: 12.5px; }
|
||||
#menu .mapcard .df { display: none; }
|
||||
#menu .mapdesc { min-height: 0; margin: 4px [...]
|
||||
|
||||
### touch-7 [MEDIUM] Co-op landscape top bar breaks at 701-760 px wide: Sound button off-screen, Wave button wraps to 3 lines
|
||||
*Status:* **CONFIRMED** (verifier severity: low)
|
||||
|
||||
- **Repro:** node $R/topbar2.js (AUTO=0 node $R/topbar2.js for no countdown); node $R/topbar.js (shots/topbar-l740.png, 740x360). Manual: 740x360 (Galaxy S9 class), join/create a co-op room, optionally enable AUTO.
|
||||
- **Observed:** With the co-op chip visible at height 360 (same at 320/393/412): widths 710/720/730 -> #btnSound right edge beyond the viewport (unreachable); widths 710-760 with AUTO countdown -> #btnWave height 63 px (text 'Wave 29 · 59s' wraps to 3 lines), topbar grows to 70 px. Without AUTO the Sound overflow remains at 710-730. Solo is fine at every width tested. Cause: the compact landscape rule hides #netChip/.lbl only up to max-width:700px, while the nowrap top bar has no shrink strategy in 701-760.
|
||||
- **Expected:** No clipped controls at any width.
|
||||
- **Suggested fix:** Extend the compact rules to max-width:760px or give #topbar flex-wrap/overflow handling and white-space:nowrap + flex:none on #btnWave.
|
||||
- **Verifier:** Reproduced from scratch with my own scripts (verify-touch/tb_real.js, fixtest.js, scan1.js, tapsound.js). I used a real co-op flow instead of the reviewer's DOM injection: host on a 700-860 x 360 mobile/touch context created a room through the real server on 8210, a desktop guest joined, and I enabled AUTO with a real tap. repo public/css/style.css was not touched (md5 unchanged).
|
||||
|
||||
CONFIRMED, with measurements:
|
||||
- At 701-737 px wide and 360 px high with AUTO on, #btnWave wraps to 3 lines (height 63, width 103) and the topbar grows 45 to 70 px. The text is "Wave 1 · 28s". The screenshot at 720x3 [...]
|
||||
- **Verifier's better fix:** The suggested max-width:760px extension is incomplete. I tested it as a CSS injection ("Fix A"): it clears 701-760 plain viewports but leaves the 63 px wave button on notched iPhones (812/44, 844/47, 852/59, 874/62 insets, effective 724-750 px), and it leaves the 2-line wrap at 761-840. A viewport width media query cannot see the safe-area padding.
|
||||
|
||||
A container query on the topbar fixes all of it. Tested at heights 320, 360 and 414, AUTO on and off, widths 690-1000, and the four notched iPhone insets. It gave zero overflow, wave button 40 px, topbar <=47 px:
|
||||
#topbar { container-type: inline- [...]
|
||||
|
||||
### touch-8 [MEDIUM] Portrait co-op on <=420 px phones: room code and Invite button are below the fold
|
||||
*Status:* **CONFIRMED** (verifier severity: low)
|
||||
|
||||
- **Repro:** node $R/coop.js (real server, two touch contexts; screens shots/coop-se.png, coop-i14.png). Manual: iPhone SE/14 portrait, Co-op online, Create room.
|
||||
- **Observed:** 375x667: #players top 669 / invite button 746-788, viewport 667; 390x844: invite 849-891, viewport 844. The top-bar room chip is display:none at max-width 420px ('moves into players panel'), so the only places to read the 4-letter code or tap Invite are off-screen; the host sees just a 2.6 s toast.
|
||||
- **Expected:** Room code/Invite reachable on first view of the game screen (e.g. a compact chip that opens the share sheet).
|
||||
- **Suggested fix:** Keep a small tap-to-share room chip in the top bar (icon + code) or show the Invite button in the stage; toast stays until dismissed on first create.
|
||||
- **Verifier:** I reproduced this with my own Playwright script against the real server (scratch under reviews/verify-touch/, ports 8210), using isMobile and hasTouch contexts. The claim's geometry matches exactly, but its wording is overstated and the severity is lower than "medium".
|
||||
|
||||
**What matches the claim**
|
||||
- 375x667: #players top 669, Invite button 746-788, viewport 667, #side 495-667.
|
||||
- 390x844: Invite button 849-891, viewport 844.
|
||||
- The Invite button is below the fold at first view on every portrait phone I tried at 420 px wide or less: 320x568, 360x740, 375x667, 390x844, 412x915 and 414x896. It is al [...]
|
||||
- **Verifier's better fix:** The suggested fix to keep the top-bar chip is sound, and the layout cost it implies does not exist. I injected `@media (max-width:420px){#netChip{display:flex!important}}` at 320x568, 360x740, 375x667 and 390x844. The chip landed in row 1 (about 70 px wide, left 246-314, top 4-5) and the top bar height was unchanged (94 to 89 at 320, 108 to 108 elsewhere). So the "keep it to two rows" justification for hiding it at 420 px or less does not hold.
|
||||
|
||||
Simplest change: delete `#netChip { display: none; }` from the `@media (max-width: 420px)` block in public/css/style.css. Then add `$('netChip').addEv [...]
|
||||
|
||||
### touch-9 [MEDIUM] Co-op: partner's touch cursor never clears (and a plain tap never shows one)
|
||||
*Status:* **CONFIRMED** (verifier severity: low)
|
||||
|
||||
- **Repro:** node $R/coop2.js (Alice and Bob on i14, real server). Bob arms Packet Filter, drags the preview (6,5)->(12,7), lifts, then taps Cancel.
|
||||
- **Observed:** Alice's view.cursors = [[1,12.5,7.5]] during the drag, and still [[1,12.5,7.5]] 3.5 s after Bob lifted and after Bob pressed Cancel: a labelled box stays on her board indefinitely. coop.js: a single tap-preview (no movement) produced 0 cursors on Alice. Cause: main.js only calls sendCursor(null) for mouse pointerleave; touch pointerup/pointercancel/cancel/confirm never clear it, tap does not send one, and RemoteController.sendCursor's 70 ms throttle can drop the final position.
|
||||
- **Expected:** Cursor shows while the preview is pending and disappears when the finger-driven preview ends or is built/cancelled.
|
||||
- **Suggested fix:** Send the cursor on touch pointerdown, send a trailing update, and sendCursor(null) on pointerup/cancel when no pending exists, on build, cancel and selectType(null).
|
||||
- **Verifier:** Reproduced with my own script (scratch dir .../reviews/verify-touch/cur2.js; real server on 127.0.0.1:8211, two i14-sized touch contexts, Alice hosts, Bob joins, CDP touch events, fresh room per scenario).
|
||||
|
||||
Code: public/js/main.js calls app.ctrl.sendCursor only at lines 564, 585, 596 (mouse hover/move and the touch pointermove branch with selType) and 627 (null, mouse pointerleave only). endPointer, btnCancelBuild (-> selectType(null)), btnConfirmBuild, updateConfirm and tap-to-build never send null. server/room.js handleCursor only clears p.cursor on x:null, disconnect, removal or rejoin, and [...]
|
||||
- **Verifier's better fix:** The suggested fix is a bit broad and has a throttle flaw. Simpler version, all in public/js/main.js and controllers.js:
|
||||
1. Make RemoteController.sendCursor(null, null) bypass the 70 ms throttle (and reset lastCursor). Otherwise a clear sent within 70 ms of the last move is silently dropped.
|
||||
2. Track the last pointer type that moved the cursor (or a touchCursorActive flag set in the touch pointermove branch and on touch pointerdown with a type selected). When pending goes from set to null (build, Cancel/selectType(null), tap-to-build, Escape) and that flag is set, send sendCursor(null, null) an [...]
|
||||
|
||||
### touch-10 [MEDIUM] Long-press ping does nothing while a build type is armed; with Firewall armed it builds a wall instead
|
||||
*Status:* **CONFIRMED** (verifier severity: medium)
|
||||
|
||||
- **Repro:** node $R/longpress.js (i14).
|
||||
- **Observed:** Nothing armed: ping works (also with 5 px jitter; 12 px drift correctly cancels). With Packet Filter armed: marks=0, pending set, Build bar shown. With Firewall armed: marks=0 and walls +1 from the long-press. The long-press timer is only started in the 'no selType' branch, yet the armed type stays selected after every build, so in normal play (and especially co-op, where pings matter) the documented 'long-press pings your partner' only works after deselecting the tool.
|
||||
- **Expected:** Long-press (about 520 ms without moving) pings regardless of the armed tool and does not place/preview.
|
||||
- **Suggested fix:** Start the long-press timer for all touch pointerdowns; if it fires, markAt() and suppress the pending placement/wall (needs the deferral from finding 1).
|
||||
- **Verifier:** Reproduced with my own script (/tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/verify-touch/lp.js) against a real server on port 8211. It uses isMobile/hasTouch Chromium and CDP Input.dispatchTouchEvent, so the game sees real pointerType=touch events. I wrapped ctrl.sendMark to count real ping calls instead of relying on renderer.marks. I ran three viewports: iPhone14 390x844, iPhone14 landscape 844x390 and SE 375x667. The results were identical on all three.
|
||||
|
||||
Code cause: in public/js/main.js (pointerdown, touch branch, about lines 540-552), [...]
|
||||
- **Verifier's better fix:** The reviewer's suggestion is right in direction but incomplete, with two points to add.
|
||||
|
||||
1. Add `&& !longFired` to the "tap previewed cell again builds" branch in endPointer. Without it, a long-press on the previewed cell still builds the tower, because after the timer fires pending still equals prevPending. This is the build-on-hold behaviour in the second observation above.
|
||||
|
||||
2. For a tower type armed, handle the ping at pointerdown time. Start the 520 ms timer in every touch branch. When it fires, restore app.pending = prevPending (or null) and call updateConfirm(), set longFired=true, then [...]
|
||||
|
||||
### touch-11 [LOW] Second tap on the preview with a few px of finger drift moves the preview instead of building
|
||||
*Status:* **CONFIRMED** (verifier severity: low)
|
||||
|
||||
- **Repro:** node $R/jitter.js. Arm Packet Filter, tap (10,8), tap it again with the finger 0.35 cell from centre drifting 4 px (below the 8 px tap slop).
|
||||
- **Observed:** 375x667 (14.1 px cells): towers 0 -> 0, pending moves to (11,8). 390x844 (18.5 px): pending moves to (10,7). pointermove updates app.pending for any movement, before the 8 px 'moved' slop is exceeded, so prevPending no longer equals pending on pointerup.
|
||||
- **Expected:** Movement under the tap slop is a tap on the originally touched cell and builds.
|
||||
- **Suggested fix:** Only update pending in pointermove once p.moved is true, or compare against the pointerdown cell on pointerup. Slop of 8 px is more than half a 12-14 px cell: scale slop with cell size.
|
||||
- **Verifier:** REPRODUCED with my own script (scratch dir .../reviews/verify-touch/jit1.js, jit2.js, jit3.js; real server on port 8214, unmodified repo; CDP Input.dispatchTouchEvent, isMobile+hasTouch).
|
||||
|
||||
Code cause confirmed in public/js/main.js: the touch pointermove handler (~line 594-596) sets app.pending = cell for ANY movement when selType is non-wall, before/independent of the 8 px p.moved slop. endPointer (~line 620) only builds if !p.moved AND prevPending === app.pending, so a sub-slop drift that crosses a cell boundary leaves pending on the neighbour and nothing is built.
|
||||
|
||||
Exact claim scenario: Pack [...]
|
||||
- **Verifier's better fix:** The first half of the reviewer's fix is right and simple; the second half is wrong. In the touch/pen branch of pointermove, only move the preview once the gesture is a real drag: `if (p.moved) { app.pending = { x: cell.x, y: cell.y }; setHover(cell); updateConfirm(); }` and keep `app.ctrl.sendCursor(cell.fx, cell.fy)` outside the guard. pointerdown already sets pending to the touchdown cell, so endPointer's existing prevPending === pending check then compares the touchdown cell, which is what a tap means. I verified this on a patched copy (verify-touch/repo2, port 8217, repo untouched): the ex [...]
|
||||
|
||||
### touch-12 [LOW] Third finger (palm) freezes pinch and the next move after it lifts jumps zoom to max
|
||||
*Status:* **CONFIRMED** (verifier severity: low)
|
||||
|
||||
- **Repro:** node $R/third.js (CDP touchEnd releases the listed points: it releases only the palm).
|
||||
- **Observed:** Pinch to zoom 2.20; palm lands: fingers spread 130 -> 260 px apart, zoom stays 2.20 (py shifts -11.1 -> 12.9 because each finger is treated as a single-finger pan); palm lifted and fingers moved 2 px: zoom 2.20 -> 4.00 in one step. Cause: pointerdown returns early at ptrs.size>2, pointermove only pinches when size===2, endPointer clears pinch only when size<2, so pinch.d is stale.
|
||||
- **Expected:** Extra touches are ignored; pinch continues smoothly.
|
||||
- **Suggested fix:** Track only the first two pointer ids for pinch (ignore others), and re-seed pinch.d/mx/my whenever the pair changes.
|
||||
- **Verifier:** REPRODUCED with my own script (390x844 touch, CDP Input.dispatchTouchEvent, real server on 8214; scripts in /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/verify-touch/pm/third.js and variants.js). Page-level pointer log shows the third finger is a genuine pointerdown id=6 and later pointerup id=6 (not a test artefact). Numbers match the claim exactly: pinch gives zoom 2.200 (py -11.1); palm down, fingers spread 130->260 px: zoom stays 2.200, py moves -11.1 -> 12.9; palm up with no move: still 2.200; fingers move 2 px: zoom 2.200 -> 4.000 in [...]
|
||||
- **Verifier's better fix:** The suggestion is correct and sufficient for the claim. A minimal version, tested on a scratch copy: add seedPinch(), which stores ids=[...ptrs.keys()].slice(0,2) plus d/mx/my. In pointerdown at ptrs.size===2 call seedPinch(). In pointermove replace `if (ptrs.size===2 && pinch)` with `if (pinch) { if (!pinch.ids.includes(e.pointerId)) return; const a=ptrs.get(pinch.ids[0]), b=ptrs.get(pinch.ids[1]); ... }`, so extra fingers are fully ignored and cannot pan or move app.pending. In endPointer, `if (pinch && pinch.ids.includes(e.pointerId)) { ptrs.size>=2 ? seedPinch() : (pinch=null); } else if ( [...]
|
||||
|
||||
### touch-13 [LOW] Touch targets below 44 px on coarse pointers
|
||||
*Status:* **CONFIRMED** (verifier severity: low)
|
||||
|
||||
- **Repro:** node $R/layout.js (small-buttons lists) and node $R/overlays.js.
|
||||
- **Observed:** Portrait info-panel Upgrade/Target/Sell: 42 px high (portrait rule .actions button min-height 42). Landscape phones: Menu 36x38, Auto 45x38, Speed/Pause/Sound 36x38 (4 px gaps) at 667x375, 40 px at 844x390/915x412; Wave 38-40 px. 320x568: all icon buttons 38 px. Menu 'How to play' and 'Fullscreen' link buttons 36 px. Adjacent 36x38 Speed/Pause/Sound makes mis-taps on Pause easy. (The 46 px default for pointer:coarse is overridden by the later landscape/340px rules.)
|
||||
- **Expected:** At least 44x44 css px with spacing on coarse pointers.
|
||||
- **Suggested fix:** Keep --btn at 44+ under (pointer:coarse) even in compact layouts, drop labels/stats instead; give link buttons min-height 44.
|
||||
- **Verifier:** Reproduced from scratch with my own script on port 8215 (own scripts in .../reviews/verify-touch/t44/: meas.js, info.js, fix44.js, chip.js). Context: Chromium isMobile+hasTouch, so (pointer: coarse) and (hover: none) both matched. I did not edit repo files.
|
||||
|
||||
MEASURED (getBoundingClientRect of visible buttons, game screen):
|
||||
- 375x667, 390x844, 412x915, 360x640, 768x1024, 1024x768: every topbar button is 46 px (Auto 49x46). No topbar button is below 44 on those sizes.
|
||||
- Landscape 667x375 and 568x320: Menu 36x38, Wave 118.5x38, Auto 45.2x38, Speed/Pause/Sound 36x38, with 4 px gaps (Speed 545-581, [...]
|
||||
- **Verifier's better fix:** Do not hand-edit each rule. In the landscape (line 62), max-width:700 (line 263) and max-width:340 (line 274) blocks, change `--btn` to 44px (or add a final `@media (pointer: coarse){ :root{--btn:44px} button.icon{min-width:44px} .actions button, button.link{min-height:44px} }` after them). Also set `button.icon{min-width:var(--btn)}` in those blocks instead of the 36/38 px literals.
|
||||
|
||||
Caveat the suggestion misses: the landscape co-op chip in the 701-756 px width range. In chip.js I forced the co-op chip visible with the text 'ABCD' and '123ms'. The topbar already overflows in the base layout a [...]
|
||||
|
||||
### touch-14 [LOW] Confirm bar position goes stale after rotation and can cover the pending cell
|
||||
*Status:* **CONFIRMED** (verifier severity: low)
|
||||
|
||||
- **Repro:** node $R/staleconfirm.js (390x844 -> 844x390 via setViewportSize with a pending turret).
|
||||
- **Observed:** updateConfirm() only runs from pointer/selection handlers, never from resize/pan/zoom/Fit, so .top is stale. Pending (16,2) in portrait (bar at top) -> landscape: cell centre (377,103) inside bar rect [195,99,413,159] (covered); pending (14,3): centre (335,124) covered. At fit zoom without rotation the bar never covered the pending cell centre over all 404 free cells on 375x667, 390x844, 667x375, 844x390 (overlap.js).
|
||||
- **Expected:** Bar re-evaluated whenever the cell's screen position changes.
|
||||
- **Suggested fix:** Call updateConfirm() from resizeCanvas() and after any camera change (or from the frame loop when pending exists).
|
||||
- **Verifier:** Reproduced with my own scripts (scratch under reviews/verify-touch/: sc1.js, sc_rot.js, sc_fit.js, sc_rec.js), real CDP touch taps against the real server on port 8215.
|
||||
|
||||
Code: updateConfirm() (public/js/main.js ~457) is called only from selectType, selectTower, pointerdown/pointermove, build/cancel and Esc. It is not called from resizeCanvas(), updateFit(), the btnFit handler, the wheel handler or frame(). The 'top' class is only chosen from cellToScreen() at call time. The in-code comment says the bar should be kept clear of the cell being placed, so the stale case contradicts the stated inte [...]
|
||||
- **Verifier's better fix:** Add a one-line updateConfirm() at the end of resizeCanvas() (after renderer.resize), and one at the end of updateFit() (it already runs after every pinch/pan/wheel/Fit click). No per-frame call is needed. It is a no-op when app.pending is null.
|
||||
|
||||
### touch-15 [LOW] Bottom safe-area inset applied twice in portrait
|
||||
*Status:* **CONFIRMED** (verifier severity: low)
|
||||
|
||||
- **Repro:** node $R/safe2.js (CDP Emulation.setSafeAreaInsetsOverride, bottom 34, i14 portrait, tower selected, side scrolled to the end).
|
||||
- **Observed:** gap between last panel and viewport bottom 8 px with inset 0 but 76 px with inset 34 (expected 42); #side clientHeight 198 -> 164 px. #app has padding var(--safe-b) and the portrait #side rule adds calc(8px + var(--safe-b)) again. Top/left/right insets behave (safe.js: topbar at y=47, landscape content at x=47).
|
||||
- **Expected:** Inset counted once.
|
||||
- **Suggested fix:** Remove + var(--safe-b) from the portrait #side padding.
|
||||
- **Verifier:** Reproduced with my own script (/tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/verify-touch/sa/v.js and v2.js, server on port 8210, Chromium 156, mobile and touch emulation, CDP Emulation.setSafeAreaInsetsOverride, solo game, #side scrolled to the end). CSS cause confirmed in public/css/style.css: line 43 gives #app `padding: var(--safe-t) var(--safe-r) var(--safe-b) var(--safe-l)`, and the portrait rule on line 58 gives #side `padding: 8px 10px calc(8px + var(--safe-b))`. The bottom inset is therefore applied twice.
|
||||
|
||||
Measured gap from the la [...]
|
||||
- **Verifier's better fix:** The suggested fix is correct and minimal. In public/css/style.css line 58, change the portrait #side padding from `8px 10px calc(8px + var(--safe-b))` to `8px 10px 8px`, because #app already pads by --safe-b. I tested exactly this override: the gap went from 76 to 42 px with no other layout change.
|
||||
|
||||
### touch-16 [LOW] Error sound plays once per cell during a wall stroke
|
||||
*Status:* **CONFIRMED** (verifier severity: low)
|
||||
|
||||
- **Repro:** node $R/errsfx.js (12 credits, 19-cell drag).
|
||||
- **Observed:** sfx calls: click 1, wall 2, error 18 (onReject plays 'error' for every rejected cell; toast is de-duplicated but the sound has no MIN_GAP). Painting while broke or along a sealing line produces a buzzer burst.
|
||||
- **Expected:** One error sound per stroke/second.
|
||||
- **Suggested fix:** Add error to MIN_GAP (e.g. 0.4 s) or throttle in onReject.
|
||||
- **Verifier:** Reproduced from scratch with my own scripts (server on 127.0.0.1:8210, now killed). Scripts are in /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/verify-touch/ (verify.js, fast.js).
|
||||
|
||||
Code: public/js/audio.js line 99 has MIN_GAP = {shot_filter, kill, arc, boom, shot_mortar, shot_ids, wall} with no 'error' entry. sfx() therefore never throttles 'error'. public/js/main.js onReject() (line 166) calls toast(), which is de-duplicated for 900 ms (line 59), and then calls Audio.sfx('error') unconditionally. paintLine() calls placeAt() for every cell [...]
|
||||
- **Verifier's better fix:** The reviewer's one-line fix is sound: add `error: 0.4` to MIN_GAP in public/js/audio.js. The error sound is about 0.21 s long, so the gap must be at least that, and 0.35-0.5 s is fine. This also covers the co-op remote-reject path, and the only caller is onReject. Caveat: during a long continuous stroke it still gives a slow buzz every 0.4 s rather than a single one. A stricter alternative is a per-stroke flag in main.js: set `strokeErrored = true` on the first reject while `painting` is true, skip Audio.sfx('error') while it is set, and clear it on pointerdown/pointerup/pointercancel. That gi [...]
|
||||
|
||||
### touch-17 [LOW] Wall stroke that starts on a turret selects the turret and silently drops the Firewall tool
|
||||
*Status:* **CONFIRMED** (verifier severity: low)
|
||||
|
||||
- **Repro:** node $R/paint.js i14 (case 3).
|
||||
- **Observed:** Firewall armed, drag from a turret cell downward: walls=0, selType=null, selTower=1; the tool is deselected and the rest of the drag does nothing. (Fast single-jump strokes, diagonal strokes, gold exhaustion, sealing rejection and pointercancel mid-paint all behaved correctly; the 16/18 result was the two dead nodes in row 3.)
|
||||
- **Expected:** At most the starting cell is skipped; stroke continues and tool stays armed.
|
||||
- **Suggested fix:** Do not call selectTower from a wall-armed pointerdown that becomes a drag; select only on a stationary tap.
|
||||
- **Verifier:** Reproduced from scratch with my own script (/tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/verify-touch/v2/mine.js, server on 8217, gold set to 9999). It fails on both input paths.
|
||||
|
||||
Steps: build a Filter turret at (10,5), arm the Firewall (wall) tool, then drag from the turret cell (10,5) down to (10,9) in four moves.
|
||||
|
||||
Observed:
|
||||
- Touch (390x844 isMobile, CDP touchStart/Move/End, portrait rot=pi/2): walls=0, selType=null, selTower=1. Gold was unchanged (9974) and the board had no new walls.
|
||||
- Mouse (1280x800, mouse down/move/up): identical r [...]
|
||||
- **Verifier's better fix:** The suggested direction (select only on a stationary tap) is right, but "do not call selectTower from a wall-armed pointerdown" is incomplete on its own, because a plain tap on a turret must still select it. I tested a minimal patch on a copy of the repo (scratchpad .../verify-touch/v2/repo, served on 8218; the real repo is untouched). In both the mouse and touch pointerdown branches, add a case before the existing selectTower branch: `if (app.selType==='wall' && ex && ex.type!=='wall') { setHover(cell); painting=true; paintCell=cell; tapTowerId=ex.id; }`. In endPointer, if `tapTowerId && !p.m [...]
|
||||
|
||||
### touch-18 [LOW] Cosmetic touch UI leftovers
|
||||
*Status:* **CONFIRMED** (verifier severity: low)
|
||||
|
||||
- **Repro:** $R/fit.js, $R/hint.js, $R/overlap.js, shots/crop-bleed.png, $R/tapbuild.js
|
||||
- **Observed:** (a) 'Reset zoom' (#btnFit) stays visible at zoom 1 after rotation reset or new game (zoom 2.92 -> 1, fitHidden=false): updateFit() is not called. (b) Hint pill: longest reject text 'That would seal the route. Leave a path!' overflows the pill at 320 (scrollW 340 > clientW 298) and 360 (340 vs 338); hint also sits over cells near the top-centre edge (pending cell centre under hint: 8 cells on 390x844 e.g. (0,6)-(1,9), 6 on 667x375, 8 on 844x390). (c) Scrolled-under text ('Upgrade 60', 'Target: First') shows through the 8 px strip above the sticky palette (palette bg is rgba .97, sticky top:-8px). (d) The red X on the Build bar also drops the armed tower type (selectType(null)), so 'wrong cell [...]
|
||||
- **Expected:** Tidy states.
|
||||
- **Suggested fix:** Call updateFit() after camera resets; add overflow:hidden/ellipsis or wrap to .hint; make sticky palette bg opaque; make X clear only pending.
|
||||
- **Verifier:** The claim is a bundle of five cosmetic items. I reproduced (a), (b), (c) and (e) with my own scripts on port 8210, and (d) is intended behaviour rather than a defect. Scripts and shots are in .../reviews/verify-touch/ (a.js, b.js, c.js, d.js, e.js, f.js, shots/). No repo files were edited.
|
||||
|
||||
(a) CONFIRMED. At 390x844 I pinch-zoomed to 3.88, then resized to 844x390. The camera reset to zoom 1 and rot 0, but #btnFit stayed visible (hidden=false, 40x40 at [560,342]) and app.zoomed stayed true; shots/a-rotated.png shows the button. After zooming again and calling ctrl.newGame(), the state was the s [...]
|
||||
- **Verifier's better fix:** (a) Call updateFit() at the end of resizeCanvas() and adoptBoard() in public/js/main.js, or sync the button once per frame from renderer.zoom. Both are one-liners, and updateFit is a hoisted function declaration.
|
||||
(b) Shorten REASONS.blocks (for example "That would seal the route") or add overflow:hidden; text-overflow:ellipsis to .hint. Wrapping is unnecessary because the toast already carries the full text.
|
||||
(c) Make the sticky palette background opaque, using a solid colour that matches the blended #side background; no margin or top changes are needed.
|
||||
(d) Leave as is.
|
||||
(e) Skip the shake and [...]
|
||||
|
||||
|
||||
## Co-op chaos / protocol races (8 findings)
|
||||
|
||||
*Coverage:* All scripts, screenshots and raw outputs are in /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/coop-chaos/ (lib.js holds the shared helpers: in-process server, order-preserving TCP proxy with freeze/refuse/jitter, raw ws client). No repo files were edited. All servers were stopped (ports 8220-8229 free at the end).
|
||||
|
||||
TESTED, and behaved correctly:
|
||||
- Races (s1_races.js raw ws, s12_ui_races.js two browsers): same-cell place at the same instant gave exactly 1 tower, one 'occupied' reject, gold charged once (3 of 3 valid UI trials; two trials were my own toggle mistake). Turret vs turret on the same cell: 1 tower. Double sell: refund once (17), second gets 'no_tower'. A sell and B's place on the same cell resolve to either result without corruption. A hostile 150-message burst closes the socket 4429 as designed. A non-host newgame gets 'not [...]
|
||||
|
||||
### coop-1 [HIGH] A client that stalls rendering for about 1 s permanently loses the partner's tower changes (ghost or missing towers, wrong route preview) until the next tower change
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** Scripts are in /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/coop-chaos/. Run `source <scratchpad>/pwenv.sh; node s2_buf.js`. In-process server with two desktop browsers. Variant 1 swaps window.requestAnimationFrame on B for a holder for 1.5 s, which is what a hidden tab does. While B is stalled, A places 2 walls. Variant 2 runs a 1 s busy loop on B's main thread while A places 1 wall. Variant 3 uses a 450 ms busy loop. Variants 1 and 2 are the failing ones. Spontaneous repro with no deliberate stall: `node dbg2.js` creates 10 fresh host+guest sessions, places 4 towers, and starts a wave. It failed in 1 of 10 runs (1 of 8 earlier). The sa [...]
|
||||
- **Observed:** Variant 1: server towers=2, but B ctrl.towers=0, ctrl.rev=0, view.rev=2, recvRev=2, gold 130 (the spend IS shown). This stayed unchanged for the full 5 s sampling window and indefinitely after that. Variant 2: server 4, B 3, same signature. Variant 3 (450 ms stall): fine, B 5 of 5. B's mirrored board.routeLen stays at the old value, so the route preview is wrong. B's click on a cell the server holds a tower on is rejected with 'Something is already there' while the cell looks empty. A sold tower would stay visible as a ghost the same way. The next tower change by anyone resynced B at once (3 of 3 towers), so the desync only lasts until the next build or sell. Cause: _push caps buf at 10 entr [...]
|
||||
- **Expected:** Client towers, board mirror and rev always equal the server's after any pause in rendering, and a desync is self-healing. Backgrounded tabs and slow phones are normal in co-op.
|
||||
- **Suggested fix:** Apply `tw` (and set this.rev and the board) when the snapshot ARRIVES, or keep the newest undisplayed `tw` outside the ring buffer so shift() cannot discard it. Additionally, in update() compare this.rev with the latest recvRev and call requestSync() if they differ for more than about 1 s. Do not drop entries that carry `ev` or `tw` when trimming. `requestSync()` already repairs the state (forced in s5b setup). Add a unit test that feeds 15 snaps with a tw on the 2nd and then calls update().
|
||||
|
||||
### coop-2 [HIGH] Half-open connection (wifi/cell switch, NAT or proxy drop): the UI looks alive but frozen for 47-65 s with no 'Reconnecting' overlay. The watchdog's ws.close() never reconnects.
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** `node s5a_freeze.js`: B loads the game through a TCP proxy on 8225 that swallows all bytes on the existing connection while still accepting new ones. `HOLD=1 node s5a_freeze.js` also stops FIN/RST from the server reaching the browser, which is a true dead path. `node s13_offline.js` section 2 uses Playwright context.setOffline(true) for 8 s. Each script polls ctrl.status, ws.readyState and the visibility of #reconnect.
|
||||
- **Observed:** Freeze without HOLD: status stays 'joined' with no overlay. At about 5-6 s readyState becomes 2 (CLOSING, the 5 s watchdog fired ws.close()), and nothing else changes. The overlay appears only at 47.3 s, when the server's own ping/pong termination closes the TCP socket and the proxy relays it. Rejoin at 48.0 s. With HOLD=1 (no close ever delivered): CLOSING from 5.3 s, overlay only at 65.1 s (Chrome's closing-handshake timeout), rejoin at 65.7 s. setOffline for 8 s: status 'joined' with overlay hidden for the whole 8 s, then 0.1 s 'reconnecting' and 0.3 s 'joined' once the network came back. Server side: the partner sees B as offline only after the server's own ping timeout, about 45 s. B's [...]
|
||||
- **Expected:** Within about 5-6 s of silence the client shows the Reconnecting overlay and opens a NEW socket (the server replaces the old connection by pid, close code 4001), without waiting for onclose. Also react to the `offline` event and to a stale lastMsg.
|
||||
- **Suggested fix:** In the watchdog and in _wake(), after ws.close(), detach the old socket's handlers (set onclose=null, this.ws=null), call this._failed()/connect() straight away and show the overlay. The server already handles the pid takeover. Optionally listen for window 'offline' and show the overlay at once.
|
||||
|
||||
### coop-3 [MEDIUM] Host leaves (or times out) while the end overlay is open: the promoted guest is stuck on 'Waiting for the host to start a new game...' with no Play again button
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** `node s3_end_menu.js`, Test 3. Host A (desktop) and guest B (phone). Set sim.lives=1 and speed=3, start a wave, and let a real leak end the game ('lost'). Both see 'Breach!'. A presses Menu on the end overlay, which leaves the room. Screenshot: scratchpad/reviews/coop-chaos/t3_guest_end_after_host_left.png.
|
||||
- **Observed:** Before: A {again:true, wait:false}, B {again:false, wait:true}. After A leaves: server room shows slot 1 host=true and B's ctrl.you.host=true, but B's #btnAgain is still hidden and #endWait ('Waiting for the host...') is still shown. The only choice is Menu. endScreen() sets btnAgain/endWait once and nothing recomputes them on a 'players' update. The server does accept B's newgame (B's newGame API call moved the room back to 'playing'). The same happens if the host just closes the tab, after the 60 s grace.
|
||||
- **Expected:** When the promotion arrives, B's end overlay switches to the host variant (Play again visible, wait text hidden).
|
||||
- **Suggested fix:** In onPlayers() (or the 'players' handler), if the end overlay is visible, recompute btnAgain/endWait from ctrl.you.host.
|
||||
|
||||
### coop-4 [MEDIUM] Opening Menu > Co-op online during a live co-op game and failing to join (bad code, full room) silently kills the current game: the player is left on a dead, frozen game screen
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** `node s3_end_menu.js`, Test 4. A hosts with B joined. A: #btnMenu, #btnCoop, type ZZZZ, #btnJoin. Then #btnLobbyBack. Screenshot: t4_after_back.png.
|
||||
- **Observed:** connectRemote() calls app.ctrl.close() first, which sends 'leave' and closes the live room, before the new connect has succeeded. The 'fatal' (no_room) handler then takes the `else lobbyMsg(...)` branch because app.ctrl is still the closed old controller. After 'Back': A's ctrl.status='closed', app.inGame=true, #reconnect hidden. The HUD and player panel still look normal (it still lists 'Alice (you) host', 'Bob'), but nothing is interactive: a place command leaves gold at 140 and the server at 0 towers. The partner B sees players ['Bob'] only, so A has left B's game without knowing it. (A successful join to a different room works: T4b.)
|
||||
- **Expected:** Keep the current session until the new join succeeds, or on failure return the player to the still-connected game or to a proper menu with a message.
|
||||
- **Suggested fix:** Create the new RemoteController first and close the old one only inside its first 'joined'. Alternatively, hide Co-op online/Join in the in-game menu, or route the failure through leaveToMenu().
|
||||
|
||||
### coop-5 [MEDIUM] Simultaneous Upgrade (and Next Wave) from both players are applied twice: the partner pays for a second upgrade they did not intend, and two waves start
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** `node s1_races.js` (raw ws clients, in-process server): sections 3 and 4. A and B both send {t:'cmd',c:'upgrade',id} for the same level-1 filter in the same tick. Sections 4 and 5 do the same for 'wave' and for conflicting pause/speed.
|
||||
- **Observed:** Double upgrade: tower ends at level 3, gold 1000 -> 915 (85 credits charged), neither client receives a reject. Simultaneous 'wave': wave counter 0 -> 2, spawnQ 19, so two waves launched. Conflicting pause (A true, B false) resolves last-writer-wins (paused=false); conflicting speed (3 vs 2) ends at 2. These are consistent but silent. (Same-cell place, double sell, sell-vs-place all resolve correctly, see coverage.)
|
||||
- **Expected:** The second of two simultaneous identical intents should be a no-op or rejected, for example 'stale', so that no one is charged twice or gets a surprise second wave.
|
||||
- **Suggested fix:** Let 'upgrade' carry the level the sender saw (`lv`) and reject if t.level != lv. For 'wave' send the wave counter the sender saw (`w`) and reject on mismatch (or debounce).
|
||||
|
||||
### coop-6 [LOW] After a server restart both players are dumped to the lobby with 'That room does not exist (any more).' (no mention of the restart). A reload with a stale saved room lands on a bare main menu with no message. After a 53 s outage Resume is wiped.
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** `node s6_restart.js` (child-process server on 8229, SIGTERM, restart after 3 s) and `node s8_lobby.js` section 1b (sessionStorage nw.room=ZZZZ plus a localStorage nw.session) and `node s5c_long.js` (proxy refuses for the full retry schedule).
|
||||
- **Observed:** SIGTERM with 2 clients connected: server exits in 142 ms with code 0, and both clients show the Reconnecting overlay (good). Restart after 3.5 s: both clients get the 'no_room' error within 1 s and go to the lobby with 'That room does not exist (any more).'. They can recover (A creates a new room, B joins by code; verified), but have to coordinate by hand and the message does not say the server restarted. Server stays down: both give up after 52.5 s (retries at 0.4, 1.0, 2.1, 3.9, 6.9, 11.9 ... 52.4 s) with 'Lost connection to the server.'. That is 7.5 s BEFORE the 60 s grace expires, and the fatal handler deletes nw.room and nw.session (Resume button gone) even though the seat is still held [...]
|
||||
- **Expected:** A clear 'The server restarted; your game was lost. Create a new room' message, visible in every path. Keep Resume until the grace period is really over.
|
||||
- **Suggested fix:** On boot-path failures call openLobby() before lobbyMsg. Map no_room after a reconnect attempt to a 'game was lost (server restarted?)' message. Do not delete nw.session on a 'connect'/'lost' fatal, only on explicit leave or no_room.
|
||||
|
||||
### coop-7 [LOW] Pending touch placement stays armed after the partner builds on that cell, with no warning until Build is pressed
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** `node s12_ui_races.js` section 3. B previews an IDS Sniper at (18,4) with a tap, A then builds a wall there. Screenshot: pending_cell_taken.png.
|
||||
- **Observed:** Pending stays {18,4}, the confirm bar stays visible, and #hint is null (ui.noGhost suppresses the hint for any cell holding a tower). Pressing Build gives the toast 'Something is already there' and clears pending (towers 2 -> 2, gold unchanged, so nothing is lost).
|
||||
- **Expected:** Clear the pending cell (or show the invalid hint) as soon as the partner's tower appears.
|
||||
- **Suggested fix:** In frame(), if app.pending and a tower now sits at that cell, set app.pending=null and updateConfirm().
|
||||
|
||||
### coop-8 [LOW] After a board swap (new game on a different map) the 'Reset zoom' button stays visible although the camera was reset (not reachable from the normal UI)
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** `node s10_newgame.js` section e. B zoomed (wheel), then A calls NW.app.ctrl.newGame('twin') and then 'hub' through the API. (The UI's Play again always reuses the current map.)
|
||||
- **Observed:** Renderer board swapped correctly (rendMap, aspect, spawns 2 and 3, routeLen A/B/server equal: 56.21 / 34.24). But the zoom went 2.3 -> 1 while #btnFit stayed visible (updateFit is not called from adoptBoard). A same-map new game does not reset the camera or the particles at all (zoom stays 2.53).
|
||||
- **Expected:** Button state follows the actual zoom after setBoard.
|
||||
- **Suggested fix:** Call updateFit() at the end of adoptBoard().
|
||||
|
||||
|
||||
## Client code review (28 findings)
|
||||
|
||||
*Coverage:* COLD-START PREAMBLE (everything was killed at the end; I did not edit any repo file, scratch scripts live only in the scratchpad). RC=/tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code . Steps: (1) source /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/pwenv.sh ; (2) cd /home/jav/git/towerdefence && PORT=8230 HOST=127.0.0.1 node server/index.js & ; (3) only for the service-worker/audio-failure scripts s1_sw.js, s2_update.js, t16*_midfail.js: node $RC/proxy.js (port 8231, forwards to 8230; mode is switched at runtime via /__mode?m=ok|502|down|v2|trunc|slowcut); (4) only for t24_coop_win.js: node $RC/srv_win.js (port 8232, test-only wrapper that makes every room win at wave 1). Then node $RC/<script>.js. Helpers: lib.js, coop_lib.js (host+guest pair), audio_init.js (instruments Audio el [...]
|
||||
|
||||
### code-1 [HIGH] Co-op: a burst or stall of >10 snapshots silently drops the partner's new towers; the guest stays desynced until the next tower change
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** Cold start per coverage preamble (server on 8230). Primary: node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/t1_net.js (host+guest in real Chromium; page.routeWebSocket holds the guest's server->client frames, then flushes them at once while the host places a wall). Also t1_tw.js (guest rAF suspended = background tab, WS still delivering) and t1_stall.js (guest main thread blocked), same dir.
|
||||
- **Observed:** t1_net.js (view towers host vs guest): 7 frames flushed -> 1 vs 1 (OK); 16 frames flushed -> host 2, guest 1; 20 frames -> host 3, guest 1. Guest gold is deducted correctly (130, 125) but the tower is missing. t1_tw.js: rAF held 300 ms -> OK; 800 ms -> host 2 / guest 1; 1500 ms -> host 3 / guest 1; still guest 1 after 6 s idle (ctrlRev 1 vs recvRev 3, mirror board solid count also stale). t1_stall.js: 400 ms main-thread stall -> host 1 / guest 0 (ctrlRev 0, recvRev 1); 700 ms and 1200 ms the same. No console errors. Mechanism: _push() does buf.shift() beyond 10 entries; a dropped snapshot carrying `tw` was never applied, but _onSnap() already set recvRev = m.rev on receipt, so the later `m.r [...]
|
||||
- **Expected:** Every tower change reaches every client (the server only sends `tw` once per rev change). A phone Wi-Fi/cell hiccup (>= ~0.55 s of queued frames delivered together), a backgrounded tab or a GC stall must not lose towers; at worst the client should resync.
|
||||
- **Suggested fix:** Never discard an unapplied snapshot that has `tw`: when trimming the buffer, apply the dropped entry's tw immediately (or carry it to the next entry), or request a 'sync' whenever an entry with tw is shifted out before twDone. Alternatively update recvRev only when tw is actually applied in update(), so the existing rev mismatch check triggers requestSync().
|
||||
|
||||
### code-2 [HIGH] Info panel is rebuilt (innerHTML) on every view.rev change, so Upgrade/Sell/Target clicks are lost while the partner builds
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** Server on 8230. node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/t2_info.js : host places a filter tower, guest selects it; guest does mouse down on the Target button, holds 150 ms, mouse up, 10 times (700 ms apart). Trial A: partner idle. Trial B: host places/sells a wall every 80 ms. A capture-phase click counter and a MutationObserver on #info count results.
|
||||
- **Observed:** Trial A (quiet): 10 of 10 clicks delivered. Trial B (partner churning rev): 1 of 10 clicks delivered, 359 #info DOM mutations in the trial (204 even in A, because the panel is rebuilt for every rev bump including the guest's own actions). Cause: frame() calls renderInfo(true) whenever view.rev changes while a tower is selected; the button under the finger/cursor is replaced between mousedown/touchstart and mouseup/touchend, so no click event is generated. #info is also aria-live=polite, so screen readers would be re-announced on each rebuild.
|
||||
- **Expected:** The selected-tower panel only changes when the selected tower's level/mode/id or the owner list changes. Buttons must stay put while a partner builds or paints walls.
|
||||
- **Suggested fix:** Call renderInfo(false) there (sig already encodes id:level:mode) or update fields in place; keep renderInfo(true) only for explicit selection changes.
|
||||
|
||||
### code-3 [MEDIUM] A still-connecting co-op controller hijacks a solo game that was started in the meantime
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** Server on 8230. node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/t3b_hijack.js (routeWebSocket adds +4 s latency to server frames): press Create room, press Back, press Play solo, build 3 walls.
|
||||
- **Observed:** Timestamped output: 6108 ms state {kind:'local', inGame:true, towers:0, gold:140}; after building 3 walls in the solo game, at 8081 ms state {kind:'remote', room:'UJ43', towers:0, gold:140}: the solo game was replaced by the room, the 3 walls and the solo game are gone, the players panel appears. There is no cancel for a pending connect; only app.ctrl is closed in connectRemote/startSolo, not the not-yet-joined rc.
|
||||
- **Expected:** Leaving the lobby (Back) or starting a solo game must cancel/close the pending RemoteController; its 'joined' must not switch controllers.
|
||||
- **Suggested fix:** Keep a module-level `pendingRc`; close it in btnLobbyBack, startSolo, leaveToMenu and before creating a new one; in 'joined' ignore if pendingRc !== rc.
|
||||
|
||||
### code-4 [MEDIUM] Double-clicking 'Create room' creates two rooms and leaves an orphan socket open
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** Server on 8230. node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/t3_double.js (page.dblclick('#btnCreate')); then read the server log.
|
||||
- **Observed:** Page: sockets readyState [1,1] (both open), ctrl in room WBG7, 1 player. Server log: '[84SL] created (map open)' and '[WBG7] created' in the same millisecond, both with the same pid 'Dbl' as host; room 84SL is never used or closed and keeps receiving snapshots until the tab closes (then holds the slot for the 60 s grace). Buttons are not disabled while connecting; the first rc is not app.ctrl yet so connectRemote's close() misses it.
|
||||
- **Expected:** One connection attempt at a time; a second click is ignored or cancels the first.
|
||||
- **Suggested fix:** Disable Create/Join while connecting (or track and close the pending rc); the server could also drop a pid's previous room join.
|
||||
|
||||
### code-5 [MEDIUM] Co-op: after 'Play again' or 'Keep going' there is no music for both players and the end stinger keeps playing over the new game
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** Server on 8230: node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/t4_coop_music.js (host sends 9 waves at 3x speed with no towers, both reach the end screen, host presses Play again; reads NW.Audio.now and instrumented Audio elements). For Keep going, start the test-only win server first (node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/srv_win.js, port 8232) and run t24_coop_win.js. (With 10 waves a rootkit is alive, bossMusic is true and music accidentally restarts, which masks the bug.)
|
||||
- **Observed:** t4: in-game both pages Audio.now={battle,file}; end screen: lose.mp3 playing; after Play again with state=playing on both: Audio.now=null on host AND guest, and lose.mp3 is still PLAYING at t=5.6 s on both. t24 (win): after the host presses Keep going the host gets battle.mp3, the guest has Audio.now=null and win.mp3 still PLAYING at t=8.6 s; no battle track at all. Only the solo branch calls Audio.music('battle') in btnAgain/btnContinue; the remote 'newgame' handler and the ended->playing frame transition never do, and music stays null until a boss wave happens.
|
||||
- **Expected:** Battle music restarts (and the stinger is stopped) whenever a game starts or continues, on every client.
|
||||
- **Suggested fix:** Call Audio.music('battle') in the 'newgame' handler and when frame() detects ended->playing; or call it from the shared place that hides the end overlay.
|
||||
|
||||
### code-6 [MEDIUM] Holding Space/Enter (OS key repeat) launches ~20 waves at once
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** Server on 8230. node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/t10_keys.js (use only the first two result lines, 'T10 before/after'): solo game, keyboard.down(' ') then 20 repeated keydowns 25 ms apart.
|
||||
- **Observed:** Before: wave 0, queued 0. After: wave 21, queued 511 monsters (21 waves started, each emitting its banner). Reproduced in solo only; in co-op the only limit is the server's MAX_MONSTER_LOAD 1500 (from reading server/room.js, not reproduced). Key repeat is also unguarded for p/f/a/m (they toggle on every repeat).
|
||||
- **Expected:** One keypress = one command; ignore e.repeat for toggles and for wave start.
|
||||
- **Suggested fix:** `if (e.repeat) return;` at the top of the game hotkey handler (maybe except none).
|
||||
|
||||
### code-7 [MEDIUM] Stale fade-out callback pauses a restarted music element: silence while Audio.now says 'playing'
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** Server on 8230 with autoplay flag. node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/t6_audio.js (T7: press M twice 90 ms apart in a running game) and node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/t22_fastagain.js (lose, then click Play again N ms after the end overlay appears). t21_win.js shows the same for 'Keep going'.
|
||||
- **Observed:** T7: after M, M within 90 ms: NW.Audio.now={battle,file}, muted=false, but battle.mp3 'paused' (vol 0.44) 3 s later; a slower mute/unmute (1 s) works. t22 (battle element playing after 2.5 s): Play again at 0 ms, 150 ms, 300 ms -> playing=false; at 500 ms, 800 ms -> true. Cause: stopCurrent() starts a rAF fade-out whose done() calls el.pause(); a restart within the fade window (0.2 s mute, 0.4 s end screen, 0.9 s track switch) reuses the same cached element, sets volume/play, but the old fade still runs to completion and pauses it. Nothing recovers until the track name changes.
|
||||
- **Expected:** A restart cancels any running fade on that element; pause only if the element is no longer current.
|
||||
- **Suggested fix:** Store a fade token on the element (el.__fade) and cancel it in fadeEl/applyMusic; in the done callback check that the element is not the current/wanted one.
|
||||
|
||||
### code-8 [LOW] Global hotkeys hijack keyboard activation of focused buttons; overlays have no focus management, focus trap or dialog semantics
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** Server on 8230. node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/t11_focus.js (event log) and node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/t12_overlay.js (T13a and T13). Ignore the T11 lines in t10_keys.js (flaky wave=0 run).
|
||||
- **Observed:** t11_focus: for focused Wave, Auto, Sound and palette buttons, Space/Enter log 'keydown, SEND:wave, keyup' with NO click event: the hotkey runs and preventDefault suppresses the button's own action. t12 T13a: Enter on the focused Menu button does not open the menu (menu opened=false) and starts a wave instead (wave=1). So a keyboard-only user cannot activate any HUD button with Space/Enter during a game. T13: after opening the menu overlay, focus stays on #btnMenu; Tab visits btnWave, btnAuto, btnSpeed, btnPause, btnSound, six palette buttons (11 controls behind the overlay) before reaching the overlay's own buttons; Enter on #btnWave behind the open menu started a wave; overlay cards have no [...]
|
||||
- **Expected:** Hotkeys ignored when the event target is a button/link (or only Enter/Space-free keys used); overlays move focus inside on open, trap Tab, restore focus on close, and use role=dialog aria-modal.
|
||||
- **Suggested fix:** In the keydown handler return early for e.target.closest('button,a,[role=button]') when key is Space/Enter; add `inert` to #topbar/#stage/#side while an overlay is open (also gives the focus trap) and focus the first control of the overlay.
|
||||
|
||||
### code-9 [LOW] Escape on the end overlay dismisses it for good and leaves a dead board
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** Server on 8230. node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/t12_overlay.js (T12). Screenshot: .../t12_escape_end.png
|
||||
- **Observed:** After losing: endHidden=false, state='lost'. After Escape: endHidden=true, endShown=true, state still 'lost', Wave button disabled; the end overlay never returns (endShown stays true) and Play again/Menu buttons are gone. Only the top-bar menu button recovers.
|
||||
- **Expected:** Escape should not close the game-over/victory overlay (or should reopen it/offer the buttons).
|
||||
- **Suggested fix:** Ignore Escape when #end is the visible overlay (and for the lobby while connecting).
|
||||
|
||||
### code-10 [LOW] Service worker serves an nginx 502/504 instead of the cached app (offline fallback only covers network errors)
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/proxy.js (port 8231, needs the game server on 8230), then node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/s1_sw.js (SW-enabled context; the proxy is switched to answer 502 'Bad Gateway' like nginx with the node app down, then to dropping connections).
|
||||
- **Observed:** With the SW installed and the app cached: upstream 502 -> reload returns status 502, body '502 Bad Gateway nginx', game booted=false. Connection dropped (fetch rejects) -> status 200 and game booted=true from cache. (Other SW results are clean, see coverage.)
|
||||
- **Expected:** When the origin is down behind the proxy (the usual failure with nginx Proxy Manager), solo play should still start from the cache.
|
||||
- **Suggested fix:** Treat 5xx (or !res.ok) for navigations and static files like a network failure: `if (!res.ok && res.status >= 500) throw` into the cache fallback.
|
||||
|
||||
### code-11 [LOW] A guest promoted to host while the end screen is up still sees 'Waiting for the host' and no Play again button
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** Server on 8230: node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/t5_hostleaves.js (both lose; host presses Menu).
|
||||
- **Observed:** Before: guest {youHost:false, btnAgainHidden:true, endWaitVisible:true}. After the host left: {youHost:true, players:['Guesty(host)'], btnAgainHidden:true, endWaitVisible:true, text 'Waiting for the host to start a new game…'}. Visibility is only computed once in endScreen().
|
||||
- **Expected:** The buttons follow the current host flag.
|
||||
- **Suggested fix:** Recompute btnAgain/endWait in onPlayers() while the end overlay is shown.
|
||||
|
||||
### code-12 [LOW] Stinger/boss tracks load lazily with no supersede token: a late-loading stinger plays over the next game, and the first boss has a silent gap
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** Server on 8230. node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/t6b_stinger_late.js (lose.mp3 delayed 2.5 s via page.route, click Play again immediately) and t34_bossgap.js (boss.mp3 delayed 2 s).
|
||||
- **Observed:** t6b: Play again pressed while lose.mp3 is still loading; ~1.5-3 s later lose.mp3 is PLAYING (vol 0.50) on top of battle.mp3 in the new running game. t34: a rootkit appears: battle fades 0.44 -> 0.11 over 1.25 s, then SILENCE from 1659 ms to 3188 ms, boss.mp3 audible only from 3597 ms. On a LAN the delays are negligible; on mobile data the 6-8 MB tracks are first fetched at the moment they are needed.
|
||||
- **Expected:** Stinger callback ignored if the game state changed; tracks preloaded (or at least the next likely track) so there is no gap.
|
||||
- **Suggested fix:** Add a token to stinger() like applyMusic has; preload boss/win/lose with preload='auto' once the first track plays.
|
||||
|
||||
### code-13 [LOW] No way to mute on the end screen: M is swallowed and the sound button is covered while the 13 s stinger plays
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** Server on 8230: node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/t36_endmute.js and t6_audio.js (T6a).
|
||||
- **Observed:** With the end overlay up: elementFromPoint at the Sound button centre returns '#end'; pressing M leaves muted=false; lose.mp3 stays PLAYING at vol 0.50. (I did not demonstrate that setMuted() itself fails to stop a stinger; it only stops the music element per the code, not verified in a browser.)
|
||||
- **Expected:** M and the mute button work on the end screen; muting stops the stinger.
|
||||
- **Suggested fix:** Allow the M key while overlays are open (it is global), and make setMuted() also stop/fade stingEl.
|
||||
|
||||
### code-14 [LOW] SIMULATED iOS autoplay rules: a rejected play() is never retried, music stays silent for the whole session
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/t8_ios.js (server on 8230). Simulation only: HTMLMediaElement.play() is made to reject with NotAllowedError unless called synchronously inside a pointerdown/keydown/click handler. Real iOS Safari was not available.
|
||||
- **Observed:** First tap: menu.mp3 play() REJECTED -> Audio.now=null; 5 more taps: no retry (still null, only 1 rejection logged); Play solo: battle.mp3 play() REJECTED -> null; further taps/keys: no retry. The code comment says 'blocked: will retry on next gesture' but unlock() returns immediately once `unlocked` is true and nothing re-applies the wanted track. The elements are also created asynchronously after the manifest fetch, i.e. outside the gesture, which is exactly what iOS refuses. Note it also clobbers `current` even if a newer token owns it.
|
||||
- **Expected:** On a blocked play(), keep `wanted` and retry in the next pointerup/keydown; prime the elements inside the gesture.
|
||||
- **Suggested fix:** In the catch set a `needsGesture` flag and call applyMusic() from the global pointerup/touchend/keydown listener while it is set; create/prime the Audio elements synchronously in unlock().
|
||||
|
||||
### code-15 [LOW] Audio file that fails before canplay: 10-35 s of silence, then synth for the rest of the session even after the server recovers
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/proxy.js (8231, needs 8230) then t16_midfail.js and t16b_midfail.js (battle.mp3 unreachable beyond 120 KB / 400 KB).
|
||||
- **Observed:** t16: Audio.now stays {battle,'pending'} (no sound) for ~8-10 s, then {battle,'synth'}; t16b: 'pending' for ~30 s, synth from 36 s (MediaError 4). After the proxy is back to normal and a new game starts the track is still synth (t16 last line: kind 'synth', battle.mp3 ERR4) because fileState is never reset. Losing the network DURING playback is fine (t16d: element stalls then resumes by itself, boss/battle switching works), so that case is not a bug.
|
||||
- **Expected:** A load timeout (e.g. 4 s) that falls back to synth immediately, and a retry on the next track change.
|
||||
- **Suggested fix:** setTimeout fallback in fileFor; don't latch 'missing' for network errors (only for 404/unsupported).
|
||||
|
||||
### code-16 [LOW] Rapid music() calls create duplicate Audio elements and parallel downloads of the same 8 MB file
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/t23_dup.js (server on 8230). Triggered with direct NW.Audio.music() calls in one tick (battle,theme,battle,theme,battle); I did not show a UI path that does this.
|
||||
- **Observed:** Audio elements created: menu.mp3, battle.mp3 x3; three 'bytes=0-' requests for battle.mp3 (8 MB each).
|
||||
- **Expected:** One element/request per track.
|
||||
- **Suggested fix:** Cache the loading promise/element per name before the first canplay.
|
||||
|
||||
### code-17 [LOW] Stale `ui.coop` after leaving a co-op room: solo turrets keep drawing co-op owner flags
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/t15_stale.js (server on 8230): host leaves a 2-player room, starts solo, builds a filter tower; canvas pixel at the tower's top-left corner is read. (The screenshot clip in that script misses the board; rely on the pixel values.)
|
||||
- **Observed:** Pixel after leaving co-op = [77,227,255] (the slot-0 cyan owner flag); control page that never joined co-op = [13,28,42].
|
||||
- **Expected:** No owner flags in solo.
|
||||
- **Suggested fix:** Reset ui.coop=false and ui.names={} in startSolo/leaveToMenu/previewMap.
|
||||
|
||||
### code-18 [LOW] Fit/zoom-reset button stays visible after the camera is reset by a new game or an orientation change
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/t15_stale.js (Play again part) and t15b_fit.js (viewport 1100x700 -> 400x900).
|
||||
- **Observed:** Zoomed 2.88x -> Fit visible; after Play again zoom=1 but Fit still visible. Zoomed 1.15 landscape -> turn to portrait: rot=1.5708, zoom=1, fitBtnVisible=true.
|
||||
- **Expected:** Fit hidden when zoom is 1.
|
||||
- **Suggested fix:** Call updateFit() from adoptBoard() and resizeCanvas() (or make the renderer emit a zoom change).
|
||||
|
||||
### code-19 [LOW] RemoteController that dies (fatal) leaves its document/window listeners registered; each failed join leaks one
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/t19_leak.js (server on 8230): join a non-existent room 5 times.
|
||||
- **Observed:** visibilitychange listeners added=5, removed=0 (same for window 'online'); each controller also stays reachable with its board.
|
||||
- **Expected:** All listeners removed on fatal/close.
|
||||
- **Suggested fix:** Move the listener removal into a _dispose() called from both _die() and close().
|
||||
|
||||
### code-20 [LOW] Wake lock is never released when returning to the main menu
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/t26_misc.js (server on 8230). navigator.wakeLock is STUBBED to count requests/releases; real device behaviour not tested.
|
||||
- **Observed:** menu: req 0/active 0; during game req 1/active 1; after lose -> Menu: still req 1/active 1 with inGame=false.
|
||||
- **Expected:** Release the lock when leaving the game.
|
||||
- **Suggested fix:** Release in leaveToMenu / btnEndMenu and re-request in startSolo.
|
||||
|
||||
### code-21 [LOW] Closing the help overlay or the menu un-pauses a game the player had paused
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/t26_misc.js (server on 8230).
|
||||
- **Observed:** P -> paused=true; H then 'Got it' -> paused=false; P, then Menu -> 'Back to game' -> paused=false.
|
||||
- **Expected:** Remember whether the player paused and restore that state.
|
||||
- **Suggested fix:** Remember `pausedBeforeOverlay` when opening and only unpause if the overlay itself caused the pause.
|
||||
|
||||
### code-22 [LOW] Wheel zoom uses a fixed 1.15x per event regardless of deltaY, so trackpads zoom far too fast
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/t26_misc.js (last line), server on 8230.
|
||||
- **Observed:** 6 wheel events with deltaY=-1 each -> zoom 1.15, 1.32, 1.52, 1.75, 2.01, 2.31.
|
||||
- **Expected:** Zoom proportional to |deltaY| (e.g. exp(-deltaY*k)).
|
||||
- **Suggested fix:** zoom *= Math.exp(-e.deltaY * 0.0015) with deltaMode normalisation.
|
||||
|
||||
### code-23 [LOW] Touch: tapping outside the board with a tower selected shows 'Build' for an off-board cell and Build silently does nothing
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/t25_touch_oob.js (touch context 844x390, server on 8230); screenshot .../t25_touch_oob.png
|
||||
- **Observed:** pending={x:-1,y:0}, confirm bar 'Build · 25' visible with no ghost on the board; tapping Build leaves pending and the bar unchanged, no toast.
|
||||
- **Expected:** Taps outside the board clear the pending cell.
|
||||
- **Suggested fix:** In the touch branch only set pending when inBounds, else clear it and call updateConfirm().
|
||||
|
||||
### code-24 [LOW] 'Resume co-op game' and the reload auto-rejoin fail silently when the room is gone
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/t33_resume.js (seeded localStorage nw.session with room ZZZZ, server on 8230).
|
||||
- **Observed:** After clicking Resume: only the menu overlay visible, lobbyMsg (hidden) = 'That room does not exist (any more).', no toast, the Resume button remains visible.
|
||||
- **Expected:** Visible feedback and the stale Resume button removed.
|
||||
- **Suggested fix:** On fatal while the lobby is hidden show a toast and call updateResumeButton().
|
||||
|
||||
### code-25 [LOW] Winning does not persist the 'best wave' record
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/t21_win.js (server on 8230).
|
||||
- **Observed:** Lose at wave 12 -> stored nw.best.open=12. Then win at wave 30 -> the end screen shows Best 30 (max of the two) but localStorage still holds 12.
|
||||
- **Expected:** Persist the best on a win as well.
|
||||
- **Suggested fix:** Drop the `!won &&` condition.
|
||||
|
||||
### code-26 [LOW] First-run help is never shown to co-op players, and is shown on every solo start when storage throws
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/t35_helpcoop.js and t18_env.js (first block, storage throwing), server on 8230.
|
||||
- **Observed:** Fresh profile that joins a co-op room (create or join by code): help overlay hidden on both, nw.helped=null. With localStorage/sessionStorage throwing, the help overlay appears again on the 2nd 'New solo game' (nw.helped can't persist). No other errors with storage failures.
|
||||
- **Expected:** A new invited player sees the help at least once.
|
||||
- **Suggested fix:** Show help from the co-op joined branch too if !nw.helped.
|
||||
|
||||
### code-27 [LOW] Accessibility basics: static Sound label without state, speed value not exposed, low-contrast unaffordable cost, zoom disabled, board not keyboard operable
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** Sound/speed: node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/t35_helpcoop.js. Contrast: computed from the CSS colour values with the WCAG formula (inline node snippet; not measured in a browser).
|
||||
- **Observed:** After muting: #btnSound aria-label still 'Sound', aria-pressed=null. #btnSpeed accessible name 'Game speed' while the visible text is '1×' (speed not announced). `.tbtn.poor .cost` red (#ff5c7a) at 72% opacity on #111b30 ~ 3.67:1 (<4.5:1); other checked pairs 5.8-12.9:1. Viewport has user-scalable=no, maximum-scale=1. The canvas has role=img but towers can only be placed with a pointer (no keyboard cursor).
|
||||
- **Expected:** State exposed to assistive tech; >= 4.5:1; page zoom allowed.
|
||||
- **Suggested fix:** aria-pressed on the sound toggle, aria-label with the speed value, drop the opacity on .poor (use a border/strike), remove user-scalable=no (the canvas already uses touch-action:none).
|
||||
|
||||
### code-28 [LOW] Defence in depth: ctrl.room is inserted unescaped via innerHTML in renderPlayers (CSP is the only barrier)
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** node /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/client-code/t32_roomsink.js (routeWebSocket rewrites the server's 'joined' room to an <img onerror> payload; server on 8230).
|
||||
- **Observed:** An <img> and <b> element are injected into #players; the onerror handler does NOT run (window.__xss=0) because CSP reports script-src-attr violations (2). Only server-supplied data reaches this sink; the real server emits 4-char codes and player names are rendered with textContent (t17_xss.js: names like <img onerror>, '"><svg/onload>', <script> -> no injected elements, no execution, no CSP violations).
|
||||
- **Expected:** Escape or use textContent for the room code.
|
||||
- **Suggested fix:** Build the room label with textContent like the names.
|
||||
|
||||
|
||||
## Visual / UX QA (22 findings)
|
||||
|
||||
*Coverage:* Harness (all under SP=/tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/visual-qa): lib.js (helpers + in-page metrics), shots.js (31 single-player states x 10 viewports), coop-shots.js (two-browser co-op incl. real server kill/restart), extra.js (fold geometry, toast/confirm overlap, zoom, fx close-ups), repro_wall.js, owner-markers.js, fps.js; ~470 PNGs and metrics-<vp>.json in shots/. Servers on ports 8240-8245 only, all killed; repo untouched (git status shows only the pre-existing untracked tools/).\n\nViewports: 1280x800, 1920x1080, tablet 768x1024 and 1024x768, phone 390x844, 360x640, 844x390, 667x375 (all phones/tablets with isMobile+hasTouch+dsf2 so coarse-pointer rules apply), plus 200% zoom emulations 640x400 and 960x540 (dsf2). States captured: menu for each map, help, lobby (empty, empty-code error, 'room does not exist', file [...]
|
||||
|
||||
### visual-1 [HIGH] Selecting a placed Firewall throws a TypeError: no info panel and walls can never be sold
|
||||
*Status:* **CONFIRMED** (verifier severity: high)
|
||||
|
||||
- **Repro:** node $SP/reviews/visual-qa/repro_wall.js (SP=/tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad). Manual: solo game, pick Firewall, place one, press Esc, click/tap the wall, press X. Also logged by shots.js state 'select-wall' at every viewport.
|
||||
- **Observed:** pageerror 'Cannot read properties of undefined (reading dmg)' at statsFor (main.js:210). renderInfo computes nxt = statsFor(type, i+1) when tower.level < 3, but TD.TOWERS.wall.levels has only 1 entry, and upCost = def.levels[tower.level].cost would throw the same way. Result on desktop and 390x844: #info stays empty (innerHTML length 0), app.selTower=1 so only the white selection bracket shows, the Sell button never exists, and pressing X leaves towers.length unchanged (1 -> 1). Because selectTower() throws, updateConfirm() and hint(null) are skipped too. Walls therefore cannot be removed or refunded from the UI in a maze-building game.
|
||||
- **Expected:** Tapping a Firewall opens a panel with name, 'Blocks the route...' and a Sell button (refund 100%), as designed.
|
||||
- **Suggested fix:** Use def.levels.length instead of the hard-coded 3: const maxLv = def.levels.length; const nxt = tower.level < maxLv ? statsFor(tower.type, i + 1) : null; const upCost = tower.level < maxLv ? def.levels[tower.level].cost : null; also in updateInfoDynamic (t.level < 3). Guard statsFor with if (!L) return []. Add an e2e step that selects a wall and sells it.
|
||||
- **Verifier:** Reproduced independently with my own Playwright scripts (v.js and v2.js under the verify-visual scratch dir), against the real server on port 8240.
|
||||
|
||||
Steps: solo game, click or tap the Firewall palette button, place a wall at cell (10,5), press Esc (selType=null, selTower=0), click or tap the wall, press X, Delete and Backspace.
|
||||
|
||||
Observed on desktop 1280x800 (mouse) and phone 390x844 (touch):
|
||||
- pageerror "Cannot read properties of undefined (reading 'dmg')", thrown at statsFor (main.js:210), called from renderInfo (main.js:237).
|
||||
- After the tap: selTower=1, #info innerHTML length 0, no [data-ac [...]
|
||||
- **Verifier's better fix:** Minimal fix: in renderInfo, compute `const maxLv = def.levels.length;` and use it in place of the hard-coded 3 at main.js:237 (`nxt = tower.level < maxLv ? statsFor(...) : null`) and main.js:245 (`upCost = tower.level < maxLv ? def.levels[tower.level].cost : null`). I tested exactly this by route-patching main.js and it fixed the wall panel and the sell. The reviewer's other suggestions are optional:
|
||||
- updateInfoDynamic (line 280) does not throw for walls, because `up` is null for a wall and `up && ...` short-circuits. Switching it to levels.length is for consistency only.
|
||||
- A `if (!L) return [...]
|
||||
|
||||
### visual-2 [HIGH] Phones: Upgrade / Target / Sell buttons are below the fold when a tower is selected
|
||||
*Status:* **CONFIRMED** (verifier severity: high)
|
||||
|
||||
- **Repro:** node shots.js p390,p360,l667 select-ids ; node extra.js <vp> infoFold (reads geometry). Screens: shots/p390-select-ids.png, p360-select-ids.png, l667-select-ids.png
|
||||
- **Observed:** Measured via getBoundingClientRect after tapping a level-2 IDS Sniper: 390x844 upgrade button top 856 / sell 904-946 vs viewport 844 (fully off-screen, #side scrolls 430 vs 245 visible); 360x640 upgrade 737-779, sell 785-827 vs 640, with only 160px of side panel visible of which the sticky palette takes 101px (so ~60px for the panel: just the tower name); 667x375 upgrade 461-499, sell 549-587 vs 375. Nothing hints that the side panel scrolls. Upgrading/selling is the main action after building, and on phones the player sees stats but not the buttons.
|
||||
- **Expected:** Upgrade and Sell reachable without scrolling in every phone layout, ideally next to the selected tower.
|
||||
- **Suggested fix:** In the stacked and landscape-phone layouts render the selected-tower actions as a docked bar like #confirm (position:absolute; bottom:10px; z-index:3; Upgrade | Target | Sell, 44px high) and hide .desc and .kv behind a 'details' toggle; or at minimum '#info .actions{order:-1}' (actions above stats) plus '.panel.info .desc{display:none}' under the compact media queries. Also reduce portrait '#stage{max-height:58dvh}' to ~50dvh when #info is non-empty.
|
||||
- **Verifier:** Reproduced from scratch with my own Playwright scripts against the real server on port 8241. The scripts are in /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/verify-visual/ as fold.js, reach.js, drag.js, matrix.js and fix.js. The server is stopped. Method: touch contexts, solo play, place an IDS Sniper, upgrade it to level 2, then select it with a real touchscreen tap on the board. I measured getBoundingClientRect and document.elementFromPoint.
|
||||
|
||||
PHONE LAYOUTS (level-2 IDS Sniper selected; viewport height vh, then the #side visible/total hei [...]
|
||||
- **Verifier's better fix:** The reviewer's minimal fix does not work. '#info .actions{order:-1}' is a no-op because .panel.info computes to display:block, so order does nothing. I measured it: Upgrade stays at 737-779 at 360x640 and 837-879 at 390x844. Adding '.panel.info .desc{display:none}' only moves Upgrade to 699-741 at 360x640 (vh 640) and 799-841 / Sell 847-889 at 390x844, which is still off-screen. Making .panel.info a column flex, putting .actions first (nowrap, one row) and hiding .desc got the buttons to about 598-640 at 360x640 (flush with the fold) and 717-759 at 390x844. That fits at 390x844 but is borderli [...]
|
||||
|
||||
### visual-3 [HIGH] Primary buttons below the fold on small phones; first-run Help auto-opens with no visible 'Got it'
|
||||
*Status:* **CONFIRMED** (verifier severity: medium)
|
||||
|
||||
- **Repro:** node extra.js l667 fold ; node extra.js p360 fold ; shots/l667-menu-open.png, l667-help-ingame.png, p360-help.png, z200s-menu-open.png
|
||||
- **Observed:** 667x375: #btnSolo/#btnCoop top 357 bottom 401 (viewport 375, half clipped), #btnHelpClose top 474 (99px below the fold), lobby back link 396-432. 360x640: #btnHelpClose top 753 bottom 805 (113px below), lobby back 609-645. .card scrolls internally (scrollHeight 444 vs 345 on l667 menu; 519 vs 345 on help) with no scrollbar or fade. startSolo() opens Help automatically the first time (nw.helped unset) so a first-time landscape-phone player gets a wall of text cut mid-sentence ('Walls paint as you drag. Pinch to zoom, two fingers to pan, long-press to...') and no visible way to start. 200% desktop zoom (640x400) shows Play solo half cut as well.
|
||||
- **Expected:** Play solo / Got it / Join always visible; text may scroll, buttons may not.
|
||||
- **Suggested fix:** Make the action row sticky: '.card .row:last-child, #help .row{position:sticky;bottom:0;background:linear-gradient(transparent,#0a1124 30%);padding-top:10px}'; add an always-visible close/X in the top-right of #help; under (orientation:landscape) and (max-height:520px) shrink h1 (clamp 22-28px), hide .tag and .mapcard .df, and put the three map cards plus the two big buttons in one 2-column layout so the menu fits 375px.
|
||||
- **Verifier:** Reproduced from scratch with my own Playwright scripts against the real server on port 8241, with fresh localStorage. Scripts and screenshots are in /tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/verify-visual/fold/ (fold.js, touchscroll.js, others.js, fix.js).
|
||||
|
||||
**Numbers match the claim.**
|
||||
- 667x375, touch: #btnSolo and #btnCoop have top 357 and bottom 401. The .card is clientHeight 345 against scrollHeight 444, with overflow-y auto and no scrollbar or fade.
|
||||
- First run on 667x375: startSolo() opens Help because nw.helped was null. #btnHelp [...]
|
||||
- **Verifier's better fix:** Add an explicit class to the action rows in public/index.html. These are the Play solo / Co-op row in #menu, the row in #help, the Create/Join area in #lobby, and the row in #end. Then add this CSS:
|
||||
|
||||
.card .row.act { position: sticky; bottom: 0; z-index: 1; margin-top: 0; padding: 12px 0 0; background: linear-gradient(rgba(10,17,36,0), #0a1124 22%); }
|
||||
|
||||
I injected this with the class added from JS. Results:
|
||||
- 667x375: Play solo and Co-op 44/44 visible, Got it 44/44.
|
||||
- 740x340: Play solo and Co-op 46/46, Got it 46/46.
|
||||
- 360x640: Play solo and Co-op 52/52, Got it 52/52.
|
||||
|
||||
Optionally set bottom:-16 [...]
|
||||
|
||||
### visual-4 [HIGH] Co-op host cannot see the room code or Invite button on phones while waiting for a partner
|
||||
*Status:* **CONFIRMED** (verifier severity: medium)
|
||||
|
||||
- **Repro:** node coop-shots.js p360 8242 ; node coop-shots.js l667 8243 ; node coop-shots.js p390 8241 (notes 'invite geometry' in shots/coop-<vp>.json; shots/p360-coop-3-waiting-partner.png)
|
||||
- **Observed:** After Create room the only prominent invite info is a 2.6s toast ('Room L32W. Send the invite link to your partner!') that sits over the server icon and fades. #netChip is display:none at max-width 420px and at landscape max-width 700px, so the HUD shows no code. The #players panel with the code and Invite button is at the bottom of the scrolling side panel: 360x640 Invite button 731-773 (viewport 640), 667x375 372-410 (viewport 375), 390x844 about 835-877. On desktop (1280) the chip and panel are visible (Invite 398-438).
|
||||
- **Expected:** Waiting-for-partner state shows the code and a big Invite button on screen until the partner joins.
|
||||
- **Suggested fix:** While ctrl.players.length < 2 show a persistent banner in #stage (top, below hint): 'Room L32W - waiting for partner' with an Invite button (min 44px), or open a small modal after Create room with the code in 28px mono, Copy and Share buttons. Keep a compact room-code chip in the top bar on phones (hide the ping only, not the code).
|
||||
- **Verifier:** Reproduced with my own script (scratchpad/reviews/verify-visual/invite.js, real server on 8242, touch contexts, host taps Co-op, then Create room). The core geometry is true, but the claim overstates it.
|
||||
|
||||
CONFIRMED
|
||||
- Invite button is below the fold at t=0.4s and t=4s in every phone viewport I tried. Button top/bottom against viewport height: 360x640 731-773/640; 390x664 (Safari with toolbars) 745-787/664; 390x844 849-891/844; 412x915 890-932/915; 430x932 903-945/932; 667x375 landscape 372-410/375; 844x390 378-418/390. Only desktop 1280x800 shows it (398-438).
|
||||
- On 360x640 and 390x664 the whole [...]
|
||||
- **Verifier's better fix:** Simplest fix, no new banner or modal:
|
||||
1. Remove the display:none for #netChip in the (max-width: 420px) and small-landscape rules in public/css/style.css. I forced '#netChip{display:flex !important}' via addStyleTag. At 360x640, 375x667 and 390x844 the chip fits on the first top-bar row (e.g. x 284-354 at 360) and #topbar height stays 108, so the 'keep the bar to two rows' rationale does not hold. At 667x375 landscape the topbar stays 45px. At 320 wide it reflows but stays two rows (94 to 89px). The chip already hides the ping on stacked layouts.
|
||||
2. Make the chip a button that calls invite() ( [...]
|
||||
|
||||
### visual-5 [MEDIUM] Toasts are hidden behind the build/confirm bar and cover the server icon
|
||||
*Status:* **CONFIRMED** (verifier severity: low)
|
||||
|
||||
- **Repro:** node extra.js p390 toastOverlap ; node extra.js p360 toastOverlap ; shots/p390-toast-confirm-reject.png, shots/p390-toastOverlap.png
|
||||
- **Observed:** With the Build bar showing (tap a cell in the top half), the 'Not enough credits' and 'Wave 3 cleared +16 credits' toasts are positioned at confirm [83,522,307,588] vs toast [83,553,307,588] (390x844); [68,403,292,469] vs [68,434,292,469] (360x640): fully behind the bar (only a stray letter shows). Without the bar, bottom-centre toasts sit on the server icon in portrait (the core is at bottom centre): shots/p390-coop-3-waiting-partner.png, p390-invalid-blocks-wall-touch.png. On touch, walls on a sealing cell show both the red hint pill AND an identical toast.
|
||||
- **Expected:** Rejection/notification text always visible, never covering the base, never duplicated.
|
||||
- **Suggested fix:** Move #toasts to the top (top:44px, under #hint) or to bottom: calc(10px + 66px) when #confirm is visible; set #toasts{z-index:5}. Suppress the toast for rejections that the hint already shows (blocks, obstacle, gold) when ui.preview is active.
|
||||
- **Verifier:** Reproduced with my own Playwright scripts on the real server (port 8240, now killed). Scripts and shots are in the verify-visual scratch dir (v1.js to v4.js, shots/).
|
||||
|
||||
1) Toast hidden behind the confirm bar: reproduced.
|
||||
- Setup: touch context, solo play, IDS Sniper selected, tap a cell in the top part of the stage. The bar then sits at bottom:10px (updateConfirm only flips it to .top when the cell is in the lower half).
|
||||
- Natural trigger, no state hacks: build one filter tower, start wave 1 at 3x, keep the pending cell. The real toast "Wave 1 cleared +12 credits" appeared at [83,561,307,596] w [...]
|
||||
- **Verifier's better fix:** Keep the toasts at the bottom and lift them clear of the bar when it is at the bottom.
|
||||
- In updateConfirm(), set a flag on #stage, e.g. stage.dataset.bar = show ? (top ? 'top' : 'bottom') : ''.
|
||||
- In CSS add `#stage[data-bar="bottom"] #toasts { bottom: 82px; }`. The bar is about 66px tall plus 10px, and :has(#confirm:not([hidden]):not(.top)) works too.
|
||||
- When the bar is at the top, leave the toasts alone.
|
||||
- Optionally in toast(), skip the toast for 'blocks', 'obstacle', 'gold' and 'occupied' rejections when ui.preview is already showing the same hint text. That fixes the duplicate, but it is co [...]
|
||||
|
||||
### visual-6 [MEDIUM] prefers-reduced-motion: every toast is invisible and the low-lives pulse disappears
|
||||
*Status:* **CONFIRMED** (verifier severity: low)
|
||||
|
||||
- **Repro:** node shots.js d1280,p390 reduced-motion (notes in shots/metrics-<vp>.json; shots/p390-reduced-motion-toast.png)
|
||||
- **Observed:** Under emulated reduce, getComputedStyle(.toast).opacity was '0' in all 8 samples over ~500ms with animationDuration 1e-05s: the animation jumps to its last keyframe (opacity:0, 'forwards'). So 'Wave N cleared +credits', partner joined/left/lost connection, 'Reconnected', 'Invite link copied', 'Room X...' and the rejection reasons are never shown. #statLives.low has 0 running animations and background stays rgb(12,19,34): no low-integrity cue except the number. The canvas ignores the setting (marching route dashes, screen shake on leak, bobbing/rotating enemies).
|
||||
- **Expected:** Reduced motion removes movement, not the message.
|
||||
- **Suggested fix:** Replace the blanket rule: '@media (prefers-reduced-motion: reduce){ .toast{animation:none;opacity:1} .spinner{animation-duration:2s} #btnWave.attn{animation:none} }' and give states a static style: '#statLives.low{background:#3a1020;border-color:var(--red)}'. Remove the blanket '*{animation-duration:.01ms}'. In render.js read matchMedia('(prefers-reduced-motion: reduce)') and skip shake, set dash speed to 0, and skip ghost bobbing.
|
||||
- **Verifier:** Reproduced from scratch with my own Playwright scripts against the real server (port 8247, scripts in .../reviews/verify-visual/mine/). The cause is public/css/style.css line 232: `@media (prefers-reduced-motion: reduce){ *,*::before,*::after{ animation-duration:.01ms !important; animation-iteration-count:1 !important; ...} }`. It collides with `.toast{animation: toast 2.6s forwards}`, whose last keyframe is `100%{opacity:0}`. The toast is created and the animation completes instantly, so the fill-forwards state is opacity 0.
|
||||
|
||||
1. Rejection toast, 390x844 touch viewport, `reducedMotion:'reduce' [...]
|
||||
- **Verifier's better fix:** Simplest correct fix is to stop the blanket rule from breaking fill-forwards animations, not to rebuild everything. Replace line 232 with something like:
|
||||
|
||||
@media (prefers-reduced-motion: reduce){
|
||||
.toast{animation:none;opacity:1} /* JS already removes it after 2.7s */
|
||||
#btnWave.attn,.spinner{animation:none}
|
||||
.banner,.banner.show{transition:none}
|
||||
#statLives.low{animation:none;background:#3a1020;box-shadow:inset 0 0 0 1px var(--red)} /* static low-integrity cue */
|
||||
}
|
||||
|
||||
Reasons not to copy the reviewer's version verbatim:
|
||||
- Keep `.spinner` visibly rotating, for example `animation-duration:2s [...]
|
||||
|
||||
### visual-7 [MEDIUM] Low-integrity warning is too weak for a first-time player
|
||||
*Status:* **REFUTED** (verifier severity: low)
|
||||
|
||||
- **Repro:** node shots.js d1280,p390 lowlives (shots/p390-lowlives-a.png, d1280-lowlives-b.png)
|
||||
- **Observed:** At lives 4/20 the only changes are the heart pill background pulsing between #0c1322 and #3a1020 (barely visible at frame b) and a thin red partial arc around the server. No banner, toast, sound cue is visible in the UI, no board vignette. Easy to miss in a busy wave on a phone.
|
||||
- **Expected:** Clear 'critical' state: someone looking at the board notices it.
|
||||
- **Suggested fix:** At lives <= 25%: pill border 2px solid var(--red) plus glow (box-shadow 0 0 0 3px rgba(255,92,122,.35)), one-off toast/banner 'INTEGRITY CRITICAL' (use banner(..., true)), and a pulsing red inner border on #stage (box-shadow: inset 0 0 40px rgba(255,60,90,.35)). Keep it static for reduced motion.
|
||||
- **Verifier:** The claim's key premise is a test artefact. The reviewer's `lowlives` scenario sets `NW.app.ctrl.sim.lives = 4` directly (visual-qa/shots.js line 197), so no leak event fires. In the real game lives only drop through `Sim.leak()` (sim.js 641-645), which emits a 'leak' event. Every leak then triggers all of these (main.js 159, render.js 287-290):
|
||||
- `Audio.sfx('leak')`, a 0.35s sawtooth sweep plus noise burst.
|
||||
- Screen shake.
|
||||
- `flashCore = 1`, a red filled disc over the server.
|
||||
- A red expanding ring.
|
||||
|
||||
I reproduced this with my own script (scratch/verify-visual/lowl/run.js, desktop 1280x800, re [...]
|
||||
- **Verifier's better fix:** No change is needed for the claimed defect. If the owner wants a stronger critical state, a cheap static fix is enough. Give `#statLives.low` a persistent `border-color: var(--red)` and a `box-shadow: 0 0 0 2px rgba(255,92,122,.35)` that are not animated, so it also works under reduced motion. Keep the existing pulse on top. Optionally fire a single `banner('INTEGRITY CRITICAL', true)` when lives first crosses 25%. The inset board vignette and the per-frame pulsing border on #stage are not worth the extra render cost and clutter.
|
||||
|
||||
### visual-8 [MEDIUM] Partner cursor name label is clipped at the stage edges (and invisible near the top)
|
||||
*Status:* **CONFIRMED** (verifier severity: low)
|
||||
|
||||
- **Repro:** node coop-shots.js p390 8241 ; node coop-shots.js d1280 8244 ; shots/p390-coop-5-cursor-top-edge.png, p390-coop-5-cursor-corner-bl.png, d1280-coop-5-cursor-corner-tr.png (guest named 'Alexandra-Longnm', 16 chars)
|
||||
- **Observed:** Label is centred above the cell at -C/2-17/sc in screen-upright space with no clamping. Cursor on the board's right edge: label cut ('Alexandra-Lo' on 1280x800, 'Alexandra-Longnm' cut at the last letter on 390x844). In rotated portrait, the cursor in the top-left board corner (world 0,15) leaves the label above the canvas: only a 2px amber sliver under the top bar is visible. Label is also 11px text drawn at 0.4-0.5x scale-compensated size, wide for 16-char names.
|
||||
- **Expected:** Label always fully visible, flips below the cell or shifts inside the board when near an edge.
|
||||
- **Suggested fix:** Compute the label rect in screen space (after cellToScreen) and clamp x to [4, W-4-tw] and flip to below the cell (+C/2+4) when y-17 < 2. Draw it outside the rotated transform. Truncate names to 10 chars plus an ellipsis on the canvas.
|
||||
- **Verifier:** Reproduced with my own script (/tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/verify-visual/cur/cur.js, own server on port 8240). Host in co-op, guest on desktop named 'Alexandra-Longnm' (16 chars, the input maxlength), guest mouse moved to edge cells, screenshot taken on the host. The code in public/js/render.js lines 447-458 has no clamping, as claimed: it centres the label at x=cell centre and puts it at y = cell top - 17/sc, in the board transform. Findings: (1) Horizontal clipping on desktop is real. At d1280 the canvas is 960 wide. A c [...]
|
||||
- **Verifier's better fix:** Clamping is enough; the name is already capped at 16 chars by the input, so the suggested ellipsis truncation is unnecessary. Simplest fix: draw the cursor labels in screen space after the board drawing. Inside frame(), ctx.save(); ctx.setTransform(dpr,0,0,dpr,0,0); for each cursor take p = this.cellToScreen(gx,gy), half = C*this.scale/2, tw = measureText(nm).width+10 using an 11px font with no /sc compensation. Then x = clamp(p.x - tw/2, 2, this.W - 2 - tw), y = p.y - half - 17; if (y < 2) y = p.y + half + 2; fillRect(x,y,tw,15); fillText at (x+tw/2, y+7.5); ctx.restore(). This removes the ro [...]
|
||||
|
||||
### visual-9 [MEDIUM] forced-colors (Windows High Contrast): selected states vanish
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** node shots.js d1280,p390,l667 forced-colors (shots/d1280-forced-colors-menu.png, d1280-forced-colors-game.png)
|
||||
- **Observed:** With forcedColors:'active' the selection is carried by background colour + border colour + box-shadow, which the UA overrides: all three map cards look identical (no indication which map is selected), the selected tower button in the palette looks like the rest, and AUTO shows no pressed state (only the 'Wave 1 - 26s' text hints). The overlay/side panel backgrounds turn white while the canvas stays dark (white strip at right of the menu on desktop). Text is still black on white and readable.
|
||||
- **Expected:** Selected/pressed state still distinguishable.
|
||||
- **Suggested fix:** Add '@media (forced-colors: active){ .tbtn.sel,.mapcard[aria-checked="true"],button.toggle[aria-pressed="true"]{outline:3px solid Highlight;outline-offset:-3px;forced-color-adjust:none;background:Highlight;color:HighlightText} .overlay{background:Canvas} #side{border-left:1px solid CanvasText} }' and add a visible check mark/'selected' text to the map card (e.g. '✓' in .nm) so it does not rely on colour.
|
||||
|
||||
### visual-10 [MEDIUM] 360x640 phones: tiny 13.5px cells, ~150px of wasted black above/below the board, and only 160px left for the panel
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** node shots.js p360 game-maze,select-ids (metrics cellPx 13.52, stage [360,371], side [160,160]); shots/p360-game-maze.png
|
||||
- **Observed:** Stage is 360x371 (ratio 1.03 so the board is NOT rotated), the 26x16 board is 352x217 inside it, leaving ~77px black bands top and bottom, with cells 13.5 CSS px (finger-size ~44) while the side panel gets only 160px of 640 (sticky palette uses 101px of that). On 390x844 cells are 18.5px, 667x375 17.7px, 844x390 20.9px, 768x1024 29px.
|
||||
- **Expected:** Use the unused stage height for the controls; larger or equal tap cells.
|
||||
- **Suggested fix:** After choosing rotation, set the stage height to the fitted board height: stage.style.height = Math.min(0.58*innerHeight, boardH+8)+'px' (or CSS aspect-ratio without max-height when the width is the limiting side). That gives the side panel ~306px at 360x640. Consider enlarging tap tolerance: pick the nearest tower within 0.6 cell of the touch point in tapSelect().
|
||||
|
||||
### visual-11 [MEDIUM] Portrait phone palette scrolls sideways and hides the 6th tower (Router Arc) with no affordance
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** node shots.js p390,p360 game-open-empty (metrics clipped #palette scrollWidth 506 vs 390); shots/p390-game-maze.png
|
||||
- **Observed:** 5th tile ('Rate Limiter') is cut mid-word at the screen edge ('Rate Limite'), Router Arc is completely off-screen, scrollbar hidden, no fade. A new player on a phone may never learn a 6th turret (the anti-chain-lightning one) exists. Scroll-snap also shifts the palette when selecting a tile (visible in p390-coop-5-*.png).
|
||||
- **Expected:** All six build options visible or an unmistakable scroll cue.
|
||||
- **Suggested fix:** Use 6 equal columns on portrait phones: '#palette{display:grid;grid-template-columns:repeat(6,1fr);gap:4px}' with '.tbtn{min-height:64px;padding:4px 2px}', '.tbtn .nm{font-size:10px}' and short labels (Filter, Sniper, Mortar, Limiter, Arc) via data-short; or keep the scroller and add 'mask-image:linear-gradient(90deg,#000 85%,transparent)' plus a one-time nudge.
|
||||
|
||||
### visual-12 [MEDIUM] Route hint pill and Build bar cover the gateway / server and top board rows in portrait
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** node shots.js p390,p360 route-long,invalid-blocks (metrics floating hint/confirm); shots/p390-route-long.png
|
||||
- **Observed:** 390x844: hint [112,116,278,148] sits exactly on the gateway globe (centre ~204,121) and the first board row (board top 112); the Build bar [83,522,307,588] covers the server (centre ~185,584) and the last rows when the pending cell is in the top half. So while previewing a route the player cannot see where it starts or ends. On desktop the hint is at the top while the cell is often at the bottom (600px away).
|
||||
- **Expected:** Preview feedback near the finger/cursor, endpoints always visible.
|
||||
- **Suggested fix:** Anchor the hint to the ghost: draw it in the canvas next to the hovered cell (clamped to the stage) or put it just above #confirm; render the bar in the black bands outside the board (stage has 46px side margins in portrait, ~75px top/bottom on 360x640) or beside the palette; add 'pointer-events:none' and 'top:calc(8px + env(safe-area-inset-top))' is not enough. At minimum offset .hint to top:auto;bottom:76px when the gateway is within 3 rows of the top.
|
||||
|
||||
### visual-13 [LOW] Touch targets below 44px in landscape phones and stacked action buttons
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** node shots.js l667,l844,p390 select-ids (metrics 'small')
|
||||
- **Observed:** 667x375: Menu/Speed/Pause/Sound 36x38, AUTO 45x38, Cancel-build 36x44 with 4px gaps; 844x390: 40x40. Portrait info buttons 42px high. The coarse-pointer 46px rule (@media pointer:coarse) is overridden by the landscape rules. Pause, speed and sound are adjacent so mis-taps are likely.
|
||||
- **Expected:** >= 44px (Apple) / 48px (Material) for touch.
|
||||
- **Suggested fix:** Move the landscape overrides inside '@media (pointer:fine)' or set '--btn:44px' for coarse pointers and drop the top-bar padding instead; '.actions button{min-height:44px}'; '#btnCancelBuild{min-width:44px}'.
|
||||
|
||||
### visual-14 [LOW] Tower level is shown only by 1-3 sub-pixel white dots
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** node shots.js d1280,p390,p360 tower-sheet (shots/*-tower-sheet-crop.png)
|
||||
- **Observed:** Pip radius is 1.4 world px: 1.3 CSS px on 1280x800, 0.65 CSS px on 390x844, 0.48 CSS px on 360x640 (so dots are ~1-2 device px and vanish on dsf-1 screens). Level 1 vs 2 differ only by one extra dot; level 3 by a slightly thicker border. At 18px cells the glyphs themselves (barrel, crosshair) are still distinguishable by colour+shape, but an upgrade has almost no visible effect on the board.
|
||||
- **Expected:** Upgrade state readable at 14-20px cells.
|
||||
- **Suggested fix:** Draw pips with radius max(S*0.07, 1.6/scale) or as bars along the bottom edge; add a level-tinted fill (lvl2 rgba(col,.18), lvl3 rgba(col,.32)) and a small corner chevron; play a brighter 'up' ring.
|
||||
|
||||
### visual-15 [LOW] Co-op ownership markers are 3-4px and can be invisible
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** node owner-markers.js (shots/owner-markers-d1280.png); shots/p390-coop-5-cursor-corner-tr.png
|
||||
- **Observed:** The marker is an 8 world px corner triangle: 3.7 CSS px at 390x844, ~2.7 at 360x640. The host's marker (slot 0, cyan) on a cyan Rate Limiter tile merges with its border and is invisible; slot 1 amber on the lime Mortar and on the green Filter has weak contrast. No legend explains the notch; ownership is otherwise only in the info byline.
|
||||
- **Expected:** Whose turret is whose readable at a glance.
|
||||
- **Suggested fix:** Draw a 3 CSS px strip along the bottom edge of the tile in the owner colour on a dark 1px halo (or tint the pip dots by owner), size = max(8, 5/scale) world px; add a colour dot next to each player's name (already present in #players) and mention it in Help.
|
||||
|
||||
### visual-16 [LOW] Text contrast failures: poor-affordability tiles, disabled Upgrade, small dim labels
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** node shots.js d1280,p390 invalid-gold,select-ids,menu-open (lowContrast lists in shots/metrics-<vp>.json)
|
||||
- **Observed:** Computed ratios (AA needs 4.5): .tbtn.poor .cost (#ff5c7a at opacity .72) 3.51:1, IDS 60 cost 2.88:1, .key 2.96-3.57:1; disabled 'Upgrade 110' 3.17:1 and cost 2.88:1 (it is the number the player needs to save for); '.df DIFFICULTY' 11px 4.29:1; '.key' 10px 4.29:1; primary hover gradient #2290b0 with #eaffff text 3.56:1 (also stuck-hover after taps); placeholder text ~4.2:1. The 'poor' tiles are still clickable tools, so the disabled exemption does not apply.
|
||||
- **Expected:** AA 4.5:1 for text under 18px.
|
||||
- **Suggested fix:** '.tbtn.poor{opacity:1} .tbtn.poor .nm{color:#9fb2d4} .tbtn.poor .cost{color:#ff8fa3} .tbtn.poor canvas{opacity:.6}'; 'button:disabled{opacity:1;color:#8da3c8;background:#0c1426} #upCost{color:var(--amber)}'; '--dim:#8ea6cc' (6.2:1); '.mapcard .df,.tbtn .key{font-size:11px;color:#9db4d8}'; primary hover: keep the start colour #1b7a96 and lighten only the border.
|
||||
|
||||
### visual-17 [LOW] Next-wave legend identifies enemies by colour only; reddish types collapse under deuteranopia
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** node shots.js d1280 enemy-cvd (shots/d1280-enemy-cvd-deuteranopia.png, -achromatopsia.png)
|
||||
- **Observed:** On the board the enemies are well distinguishable by shape even in deuteranopia/achromatopsia (ping ring, worm blob with tail, trojan hexagon with padlock, spam arrow, spoof square floating above a shadow, rootkit spiked octagon, air units clearly different). The legend only shows a coloured 10px square: under deuteranopia 'Worm' (#ff9f43) and 'Rootkit' (#ff3b3b) squares are both khaki, ping/trojan too, so the legend does not tell the player what to look for.
|
||||
- **Expected:** Legend matches the board symbols.
|
||||
- **Suggested fix:** Draw 14px canvas icons (reuse drawMonster with a tiny scale) instead of the square, and keep the AIR/BOSS tags; add title text per entry.
|
||||
|
||||
### visual-18 [LOW] Paused state: resume icon duplicates the Wave button icon and board is not dimmed
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** node shots.js d1280,p390 paused (shots/d1280-paused.png)
|
||||
- **Observed:** The only cues are an amber 'PAUSED' pill centred over the board (covering a tower and route at 1280 and 390) and the pause button swapping to a play triangle that looks the same as the 'Wave 2' triangle next to it. Enemies, grid and effects look alive; no label says how to resume.
|
||||
- **Expected:** Obvious paused state with a clear resume affordance.
|
||||
- **Suggested fix:** '#stage.paused::after{content:"";position:absolute;inset:0;background:rgba(4,7,14,.45)}' plus 'PAUSED - tap to resume' in the pill, make the pill itself a button; use a distinct icon/colour (amber outline) for the pause button while paused.
|
||||
|
||||
### visual-19 [LOW] Reconnect overlay covers only the board; HUD stays live and there is no outcome/timeout message
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** node coop-shots.js p390 8241 (shots/p390-coop-9-reconnect-overlay.png, p390-coop-10-after-restart.png)
|
||||
- **Observed:** After killing the server the overlay appears within ~12s: dimmed board with spinner and 'Connection lost. Reconnecting...' (clear, 16px). Palette, wave, pause and sound buttons stay enabled; after the server comes back without the room the player lands on the lobby with only 'That room does not exist (any more).' (the in-progress game is gone, with no hint that the server was restarted). Under reduced motion the spinner will not spin.
|
||||
- **Expected:** Whole UI looks disabled and the failure reason is explained.
|
||||
- **Suggested fix:** Make the overlay inset:0 on #app (below only #btnMenu), add 'attempt n/14' text, and on fatal show 'The server restarted and the room was closed. Create a new room.'
|
||||
|
||||
### visual-20 [LOW] Everything is sized in px: system/browser text-size settings are ignored; viewport blocks UI zoom; 200% zoom lands in the cramped phone layout
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** node shots.js z200s,z200l all ; node shots.js d1280 font-scale
|
||||
- **Observed:** CDP Page.setFontSizes standard=32px changes nothing (h1 46px, .tag 15px, button height 46px before and after), so Android 'Largest font', Chrome 'Font size: very large' and desktop default-size settings have no effect. 200% desktop zoom of 1280x800 -> 640x400 CSS px uses the landscape-phone rules: menu Play solo cut, select-ids Upgrade cut (shots/z200s-*.png); 960x540 is fine except Target/Sell cut. 10-11px labels (.lbl, .key, .df, tbtn .nm 10.5-11.5px) stay tiny.
|
||||
- **Expected:** UI text scales with user preferences; zoom keeps core controls reachable.
|
||||
- **Suggested fix:** Convert UI fonts to rem (html{font-size:100%}, body 0.9375rem), use min-height in em for buttons, drop 'maximum-scale=1,user-scalable=no' (the canvas already sets touch-action:none, so pinch on the board is unaffected), raise the smallest labels to >=12px.
|
||||
|
||||
### visual-21 [LOW] Board is flush with the stage edge: server and gateway rings are cut off
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** node shots.js d1280,d1920 game-maze (shots/d1280-game-maze.png: right half of the green server ring clipped at x=960; shots/d1920-game-maze.png)
|
||||
- **Observed:** The core sits in the last column and its 25 world px ring extends past the 20px half-cell and the 4px padding, so it is clipped on the right on desktop; the gateway ring is clipped at the left edge. Same for the pulse ring (radius up to 28) on every map with edge spawns.
|
||||
- **Expected:** Endpoints fully visible.
|
||||
- **Suggested fix:** Increase pad to 14 (this.fit uses (W-pad*2)) or draw the board plate inside a 12 world px margin.
|
||||
|
||||
### visual-22 [LOW] Minor wording/legibility issues in the HUD and help
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** shots/l667-game-maze.png, l667-help.png, p390-route-long.png
|
||||
- **Observed:** On small landscape phones the wave counter reads just '1 /30' (WAVE label hidden); the first Help bullet says 'Hover to preview the new route' even on touch devices (the touch paragraph is only in the Controls bullet); the preview hint 'Route 44 -> 45 (+1)' never says what the number is (cells of path length, averaged over gateways), and the current route is drawn at 10% alpha during a preview so it cannot be compared with the amber one. The Build button stays enabled when credits are insufficient (tap just produces a toast).
|
||||
- **Expected:** Self-explanatory numbers and touch-appropriate copy.
|
||||
- **Suggested fix:** Keep a short 'W' prefix or use aria-label/title with a visible tooltip; change help to '<span class=kbd-only>Hover</span><span class=touch-only>Tap</span> to preview'; hint 'Route 44 -> 45 steps (+1)' and draw the old route at 0.35 alpha during preview; set #btnConfirmBuild disabled + 'Need N more' when gold < cost.
|
||||
|
||||
|
||||
## Reverse proxy (nginx / NPM) (9 findings)
|
||||
|
||||
*Coverage:* TESTED (all through a real nginx, not a fake). nginx 1.26.3 (Debian trixie .deb, apt-get download + dpkg-deb -x, no root) ran inside a private user+net+mount namespace (unshare -Urnm, scripts in $R=/tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/proxy/scripts: keeper.sh, ns, nginx-start, node-start, aux-start, nn, e2e). That gave real ports 80/443, [::]:80/443 and ::1, extra loopback aliases (203.0.113.5-7, 2001:db8::5-6, 192.168.77.9) as distinct client IPs, and a bind-mounted /etc/hosts. Nothing touched ports outside the namespace; node servers used 8251, 8253, 8255, 8256, 8254, 8257 inside it. I fetched NPM v2.16.0's real templates from GitHub (nginx.conf, proxy.conf, _location.conf, proxy_host.conf, force-ssl, assets, block-exploits, ssl-*, access list) and rendered them instead of the brief's header list; the http-level settings ar [...]
|
||||
|
||||
### proxy-1 [MEDIUM] Co-op returns 403 when the public URL has a non-default port; DEPLOY.md says NPM passes Host through and its fix does not cover ports
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** Harness: R=/tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad/reviews/proxy. Start the namespace (setsid unshare -Urnm --propagation private $R/scripts/keeper.sh &), then $R/scripts/ns $R/scripts/node-start main 8251 and $R/scripts/ns $R/scripts/nginx-start. Host highport.test is the NPM-faithful proxy host (proxy.conf from NPM v2.16.0: proxy_set_header Host $host) listening on 8250 (http) and 8252 (https). Run: $R/scripts/nn $R/probes/lobbymsg.js http://highport.test:8250/ and the same with https://highport.test:8252/. Then restart with $R/scripts/ns $R/scripts/node-start main 8251 ALLOWED_ORIGINS=http://highport.test:8250,https://highport.test:8252 [...]
|
||||
- **Observed:** Both browsers get HTTP 403 on /ws. The lobby shows only 'Could not reach the game server.'. Server log: refused websocket from ::1: Origin "https://highport.test:8252" does not match Host "highport.test". nginx $host drops the port, and NPM never sends X-Forwarded-Host or X-Forwarded-Port. With ALLOWED_ORIGINS that includes the port, both join. The same host on ports 80/443 works (all e2e scenarios pass). ALLOWED_ORIGINS=https://game.example.com without the port would not match Origin https://game.example.com:8443 (normalizeHost keeps non-default ports).
|
||||
- **Expected:** DEPLOY.md claims 'NPM passes the original Host header through ... no extra configuration is needed' and 'set ALLOWED_ORIGINS=https://game.example.com'. That holds only on 80/443. Anyone publishing NPM on a port such as 8443 gets a dead co-op and an unhelpful message.
|
||||
- **Suggested fix:** Docs: say the public port must be part of ALLOWED_ORIGINS when it is not 80/443 (for example https://game.example.com:8443), and that NPM's $host strips the port. Code, optional: when the refusal is a 403, have the lobby say 'the server refused this origin; see ALLOWED_ORIGINS'.
|
||||
|
||||
### proxy-2 [MEDIUM] DEPLOY.md's 'make the proxy send X-Forwarded-Host / set Host' cannot be done from NPM's Advanced tab for the default location
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** $R/scripts/ns curl -s http://echo.test/x (host echo.test = NPM default location with proxy_set_header X-Forwarded-Host $host; proxy_set_header Host an.internal.name; at server level, which is where NPM renders the Advanced tab). Also curl http://echo2.test/c/x (same two lines inside a custom location). Then $R/scripts/nn $R/probes/join.js ws://rewrite.test/ws http://rewrite.test (same Advanced lines in front of the real server on 8255).
|
||||
- **Observed:** Default location: the upstream echo shows host=echo.test and no X-Forwarded-Host at all. The Advanced lines are silently ignored, because NPM's location / sets its own proxy_set_header lines (proxy.conf) and nginx then inherits none from server level. In the custom location, X-Forwarded-Host: echo2.test does arrive. In NPM v2.16.0 backend/internal/nginx.js, an Advanced box that contains its own 'location / {' replaces NPM's default location (advancedConfigHasDefaultLocation), but then the user must re-add every proxy header and the Upgrade/Connection pair. With a hand-written config that does send X-Forwarded-Host (rw2.test), TRUST_PROXY=auto joins, TRUST_PROXY=0 gives 403, and ALLOWED_ORIGI [...]
|
||||
- **Expected:** The doc offers the X-Forwarded-Host route as an equal alternative; for an NPM user it is a dead end without a full custom 'location /' block.
|
||||
- **Suggested fix:** Recommend ALLOWED_ORIGINS as the one NPM-compatible fix. Mention X-Forwarded-Host only for hand-written nginx, or give the full 'location / {...}' block to paste into Advanced.
|
||||
|
||||
### proxy-3 [MEDIUM] Path-prefix section does not tell NPM users how to get prefix stripping; two plausible NPM inputs break co-op or everything
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** Hosts with NPM's _location.conf rendering and NPM TLS settings: example.test (location /netwall/, proxy_pass http://127.0.0.1:8251/), ex2.test (location /netwall without trailing slash, proxy_pass .../), ex3.test (location /netwall/, proxy_pass without URI), ex4.test (DEPLOY.md section 7 block pasted verbatim into the Advanced position). For each: curl -sk -o /dev/null -w '%{http_code}\n' https://<host>/netwall/healthz and https://<host>/netwall/ws; then NODE_TLS_REJECT_UNAUTHORIZED=0 node $R/probes/join.js wss://<host>/netwall/ws https://<host>; browser: $R/scripts/nn $R/probes/browse.js https://example.test/netwall/ coop. All five e2e scenarios also ran against https://example.test/netwall [...]
|
||||
- **Observed:** example.test and ex4.test (the doc's verbatim block): everything works. Page, css/js/icons (h2), manifest start_url/scope /netwall/, service worker scope https://example.test/netwall/, wss://example.test/netwall/ws joined, music 206 under /netwall/assets/music/, no console errors, e2e 5/5 PASS. ex2 (no trailing slash in the location): static files load but /netwall/healthz -> 404 and /netwall/ws -> 404 (upstream sees //ws), so co-op fails with 'WebSocket ... Unexpected response code: 404'. ex3 (no URI in proxy_pass): every /netwall/* is 404. Also, nginx itself 301s /netwall to /netwall/ for a location ending in '/', so 'location = /netwall { return 301 /netwall/; }' is redundant (observed on [...]
|
||||
- **Expected:** A reader should be able to reproduce the working block from the NPM UI. Section 7 only says 'the dialog differs ... the result must be the block above'.
|
||||
- **Suggested fix:** Document that the custom-location path must be /netwall/ (with trailing slash). In NPM v2.16.0 backend/internal/nginx.js, renderLocations turns a slash inside Forward Hostname ('192.168.1.50/') into forward_path '/', which gives proxy_pass http://ip:port/ (I confirmed this from the backend code, not from the UI). Otherwise paste the block into the host's Advanced tab (verified working). Drop the redundant 'location =' line.
|
||||
|
||||
### proxy-4 [LOW] TRUST_PROXY=auto does not trust a proxy on a global IPv6 or CGNAT/Tailscale address, so all players share one per-IP bucket
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** $R/scripts/ns $R/scripts/node-start main 8251 MAX_CONN_PER_IP=3 (and again with TRUST_PROXY=1). Host v6gua.test forwards nginx to [2001:db8::6]:8251. Three parallel runs of: HOSTHDR=v6gua.test $R/scripts/nn $R/probes/join.js ws://127.0.0.1/ws http://v6gua.test <203.0.113.5|.6|.7> 2 3000. Trust list: $R/scripts/nn -e "require('/home/jav/git/towerdefence/server/net').isPrivateIp('100.64.1.1')".
|
||||
- **Observed:** auto: log shows 'from 2001:db8::6' for everybody; 3 sockets join and the rest get 429 across three different client IPs. TRUST_PROXY=1: client IPs 203.0.113.5/.6/.7 are each counted separately (2 joined each). isPrivateIp is false for 2001:db8::6, 2a0a:3e40:b00b:100::7 (this machine's own LAN GUA), 100.64.1.1 and ::ffff:100.64.0.1; true for 10/8, 172.16/12, 192.168/16, fc00::/7, fe80::/10, 127/8, ::1. 172.32.0.1 is correctly untrusted.
|
||||
- **Expected:** Section 6 says auto is 'meant for exactly this setup: only private-range peers (the proxy) are believed' and lists ULA only. On a dual-stack LAN the proxy may well connect from a GUA. The effect is a global cap of 40 sockets, the proxy IP in the logs, and X-Forwarded-Host ignored.
|
||||
- **Suggested fix:** Add a sentence to sections 4 and 6: if NPM reaches the LXC over a global IPv6 address or 100.64/10, set TRUST_PROXY=1 and firewall port 8080. Optionally add 100.64.0.0/10 to the private list.
|
||||
|
||||
### proxy-5 [LOW] DEPLOY.md keep-alive statements are inaccurate: NPM's default read timeout is 90 s, and the 25 s pings are not what keeps a joined game alive
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** keep-alive: $R/scripts/nn $R/probes/idle.js ws://short.test/ws 130 http://short.test (30 s proxy_read_timeout, harness server 8253 with the join window lengthened) and ws://s20.test/ws (20 s). In-game: $R/scripts/nn $R/probes/paused.js http://short.test/ 150 and http://s20.test/ 60. NPM defaults: $R/npm/v2160/nginx.conf. Dead peer: $R/scripts/ns env PATH=$PATH NODE_PATH=/home/jav/git/towerdefence/node_modules node $R/probes/deadpeer.js ws://127.0.0.1/ws http://plain.test plain.test
|
||||
- **Observed:** NPM v2.16.0 nginx.conf sets proxy_connect/send/read_timeout 90s and keepalive_timeout 90s, not 60 s. Never-joined raw socket: 30 s timeout survived 130 s with pings at 24.7/49.7/74.7/99.7/124.7 s; 20 s timeout died at 20.1 s (1006); the real server closes unjoined sockets at 10 s anyway (4408). Joined two-player room, paused: via 30 s timeout 150 s and via 20 s timeout 60 s, each browser 1 WebSocket open / 0 closes, 20.5 snapshot frames/s per client, because the server keeps broadcasting snapshots at 20 Hz while paused (room.js broadcastSnap is gated only on someone being online). A client that never answers pings was terminated by the server at 47.5 s through nginx, so ping-based dead-peer [...]
|
||||
- **Expected:** Doc: pings keep 'nginx's proxy_read_timeout (default 60 s) from firing on an idle but healthy game', and a read timeout below 25 s breaks it. In practice snapshots do that, a 20 s timeout does not hurt joined players, and NPM's default is 90 s. Pings matter only for detecting a dead peer.
|
||||
- **Suggested fix:** Reword: NPM default is 90 s; snapshots (20 Hz even when paused) keep the socket busy; pings are for dead-peer detection. Drop or soften the '<25 s' cause in the troubleshooting row.
|
||||
|
||||
### proxy-6 [LOW] Service worker serves nginx's 502 page instead of the cached game when the upstream is down
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** $R/scripts/ns env R=$R PATH=$PATH LD_LIBRARY_PATH=$LD_LIBRARY_PATH PLAYWRIGHT_BROWSERS_PATH=$PLAYWRIGHT_BROWSERS_PATH NODE_PATH=/home/jav/git/towerdefence/node_modules node $R/probes/sw502.js https://game.test/ and again with http://127.0.0.1:8251/ (direct).
|
||||
- **Observed:** Via nginx: SW is controlling, node is stopped, reload returns HTTP 502, title '502 Bad Gateway', #btnSolo absent. Direct to node: reload is served from the SW cache, title 'Netwall', and solo starts (ctrl.kind local). A 502 resolves rather than rejects, so the catch-branch fallback never runs.
|
||||
- **Expected:** The offline solo fallback should also work while the app server is restarting or unreachable behind the proxy.
|
||||
- **Suggested fix:** In sw.js treat a response with status >= 500 (or !res.ok for navigations) as a failure and fall back to caches.match.
|
||||
|
||||
### proxy-7 [LOW] NPM's real_ip handling lets LAN clients choose any client IP (per-IP cap bypass)
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** Host plain.test; node main 8251 with MAX_CONN_PER_IP=3; 8 parallel sockets from source 192.168.77.9 (loopback alias) with XRI=198.51.100.N each: XRI=198.51.100.$i HOSTHDR=plain.test $R/scripts/nn $R/probes/join.js ws://127.0.0.1/ws http://plain.test 192.168.77.9 1 5000. Control: real public source 203.0.113.5 x5, with and without XFF: 198.51.100.1.
|
||||
- **Observed:** Public client: 3 joined / 2 x 429, and a forged XFF does not help (rightmost non-private entry wins, log 'from 203.0.113.5'). LAN client with forged X-Real-IP: all 8 joined, logged as 198.51.100.1..8, because NPM nginx.conf has set_real_ip_from 10/8, 172.16/12, 192.168/16 and real_ip_header X-Real-IP, so $remote_addr is replaced before NPM builds X-Forwarded-For. 5 unforged LAN sockets from 192.168.77.9 were capped at 3 as expected.
|
||||
- **Expected:** Doc says a private-LAN client 'can still choose its own address'; with NPM it can choose any address, public ones included. Impact is limited to the cap and the log.
|
||||
- **Suggested fix:** Docs only: note it. Rely on the firewall and trusted LAN.
|
||||
|
||||
### proxy-8 [LOW] Large Cookie header: nginx answers 400 on the WebSocket upgrade above about 8 KB, while the page still loads over HTTP/2
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** for n in 4000 7800 8300 16000 17000; ck=$(head -c $n /dev/zero | tr '\0' a); $R/scripts/ns curl -sk --http2 -H "Cookie: a=$ck" https://game.test/healthz; and the same with --http1.1 and the Upgrade headers against /ws. Compare http://plain.test (h1.1) and node directly on 127.0.0.1:8251.
|
||||
- **Observed:** nginx (NPM default large_client_header_buffers 4 8k): 8300 B cookie gives 400 on h1.1 (page and WebSocket) and on the /ws upgrade over https; plain GET over h2 still returns 200 at 8300 B but fails (curl 000) at 16000 B. Node directly accepts up to 16 KB (431 at 17000 B). Request URLs of 8300 B give 414 at nginx. The game sets no cookies; they would come from other apps on the same parent domain.
|
||||
- **Expected:** A user with large parent-domain cookies sees the page load and co-op not connect, with no hint in the doc.
|
||||
- **Suggested fix:** Add a troubleshooting row: 400 'Request Header Or Cookie Too Large' means add 'large_client_header_buffers 4 16k;' in the NPM Advanced tab, or clear the cookies.
|
||||
|
||||
### proxy-9 [LOW] Minor DEPLOY.md/README accuracy and gaps
|
||||
*Status:* **UNVERIFIED**
|
||||
|
||||
- **Repro:** Run the doc's section 8 node -e snippet ($R/probes/doc-snippet.sh); git -C /home/jav/git/towerdefence status --short; compare README.md with docs/DEPLOY.md installation steps.
|
||||
- **Observed:** (1) The section 8 snippet works verbatim ('joined LMKN') but also prints a second line 'snap', not just 'joined XXXX'. (2) The gzip snippet is correct (main.js 48157 -> 16279 B, style.css 18776 -> 6020, sw.js, icon.svg, tracks.json compressed; NPM's own global gzip on compresses only text/html), but application/manifest+json is not in the list (733 B uncompressed). (3) README step 1 clones ssh://forgejo@int.git.vanvikinternet.no/... inside the LXC, which needs an SSH key or deploy key that the guide never mentions, while DEPLOY.md uses rsync: inconsistent. (4) tools/ is untracked while the README points to tools/bot.js, so a clone lacks it. (5) The working tree also shows ' M test/sim.test.j [...]
|
||||
- **Expected:** Docs should match behaviour and a clone should match the README.
|
||||
- **Suggested fix:** Fix the sample output line; add application/manifest+json to gzip_types; add a deploy-key note or use one install method; git add tools/ if it is meant to ship.
|
||||
|
||||
178
docs/review-2026-10-09/phase2-workflow.js
Normal file
178
docs/review-2026-10-09/phase2-workflow.js
Normal file
|
|
@ -0,0 +1,178 @@
|
|||
export const meta = {
|
||||
name: 'netwall-client-and-proxy-hardening',
|
||||
description: 'Independent reviewers (touch UX, co-op chaos, client code, visual QA, reverse proxy) -> adversarial verification -> single fixer -> final regression check',
|
||||
phases: [
|
||||
{ title: 'Review', detail: 'five reviewers probe the real game in real browsers' },
|
||||
{ title: 'Verify', detail: 'each finding is independently re-checked; only reproduced ones survive' },
|
||||
{ title: 'Fix', detail: 'one agent applies the verified findings and adds regression tests' },
|
||||
{ title: 'Final', detail: 'fresh agent re-runs everything and hunts regressions' },
|
||||
],
|
||||
}
|
||||
|
||||
const SP = '/tmp/claude-1000/-home-jav-git-towerdefence/417476cf-3c23-4caf-be25-6f9a83ee50b9/scratchpad'
|
||||
const ROOT = '/home/jav/git/towerdefence'
|
||||
|
||||
const COMMON = `
|
||||
PROJECT: "Netwall", an HTML5 maze-building tower defence game with solo play and two-player co-op. Repo: ${ROOT} (a git repo; do NOT run git commit/push; the lead does that).
|
||||
Read ${ROOT}/README.md first, then as needed ${ROOT}/docs/PROTOCOL.md and ${ROOT}/docs/DEPLOY.md.
|
||||
Layout: public/ (static client: index.html, css/style.css, js/sim.js shared pure rules, js/controllers.js Local+Remote controllers, js/render.js canvas renderer incl. 90-degree portrait rotation,
|
||||
js/main.js UI/input/lobby, js/audio.js, sw.js), server/ (Node, ws: static files + authoritative co-op rooms), test/ (node:test; ONLY real test files there), e2e/ (Playwright scenarios; run with "npm run e2e [-- filter]"), tools/bot.js (balance bot).
|
||||
The user plays on desktop AND phones (portrait + landscape, touch), solo and co-op, with the server behind nginx Proxy Manager on Debian 13, dual stack.
|
||||
ENVIRONMENT (no system Node/browser): source ${SP}/pwenv.sh -> puts Node 24 on PATH, sets LD_LIBRARY_PATH for headless Chromium and PLAYWRIGHT_BROWSERS_PATH.
|
||||
Playwright: require('playwright-core') works from ${ROOT} (node_modules). Launch with chromium.launch({args:['--no-sandbox']}). Working examples of every kind of browser test are in ${ROOT}/e2e/scenarios/*.js
|
||||
and ${SP}/{smoke,touch,coop,endflow,matrix,perf}.js. Screenshots can be looked at with the Read tool (it renders PNGs): use that, it is the best way to judge visuals.
|
||||
Start the real server with: cd ${ROOT} && PORT=<your port> HOST=127.0.0.1 node server/index.js (it serves public/ too; kill it when done). Use ONLY the port range given in your brief so parallel agents do not collide.
|
||||
Put scratch scripts/screenshots under ${SP}/reviews/<your-key>/ (create it), never in the repo, except regression tests when your brief says so.
|
||||
Do not edit repo files unless your brief explicitly says you may (reviewers are report-only). Report only what you reproduced; quote exact steps, observed vs expected, and numbers.
|
||||
Be skeptical of the code and of earlier claims; the author is an AI and the happy paths were only lightly exercised.`
|
||||
|
||||
const FINDINGS = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
findings: {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
title: { type: 'string' },
|
||||
severity: { type: 'string', enum: ['critical', 'high', 'medium', 'low'] },
|
||||
area: { type: 'string' },
|
||||
repro: { type: 'string', description: 'exact steps or script path that reproduces it' },
|
||||
observed: { type: 'string' },
|
||||
expected: { type: 'string' },
|
||||
suggestedFix: { type: 'string' },
|
||||
},
|
||||
required: ['title', 'severity', 'repro', 'observed', 'expected'],
|
||||
},
|
||||
},
|
||||
coverage: { type: 'string', description: 'what you tested, and what you could not test' },
|
||||
},
|
||||
required: ['findings', 'coverage'],
|
||||
}
|
||||
|
||||
const VERDICT = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
confirmed: { type: 'boolean' },
|
||||
severity: { type: 'string', enum: ['critical', 'high', 'medium', 'low', 'none'] },
|
||||
evidence: { type: 'string' },
|
||||
betterFix: { type: 'string' },
|
||||
},
|
||||
required: ['confirmed', 'evidence'],
|
||||
}
|
||||
|
||||
const FIX = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
fixed: { type: 'array', items: { type: 'object', properties: { title: { type: 'string' }, how: { type: 'string' }, files: { type: 'array', items: { type: 'string' } } }, required: ['title', 'how'] } },
|
||||
notFixed: { type: 'array', items: { type: 'object', properties: { title: { type: 'string' }, why: { type: 'string' } }, required: ['title', 'why'] } },
|
||||
testsAdded: { type: 'array', items: { type: 'string' } },
|
||||
unitTests: { type: 'string' },
|
||||
e2e: { type: 'string' },
|
||||
},
|
||||
required: ['fixed', 'notFixed', 'unitTests', 'e2e'],
|
||||
}
|
||||
|
||||
const DIMS = [
|
||||
{
|
||||
key: 'touch',
|
||||
ports: '8210-8219',
|
||||
prompt: `${COMMON}
|
||||
YOUR BRIEF (reviewer "touch-ux", ports ${'8210-8219'}): find bugs and UX problems for TOUCH play on phones and tablets. Drive Chromium with real touch via CDP Input.dispatchTouchEvent and Playwright device emulation
|
||||
(iPhone SE 375x667, iPhone 14 390x844, Pixel 7 412x915, small Android 360x640, landscape variants 667x375 / 844x390 / 915x412, iPad 768x1024 and 1024x768). Serve public/ (via the real server).
|
||||
Probe at least: tap-to-preview then confirm for every tower type; tapping the preview cell again; wall drag-painting incl. very fast drags and drags that leave the board; pinch zoom/pan clamping and recovery, zoom then rotate the device mid-game
|
||||
(resize the viewport while a pending placement, a selected tower, a zoomed camera and an open menu exist); two-finger gestures that start while one finger is painting; long-press ping vs scroll; tapping tiny cells at the minimum cell size
|
||||
(is the intended cell hit? check cellToScreen/screenToCell round trips under rotation + zoom + pan); the confirm bar/hint overlap with the board; top bar wrapping, buttons >= 44px tall on coarse pointers, text clipped,
|
||||
the info panel/palette scrolling in portrait, sticky palette; sound unlock on first touch; lobby inputs with a soft keyboard (16px font, viewport resize), the page never scrolling/bouncing/zooming; safe-area insets (emulate with env()
|
||||
overrides if you can); the stage 'touchmove preventDefault' not breaking palette scrolling; prefers-reduced-motion. Also check what happens when pointercancel fires mid-gesture (browser steals the touch).
|
||||
Report real defects with exact repro.`,
|
||||
},
|
||||
{
|
||||
key: 'coop',
|
||||
ports: '8220-8229',
|
||||
prompt: `${COMMON}
|
||||
YOUR BRIEF (reviewer "coop-chaos", ports ${'8220-8229'}): attack the CO-OP experience end to end with 2-3 real browser contexts against the real server (and raw 'ws' clients where useful). Probe: both players building on the same cell at the same instant;
|
||||
both selling/upgrading the same tower; a player placing while the partner's sell is in flight; selling the tower the partner has selected (their info panel must close, no stale actions); new game started by the host while the guest is mid-gesture, has a pending
|
||||
placement, or the end overlay open; map change on new game (renderer board swap, camera reset); a guest who joins mid-wave (does the snapshot/interpolation start cleanly? any ghost monsters?); reconnect during a wave, during pause, during the end screen,
|
||||
with the server's tw/rev changing while offline (state must be correct after resume); socket killed uncleanly (page.route abort / context.setOffline / kill the websocket from the server side) and the visible 'Reconnecting' overlay lifecycle; server restart while two
|
||||
clients are connected (what does each client show? can they recover or are they stranded? is the message sensible?); the server process receiving SIGTERM; invalid/expired invite codes, lowercase codes, ?room= with garbage, a third player joining a full room, the same
|
||||
browser tab reloading mid-game (sessionStorage resume) and a duplicated tab (same pid, close code 4001: what does the old tab show?), localStorage 'Resume' button flows, leaving the room via menu/leave, then creating another; host leaves -> guest promoted -> end screen 'Play again' available?;
|
||||
cursor/ping behaviour with different viewport sizes and a rotated (portrait) partner; pause/speed commands from both; sound/toasts on join/leave; interpolation smoothness (render a few hundred frames and look for monster teleports/backwards motion in the interpolated positions);
|
||||
long sessions (run 3x speed for a couple of minutes: memory growth in the page, snapshot buffer sizes, listener leaks). Report defects with exact repro. You may write throwaway scripts only in your scratch folder.`,
|
||||
},
|
||||
{
|
||||
key: 'code',
|
||||
ports: '8230-8239',
|
||||
prompt: `${COMMON}
|
||||
YOUR BRIEF (reviewer "client-code", ports ${'8230-8239'}): do a rigorous line-by-line review of ${ROOT}/public/js/main.js, controllers.js, render.js, audio.js, sw.js, index.html and css/style.css, then PROVE each suspected bug in a real browser before reporting it.
|
||||
Hunt for: null/undefined derefs and races between async events (controller 'joined'/'newgame'/'state' vs renderer.setBoard), stale state after leaving a room / starting a new solo game (selection, pending, hover, preview, ui flags, end overlay, music state, timers such as banner/long-press,
|
||||
wake lock), event listener and timer leaks (useController attaches listeners per controller; RemoteController timers/visibility listeners), per-frame allocations or O(n^2) work, memory growth in the renderer maps (aim/trk) and particle arrays, division by zero / NaN in camera math
|
||||
(zero-size stage during layout, orientation change), rotation math errors (screenToCell/cellToScreen inverse property under rotation, zoom and pan: write a randomised property test in the page), keyboard handling when overlays/inputs are focused, Space/Enter triggering a focused button AND the hotkey,
|
||||
innerHTML construction with any server- or user-supplied string (player names, room codes: XSS!), CSP compatibility (the server sends default-src 'self'; style-src 'unsafe-inline'), service worker behaviour (does it ever serve a stale game after an update? does it cache the websocket upgrade or /healthz? cache.put on partial content?),
|
||||
audio edge cases with the REAL files now in public/assets/music (menu/battle/boss are several MB, win/lose are 13 s stingers; tracks.json maps them; autoplay policy, rapid music()/stinger() calls, a track failing to load mid-game, the service worker and HTTP 206 range responses for audio, mute while a fade is running, switching map/leaving a room while music plays, iOS-style first-gesture unlock), accessibility basics (labels, focus order, focus trap in overlays, contrast), localStorage/sessionStorage failures (Safari private mode: simulate by making Storage throw), the first-run flow (help overlay), and browsers lacking APIs
|
||||
(no ResizeObserver, no AudioContext, no wakeLock, no clipboard). Fix nothing; report with proof (page.evaluate outputs, console errors, screenshots).`,
|
||||
},
|
||||
{
|
||||
key: 'visual',
|
||||
ports: '8240-8249',
|
||||
prompt: `${COMMON}
|
||||
YOUR BRIEF (reviewer "visual-qa", ports ${'8240-8249'}): act as a picky game UI/UX designer. Take screenshots (and LOOK at them with the Read tool) of every screen and state at desktop 1280x800, 1920x1080, tablet portrait/landscape, phone portrait 390x844 and 360x640, phone landscape 844x390 and 667x375:
|
||||
main menu (each map selected), help, lobby (empty, error message, joined waiting for partner), playing: empty board, after building a maze, with a long route preview (amber route + hint), invalid placement (red ghost + hint), selected tower with range ring, each tower type at levels 1-3 (glyphs readable? upgrade
|
||||
clearly visible?), each enemy type (shapes distinguishable at small size? air units clearly different from ground?), health bars, slow ring, boss wave banner, many monsters at once, explosions/arcs/tracers, partner cursor labels in rotated portrait mode, co-op ownership markers, end screens (win/lose), toasts, the reconnect overlay, paused state (is it obvious the game is paused?), low-lives warning.
|
||||
Judge: legibility, contrast (WCAG AA for text), tap-target sizes, alignment, clipped/overlapping elements, inconsistent spacing, anything confusing for a first-time player, whether the route preview and 'blocks the route' feedback are understandable, whether the board looks good (not just correct). Also test 200% browser zoom/large system font and the 'prefers-reduced-motion' and 'forced-colors' cases.
|
||||
Report concrete, fixable problems with the file/selector involved and a specific proposed change (CSS values, drawing tweaks). Rank by how much they hurt a new player. Do not report pure taste unless it hurts clarity.`,
|
||||
},
|
||||
{
|
||||
key: 'proxy',
|
||||
ports: '8250-8259',
|
||||
prompt: `${COMMON}
|
||||
YOUR BRIEF (reviewer "reverse-proxy", ports ${'8250-8259'}): verify the server works behind nginx exactly the way nginx Proxy Manager runs it. There is no system nginx and no root. Obtain nginx WITHOUT root: in ${SP}/reviews/proxy/ run "apt-get download nginx nginx-common libnginx-mod-... (only what is needed; check apt-cache depends)"
|
||||
plus any missing shared libraries, extract with "dpkg-deb -x" into a private prefix, and run it as an unprivileged user with your own nginx.conf (listen on a high port, pid/log/temp paths under your folder, daemon off, include mime types). If nginx genuinely cannot be run this way after a serious attempt, say so and fall back to a faithful Node reverse proxy
|
||||
(http + upgrade handling, HTTP/1.1, same header behaviour) while clearly stating the difference.
|
||||
Configure it like NPM does for a Proxy Host with Websockets Support: proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; Connection $connection_upgrade (map); Host $host; X-Forwarded-For $proxy_add_x_forwarded_for; X-Forwarded-Proto/Host/Port; X-Real-IP; proxy_pass http://127.0.0.1:<server port>;
|
||||
plus the Advanced snippet from docs/DEPLOY.md (read/send timeouts). Then, THROUGH the proxy, run the real browser e2e scenarios (point E2E_URL at the proxy; see e2e/run.js) and extra probes: WebSocket survives > 60 s idle with a short proxy_read_timeout=30s (keep-alive pings must hold it), an idle paused 2-player room for 2+ minutes,
|
||||
path-prefix deployment (location /netwall/ { proxy_pass http://127.0.0.1:<port>/; } with the client loading at /netwall/: do manifest, service worker scope, ws URL, css/js/icon URLs all resolve? check the browser console), HTTPS-like behaviour (X-Forwarded-Proto https; the client uses location.protocol, so also run nginx with a self-signed cert on a high port, use ignoreHTTPSErrors, and confirm wss:// works and the service worker registers),
|
||||
the Origin check with Host rewritten (proxy_set_header Host an.internal.name) and with ALLOWED_ORIGINS/TRUST_PROXY variants, per-IP connection cap seeing real client IPs from X-Forwarded-For, IPv6 (listen [::]:port in nginx, connect via http://[::1]:port/ with a browser and with curl -6; server bound to ::), gzip of static assets at the proxy, large header/cookie cases, nginx returning 502 while the server restarts (what does the client show? does it recover?), HTTP/2 to the browser.
|
||||
Also re-verify the claims in docs/DEPLOY.md against what you observe, and list every statement that is wrong or missing. Report findings; you may NOT edit repo files.`,
|
||||
},
|
||||
]
|
||||
|
||||
const verifyPrompt = (d, f) => `${COMMON}
|
||||
YOUR BRIEF: you are an adversarial VERIFIER. A reviewer ("${d.key}") claims this defect in the Netwall repo. Your job is to try hard to REFUTE it: reproduce it yourself from scratch with your own script (ports ${d.ports}; scratch under ${SP}/reviews/verify-${d.key}/), check whether it is intended behaviour, a test artefact, or already handled elsewhere, and judge the real severity for a real player on a real phone/desktop.
|
||||
Default to confirmed=false when you cannot reproduce it. If you confirm it, say precisely what evidence you saw, and propose a better/simpler fix if the suggestion is flawed. Do not edit repo files.
|
||||
CLAIM: ${JSON.stringify(f)}`
|
||||
|
||||
const results = await pipeline(
|
||||
DIMS,
|
||||
(d) => agent(d.prompt, { label: 'review:' + d.key, phase: 'Review', schema: FINDINGS }),
|
||||
(r, d) => parallel(((r && r.findings) || []).map((f, i) => () =>
|
||||
agent(verifyPrompt(d, f), { label: 'verify:' + d.key + ':' + (i + 1), phase: 'Verify', schema: VERDICT })
|
||||
.then((v) => ({ dim: d.key, finding: f, verdict: v })))),
|
||||
)
|
||||
|
||||
const all = results.filter(Boolean).flat().filter(Boolean)
|
||||
const confirmed = all.filter((x) => x.verdict && x.verdict.confirmed)
|
||||
const dismissed = all.filter((x) => !(x.verdict && x.verdict.confirmed))
|
||||
log('findings: ' + all.length + ', confirmed: ' + confirmed.length + ', dismissed: ' + dismissed.length)
|
||||
|
||||
phase('Fix')
|
||||
const fix = confirmed.length === 0 ? { fixed: [], notFixed: [], unitTests: 'skipped (nothing confirmed)', e2e: 'skipped (nothing confirmed)' } : await agent(`${COMMON}
|
||||
YOUR BRIEF (the FIXER): below are defects that independent reviewers found AND an independent verifier reproduced. You may edit repo files now (public/, server/, test/, e2e/, docs/, README, deploy/; NOT tools/bot.js or the balance constants in public/js/sim.js, those are being tuned elsewhere).
|
||||
Work through them in order of severity. For each: understand the root cause (do not paper over symptoms), fix it with minimal clean changes that match the surrounding style, and add a regression test where feasible (unit test in test/ for server/sim; an e2e scenario or an added assertion in e2e/scenarios for browser behaviour; keep every scenario deterministic).
|
||||
Respect the wire contract in docs/PROTOCOL.md; if a fix needs a protocol change, change server, client, tests AND the doc together. Re-run "cd ${ROOT} && node --test" and "cd ${ROOT} && npm run e2e" until both are green. If a finding is wrong or not worth fixing, say why in notFixed.
|
||||
Use your own ports 8260-8269 for any server you start.
|
||||
VERIFIED FINDINGS:
|
||||
${JSON.stringify(confirmed.map((x) => ({ dim: x.dim, ...x.finding, verifierEvidence: x.verdict.evidence, verifierSeverity: x.verdict.severity, verifierBetterFix: x.verdict.betterFix })), null, 1)}`,
|
||||
{ label: 'fix', phase: 'Fix', schema: FIX })
|
||||
|
||||
phase('Final')
|
||||
const final = await agent(`${COMMON}
|
||||
YOUR BRIEF (final QA, ports 8270-8279): a fixer just changed the repo to address these verified findings: ${JSON.stringify(fix)}.
|
||||
Run "cd ${ROOT} && node --test" and "cd ${ROOT} && npm run e2e" yourself. Then review the full change (diff the repo against its last commit: "git -C ${ROOT} diff" and "git -C ${ROOT} status", read-only git commands are fine) for regressions, sloppy fixes, leftover debug code, broken styling, files that should not exist,
|
||||
and anything inconsistent between server, client and docs/PROTOCOL.md. Play a short solo game and a short co-op game in a real browser at desktop and phone sizes and look at screenshots. Fix any trivial regression you find yourself (say what you changed); report anything bigger.`,
|
||||
{ label: 'final', phase: 'Final', schema: {
|
||||
type: 'object',
|
||||
properties: { unitTests: { type: 'string' }, e2e: { type: 'string' }, regressions: { type: 'array', items: { type: 'string' } }, changedByMe: { type: 'array', items: { type: 'string' } }, verdict: { type: 'string' } },
|
||||
required: ['unitTests', 'e2e', 'verdict'] } })
|
||||
|
||||
return { confirmed: confirmed.map((x) => ({ dim: x.dim, title: x.finding.title, severity: x.verdict.severity })), dismissed: dismissed.map((x) => ({ dim: x.dim, title: x.finding.title, why: x.verdict && x.verdict.evidence })), fix, final }
|
||||
BIN
docs/review-2026-10-09/repro-scripts.tgz
Normal file
BIN
docs/review-2026-10-09/repro-scripts.tgz
Normal file
Binary file not shown.
|
|
@ -38,8 +38,8 @@ test('placement validation: bounds, special cells, obstacles, occupancy, gold',
|
|||
assert.equal(s.place({}, 5, 5).reason, 'bad_type');
|
||||
assert.ok(s.place('wall', 5, 5).ok);
|
||||
assert.equal(s.place('wall', 5, 5).reason, 'occupied');
|
||||
assert.equal(s.gold, 95);
|
||||
s.gold = 1;
|
||||
assert.equal(s.gold, 100 - TOWERS.wall.levels[0].cost);
|
||||
s.gold = TOWERS.wall.levels[0].cost - 1;
|
||||
assert.equal(s.place('wall', 6, 5).reason, 'gold');
|
||||
assert.equal(s.place('ids', 6, 5).reason, 'gold');
|
||||
});
|
||||
|
|
@ -110,7 +110,7 @@ test('monsters walk to the core and cost lives; flyers go straight', () => {
|
|||
s.spawnQ.push({ t: 0, k: 'ghost', wave: 1 });
|
||||
s.wave = 1;
|
||||
run(s, 40);
|
||||
assert.equal(s.lives, 18, 'ping 1 + ghost 1 leaked');
|
||||
assert.equal(s.lives, 20 - ENEMIES.ping.leak - ENEMIES.ghost.leak, 'ping + ghost leaked');
|
||||
assert.equal(s.monsters.length, 0);
|
||||
});
|
||||
|
||||
|
|
@ -171,10 +171,12 @@ test('selling and upgrading', () => {
|
|||
assert.ok(s.upgrade(t.id).ok);
|
||||
assert.equal(s.upgrade(t.id).reason, 'max');
|
||||
assert.equal(t.level, 3);
|
||||
assert.equal(t.spent, 25 + 30 + 55);
|
||||
const lv = TOWERS.filter.levels;
|
||||
assert.equal(lv.length, 3);
|
||||
assert.equal(t.spent, lv[0].cost + lv[1].cost + lv[2].cost);
|
||||
const g = s.gold;
|
||||
const sold = s.sell(t.id);
|
||||
assert.equal(sold.refund, Math.floor(110 * TD.SELL_RATIO));
|
||||
assert.equal(sold.refund, Math.floor(t.spent * TD.SELL_RATIO));
|
||||
assert.equal(s.gold, g + sold.refund);
|
||||
assert.equal(s.towers.length, 0);
|
||||
assert.equal(s.sell(t.id).reason, 'no_tower');
|
||||
|
|
@ -217,7 +219,7 @@ test('towers kill monsters and pay out; mortar cannot hit flyers', () => {
|
|||
s2.spawnQ.push({ t: 0, k: 'ghost', wave: 1 });
|
||||
run(s2, 20);
|
||||
assert.equal(s2.kills, 0);
|
||||
assert.equal(s2.lives, 19);
|
||||
assert.equal(s2.lives, 20 - ENEMIES.ghost.leak);
|
||||
});
|
||||
|
||||
test('throttle slows monsters; rootkit is partly resistant', () => {
|
||||
|
|
@ -227,8 +229,10 @@ test('throttle slows monsters; rootkit is partly resistant', () => {
|
|||
const a = mk('ping', 5.5, 7.5), b = mk('rootkit', 5.5, 7.5);
|
||||
s.monsters = [a, b];
|
||||
s.updateTower(s.towers[0], STEP);
|
||||
assert.ok(Math.abs(a.slow - 0.35) < 1e-9);
|
||||
assert.ok(Math.abs(b.slow - 0.175) < 1e-9);
|
||||
const slow1 = TOWERS.throttle.levels[0].slow;
|
||||
assert.ok(Math.abs(a.slow - slow1) < 1e-9);
|
||||
assert.ok(Math.abs(b.slow - slow1 * (1 - ENEMIES.rootkit.slowRes)) < 1e-9);
|
||||
assert.ok(b.slow < a.slow);
|
||||
});
|
||||
|
||||
test('waves: queue, clear bonus, win and lose states, auto waves', () => {
|
||||
|
|
@ -237,7 +241,9 @@ test('waves: queue, clear bonus, win and lose states, auto waves', () => {
|
|||
assert.ok(s.spawnQ.length > 0);
|
||||
run(s, 60);
|
||||
assert.equal(s.state, 'won');
|
||||
assert.equal(s.gold, 12, 'wave clear bonus 10 + 2*wave');
|
||||
const clear = s.drainEvents().find((e) => e.e === 'clear');
|
||||
assert.ok(clear && clear.bonus > 0 && clear.n === 1, 'a clear event with a positive bonus');
|
||||
assert.equal(s.gold, clear.bonus, 'the wave clear bonus is the only income of an undefended wave');
|
||||
assert.ok(s.continueEndless().ok);
|
||||
assert.equal(s.state, 'playing');
|
||||
assert.ok(s.startWave().ok);
|
||||
|
|
@ -305,3 +311,39 @@ test('fuzz: garbage commands never throw', () => {
|
|||
for (const j of junk) assert.doesNotThrow(() => s.cmd(j));
|
||||
assert.equal(s.towers.length, 0);
|
||||
});
|
||||
|
||||
test('balance tables keep the shape the client and server rely on', () => {
|
||||
assert.deepEqual(TD.TOWER_ORDER, ['wall', 'filter', 'ids', 'mortar', 'throttle', 'arc']);
|
||||
assert.deepEqual(TD.ENEMY_ORDER, ['ping', 'worm', 'trojan', 'spam', 'ghost', 'rootkit']);
|
||||
assert.equal(TOWERS.wall.levels.length, 1);
|
||||
assert.ok(TOWERS.wall.refund, 'walls refund in full');
|
||||
for (const k of TD.TOWER_ORDER) {
|
||||
const t = TOWERS[k];
|
||||
assert.ok(t.name && t.color && t.key && t.desc, k + ' has display fields');
|
||||
if (k === 'wall') continue;
|
||||
assert.equal(t.levels.length, 3, k + ' has exactly 3 levels');
|
||||
t.levels.forEach((lv, i) => {
|
||||
assert.ok(lv.cost > 0 && lv.range > 0, k + ' L' + (i + 1) + ' cost/range');
|
||||
if (k === 'throttle') assert.ok(lv.slow > 0 && lv.slow <= 0.6, 'slow is capped at 0.6 by the sim');
|
||||
else assert.ok(lv.dmg > 0 && lv.rate > 0, k + ' L' + (i + 1) + ' dmg/rate');
|
||||
if (k === 'mortar') assert.ok(lv.splash > 0);
|
||||
if (k === 'arc') assert.ok(lv.chains >= 1 && lv.chainRange > 0 && lv.falloff > 0 && lv.falloff < 1);
|
||||
if (i > 0) assert.ok(lv.range >= t.levels[i - 1].range, 'range never shrinks on upgrade');
|
||||
});
|
||||
}
|
||||
for (const k of TD.ENEMY_ORDER) {
|
||||
const e = ENEMIES[k];
|
||||
assert.ok(e.name && e.color && e.hp > 0 && e.speed > 0 && e.reward > 0 && e.leak > 0 && e.armor >= 0 && e.r > 0, k);
|
||||
}
|
||||
assert.ok(TD.START_GOLD >= TOWERS.filter.levels[0].cost * 2, 'the opening credits buy at least two turrets');
|
||||
assert.ok(TD.SELL_RATIO > 0 && TD.SELL_RATIO < 1, 'selling a turret always loses credits');
|
||||
// no way to turn credits into more credits by buying, upgrading and selling
|
||||
for (const k of TD.TOWER_ORDER) {
|
||||
if (k === 'wall') continue;
|
||||
const spent = TOWERS[k].levels.reduce((a, l) => a + l.cost, 0);
|
||||
assert.ok(Math.floor(spent * TD.SELL_RATIO) < spent);
|
||||
}
|
||||
// the opening waves are survivable with the opening credits and wave pressure never decreases
|
||||
for (let n = 2; n <= 60; n++) assert.ok(TD.hpScale(n) > TD.hpScale(n - 1));
|
||||
for (let n = 2; n <= 60; n++) assert.ok(TD.rewardScale(n) >= TD.rewardScale(n - 1));
|
||||
});
|
||||
|
|
|
|||
885
tools/bot.js
Normal file
885
tools/bot.js
Normal file
|
|
@ -0,0 +1,885 @@
|
|||
#!/usr/bin/env node
|
||||
'use strict';
|
||||
/*
|
||||
* NETWALL balance bot - a headless "player" that drives Sim only through sim.cmd() / sim.preview() / sim.monsterCells()
|
||||
* and ticks with TD.STEP. It is a DEV TOOL (not a test): it exists to measure how the numbers in public/js/sim.js play.
|
||||
*
|
||||
* const { playGame } = require('./tools/bot');
|
||||
* const r = playGame({ map: 'open', strategy: 'maze', maxWave: 30, seed: 1 });
|
||||
* r.result -> { survivedWaves, won, livesLeft, ... } r.log -> [{ wave, lives, gold, towers, routeLen, kills, leaks, ... }]
|
||||
*
|
||||
* CLI (runs a matrix of games on all CPU cores and prints tables):
|
||||
* node tools/bot.js --maps open,twin,hub --strategies maze,nomaze,spam-filter,lazy --seeds 6 --max 30
|
||||
* node tools/bot.js --sim /path/to/other/sim.js ... (or SIM_PATH=...) to measure another copy of the sim (baselines)
|
||||
* node tools/bot.js --json out.json --detail (raw results / per-game rows)
|
||||
*
|
||||
* Strategies: maze | nomaze | spam-filter | spam-ids | spam-mortar | spam-arc | lazy
|
||||
* maze-no-<type> (ablation: the mixed maze build without one tower type, e.g. maze-no-ids)
|
||||
* any of them can take overrides: "maze:share=0.6,S=1.2" (see DEFAULTS)
|
||||
*
|
||||
* How the "mixed" build decides (it must adapt to whatever numbers are in the TOWERS / ENEMIES tables):
|
||||
* - The upcoming waves (next 3, plus a Rootkit wave up to 8 ahead) come from TD.waveSummary / TD.waveGroups and
|
||||
* hpScale. Each wave entry (kind, count, scaled hp, leak value, stream spacing) is a "threat".
|
||||
* - A cheap analytic model estimates how much damage the current defence deals to ONE packet of that kind during its walk
|
||||
* along the traced route (time inside each tower's range, throttle slows, armour, splash / chain multipliers,
|
||||
* flow-sharing when a dense stream is in range). Expected lives lost = sum threat.count * leak * (1 - min(1, dmg / (S*hp))).
|
||||
* - Every candidate purchase (new tower at a site, upgrade) is scored by the reduction of that surrogate per credit.
|
||||
* - The maze: greedy hill climbing on route length per credit over wall LINE segments anchored on a border / existing
|
||||
* solid cell (a single wall on open ground gains almost nothing, a whole line with a gap gains a lot), only under a wall
|
||||
* budget (a fraction of all credits seen so far). Turrets are placed on off-route sites with good coverage, or swapped
|
||||
* for an existing wall (walls refund 100%, so a swap costs only the turret).
|
||||
* - All randomness is a seeded PRNG used for per-seed "personality" (wall share, caution) and score jitter.
|
||||
*/
|
||||
const path = require('path');
|
||||
|
||||
const DEFAULT_SIM = process.env.SIM_PATH || path.join(__dirname, '..', 'public', 'js', 'sim.js');
|
||||
const ALL_TYPES = ['filter', 'ids', 'mortar', 'throttle', 'arc'];
|
||||
|
||||
const DEFAULTS = {
|
||||
maze: true, // build wall lines
|
||||
types: ALL_TYPES, // turret types the bot may buy
|
||||
share: 0.25, // walls may take this fraction of all credits seen so far (0.4 starves the turrets: measured worse at every difficulty)
|
||||
S: 1.4, // caution: want S x hp of damage per packet
|
||||
minGain: 3, // a wall segment must add at least this much route length (sum over spawns)
|
||||
minTurrets: 2, // turrets before the first wall
|
||||
idsStrong: false, // set IDS snipers to 'strong' targeting (off: it makes them ignore fast flyers when armoured ground units are in range)
|
||||
flat: false, // 'nomaze': refuse turret sites that lengthen the route
|
||||
lazy: false,
|
||||
jitter: 0.12, // relative score noise
|
||||
explore: 1.7, // curiosity: until exploreUntil, a type with fewer than 2 towers gets this bonus on new purchases
|
||||
exploreUntil: 10,
|
||||
learn: 0.5, // exponent of the damage-per-credit feedback (0 = off)
|
||||
persona: true, // randomise share / S per seed
|
||||
waitClear: true, // call next wave as soon as the previous is cleared (else only on the timer)
|
||||
waveTimer: 0, // sim seconds after which the next wave is called anyway (0 = TD.WAVE_INTERVAL, the server's auto-wave timer)
|
||||
thinkEvery: 60, // ticks between decisions during a wave (60 = once per sim second)
|
||||
horizon: 6, // waves looked ahead (the wave pattern repeats every 8, a human sees it coming)
|
||||
maxSegLen: 22,
|
||||
gate: false, // build a wall line only when its surrogate value per credit beats the best turret purchase
|
||||
kappa: 0.7,
|
||||
mazeFuture: 1.5, // a maze also boosts turrets bought later
|
||||
rampStart: 3, // wall budget share ramps up from this wave ...
|
||||
rampLen: 6, // ... over this many waves
|
||||
coreBias: 1.0, // prefer wall lines near the server (flyers end there too)
|
||||
compact: 1.0, // bonus for wall lines two cells from another solid line
|
||||
};
|
||||
|
||||
function parseStrategy(spec) {
|
||||
let name = spec, over = {};
|
||||
if (spec && typeof spec === 'object') { name = spec.name; over = spec; }
|
||||
else if (typeof spec === 'string' && spec.indexOf(':') >= 0) {
|
||||
name = spec.slice(0, spec.indexOf(':'));
|
||||
for (const kv of spec.slice(spec.indexOf(':') + 1).split(',')) {
|
||||
const [k, v] = kv.split('=');
|
||||
over[k] = v === 'true' ? true : v === 'false' ? false : isNaN(+v) ? v : +v;
|
||||
}
|
||||
}
|
||||
const s = Object.assign({}, DEFAULTS, { name: typeof spec === 'string' ? spec : name });
|
||||
if (name === 'maze') { /* defaults */ }
|
||||
else if (name === 'nomaze') { s.maze = false; s.flat = true; }
|
||||
else if (name.startsWith('spam-')) { s.types = [name.slice(5)]; }
|
||||
else if (name.startsWith('maze-no-')) { s.types = ALL_TYPES.filter((t) => t !== name.slice(8)); }
|
||||
else if (name === 'lazy') { s.lazy = true; s.maze = false; s.waitClear = false; }
|
||||
else throw new Error('unknown strategy ' + name);
|
||||
for (const k of Object.keys(over)) if (k !== 'name') s[k] = over[k];
|
||||
return s;
|
||||
}
|
||||
|
||||
function prng(seed) { // mulberry32
|
||||
let a = seed >>> 0;
|
||||
return function () {
|
||||
a = (a + 0x6D2B79F5) >>> 0;
|
||||
let t = a;
|
||||
t = Math.imul(t ^ (t >>> 15), t | 1);
|
||||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
const clamp = (v, lo, hi) => (v < lo ? lo : v > hi ? hi : v);
|
||||
const perHit = (d, armor) => Math.max(d - armor, d * 0.25);
|
||||
|
||||
class Bot {
|
||||
constructor(TD, sim, strat, rng, ctx) {
|
||||
this.TD = TD; this.sim = sim; this.s = Object.assign({}, strat); this.rng = rng;
|
||||
this.maxWave = ctx.maxWave;
|
||||
if (this.s.persona && !this.s.lazy) {
|
||||
this.s.share *= 0.7 + 0.6 * rng();
|
||||
this.s.S *= 0.85 + 0.3 * rng();
|
||||
this.s.minTurrets += Math.floor(rng() * 3);
|
||||
this.s.jitter *= 1 + rng();
|
||||
this.typeBias = {}; // every "player" has favourites
|
||||
for (const t of ALL_TYPES) this.typeBias[t] = 0.85 + 0.3 * rng();
|
||||
}
|
||||
this.kinds = TD.ENEMY_ORDER.map((k) => {
|
||||
const d = TD.ENEMIES[k];
|
||||
return { k, v: d.speed, armor: d.armor, air: !!d.air, slowRes: d.slowRes || 0, hp: d.hp, leak: d.leak };
|
||||
});
|
||||
this.typeBias = this.typeBias || {};
|
||||
this.kindIdx = {};
|
||||
this.kinds.forEach((k, i) => { this.kindIdx[k.k] = i; });
|
||||
this.wallCost = TD.TOWERS.wall.levels[0].cost;
|
||||
this.spentWalls = 0; this.spentOther = 0;
|
||||
this.plan = [];
|
||||
this.noPlanRev = -1;
|
||||
this.rev = -1;
|
||||
this.nSp = sim.board.spawns.length;
|
||||
this.minCost = Math.min.apply(null, this.s.types.map((t) => TD.TOWERS[t].levels[0].cost));
|
||||
this.lazyState = { init: false, done: {} };
|
||||
this.ema = {}; this.learned = {}; this.lastD = new Map();
|
||||
this.actions = 0;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ geometry cache
|
||||
// ground path points (cell centres) of every spawn's traced route
|
||||
pathsFromRoutes(routes) {
|
||||
const b = this.sim.board;
|
||||
const gx = [], gy = [], gl = [], gs = [];
|
||||
const onRoute = new Uint8Array(b.cols * b.rows);
|
||||
const touch = new Uint8Array(b.cols * b.rows);
|
||||
routes.forEach((route, ri) => {
|
||||
for (let j = 0; j < route.length; j++) {
|
||||
const c = route[j], p = route[j - 1], n = route[j + 1];
|
||||
let len = 0;
|
||||
if (p) len += Math.hypot(c[0] - p[0], c[1] - p[1]);
|
||||
if (n) len += Math.hypot(c[0] - n[0], c[1] - n[1]);
|
||||
gx.push(c[0] + 0.5); gy.push(c[1] + 0.5); gl.push(len / 2); gs.push(ri);
|
||||
onRoute[c[1] * b.cols + c[0]] = 1;
|
||||
touch[c[1] * b.cols + c[0]] = 1;
|
||||
if (n && n[0] !== c[0] && n[1] !== c[1]) { // diagonal step: both corner cells matter
|
||||
touch[c[1] * b.cols + n[0]] = 1; touch[n[1] * b.cols + c[0]] = 1;
|
||||
}
|
||||
}
|
||||
});
|
||||
return { g: { x: Float64Array.from(gx), y: Float64Array.from(gy), l: Float64Array.from(gl), s: Int32Array.from(gs), n: gx.length }, onRoute, touch };
|
||||
}
|
||||
|
||||
refresh() {
|
||||
const sim = this.sim, b = sim.board;
|
||||
if (this.rev === sim.rev && this.g) return;
|
||||
this.rev = sim.rev;
|
||||
const P = this.pathsFromRoutes(b.routes);
|
||||
this.g = P.g; this.onRoute = P.onRoute; this.touch = P.touch;
|
||||
if (!this.a) { // flyers go straight spawn -> core (static)
|
||||
const ax = [], ay = [], al = [], as = [];
|
||||
b.spawns.forEach((sp, si) => {
|
||||
const x0 = sp.x + 0.5, y0 = sp.y + 0.5, x1 = b.core.x + 0.5, y1 = b.core.y + 0.5;
|
||||
const d = Math.hypot(x1 - x0, y1 - y0), n = Math.max(2, Math.ceil(d / 0.25));
|
||||
for (let i = 0; i <= n; i++) { ax.push(x0 + (x1 - x0) * i / n); ay.push(y0 + (y1 - y0) * i / n); al.push(d / n); as.push(si); }
|
||||
});
|
||||
this.a = { x: Float64Array.from(ax), y: Float64Array.from(ay), l: Float64Array.from(al), s: Int32Array.from(as), n: ax.length };
|
||||
}
|
||||
this.specs = this.specsNow();
|
||||
}
|
||||
|
||||
specsNow() {
|
||||
const out = [];
|
||||
for (const t of this.sim.towers) {
|
||||
if (t.type === 'wall') continue;
|
||||
out.push({ id: t.id, type: t.type, level: t.level, x: t.x + 0.5, y: t.y + 0.5, st: this.TD.TOWERS[t.type].levels[t.level - 1] });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ threat model
|
||||
entries() {
|
||||
const sim = this.sim, TD = this.TD, nSp = this.nSp;
|
||||
const out = [];
|
||||
const add = (w, weight, onlyBoss) => {
|
||||
if (w > this.maxWave) return;
|
||||
const sum = TD.waveSummary(w), groups = TD.waveGroups(w);
|
||||
for (const q of sum) {
|
||||
if (onlyBoss && q.k !== 'rootkit') continue;
|
||||
const ki = this.kindIdx[q.k], K = this.kinds[ki];
|
||||
let gs = 0, gn = 0;
|
||||
for (const g of groups) if (g.k === q.k) { gs += g.gap * g.c; gn += g.c; }
|
||||
const g = (gn ? gs / gn : 1) * nSp; // seconds between consecutive packets on ONE route
|
||||
const h = Math.round(TD.ENEMIES[q.k].hp * TD.hpScale(w));
|
||||
out.push({ ki, N: q.c, Nr: Math.max(1, q.c / nSp), h, leak: K.leak, v: K.v, armor: K.armor, air: K.air, g, spacing: Math.max(0.2, K.v * g), w: weight });
|
||||
}
|
||||
};
|
||||
const cur = sim.wave, alive = sim.monsters.length > 0 || sim.spawnQ.length > 0;
|
||||
if (alive && cur >= 1) add(cur, 0.5, false);
|
||||
const wts = [1.0, 0.75, 0.55, 0.42, 0.32, 0.25, 0.2, 0.15];
|
||||
for (let i = 1; i <= this.s.horizon; i++) add(cur + i, wts[i - 1] || 0.15, false);
|
||||
for (let w = cur + this.s.horizon + 1; w <= cur + 10; w++) if (w % 10 === 0) add(w, 0.4, true);
|
||||
return out;
|
||||
}
|
||||
|
||||
slowFields(specs, G) {
|
||||
// per kind: slow factor at each path point from the throttles
|
||||
const out = [];
|
||||
specs = specs || this.specs; G = G || this.g;
|
||||
for (let ki = 0; ki < this.kinds.length; ki++) {
|
||||
const K = this.kinds[ki], P = K.air ? this.a : G;
|
||||
const arr = new Float64Array(P.n);
|
||||
for (const sp of specs) {
|
||||
if (sp.type !== 'throttle') continue;
|
||||
const r2 = sp.st.range * sp.st.range, eff = Math.min(0.6, sp.st.slow * (1 - K.slowRes));
|
||||
for (let i = 0; i < P.n; i++) {
|
||||
const dx = P.x[i] - sp.x, dy = P.y[i] - sp.y;
|
||||
if (dx * dx + dy * dy <= r2 && eff > arr[i]) arr[i] = eff;
|
||||
}
|
||||
}
|
||||
out.push(arr);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// damage one packet of entry e takes from tower spec sp over its whole walk (analytic model)
|
||||
capSpec(sp, e, slow, G) {
|
||||
if (sp.type === 'throttle') return 0;
|
||||
const TD = this.TD, td = TD.TOWERS[sp.type], st = sp.st;
|
||||
if (e.air ? !td.air : !td.ground) return 0;
|
||||
const hit0 = Math.min(perHit(st.dmg, e.armor), e.h); // no credit for overkill
|
||||
let dps = hit0 * st.rate, M = 1;
|
||||
if (sp.type === 'mortar') {
|
||||
dps *= 0.8;
|
||||
M = clamp(1 + 2 * st.splash / e.spacing, 1, Math.max(1, e.N));
|
||||
} else if (sp.type === 'arc') {
|
||||
const avail = 2 * st.chainRange / e.spacing;
|
||||
let tot = hit0, d = st.dmg;
|
||||
for (let i = 1; i <= st.chains; i++) {
|
||||
d *= st.falloff;
|
||||
const q = clamp(avail - (i - 1), 0, 1) * (i <= e.N - 1 ? 1 : 0);
|
||||
tot += q * Math.min(perHit(d, e.armor), e.h);
|
||||
}
|
||||
M = tot / hit0;
|
||||
}
|
||||
const P = e.air ? this.a : (G || this.g);
|
||||
const r2 = st.range * st.range;
|
||||
const Nr = e.Nr, flow = M * e.g;
|
||||
let total = 0, T = 0, seg = -1;
|
||||
const fin = () => dps * ((Nr - 1) * Math.min(T, flow) + T) / Nr;
|
||||
for (let i = 0; i < P.n; i++) {
|
||||
const sg = P.s[i];
|
||||
if (sg !== seg) { if (T > 0) total += fin(); T = 0; seg = sg; }
|
||||
const dx = P.x[i] - sp.x, dy = P.y[i] - sp.y;
|
||||
if (dx * dx + dy * dy <= r2) T += P.l[i] / (e.v * (1 - (slow ? slow[i] : 0)));
|
||||
else if (T > 0) { total += fin(); T = 0; }
|
||||
}
|
||||
if (T > 0) total += fin();
|
||||
return total / this.nSp;
|
||||
}
|
||||
|
||||
capsFor(specs, ents, slows, G) {
|
||||
const caps = new Float64Array(ents.length);
|
||||
for (const sp of specs) for (let i = 0; i < ents.length; i++) caps[i] += this.capSpec(sp, ents[i], slows[ents[i].ki], G);
|
||||
return caps;
|
||||
}
|
||||
|
||||
value(caps, ents) {
|
||||
let v = 0;
|
||||
for (let i = 0; i < ents.length; i++) {
|
||||
const e = ents[i], u = caps[i] / (this.s.S * e.h);
|
||||
v += e.w * e.N * e.leak * (Math.min(u, 1) + 0.08 * Math.min(u, 3));
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ turret sites
|
||||
sites() {
|
||||
const sim = this.sim, b = sim.board, cols = b.cols, TD = this.TD;
|
||||
const res = sim.monsterCells().reserved;
|
||||
const g = this.g, a = this.a;
|
||||
// one coverage ranking per distinct tower range (a sniper wants a different spot than a filter)
|
||||
const ranges = [];
|
||||
for (const t of this.s.types) { const r = TD.TOWERS[t].levels[1] ? TD.TOWERS[t].levels[1].range : TD.TOWERS[t].levels[0].range; if (!ranges.some((q) => Math.abs(q - r) < 0.3)) ranges.push(r); }
|
||||
const list = [];
|
||||
for (let y = 0; y < b.rows; y++) {
|
||||
for (let x = 0; x < cols; x++) {
|
||||
const i = y * cols + x;
|
||||
if (b.obst[i] || this.onRoute[i] || res.has(i) || b.isSpecial(x, y)) continue;
|
||||
const tw = sim.towerAt[i];
|
||||
if (b.solid[i] && !(tw && tw.type === 'wall')) continue;
|
||||
const cx = x + 0.5, cy = y + 0.5;
|
||||
const sc = ranges.map((r) => {
|
||||
const r2 = r * r; let sg = 0, sa = 0;
|
||||
for (let k = 0; k < g.n; k++) { const dx = g.x[k] - cx, dy = g.y[k] - cy; if (dx * dx + dy * dy <= r2) sg += g.l[k]; }
|
||||
for (let k = 0; k < a.n; k++) { const dx = a.x[k] - cx, dy = a.y[k] - cy; if (dx * dx + dy * dy <= r2) sa += a.l[k]; }
|
||||
return { g: sg, a: sa, c: sg + 0.5 * sa };
|
||||
});
|
||||
if (sc[0].c > 0 || sc[sc.length - 1].c > 0) list.push({ x, y, i, sc, wall: !!tw });
|
||||
}
|
||||
}
|
||||
const pick = new Map();
|
||||
ranges.forEach((r, ri) => {
|
||||
const byC = list.slice().sort((p, q) => q.sc[ri].c - p.sc[ri].c);
|
||||
const byA = list.slice().sort((p, q) => q.sc[ri].a - p.sc[ri].a);
|
||||
for (const c of byC.slice(0, 9)) pick.set(c.i, c);
|
||||
for (const c of byA.slice(0, 5)) pick.set(c.i, c);
|
||||
});
|
||||
const rest = list.filter((c) => !pick.has(c.i));
|
||||
for (let k = 0; k < 6 && rest.length; k++) { const c = rest.splice(Math.floor(this.rng() * rest.length), 1)[0]; pick.set(c.i, c); }
|
||||
return Array.from(pick.values());
|
||||
}
|
||||
|
||||
jit(v) { return v * (1 + this.s.jitter * (this.rng() - 0.5) * 2); }
|
||||
|
||||
// best purchase (new tower or upgrade) by surrogate value per credit; null when nothing is worth it
|
||||
bestOption() {
|
||||
const sim = this.sim, TD = this.TD;
|
||||
this.refresh();
|
||||
const ents = this.entries();
|
||||
if (!ents.length) return null;
|
||||
const slows = this.slowFields();
|
||||
const baseCaps = this.capsFor(this.specs, ents, slows);
|
||||
const baseV = this.value(baseCaps, ents);
|
||||
const perSpec = this.specs.map((sp) => ents.map((e) => this.capSpec(sp, e, slows[e.ki])));
|
||||
const opts = [];
|
||||
const consider = (o, newCaps) => {
|
||||
const dv = this.value(newCaps, ents) - baseV;
|
||||
o.ratio = this.jit(dv / o.cost) * (this.typeBias[o.type] || 1) * (this.learned[o.type] || 1) * (o.kind === 'new' && this.sim.wave <= this.s.exploreUntil && (this.typeCount[o.type] || 0) < 2 ? this.s.explore : 1);
|
||||
o.dv = dv;
|
||||
opts.push(o);
|
||||
};
|
||||
// upgrades
|
||||
this.specs.forEach((sp, si) => {
|
||||
const lv = TD.TOWERS[sp.type].levels[sp.level];
|
||||
if (!lv || !this.s.types.includes(sp.type)) return;
|
||||
const nsp = Object.assign({}, sp, { st: lv, level: sp.level + 1 });
|
||||
let nc;
|
||||
if (sp.type === 'throttle') {
|
||||
const specs2 = this.specs.map((q, j) => (j === si ? nsp : q));
|
||||
nc = this.capsFor(specs2, ents, this.slowFieldsFor(specs2));
|
||||
} else {
|
||||
nc = Float64Array.from(baseCaps);
|
||||
for (let i = 0; i < ents.length; i++) nc[i] += this.capSpec(nsp, ents[i], slows[ents[i].ki]) - perSpec[si][i];
|
||||
}
|
||||
consider({ kind: 'up', id: sp.id, type: sp.type, cost: lv.cost }, nc);
|
||||
});
|
||||
// new towers
|
||||
const sites = this.sites();
|
||||
this.typeCount = {};
|
||||
for (const sp of this.specs) this.typeCount[sp.type] = (this.typeCount[sp.type] || 0) + 1;
|
||||
for (const type of this.s.types) {
|
||||
const lv = TD.TOWERS[type].levels[0];
|
||||
const sl = type === 'throttle' ? sites.filter((q, ix) => ix % 3 === 0) : sites; // throttle evaluation is the expensive one
|
||||
for (const site of sl) {
|
||||
const nsp = { type, level: 1, x: site.x + 0.5, y: site.y + 0.5, st: lv };
|
||||
let nc;
|
||||
if (type === 'throttle') {
|
||||
const specs2 = this.specs.concat([nsp]);
|
||||
nc = this.capsFor(specs2, ents, this.slowFieldsFor(specs2));
|
||||
} else {
|
||||
nc = Float64Array.from(baseCaps);
|
||||
for (let i = 0; i < ents.length; i++) nc[i] += this.capSpec(nsp, ents[i], slows[ents[i].ki]);
|
||||
}
|
||||
consider({ kind: 'new', type, x: site.x, y: site.y, wall: site.wall, cost: lv.cost }, nc);
|
||||
}
|
||||
}
|
||||
return opts;
|
||||
}
|
||||
|
||||
slowFieldsFor(specs) { return this.slowFields(specs, this.g); }
|
||||
|
||||
buyBest() {
|
||||
const sim = this.sim;
|
||||
if (sim.gold < Math.max(this.minCost, this.waitCost || 0)) return false;
|
||||
this.waitCost = 0;
|
||||
let opts = this.bestOption();
|
||||
if (!opts || !opts.length) return false;
|
||||
opts.sort((p, q) => q.ratio - p.ratio);
|
||||
const best = opts[0];
|
||||
if (!(best.ratio > 0)) return false;
|
||||
this.waitCost = Math.min(best.cost, ...opts.filter((o) => o.ratio >= 0.6 * best.ratio).map((o) => o.cost));
|
||||
let pick = null;
|
||||
for (const o of opts) {
|
||||
if (o.ratio <= 0) break;
|
||||
if (o.cost > sim.gold) continue;
|
||||
if (this.s.flat && o.kind === 'new' && !o.wall) {
|
||||
const p = sim.preview(o.x, o.y, false);
|
||||
if (!p.ok || p.after - p.before > 0.5 * this.nSp) continue;
|
||||
}
|
||||
pick = o; break;
|
||||
}
|
||||
if (!pick) return false;
|
||||
if (pick.ratio < 0.6 * best.ratio && pick !== best) return false; // rather save for the clearly better option
|
||||
return this.exec(pick);
|
||||
}
|
||||
|
||||
exec(o) {
|
||||
const sim = this.sim;
|
||||
this.waitCost = 0;
|
||||
if (o.kind === 'up') {
|
||||
const r = sim.cmd({ c: 'upgrade', id: o.id });
|
||||
if (r.ok) { this.spentOther += o.cost; this.actions++; }
|
||||
return r.ok;
|
||||
}
|
||||
if (o.wall) { // swap an existing wall for the turret (walls refund 100%)
|
||||
const t = sim.towerAt[o.y * sim.board.cols + o.x];
|
||||
if (!t || t.type !== 'wall' || sim.gold + this.wallCost < o.cost) return false;
|
||||
const s = sim.cmd({ c: 'sell', id: t.id });
|
||||
if (!s.ok) return false;
|
||||
this.spentWalls -= this.wallCost;
|
||||
const r = sim.cmd({ c: 'place', type: o.type, x: o.x, y: o.y, by: 0 });
|
||||
if (!r.ok) {
|
||||
const back = sim.cmd({ c: 'place', type: 'wall', x: o.x, y: o.y, by: 0 });
|
||||
if (back.ok) this.spentWalls += this.wallCost;
|
||||
return false;
|
||||
}
|
||||
this.spentOther += o.cost; this.actions++;
|
||||
this.afterPlace(r.id, o.type);
|
||||
return true;
|
||||
}
|
||||
const r = sim.cmd({ c: 'place', type: o.type, x: o.x, y: o.y, by: 0 });
|
||||
if (!r.ok) return false;
|
||||
this.spentOther += o.cost; this.actions++;
|
||||
this.afterPlace(r.id, o.type);
|
||||
return true;
|
||||
}
|
||||
|
||||
afterPlace(id, type) {
|
||||
if (type === 'ids' && this.s.idsStrong) this.sim.cmd({ c: 'target', id, mode: 'strong' });
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ the maze
|
||||
turretCount() { let n = 0; for (const t of this.sim.towers) if (t.type !== 'wall') n++; return n; }
|
||||
wallCount() { let n = 0; for (const t of this.sim.towers) if (t.type === 'wall') n++; return n; }
|
||||
|
||||
wallBudget() {
|
||||
const total = this.spentWalls + this.spentOther + this.sim.gold;
|
||||
const ramp = clamp((this.sim.wave - this.s.rampStart) / this.s.rampLen, 0, 1); // early waves are cheap to hold; the maze can wait
|
||||
return this.s.share * ramp * total + 10 * (ramp > 0 ? 1 : 0) - this.spentWalls;
|
||||
}
|
||||
|
||||
// greedy hill climb: the wall line segment with the best route-length gain per credit that we can afford under the budget
|
||||
bestSegment(maxCells) {
|
||||
const TD = this.TD, sim = this.sim, b = sim.board, cols = b.cols, rows = b.rows;
|
||||
this.refresh();
|
||||
const mc = sim.monsterCells();
|
||||
const solid = Uint8Array.from(b.solid);
|
||||
const base = b.routeLen;
|
||||
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
|
||||
const cands = [];
|
||||
const maxL = Math.min(this.s.maxSegLen, maxCells);
|
||||
for (let y = 0; y < rows; y++) {
|
||||
for (let x = 0; x < cols; x++) {
|
||||
const i0 = y * cols + x;
|
||||
if (solid[i0] || b.isSpecial(x, y) || mc.reserved.has(i0)) continue;
|
||||
for (const d of dirs) {
|
||||
const bx = x - d[0], by = y - d[1];
|
||||
if (!(bx < 0 || by < 0 || bx >= cols || by >= rows || solid[by * cols + bx])) continue; // anchored start only
|
||||
let cx = x, cy = y, touched = false;
|
||||
const added = [];
|
||||
let bestL = null;
|
||||
for (let l = 1; l <= maxL; l++) {
|
||||
if (cx < 0 || cy < 0 || cx >= cols || cy >= rows) break;
|
||||
const ci = cy * cols + cx;
|
||||
if (solid[ci] || b.isSpecial(cx, cy) || mc.reserved.has(ci)) break;
|
||||
solid[ci] = 1; added.push(ci);
|
||||
if (this.touch[ci]) touched = true;
|
||||
if (touched) {
|
||||
const f = TD.buildField(cols, rows, solid, b.coreIdx);
|
||||
let blocked = false, after = 0;
|
||||
for (const sp of b.spawns) { const v = f[sp.y * cols + sp.x]; if (!isFinite(v)) { blocked = true; break; } after += v; }
|
||||
if (!blocked) for (const m of mc.must) if (!isFinite(f[m])) { blocked = true; break; }
|
||||
if (blocked) break;
|
||||
const gain = after - base;
|
||||
const ratio = gain / (this.wallCost * l);
|
||||
if (gain >= this.s.minGain && (!bestL || ratio > bestL.ratio * 1.001)) bestL = { l, gain, ratio };
|
||||
}
|
||||
cx += d[0]; cy += d[1];
|
||||
}
|
||||
for (const ci of added) solid[ci] = 0;
|
||||
if (bestL) {
|
||||
// compactness: a tight serpentine (parallel lines two cells apart) puts every turret next to several corridors
|
||||
let comp = 0;
|
||||
const px = d[1], py = d[0]; // perpendicular
|
||||
for (let k = 0; k < bestL.l; k++) {
|
||||
const qx = x + d[0] * k, qy = y + d[1] * k;
|
||||
for (const sgn of [1, -1]) {
|
||||
const ox = qx + sgn * px * 2, oy = qy + sgn * py * 2, mx = qx + sgn * px, my = qy + sgn * py;
|
||||
const outside = ox < 0 || oy < 0 || ox >= cols || oy >= rows;
|
||||
const wallThere = outside || solid[oy * cols + ox];
|
||||
const midFree = mx >= 0 && my >= 0 && mx < cols && my < rows && !solid[my * cols + mx];
|
||||
if (wallThere && midFree) { comp++; break; }
|
||||
}
|
||||
}
|
||||
const mx = x + d[0] * (bestL.l - 1) / 2 + 0.5, my = y + d[1] * (bestL.l - 1) / 2 + 0.5;
|
||||
const near = 1 - clamp(Math.hypot(mx - b.core.x - 0.5, my - b.core.y - 0.5) / 18, 0, 1); // keep the maze where the flight line ends too
|
||||
cands.push({ x, y, d, l: bestL.l, gain: bestL.gain, ratio: bestL.ratio * (1 + this.s.compact * comp / bestL.l) * (1 + this.s.coreBias * near), len: bestL.ratio });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!cands.length) return null;
|
||||
cands.sort((p, q) => q.ratio - p.ratio);
|
||||
// turret awareness: a segment that drags the route away from the existing turrets is worth less
|
||||
let pool = cands.slice(0, 8);
|
||||
if (this.specs.length) {
|
||||
const ents = this.entries();
|
||||
if (ents.length) {
|
||||
const J0 = this.value(this.capsFor(this.specs, ents, this.slowFields(), this.g), ents);
|
||||
for (const c of pool) {
|
||||
const sl = Uint8Array.from(b.solid);
|
||||
for (let k = 0; k < c.l; k++) sl[(c.y + c.d[1] * k) * cols + c.x + c.d[0] * k] = 1;
|
||||
const f = TD.buildField(cols, rows, sl, b.coreIdx);
|
||||
const routes = b.spawns.map((sp) => TD.traceRoute(cols, rows, sl, f, sp.x, sp.y));
|
||||
const P = this.pathsFromRoutes(routes);
|
||||
const J1 = this.value(this.capsFor(this.specs, ents, this.slowFields(this.specs, P.g), P.g), ents);
|
||||
c.dJ = J1 - J0;
|
||||
c.ret = J0 > 0 ? J1 / J0 : 1;
|
||||
c.score = c.ratio * Math.min(c.ret, 1.3) * (c.ret < 0.8 ? 0.3 : 1);
|
||||
}
|
||||
} else pool.forEach((c) => { c.score = c.ratio; });
|
||||
} else pool.forEach((c) => { c.score = c.ratio; });
|
||||
pool.sort((p, q) => q.score - p.score);
|
||||
const top = pool[0].score;
|
||||
if (!(top > 0)) return null;
|
||||
const near = pool.filter((c) => c.score >= top * 0.94);
|
||||
const c = near[Math.floor(this.rng() * near.length)];
|
||||
const cells = [];
|
||||
for (let k = 0; k < c.l; k++) cells.push([c.x + c.d[0] * k, c.y + c.d[1] * k]);
|
||||
return { cells, dJr: (c.dJ || 0) / (this.wallCost * c.l) };
|
||||
}
|
||||
|
||||
wallStep() {
|
||||
const sim = this.sim;
|
||||
if (!this.plan.length) {
|
||||
if (this.noPlanRev === sim.rev) return 0;
|
||||
if (this.wallBudget() < this.wallCost || sim.gold < this.wallCost) return 0;
|
||||
const seg = this.bestSegment(this.s.maxSegLen);
|
||||
if (!seg) { this.noPlanRev = sim.rev; return 0; }
|
||||
if (this.s.gate) {
|
||||
// is a wall line worth more per credit than the best turret purchase right now?
|
||||
const opts = this.bestOption() || [];
|
||||
let bt = 0;
|
||||
for (const o of opts) if (o.ratio > bt) bt = o.ratio;
|
||||
if (seg.dJr * this.s.mazeFuture < this.s.kappa * bt) { this.noPlanRev = sim.rev; return 0; }
|
||||
}
|
||||
this.plan = seg.cells;
|
||||
}
|
||||
let placed = 0;
|
||||
// walls are built incrementally as the wall budget (a share of all credits) and gold allow; a half-built line costs nothing but idle credits
|
||||
while (this.plan.length && sim.gold >= this.wallCost && this.wallBudget() >= this.wallCost) {
|
||||
const [x, y] = this.plan[0];
|
||||
const r = sim.cmd({ c: 'place', type: 'wall', x, y, by: 0 });
|
||||
if (r.ok) { placed++; this.spentWalls += this.wallCost; this.plan.shift(); }
|
||||
else if (r.reason === 'gold') break;
|
||||
else if (r.reason === 'monster') break; // retry later
|
||||
else if (r.reason === 'occupied') this.plan.shift();
|
||||
else { this.plan = []; break; }
|
||||
}
|
||||
if (placed) this.actions++;
|
||||
return placed;
|
||||
}
|
||||
|
||||
// sell a turret that covers none of the route / flight line any more (e.g. the maze moved the route away)
|
||||
prune() {
|
||||
const sim = this.sim;
|
||||
this.refresh();
|
||||
let sold = 0;
|
||||
for (const sp of this.specs) {
|
||||
if (sp.level > 1) continue;
|
||||
const r2 = sp.st.range * sp.st.range;
|
||||
let hit = false;
|
||||
for (let i = 0; i < this.g.n && !hit; i++) { const dx = this.g.x[i] - sp.x, dy = this.g.y[i] - sp.y; if (dx * dx + dy * dy <= r2) hit = true; }
|
||||
for (let i = 0; i < this.a.n && !hit; i++) { const dx = this.a.x[i] - sp.x, dy = this.a.y[i] - sp.y; if (dx * dx + dy * dy <= r2) hit = true; }
|
||||
if (!hit) { const r = sim.cmd({ c: 'sell', id: sp.id }); if (r.ok) { sold++; this.spentOther -= r.refund; } }
|
||||
}
|
||||
return sold;
|
||||
}
|
||||
|
||||
// A human watches the damage counters on the towers and buys more of what visibly works. Per wave: damage dealt per credit
|
||||
// invested, per tower type (exponential average); the types that beat the average get a bonus on their purchase score.
|
||||
learn() {
|
||||
if (!this.s.learn) return;
|
||||
const acc = {};
|
||||
for (const t of this.sim.towers) {
|
||||
if (t.type === 'wall' || t.type === 'throttle') continue;
|
||||
const prev = this.lastD.get(t.id);
|
||||
if (prev !== undefined) { const a = acc[t.type] || (acc[t.type] = { d: 0, c: 0 }); a.d += t.dealt - prev.d; a.c += prev.spent; }
|
||||
this.lastD.set(t.id, { d: t.dealt, spent: t.spent });
|
||||
}
|
||||
for (const k of Object.keys(acc)) {
|
||||
if (acc[k].c < 40) continue;
|
||||
const e = acc[k].d / acc[k].c;
|
||||
this.ema[k] = this.ema[k] === undefined ? e : 0.6 * this.ema[k] + 0.4 * e;
|
||||
}
|
||||
const ks = Object.keys(this.ema).filter((k) => this.ema[k] > 0);
|
||||
if (ks.length < 2) return;
|
||||
let lg = 0; for (const k of ks) lg += Math.log(this.ema[k]);
|
||||
const gm = Math.exp(lg / ks.length);
|
||||
for (const k of ks) this.learned[k] = clamp(Math.pow(this.ema[k] / gm, this.s.learn), 0.5, 2.5);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ the lazy player
|
||||
nearRoute(type, routeIdx) {
|
||||
const sim = this.sim, b = sim.board;
|
||||
this.refresh();
|
||||
const route = b.routes[0];
|
||||
const c = route[Math.min(route.length - 2, routeIdx)];
|
||||
const res = sim.monsterCells().reserved;
|
||||
for (let ring = 1; ring <= 3; ring++) {
|
||||
for (let dy = -ring; dy <= ring; dy++) for (let dx = -ring; dx <= ring; dx++) {
|
||||
const x = c[0] + dx, y = c[1] + dy;
|
||||
if (!b.inBounds(x, y)) continue;
|
||||
const i = y * b.cols + x;
|
||||
if (b.solid[i] || this.onRoute[i] || res.has(i) || b.isSpecial(x, y)) continue;
|
||||
const r = sim.cmd({ c: 'place', type, x, y, by: 0 });
|
||||
if (r.ok) { this.actions++; return true; }
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
lazyThink() {
|
||||
const sim = this.sim, TD = this.TD, ls = this.lazyState;
|
||||
if (!ls.init) {
|
||||
ls.init = true;
|
||||
let k = 0;
|
||||
while (sim.gold >= TD.TOWERS.filter.levels[0].cost && k < 4) { this.nearRoute('filter', 6 + 5 * k); k++; }
|
||||
return;
|
||||
}
|
||||
if (sim.wave > 0 && sim.wave % 6 === 0 && !ls.done[sim.wave]) {
|
||||
ls.done[sim.wave] = true;
|
||||
let guard = 0;
|
||||
while (guard++ < 4) { // a few clicks: upgrade the oldest tower that can be upgraded, else a filter
|
||||
const t = sim.towers.find((q) => q.type !== 'wall' && TD.TOWERS[q.type].levels[q.level]);
|
||||
if (t && sim.gold >= TD.TOWERS[t.type].levels[t.level].cost) sim.cmd({ c: 'upgrade', id: t.id });
|
||||
else if (sim.gold >= TD.TOWERS.ids.levels[0].cost) this.nearRoute('ids', 10 + 4 * guard);
|
||||
else break;
|
||||
this.actions++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ one round of decisions
|
||||
think(maxActions) {
|
||||
if (this.s.lazy) { this.lazyThink(); return; }
|
||||
let n = 0;
|
||||
if (this.s.maze && this.sim.rev !== this.prunedRev) { this.prune(); this.prunedRev = this.sim.rev; }
|
||||
while (n++ < (maxActions || 40)) {
|
||||
let did = false;
|
||||
if (this.s.maze && this.turretCount() >= this.s.minTurrets) did = this.wallStep() > 0;
|
||||
if (!did) did = this.buyBest();
|
||||
if (!did) break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------- the game driver
|
||||
function playGame(opts) {
|
||||
opts = opts || {};
|
||||
const TD = require(opts.simPath || DEFAULT_SIM);
|
||||
const strat = parseStrategy(opts.strategy || 'maze');
|
||||
const seed = opts.seed === undefined ? 1 : opts.seed;
|
||||
const rng = prng(seed * 7919 + 13);
|
||||
const maxWave = opts.maxWave || 30;
|
||||
const simOpts = { map: opts.map || 'open', events: false };
|
||||
if (opts.startGold !== undefined) simOpts.gold = opts.startGold;
|
||||
if (opts.lives !== undefined) simOpts.lives = opts.lives;
|
||||
const sim = new TD.Sim(simOpts);
|
||||
if (!strat.waveTimer) strat.waveTimer = TD.WAVE_INTERVAL;
|
||||
const bot = new Bot(TD, sim, strat, rng, { maxWave });
|
||||
|
||||
// instrumentation (does not change the sim's behaviour)
|
||||
const leakByKind = {};
|
||||
const origLeak = sim.leak;
|
||||
sim.leak = function (m) { leakByKind[m.kind] = (leakByKind[m.kind] || 0) + m.leak; return origLeak.call(this, m); };
|
||||
|
||||
const log = [];
|
||||
const anomalies = [];
|
||||
const births = new Map();
|
||||
let bonusesPaid = 0, lastBonus = 0, waveT0 = -1e9, waveStart = null, won = false;
|
||||
let bossLeaks = 0;
|
||||
const wallTime = Date.now();
|
||||
|
||||
const snapshot = (w) => {
|
||||
const types = {};
|
||||
let walls = 0;
|
||||
for (const t of sim.towers) { if (t.type === 'wall') walls++; else types[t.type] = (types[t.type] || 0) + 1; }
|
||||
return { wave: w, lives: sim.lives, gold: sim.gold, towers: sim.towers.length - walls, walls, types, routeLen: Math.round(sim.board.routeLen * 10) / 10,
|
||||
kills: sim.kills, leaks: sim.leaks, time: Math.round(sim.time), alive: sim.monsters.length, spentWalls: bot.spentWalls, spentOther: bot.spentOther };
|
||||
};
|
||||
const closeWave = () => {
|
||||
if (!waveStart) return;
|
||||
const s = snapshot(waveStart.wave);
|
||||
s.waveKills = sim.kills - waveStart.kills; s.waveLeaks = sim.leaks - waveStart.leaks;
|
||||
s.lifeLoss = waveStart.lives - sim.lives; s.goldBefore = waveStart.gold;
|
||||
s.bonuses = bonusesPaid;
|
||||
log.push(s);
|
||||
waveStart = null;
|
||||
};
|
||||
|
||||
bot.think(60);
|
||||
let tick = 0;
|
||||
const hardLimit = (maxWave * 140 + 900);
|
||||
for (;;) {
|
||||
if (sim.state === 'lost') break;
|
||||
if (sim.state === 'won') {
|
||||
won = true;
|
||||
if (maxWave > sim.wave && opts.continueAfterWin !== false) sim.cmd({ c: 'continue' });
|
||||
else break;
|
||||
}
|
||||
const inWave = sim.monsters.length > 0 || sim.spawnQ.length > 0;
|
||||
if (!inWave && sim.wave >= maxWave) break;
|
||||
if (sim.wave < maxWave && sim.wave < sim.winWave && ((!inWave && (strat.waitClear || sim.time - waveT0 >= strat.waveTimer)) || sim.time - waveT0 >= strat.waveTimer)) {
|
||||
closeWave();
|
||||
bot.waitCost = 0;
|
||||
bot.learn();
|
||||
bot.think(60);
|
||||
if (opts.onWave) opts.onWave(bot, sim);
|
||||
const gBefore = sim.gold, lBefore = sim.lives;
|
||||
sim.cmd({ c: 'wave' });
|
||||
waveT0 = sim.time;
|
||||
waveStart = { wave: sim.wave, kills: sim.kills, leaks: sim.leaks, gold: gBefore, lives: lBefore };
|
||||
}
|
||||
sim.tick(TD.STEP); tick++;
|
||||
if (sim.bonusWave !== lastBonus) { bonusesPaid++; lastBonus = sim.bonusWave; }
|
||||
if (tick % strat.thinkEvery === 0) {
|
||||
if (inWave && sim.gold >= Math.max(bot.minCost, bot.waitCost || 0)) bot.think(3);
|
||||
if (tick % 600 === 0) { // stuck-monster watchdog
|
||||
for (const m of sim.monsters) {
|
||||
if (!births.has(m.id)) births.set(m.id, sim.time);
|
||||
else if (sim.time - births.get(m.id) > 1500 && anomalies.length < 5) anomalies.push('monster ' + m.kind + '#' + m.id + ' alive for ' + Math.round(sim.time - births.get(m.id)) + 's at wave ' + sim.wave);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (sim.time > hardLimit) { anomalies.push('time limit hit at wave ' + sim.wave); break; }
|
||||
}
|
||||
closeWave();
|
||||
if (sim.state === 'lost' && log.length) { log[log.length - 1].lives = 0; }
|
||||
const lost = sim.state === 'lost';
|
||||
const result = {
|
||||
survivedWaves: lost ? Math.max(0, sim.wave - 1) : sim.bonusWave,
|
||||
won, lost, livesLeft: sim.lives, diedAtWave: lost ? sim.wave : 0, finalWave: sim.wave,
|
||||
leaks: sim.leaks, kills: sim.kills, leakByKind, actions: bot.actions, bonusesPaid,
|
||||
wallsBuilt: bot.wallCount(), spentWalls: bot.spentWalls, spentOther: bot.spentOther, goldEnd: sim.gold,
|
||||
simSeconds: Math.round(sim.time), wallMs: Date.now() - wallTime, anomalies,
|
||||
dealt: dealtByType(sim), towers: snapshot(sim.wave).types, routeLenEnd: snapshot(sim.wave).routeLen,
|
||||
};
|
||||
return { log, result, map: simOpts.map, strategy: strat.name, seed };
|
||||
}
|
||||
|
||||
function dealtByType(sim) {
|
||||
const o = {};
|
||||
for (const t of sim.towers) if (t.type !== 'wall') o[t.type] = Math.round((o[t.type] || 0) + t.dealt);
|
||||
return o;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------- CLI: matrix runner + tables
|
||||
function parseArgs(argv) {
|
||||
const a = { maps: ['open', 'twin', 'hub'], strategies: ['maze', 'nomaze', 'spam-filter', 'spam-ids', 'spam-mortar', 'spam-arc', 'lazy'],
|
||||
seeds: 6, max: 30, jobs: Math.max(1, require('os').cpus().length), sim: null, json: null, detail: false, verbose: false, seedStart: 1, startGold: undefined };
|
||||
for (let i = 2; i < argv.length; i++) {
|
||||
const k = argv[i];
|
||||
const next = () => argv[++i];
|
||||
if (k === '--maps') a.maps = next().split(',');
|
||||
else if (k === '--strategies') { const v = next(); a.strategies = v.indexOf(';') >= 0 || v.indexOf(':') >= 0 ? v.split(';') : v.split(','); } // use ';' between strategies that carry :k=v,k=v overrides
|
||||
else if (k === '--seeds') a.seeds = +next();
|
||||
else if (k === '--seed-start') a.seedStart = +next();
|
||||
else if (k === '--max') a.max = +next();
|
||||
else if (k === '--jobs') a.jobs = +next();
|
||||
else if (k === '--sim') a.sim = path.resolve(next());
|
||||
else if (k === '--json') a.json = next();
|
||||
else if (k === '--gold') a.startGold = +next();
|
||||
else if (k === '--detail') a.detail = true;
|
||||
else if (k === '--verbose') a.verbose = true;
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
const mean = (xs) => (xs.length ? xs.reduce((s, v) => s + v, 0) / xs.length : 0);
|
||||
const pad = (v, n) => String(v).padStart(n);
|
||||
const padr = (v, n) => String(v).padEnd(n);
|
||||
function logAt(r, w) { let best = null; for (const e of r.log) if (e.wave <= w) best = e; return best; }
|
||||
|
||||
function printTables(results, a) {
|
||||
const maps = a.maps, strats = a.strategies;
|
||||
for (const map of maps) {
|
||||
console.log('\n=== map ' + map + ' (' + a.seeds + ' seeds, up to wave ' + a.max + ') ===');
|
||||
console.log(padr('strategy', 16) + pad('win', 6) + pad('surv', 7) + pad('min-max', 9) + pad('lives', 7) + pad('leaks', 7) + pad('gold@5', 8) + pad('gold@10', 8) + pad('gold@15', 8) + pad('gold@20', 8) + pad('gold@30', 8) + pad('rt@10', 7) + pad('rt@20', 7) + pad('rt@30', 7) + pad('twr@20', 7) + pad('walls', 6) + pad('actions', 8));
|
||||
for (const st of strats) {
|
||||
const rs = results.filter((r) => r.map === map && r.strategy === st);
|
||||
if (!rs.length) continue;
|
||||
const surv = rs.map((r) => r.result.survivedWaves);
|
||||
const g = (w, f) => { const v = rs.map((r) => logAt(r, w)).filter(Boolean).map(f); return v.length ? Math.round(mean(v)) : '-'; };
|
||||
console.log(padr(st, 16) + pad(rs.filter((r) => r.result.won).length + '/' + rs.length, 6) + pad(mean(surv).toFixed(1), 7) + pad(Math.min(...surv) + '-' + Math.max(...surv), 9)
|
||||
+ pad(mean(rs.map((r) => r.result.livesLeft)).toFixed(1), 7) + pad(mean(rs.map((r) => r.result.leaks)).toFixed(0), 7)
|
||||
+ pad(g(5, (e) => e.gold), 8) + pad(g(10, (e) => e.gold), 8) + pad(g(15, (e) => e.gold), 8) + pad(g(20, (e) => e.gold), 8) + pad(g(30, (e) => e.gold), 8)
|
||||
+ pad(g(10, (e) => e.routeLen), 7) + pad(g(20, (e) => e.routeLen), 7) + pad(g(30, (e) => e.routeLen), 7) + pad(g(20, (e) => e.towers), 7)
|
||||
+ pad(Math.round(mean(rs.map((r) => r.result.wallsBuilt))), 6) + pad(Math.round(mean(rs.map((r) => r.result.actions))), 8));
|
||||
}
|
||||
}
|
||||
// where do games end?
|
||||
console.log('\n--- death waves (wave in which the game was lost; "W" = reached the end) ---');
|
||||
for (const map of maps) for (const st of strats) {
|
||||
const rs = results.filter((r) => r.map === map && r.strategy === st);
|
||||
if (!rs.length) continue;
|
||||
console.log(padr(map, 6) + padr(st, 16) + rs.map((r) => (r.result.lost ? pad(r.result.diedAtWave, 3) : pad(r.result.won ? 'W' + (r.result.finalWave > 30 ? r.result.finalWave : '') : 'ok', 3))).join(' '));
|
||||
}
|
||||
// tower mix of mixed builds
|
||||
console.log('\n--- average final tower mix (maze strategies) ---');
|
||||
for (const map of maps) for (const st of strats) {
|
||||
if (!/^maze/.test(st)) continue;
|
||||
const rs = results.filter((r) => r.map === map && r.strategy === st);
|
||||
if (!rs.length) continue;
|
||||
const mix = {};
|
||||
for (const r of rs) for (const k of Object.keys(r.result.towers)) mix[k] = (mix[k] || 0) + r.result.towers[k] / rs.length;
|
||||
const dealt = {};
|
||||
let tot = 0;
|
||||
for (const r of rs) for (const k of Object.keys(r.result.dealt)) { dealt[k] = (dealt[k] || 0) + r.result.dealt[k]; tot += r.result.dealt[k]; }
|
||||
console.log(padr(map, 6) + padr(st, 16) + Object.keys(mix).map((k) => k + ' ' + mix[k].toFixed(1) + ' (' + Math.round(100 * (dealt[k] || 0) / Math.max(1, tot)) + '%dmg)').join(' '));
|
||||
}
|
||||
// leak sources
|
||||
console.log('\n--- lives lost by packet kind (sum over seeds) ---');
|
||||
for (const map of maps) for (const st of strats) {
|
||||
const rs = results.filter((r) => r.map === map && r.strategy === st);
|
||||
if (!rs.length) continue;
|
||||
const lk = {};
|
||||
for (const r of rs) for (const k of Object.keys(r.result.leakByKind)) lk[k] = (lk[k] || 0) + r.result.leakByKind[k];
|
||||
console.log(padr(map, 6) + padr(st, 16) + Object.keys(lk).map((k) => k + ' ' + lk[k]).join(' '));
|
||||
}
|
||||
const an = results.filter((r) => r.result.anomalies.length);
|
||||
if (an.length) { console.log('\n--- ANOMALIES ---'); for (const r of an) console.log(r.map, r.strategy, r.seed, r.result.anomalies.join('; ')); }
|
||||
}
|
||||
|
||||
function printDetail(results) {
|
||||
for (const r of results) {
|
||||
console.log('\n## ' + r.map + ' ' + r.strategy + ' seed ' + r.seed + ' -> ' + JSON.stringify(r.result));
|
||||
console.log('wave lives gold twr walls route kills leaks wKills wLeaks time mix');
|
||||
for (const e of r.log) console.log(pad(e.wave, 4) + pad(e.lives, 6) + pad(e.gold, 6) + pad(e.towers, 4) + pad(e.walls, 5) + pad(e.routeLen, 7) + pad(e.kills, 6) + pad(e.leaks, 6) + pad(e.waveKills, 7) + pad(e.waveLeaks, 7) + pad(e.time, 6) + ' ' + JSON.stringify(e.types));
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
const a = parseArgs(process.argv);
|
||||
const jobs = [];
|
||||
for (const map of a.maps) for (const strategy of a.strategies) for (let s = 0; s < a.seeds; s++) jobs.push({ map, strategy, seed: a.seedStart + s, maxWave: a.max, simPath: a.sim || undefined, startGold: a.startGold });
|
||||
const { fork } = require('child_process');
|
||||
const results = [];
|
||||
let next = 0, running = 0, done = 0;
|
||||
const t0 = Date.now();
|
||||
const startOne = () => {
|
||||
if (next >= jobs.length) return;
|
||||
const job = jobs[next++];
|
||||
running++;
|
||||
const child = fork(__filename, ['--worker'], { stdio: ['ignore', 'inherit', 'inherit', 'ipc'] });
|
||||
child.on('message', (m) => {
|
||||
results.push(m);
|
||||
done++;
|
||||
if (a.verbose) process.stderr.write('[' + done + '/' + jobs.length + '] ' + m.map + ' ' + m.strategy + ' s' + m.seed + ' surv=' + m.result.survivedWaves + ' ' + m.result.wallMs + 'ms\n');
|
||||
child.kill();
|
||||
});
|
||||
child.on('exit', () => { running--; if (next < jobs.length) startOne(); else if (!running) finish(); });
|
||||
child.send(job);
|
||||
};
|
||||
const finish = () => {
|
||||
results.sort((p, q) => (p.map + p.strategy + String(1000 + p.seed)).localeCompare(q.map + q.strategy + String(1000 + q.seed)));
|
||||
if (a.json) require('fs').writeFileSync(a.json, JSON.stringify(results));
|
||||
printTables(results, a);
|
||||
if (a.detail) printDetail(results);
|
||||
console.log('\n(' + jobs.length + ' games, ' + ((Date.now() - t0) / 1000).toFixed(0) + ' s wall clock, sim=' + (a.sim || DEFAULT_SIM) + ')');
|
||||
};
|
||||
for (let i = 0; i < Math.min(a.jobs, jobs.length); i++) startOne();
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
if (process.argv.includes('--worker')) {
|
||||
process.on('message', (job) => { process.send(playGame(job)); });
|
||||
} else main();
|
||||
}
|
||||
|
||||
module.exports = { playGame, parseStrategy, Bot, prng, DEFAULTS };
|
||||
Loading…
Add table
Add a link
Reference in a new issue