(Body Snatcher) Prepare Pass 4

This commit is contained in:
AlexKucera committed 2026-08-13 08:56:50 +02:00
1 parent 47c630801a
commit e2a47aba6b
41 files changed
+61 -9422

No files matched your search

+43 -37
View File
@@ -1,4 +1,4 @@
# CLAUDE.md — Body Snatcher
# Body Snatcher — Build Spec (AGENTS.md)
You are building a browser-based roguelike game called **Body Snatcher**. Read this file completely before writing any code. Refer back to it at every phase.
@@ -16,22 +16,24 @@ You are a ghost. 1 HP. No attack. You explore a procedurally generated dungeon.
## Visual Style
- Top-down 2D grid, tile-based (each tile = 32px)
- Dark dungeon background, grid lines visible
- Entities are colored shapes with distinct silhouettes (no sprites needed):
- Ghost: white translucent circle with eyes
- Brute: large red square
- Skitterer: small orange triangle
- Sentinel: purple hexagon
- Shielder: blue square with front line
- Bomber: dark red circle with fuse
- Healer: green cross
- Phaser: cyan diamond
- Turret: gray octagon
- Charger: yellow arrow shape
- Siren: pink circle with rings
- Mimic: looks like a chest until provoked
- Leech: dark purple teardrop
- Minimal but readable. Color + shape communicates everything.
- **High-polish, intricate vector art drawn entirely on `<canvas>`** — NO external image, sprite, or font assets (the zero-dependency rule still applies). Every entity and tile is composed from many canvas primitives (linear/radial gradients, layered shapes, highlights, bevels, outlines, soft drop shadows, eyes, equipment) so the game looks hand-crafted — never flat single-rect placeholders.
- Atmospheric dungeon: dark stone walls with beveled edges, cracks and mortar lines; subtly lit floor flagstones; glowing runic exit stairs; ornate gilded chests; warm torch-light color grading and a soft vignette. Faint grid lines as structure only.
- Each entity has a DISTINCT, DETAILED silhouette with personality: eyes that track movement/facing, equipment, a gentle idle bob/breath animation, and (on the player's current body) a possession aura. Color still signals faction/type at a glance, but every shape is layered and shaded.
- Smooth radial fog of war (soft gradient falloff, not a hard circle); explored-but-unseen tiles dimmed with a cool memory tint.
- Quick color/silhouette reference (full per-enemy sprite breakdown in §Enemy Roster):
- Ghost: translucent wisp, glowing tracking eyes, tattered tail
- Brute: hulking crimson armored body
- Skitterer: orange insectile carapace
- Sentinel: purple floating crystal pod
- Shielder: blue body behind a tower-shield
- Bomber: dark-red iron shell with a sparking fuse
- Healer: green hooded robe with an ankh sigil
- Phaser: cyan faceted crystal
- Turret: gray bolted octagon with a swivel barrel
- Charger: yellow coiled beast with a forward horn
- Siren: pink orb with concentric lure-rings
- Mimic: ornate chest that splits into a fanged maw
- Leech: dark-purple bulbous sucker
## Grid + Rendering
@@ -42,12 +44,13 @@ You are a ghost. 1 HP. No attack. You explore a procedurally generated dungeon.
- Before play starts, the title screen MUST show a concise controls panel explaining movement, possession/attack, facing, confirm, and pause.
- During play, the HUD MUST show a short contextual hint for SPACE (possess while ghost; current body attack/special while possessed).
- The pause and shop screens MUST show the controls needed to leave or confirm those screens.
- **Render quality rules:** use sub-pixel entity positions, anti-aliased layered primitives, gradients for bodies and lighting, soft shadows under entities, and subtle idle/breathing animation. Draw tiles with depth (beveled walls casting onto floor, lit center / darker edges). The title, HUD, shop, and pause overlays must be equally polished — bordered panels, icons, and accent colors, not bare text.
## Player States
### Ghost State
- 1 HP, no attack
- Movement: arrow keys / WASD, one tile per turn
- Movement: arrow keys / WASD, one tile per turn (snappy ~85ms interpolation; HOLD a direction to move continuously at the turn cadence)
- Cannot walk through walls (unless Ghost Tree T3 unlocked)
- Hold SPACE adjacent to enemy → possession (takes 1 turn)
- Ghost timer: 15s real-time countdown (20s with Ghost T1)
@@ -74,67 +77,67 @@ The default feel must be EXPLORATORY, not a swarm. Honor ALL of these — they a
## Enemy Roster
Each enemy is a **dual system**: it behaves one way as an opponent and differently when you possess it. Define each as a data object with both AI behavior and player kit.
Each enemy is a **dual system**: it behaves one way as an opponent and differently when you possess it. Define each as a data object with both AI behavior and player kit. The **Sprite** line describes the intricate canvas-vector art to draw (layered/shaded, no external assets).
### 1. Brute
- **Enemy AI:** Slow chase (moves every 2 turns). A* pathfinding toward player. Heavy melee (2 damage) on adjacent tile.
- **Player kit:** High HP (8), slow movement (every 2 turns), high damage (3 per hit).
- **Color:** Red. **Shape:** Large square (28px).
- **Color:** Crimson. **Sprite:** Hulking armored brute — beveled plate-body, heavy brow, glowing eyes, dragging knuckle-fists, subtle idle sway (~28px).
### 2. Skitterer
- **Enemy AI:** Moves every 2 turns. Loose swarm — drifts toward other Skitterers and flanks the player once aggroed. Weak melee (1 damage).
- **Player kit:** Low HP (2), fast movement, rapid weak hits (1 damage per turn).
- **Color:** Orange. **Shape:** Small triangle (16px).
- **Color:** Orange. **Sprite:** Insectile skitterer — segmented carapace, three pointed legs, twitching mandibles, quick leg-shuffle animation (~16px).
### 3. Sentinel
- **Enemy AI:** Keeps distance (maintains 4-tile range). Fires a BURST of 3 shots (1 per turn) toward the player, then OVERHEATS for 3 turns — it cannot fire while overheated and only repositions slowly, giving the player a clear window to close or possess. Moves away if the player gets close. Projectiles hit the player only, never other enemies.
- **Player kit:** Medium HP (4). Shoot projectiles in facing direction. Cannot melee. Same burst/overheat rhythm as the enemy (3 shots, then a short cooldown) so it cannot infinitely stunlock.
- **Color:** Purple. **Shape:** Hexagon.
- **Color:** Purple. **Sprite:** Floating crystalline hex pod — faceted shell, single aiming eye, energy coils, muzzle that glows before each burst.
### 4. Shielder
- **Enemy AI:** Slow chase. Frontal shield blocks all damage from the direction it's facing. Takes damage from sides/back.
- **Player kit:** Medium HP (5). Frontal shield active. Must rotate (Q/E keys) to face threats.
- **Color:** Blue. **Shape:** Square with front line indicator.
- **Color:** Blue. **Sprite:** Stocky body behind a tall embossed tower-shield (rotates with facing), crest + rivets, narrow visor slit.
### 5. Bomber
- **Enemy AI:** Chase player when aggroed. On death or when adjacent, explodes (3x3 AoE, 3 damage **to the player only — never other enemies**).
- **Player kit:** Low HP (3). Press SPACE to detonate (suicide, 3x3 AoE, 4 damage). Ejects you as ghost.
- **Color:** Dark red. **Shape:** Circle with fuse indicator.
- **Color:** Dark red. **Sprite:** Round cast-iron shell with an exposed fuse; the sparking tip intensifies as it nears detonation; small soot puffs trailing.
### 6. Healer
- **Enemy AI:** Stays near other enemies. Heals nearby enemies (+1 HP per turn within 3 tiles). Fleees from player.
- **Player kit:** Low HP (3). Press SPACE for AoE heal pulse (heal self +2, all allies +1 within 3 tiles). Low offensive capability.
- **Color:** Green. **Shape:** Cross.
- **Color:** Green. **Sprite:** Hooded robe with a glowing ankh/cross sigil on the chest, soft healing motes drifting up, raised hands.
### 7. Phaser
- **Enemy AI:** Teleports toward player every 3 turns (within line of sight). Materializes, attacks, dematerializes.
- **Player kit:** Medium HP (4). Press SPACE to blink 5 tiles in facing direction (through walls). 2-turn cooldown.
- **Color:** Cyan. **Shape:** Diamond.
- **Color:** Cyan. **Sprite:** Faceted crystal diamond that fractures/scatters when dematerializing, sharp edges, faint afterimage trail on teleport.
### 8. Turret
- **Enemy AI:** Stationary. 360° fire at an aggroed player in a BURST (3 shots, 1 every 2 turns), then OVERHEATS for 3 turns — fully silenced and vulnerable during overheat, the window to rush it. Projectiles hit the player only, never other enemies.
- **Player kit:** Medium HP (4). Rooted — cannot move. Press SPACE to fire in facing direction (Q/E to rotate). High DPS in bursts, with the same overheat cooldown so it cannot fire forever.
- **Color:** Gray. **Shape:** Octagon.
- **Color:** Gray. **Sprite:** Bolted octagonal base mounting a swivel barrel that tracks facing; cooling vents glow red as it nears overheat.
### 9. Charger
- **Enemy AI:** When aggroed, telegraphs (flashes for 1 turn), then charges in a straight line toward the player's position at telegraph time. Collision with the player = 3 damage. Hits walls = stunned 2 turns. The charge does NOT damage other enemies.
- **Player kit:** Medium HP (5). Press SPACE to dash-charge 4 tiles in facing direction. Damages enemies in path (2 per enemy hit).
- **Color:** Yellow. **Shape:** Arrow.
- **Color:** Yellow. **Sprite:** Coiled beast with a forward horn/arrow crest; telegraph flash + paw-stomp windup; motion streak on the charge.
### 10. Siren
- **Enemy AI:** Stationary or slow drift. Emits pull field (drags player 1 tile toward it per turn if within 5 tiles). Weak melee.
- **Player kit:** Low HP (3). Press SPACE to pull all enemies within 4 tiles one tile toward you. Useful for grouping.
- **Color:** Pink. **Shape:** Circle with ring animation.
- **Color:** Pink. **Sprite:** Eerie floating orb-entity with concentric pulsing lure-rings and trailing wisps around a hollow glowing core.
### 11. Mimic
- **Enemy AI:** Disguised as a chest. When player is adjacent, reveals true form and bursts (2 damage in cross pattern).
- **Player kit:** Medium HP (4). Passive: enemies don't aggro you while disguised. Press SPACE for surprise burst (2 damage 3x3 cross).
- **Color:** Brown (disguised) / dark gold (revealed). **Shape:** Chest → reveal.
- **Color:** Brown (disguised) / dark gold (revealed). **Sprite:** Ornate treasure chest (gold trim, lock, wood grain) that splits open into a fanged maw with a lolling tongue on reveal.
### 12. Leech
- **Enemy AI:** Slow chase. On hit, drains 1 HP from player and heals self +1.
- **Player kit:** Medium HP (4). Every hit deals 1 damage and heals you +1. Sustain machine.
- **Color:** Dark purple. **Shape:** Teardrop.
- **Color:** Dark purple. **Sprite:** Bulbous segmented body tapering to a sucker maw, glossy wet highlight, drip trail; puffs red when it drains.
## Enemy Legend (in-game bestiary)
@@ -195,11 +198,12 @@ Present 3 random upgrades from the pool below. Player picks one or skips.
## Game Feel
- Screen shake on explosions and big hits
- Particle effects on death, possession, essence pickup
- Hit flash (entity flashes white for 100ms on damage)
- Smooth movement interpolation between tiles (150ms ease)
- Sound: use Web Audio API to generate simple tones (no audio files needed). Hit sound, possess sound, death sound, pickup sound, explosion sound. Procedural beeps.
- **Snappy movement.** Smooth movement interpolation between tiles is a quick ~85ms ease (down from 150ms) so the player feels responsive. Holding a movement key auto-repeats at the turn cadence for continuous travel. The real-time live loop advances turns at a brisk ~600ms cadence (down from 1000ms) so the dungeon feels alive without swarming. NOTE: this is presentation/cadence only — the core turn model stays one-tile-per-turn and `tick(n)` stays deterministic for the headless harness; never tie game state to wall-clock time.
- Screen shake on explosions and big hits (scaled to intensity)
- Particle effects on death, possession, essence pickup, and light footstep/dust on movement
- Hit flash (entity flashes white ~100ms on damage) plus hit sparks / small damage numbers
- Polished possession VFX: an aura on the player's current host; dissolve/flash on possess and eject
- Sound: use Web Audio API to generate tones (no audio files). Hit, possess, death, pickup, explosion, plus subtle UI blips. Guard if AudioContext is unavailable.
## Achievements (localStorage-tracked)
@@ -216,7 +220,7 @@ Present 3 random upgrades from the pool below. Player picks one or skips.
These controls must be explained on the title screen before the run starts, not only documented here:
- **WASD / Arrow Keys:** Move one tile per turn.
- **WASD / Arrow Keys:** Move one tile per turn (hold to move continuously).
- **SPACE while ghost:** Possess an enemy within range. Explain that the ghost cannot attack.
- **SPACE while possessed:** Use the current host's attack or special ability. Show the current action in the HUD.
- **X while possessed:** Abandon your current host — eject as a ghost (the host survives, briefly pacified; see Possessed State). Show this in the contextual HUD hint while possessed.
@@ -255,6 +259,7 @@ The game MUST meet ALL of these. Do not consider yourself done until every one p
23. Enemies idle until the player enters their aggro radius (≈6 tiles, line of sight); the whole floor does not swarm the player on spawn
24. An in-game enemy legend (bestiary) is reachable before play and explains each enemy's behavior + possessed kit
25. The ghost can voluntarily abandon a host (press X while possessed): returns to ghost form with the timer resumed (>0), the former host survives in the enemy list, and that host cannot be immediately re-possessed (short lockout)
26. **Visual polish:** entities and tiles are intricate layered/shaded canvas-vector art per §Visual Style and each enemy's Sprite line — not flat single-rect placeholders. Movement feels snappy (~85ms interpolation, hold-to-move).
## Testability (REQUIRED)
@@ -286,5 +291,6 @@ The game MUST expose its state for automated testing. Expose ALL of this on `win
- DO NOT write more code than needed. Bloat is penalized.
- DO NOT skip the fog of war, audio, or save/load — they are completion criteria.
- DO NOT use placeholder art or "TODO" comments. Everything must work.
- DO NOT use flat single-rect entities or bare-text overlays — draw the intricate vector sprites and polished panels described in §Visual Style and §Grid + Rendering.
- DO NOT add multiplayer, online features, or any server component.
- DO NOT stop until all completion criteria pass.
+5
View File
@@ -20,6 +20,11 @@ Read AGENTS.md. That is the full game spec for "Body Snatcher" — a browser-bas
Your task: Build the complete game as a single index.html file. Follow the spec exactly.
## Build Priorities (this run)
- **High-polish visuals.** Draw intricate, layered/shaded canvas-vector art for every entity and tile per AGENTS.md §Visual Style, §Grid + Rendering, and each enemy's Sprite line — gradients, bevels, highlights, soft shadows, animated details. No flat single-rect placeholders, no bare-text overlays.
- **Snappy movement.** ~85ms tile interpolation, hold-to-move continuous travel, ~600ms live-tick cadence (AGENTS.md §Game Feel). Keep the deterministic one-tile-per-turn `tick(n)` model for the headless harness — the quickness is presentation/cadence only.
## ARCHITECTURE: You are building a self-orchestrating software factory.
Do NOT write the game directly in this conversation. Instead, write two scripts — `build.sh` and `verify.js` — then run `build.sh` and let it orchestrate the entire build using `pi -p` as the primitive. This gives you subagent isolation, mechanical verification gates, and retry loops.
-279
View File
@@ -1,279 +0,0 @@
#!/usr/bin/env bash
# build.sh — self-orchestrating factory for Body Snatcher.
# Drives the build in phases via `pi -p` (fresh isolated context each phase),
# gated mechanically by `node verify.js <phase>`. Max 3 retries + targeted fix.
set -uo pipefail
cd "$(dirname "$0")"
MAX_RETRIES=3
MODEL="--model openai/gpt-5.2 --thinking high"
mkdir -p build
LOG=build/build.log
: > "$LOG"
if [ ! -f verify.js ]; then echo "FATAL: verify.js missing" >&2; exit 1; fi
# ---- shared contract + phase scopes written to build/_*.md ------------------
cat > build/_contract.md <<'EOF'
You are building "Body Snatcher" — a single index.html browser possession roguelike.
STEP 0: Read AGENTS.md in THIS directory COMPLETELY. It is the authoritative spec.
Then, if index.html already exists, read ALL of the current index.html before editing.
After phase 1, NEVER rewrite index.html from scratch — edit it incrementally and
PRESERVE every working system from earlier phases.
HARD CONSTRAINTS (every phase):
- Single index.html. Zero external dependencies: no CDN, no npm, no ES `import`,
no <script src=>. All CSS and JS inline.
- The game MUST NOT auto-start play on load. It sits on the title screen until
start() or a valid user key.
- MUST NOT crash if Canvas.getContext('2d') or AudioContext are no-op mocks.
Guard every canvas/audio call.
- Core game logic is DETERMINISTIC and step-driven, NOT wall-clock. tick(n) advances
enemy AI AND decrements the ghost timer by exactly n steps. 1 step = 1 second.
Base ghost timer = 15 steps; Ghost T1 = 20 steps. (Visuals/audio may use real time;
the timer and AI must not.)
- Expose window.GAME = { state, player, enemies, grid, floor, essence, upgrades,
achievements, projectiles, log, start, input, tick, spawn, setFloor, newRun,
save, load, openShop, buy }.
* state is one of: title, playing, possessed, shop, paused, won, lost.
* player = { x, y, ghost(bool), timer, host, facing }.
* enemy = { type, hp, maxHp, damage, speed, x, y, ... }.
* grid[y][x] = number (0 floor, 1 wall, 2 door, 3 exit, 4 shop, 5 chest)
OR an object { type, solid }. Pick one shape and stay consistent.
- input(key) accepts: ArrowUp/Down/Left/Right, w a s d, ' ' and 'Space', q e,
x (abandon host), Enter, Escape, l (legend toggle).
- spawn(type, tx, ty) creates and returns the enemy. setFloor(n) regenerates floor n
and places the ghost at spawn (state playing). newRun() starts a fresh floor-1 run
with a NEW random layout. openShop() (debug) enters shop state AND grants a test
stipend (set essence >= 30) so buy() can succeed; the real between-floor shop uses
earned essence. buy(index) purchases; hard-block if essence is insufficient; enforce
per-tree prerequisites (T1 -> T2 -> T3 -> T4). After openShop and after the
between-floor shop, expose the 3 choices on GAME as G.choices (the harness also
accepts G.shopChoices / G.upgradeChoices); make choice[0] a prereq-met, unowned item.
- Title screen MUST visibly explain WASD/arrows, SPACE, Q/E (facing), ENTER, ESC.
It MUST offer an enemy Legend/Bestiary panel (toggle 'l') listing each enemy's
behavior AND its possessed kit. The live HUD shows a contextual SPACE hint (possess
while ghost; attack/special while possessed; press X to abandon host while
possessed). Pause (ESC) and shop screens show their own controls.
PACING RULES — these are completion criteria and verify.js checks them directly:
- NO friendly fire between enemies. Enemy melee, AoE explosions, charges, and
projectiles damage the PLAYER ONLY and never reduce another enemy's HP. (Your
possessed host's attacks and your host's AoE still damage enemies normally, and you
still gain essence for those kills.) verify.js places a "meat" enemy on the line of
an enemy Sentinel/Turret shot, inside an enemy Bomber's blast, and on an enemy
Charger's charge line, and asserts that enemy's HP is unchanged WHILE confirming the
AoE/projectile actually happened.
- Aggro radius ~6 tiles, line-of-sight gated. Enemies start DOCILE and only chase /
attack when the player is within radius AND visible. Outside it they idle and do NOT
path toward the player. The whole floor MUST NOT swarm on spawn. Keep the spawn area
clear (place enemies at least 6 manhattan tiles from spawn).
- Sentinel and Turret fire a 3-shot BURST then OVERHEAT into a forced multi-turn (>=3)
no-fire window during which they cannot shoot (Turret is also fully vulnerable then).
verify.js places them 5-7 tiles away along a cleared corridor and asserts a burst
followed by >=3 consecutive no-fire turns. No infinite-fire enemies.
SELF-CHECK before you report done: run `node verify.js <this phase>` and every lower
phase too (to confirm no regression), and FIX every failure. The harness is headless:
it evals your inline <script> with mocked DOM/canvas/audio/localStorage and drives the
game exclusively through window.GAME. If a check fails, read its message — it names the
exact expectation.
EOF
cat > build/_p1.md <<'EOF'
Implement PHASE 1 ONLY (core engine). Do not implement possession, enemies, procgen
beyond a basic floor, shop, or save/load yet.
- HTML5 Canvas (25x18 tile grid, 800x576 canvas + HUD bar), game loop, grid system,
tile rendering with visible grid lines.
- Wall collision. Ghost movement: WASD / arrows, one tile per turn.
- Base ghost timer = 15 steps, decremented by tick(n). Show it in the HUD.
- Fog of war: visible radius around the player; explored-but-unseen tiles dimmed.
- Title screen that visibly explains WASD/arrows, SPACE, Q/E, ENTER, ESC, AND offers
the enemy Legend/Bestiary panel (toggle 'l'). Live HUD shows a contextual SPACE hint.
- A basic floor for now: a simple carved layout with walls, floor, and an exit tile.
Full procedural generation is phase 4 — do not build it yet.
- start() must initialize to the TITLE screen. Expose window.GAME per the contract.
Finish by running: node verify.js 1 (must exit 0).
EOF
cat > build/_p2.md <<'EOF'
Implement PHASE 2 ONLY (possession + first 3 enemies). Preserve all of phase 1.
- Possession: SPACE on an orthogonally adjacent enemy -> state becomes 'possessed';
the player takes that host's hp/stats/attack and occupies its tile. Adjacency test
must also accept a diagonally-adjacent enemy (use Chebyshev distance in the fallback).
- Voluntary ABANDON: press X while possessed -> return to ghost (state playing), host
SURVIVES at its current HP and stays in the enemy list, pacified for 2 turns with a
2-turn re-possess LOCKOUT (so input('Space') right after abandon must NOT re-possess).
The ghost timer RESUMES from where it paused — it is NOT reset to 15.
- Brute: enemy maxHp 8, damage 3, slow chase every 2 turns via A*/BFS. Player kit high
HP / slow / 3 dmg.
- Skitterer: maxHp 2, damage 1, moves every 2 turns, loose swarm + flank. Player kit
low HP / fast / 1 dmg/turn.
- Sentinel: maxHp 4, ranged. Fires a BURST of 3 shots (toward the player, projectiles
hit PLAYER only) then OVERHEATS for 3 turns (cannot fire, repositions slowly). Keeps
distance. No melee. Player kit same burst/overheat rhythm, shoot in facing, no melee.
- A*/BFS pathfinding: enemies navigate AROUND walls toward the ghost.
- Essence: when YOUR host kills an enemy, essence increases (values per AGENTS.md) and
accumulates in G.essence.
- Host death: check host hp <= 0 EVERY tick; when it dies, eject the ghost with a FRESH
timer (15, or 20 with Ghost T1). If ejection happens during a tick, do NOT decrement
that fresh timer on the same step.
Finish by running: node verify.js 1 && node verify.js 2 (both must exit 0).
EOF
cat > build/_p3.md <<'EOF'
Implement PHASE 3 ONLY (the remaining 9 enemies). Each needs full enemy AI + player
kit, with stats distinct from every other enemy. Preserve phases 1-2.
- Shielder (maxHp 5): frontal shield blocks damage from facing; Q/E rotate. Enemy slow
chase; player must rotate to face threats.
- Bomber (maxHp 3): ENEMY chases when aggroed and explodes 3x3 AoE 3 dmg to the PLAYER
ONLY on death or when adjacent (never other enemies). HOST: SPACE detonates (suicide,
3x3 AoE 4 dmg) and ejects you as ghost.
- Healer (maxHp 3): ENEMY stays near other enemies, heals nearby enemies +1/turn within
3 tiles, flees the player. HOST: SPACE AoE heal pulse (self +2, allies +1 within 3).
- Phaser (maxHp 4): ENEMY teleports toward the player every 3 turns (within LOS),
materializes/attacks/dematerializes. HOST: SPACE blink 5 tiles in facing (through
walls), 2-turn cooldown.
- Turret (maxHp 4): ENEMY stationary, fires a BURST (3 shots, 1 every 2 turns) at an
aggroed player then OVERHEATS 3 turns (fully silenced + vulnerable) — projectiles hit
PLAYER only, never enemies. HOST: rooted, SPACE fires in facing (Q/E rotate), same
overheat rhythm so it cannot fire forever.
- Charger (maxHp 5): ENEMY telegraphs 1 turn, then charges straight toward the player's
telegraphed position; collision with player = 3 dmg to PLAYER only; hits a wall =
stunned 2 turns; the charge does NOT damage other enemies. HOST: SPACE dash-charge 4
tiles in facing, 2 dmg per enemy hit in path.
- Siren (maxHp 3): ENEMY slow drift, emits pull field (drags player 1 tile/turn within 5)
+ weak melee. HOST: SPACE pulls all enemies within 4 one tile toward you.
- Mimic (maxHp 4): ENEMY disguised as a chest; when the player is adjacent it reveals
and bursts 2 dmg in a cross. HOST: passive (enemies don't aggro you while disguised);
SPACE surprise burst (2 dmg 3x3 cross).
- Leech (maxHp 4): ENEMY slow chase; on hit drains 1 from the player and heals self +1.
HOST: every hit deals 1 and heals you +1.
Re-enforce: enemy Bomber blast, enemy Charger charge, and enemy Turret shots damage the
PLAYER only and never reduce other enemies' HP (verify.js checks each). Pathfinder must
route around walls, never through them.
Finish by running: node verify.js 1 && node verify.js 2 && node verify.js 3 (all 0).
EOF
cat > build/_p4.md <<'EOF'
Implement PHASE 4 ONLY (procgen + progression + shop + save/load). Preserve 1-3.
- Procedural dungeon: random walk + room carving. Per floor: 5-8 rooms (4x4 to 8x6),
L-shaped 1-wide corridors (never diagonal), exit stairs in the FARthest room from
spawn, shop pad on floors 3/5/7/9, enemies scale 4+N per floor, 1-2 chests. Layouts
MUST differ across runs (Math.random-based) — verify.js generates 3 and compares wall
positions. Difficulty scaling per AGENTS.md (which enemy types appear on which floors).
- 10 floors with escalating enemy variety.
- Between-floor shop: after every floor exit (descend), show a shop with 3 random
upgrade choices BEFORE the next floor. All 11 upgrades across Ghost/Body/Meta trees
with per-tree prerequisites (T1->T2->T3->T4) and the essence costs in AGENTS.md.
- Save/load via localStorage key 'bodysnatcher_save'. Autosave on floor transition,
shop purchase, possession change. Save floor, essence, upgrades, player state (incl.
the possessed host), and the current floor layout. load() MUST validate/normalize the
stored data (treat it as untrusted/malformed), re-link player.host/body to the
restored host object, and restore G._exit by scanning the grid. Because verify.js may
overwrite the exit tile TYPE during other tests, ALSO trigger descend when the player
stands on the recorded G._exit coordinates during step().
- Shop API: openShop() (debug) sets state 'shop' AND grants essence>=30 so buy(0) works;
the between-floor shop uses earned essence; buy() hard-blocks insufficient essence and
enforces prereqs; expose the 3 choices on G.choices.
Finish by running (procgen is randomized, so run it a few times):
for i in 1 2 3 4 5; do node verify.js $i || break; done (all must exit 0).
EOF
cat > build/_p5.md <<'EOF'
Implement PHASE 5 ONLY (polish + audio + achievements + win/lose). Preserve everything.
- Web Audio API procedural sounds (hit, possess, death, pickup, explosion) via simple
oscillators — no audio files. Guard if AudioContext is unavailable/mock.
- Game feel: screen shake on explosions/big hits, particles on death/possession/essence
pickup, hit flash (white ~100ms), smooth movement interpolation (150ms ease). NONE of
this may break the deterministic tick.
- All 8 achievements, tracked in G.achievements and localStorage: First Possession,
Body Hopper (5 different enemy types one run), Pacifist Ghost (reach floor 3 with no
host damage), Essence Hoarder (>=30), Deep Diver (floor 7), Escape Artist (win),
Bomberman (3 kills in one Bomber blast), Dual Wield (unlock Body T3).
- Win state: reach the floor-10 exit -> state 'won' victory screen.
- Lose state: ghost timer hits 0 -> state 'lost' with run stats.
- Pause menu (ESC) with Save + Quit, controls, and the bestiary reachable from it.
- Complete contextual controls on title, HUD, shop, and pause screens.
Finish by running: for i in 1 2 3 4 5; do node verify.js $i || break; done (all 0),
and mentally stress a 200-tick session (the harness does this for you).
EOF
cat > build/_review.md <<'EOF'
You are an adversarial QA reviewer for Body Snatcher. Read AGENTS.md and the COMPLETE
current index.html. Find bugs / missing features / spec violations and FIX them directly
in index.html (do not just report). Focus on:
- Any JS error or crash path (especially with mocked canvas/audio/localStorage).
- Enemies whose AI or player kit is broken; abilities that throw.
- Save/load edge cases (corrupt/missing/partial data) leaving bad state.
- Missing or untriggered achievements.
- Fog-of-war bugs.
- Base ghost timer below 15 steps.
- PACING VIOLATIONS (the most important): friendly fire between enemies; the whole floor
swarming on spawn instead of ~6-tile line-of-sight-gated aggro; Sentinel/Turret that
never overheat into a forced no-fire window.
- Missing controls text on title / HUD / shop / pause; missing bestiary.
After fixing, run and ensure ALL pass:
node verify.js 1 && node verify.js 2 && node verify.js 3 && node verify.js 4 && node verify.js 5
EOF
# ---- phase runner -----------------------------------------------------------
run_phase() {
local phase=$1 contract=$2 scope=$3 attempt ok p
local prompt; prompt="$(cat "$contract")"$'\n\n'"$(cat "$scope")"
for ((attempt=1; attempt<=MAX_RETRIES; attempt++)); do
echo "=== Phase $phase (attempt $attempt/$MAX_RETRIES) ===" | tee -a "$LOG"
pi -p -a $MODEL "$prompt" >"build/phase${phase}.attempt${attempt}.log" 2>&1 || true
tail -n 5 "build/phase${phase}.attempt${attempt}.log" | tee -a "$LOG"
ok=1
for ((p=1; p<=phase; p++)); do
if ! node verify.js "$p" >>"$LOG" 2>&1; then ok=0; fi
done
if [ $ok -eq 1 ]; then
echo "=== Phase $phase PASSED (gates 1..$phase green) ===" | tee -a "$LOG"
return 0
fi
echo "=== Phase $phase gate FAILED (attempt $attempt) ===" | tee -a "$LOG"
node verify.js "$phase" 2>&1 | tail -n 16 | tee -a "$LOG"
if [ $attempt -eq $MAX_RETRIES ]; then
echo "=== Phase $phase: targeted fix from gate output ===" | tee -a "$LOG"
local fix; fix="$(node verify.js "$phase" 2>&1 || true)"
pi -p -a $MODEL "Phase $phase of Body Snatcher failed its verify.js gate. Read AGENTS.md and the CURRENT index.html. The gate output was:
$fix
Fix ONLY the specific failures — do NOT rewrite index.html from scratch. Then run 'node verify.js $phase' (and lower phases) until green." >"build/phase${phase}.fix.log" 2>&1 || true
ok=1
for ((p=1; p<=phase; p++)); do
if ! node verify.js "$p" >>"$LOG" 2>&1; then ok=0; fi
done
if [ $ok -eq 1 ]; then
echo "=== Phase $phase PASSED after fix ===" | tee -a "$LOG"
return 0
fi
fi
done
echo "=== Phase $phase FAILED after all retries ===" | tee -a "$LOG"
return 1
}
run_phase 1 build/_contract.md build/_p1.md || { echo "HALT: phase 1 failed" | tee -a "$LOG"; exit 1; }
run_phase 2 build/_contract.md build/_p2.md || { echo "HALT: phase 2 failed" | tee -a "$LOG"; exit 1; }
run_phase 3 build/_contract.md build/_p3.md || { echo "HALT: phase 3 failed" | tee -a "$LOG"; exit 1; }
run_phase 4 build/_contract.md build/_p4.md || { echo "HALT: phase 4 failed" | tee -a "$LOG"; exit 1; }
run_phase 5 build/_contract.md build/_p5.md || { echo "HALT: phase 5 failed" | tee -a "$LOG"; exit 1; }
echo "=== ADVERSARIAL REVIEW ===" | tee -a "$LOG"
pi -p -a $MODEL "$(cat build/_review.md)" >build/review.log 2>&1 || true
tail -n 5 build/review.log | tee -a "$LOG"
echo "=== FINAL VERIFICATION ===" | tee -a "$LOG"
final=0
for p in 1 2 3 4 5; do
if node verify.js "$p" 2>&1 | tee -a "$LOG"; then
echo "Phase $p: PASS" | tee -a "$LOG"
else
echo "Phase $p: FAIL" | tee -a "$LOG"; final=1
fi
done
echo "=== BUILD COMPLETE (final=$final) ===" | tee -a "$LOG"
exit $final
-63
View File
@@ -1,63 +0,0 @@
You are building "Body Snatcher" — a single index.html browser possession roguelike.
STEP 0: Read AGENTS.md in THIS directory COMPLETELY. It is the authoritative spec.
Then, if index.html already exists, read ALL of the current index.html before editing.
After phase 1, NEVER rewrite index.html from scratch — edit it incrementally and
PRESERVE every working system from earlier phases.
HARD CONSTRAINTS (every phase):
- Single index.html. Zero external dependencies: no CDN, no npm, no ES `import`,
no <script src=>. All CSS and JS inline.
- The game MUST NOT auto-start play on load. It sits on the title screen until
start() or a valid user key.
- MUST NOT crash if Canvas.getContext('2d') or AudioContext are no-op mocks.
Guard every canvas/audio call.
- Core game logic is DETERMINISTIC and step-driven, NOT wall-clock. tick(n) advances
enemy AI AND decrements the ghost timer by exactly n steps. 1 step = 1 second.
Base ghost timer = 15 steps; Ghost T1 = 20 steps. (Visuals/audio may use real time;
the timer and AI must not.)
- Expose window.GAME = { state, player, enemies, grid, floor, essence, upgrades,
achievements, projectiles, log, start, input, tick, spawn, setFloor, newRun,
save, load, openShop, buy }.
* state is one of: title, playing, possessed, shop, paused, won, lost.
* player = { x, y, ghost(bool), timer, host, facing }.
* enemy = { type, hp, maxHp, damage, speed, x, y, ... }.
* grid[y][x] = number (0 floor, 1 wall, 2 door, 3 exit, 4 shop, 5 chest)
OR an object { type, solid }. Pick one shape and stay consistent.
- input(key) accepts: ArrowUp/Down/Left/Right, w a s d, ' ' and 'Space', q e,
x (abandon host), Enter, Escape, l (legend toggle).
- spawn(type, tx, ty) creates and returns the enemy. setFloor(n) regenerates floor n
and places the ghost at spawn (state playing). newRun() starts a fresh floor-1 run
with a NEW random layout. openShop() (debug) enters shop state AND grants a test
stipend (set essence >= 30) so buy() can succeed; the real between-floor shop uses
earned essence. buy(index) purchases; hard-block if essence is insufficient; enforce
per-tree prerequisites (T1 -> T2 -> T3 -> T4). After openShop and after the
between-floor shop, expose the 3 choices on GAME as G.choices (the harness also
accepts G.shopChoices / G.upgradeChoices); make choice[0] a prereq-met, unowned item.
- Title screen MUST visibly explain WASD/arrows, SPACE, Q/E (facing), ENTER, ESC.
It MUST offer an enemy Legend/Bestiary panel (toggle 'l') listing each enemy's
behavior AND its possessed kit. The live HUD shows a contextual SPACE hint (possess
while ghost; attack/special while possessed; press X to abandon host while
possessed). Pause (ESC) and shop screens show their own controls.
PACING RULES — these are completion criteria and verify.js checks them directly:
- NO friendly fire between enemies. Enemy melee, AoE explosions, charges, and
projectiles damage the PLAYER ONLY and never reduce another enemy's HP. (Your
possessed host's attacks and your host's AoE still damage enemies normally, and you
still gain essence for those kills.) verify.js places a "meat" enemy on the line of
an enemy Sentinel/Turret shot, inside an enemy Bomber's blast, and on an enemy
Charger's charge line, and asserts that enemy's HP is unchanged WHILE confirming the
AoE/projectile actually happened.
- Aggro radius ~6 tiles, line-of-sight gated. Enemies start DOCILE and only chase /
attack when the player is within radius AND visible. Outside it they idle and do NOT
path toward the player. The whole floor MUST NOT swarm on spawn. Keep the spawn area
clear (place enemies at least 6 manhattan tiles from spawn).
- Sentinel and Turret fire a 3-shot BURST then OVERHEAT into a forced multi-turn (>=3)
no-fire window during which they cannot shoot (Turret is also fully vulnerable then).
verify.js places them 5-7 tiles away along a cleared corridor and asserts a burst
followed by >=3 consecutive no-fire turns. No infinite-fire enemies.
SELF-CHECK before you report done: run `node verify.js <this phase>` and every lower
phase too (to confirm no regression), and FIX every failure. The harness is headless:
it evals your inline <script> with mocked DOM/canvas/audio/localStorage and drives the
game exclusively through window.GAME. If a check fails, read its message — it names the
exact expectation.
-13
View File
@@ -1,13 +0,0 @@
Body Snatcher's index.html currently has a JavaScript SYNTAX ERROR and will not load. The headless harness (verify.js) reports, when parsing the inline <script>:
SyntaxError: Unexpected token ')' at the final })(); (file line 2649)
This means there is an UNBALANCED brace or paren EARLIER in the inline script — one extra '{' (or a missing '}') somewhere in the body, so the file's final '}' closes the wrong block and the trailing ')' is unexpected.
YOUR TASK (narrow, surgical):
1. Read index.html. Locate the unbalanced brace/paren. (Tip: espree is installed at /opt/homebrew/lib/node_modules/eslint/node_modules/espree/dist/espree.cjs — you can tokenize the inline script and match {/} ( /) to find the unmatched opener, or bisect.)
2. Fix ONLY the syntax error — add the missing '}' (or remove the stray '{') so the inline script parses cleanly. Do NOT rewrite the file, do NOT change game logic, do NOT add features. The game was fully working and passing all gates before this single brace got dropped during a polish edit.
3. Verify: run `node verify.js 1 && node verify.js 2 && node verify.js 3 && node verify.js 4 && node verify.js 5` and confirm ALL exit 0.
4. Report which line you fixed.
Constraints: single index.html, zero external deps, inline JS. Preserve everything else.
-13
View File
@@ -1,13 +0,0 @@
Implement PHASE 1 ONLY (core engine). Do not implement possession, enemies, procgen
beyond a basic floor, shop, or save/load yet.
- HTML5 Canvas (25x18 tile grid, 800x576 canvas + HUD bar), game loop, grid system,
tile rendering with visible grid lines.
- Wall collision. Ghost movement: WASD / arrows, one tile per turn.
- Base ghost timer = 15 steps, decremented by tick(n). Show it in the HUD.
- Fog of war: visible radius around the player; explored-but-unseen tiles dimmed.
- Title screen that visibly explains WASD/arrows, SPACE, Q/E, ENTER, ESC, AND offers
the enemy Legend/Bestiary panel (toggle 'l'). Live HUD shows a contextual SPACE hint.
- A basic floor for now: a simple carved layout with walls, floor, and an exit tile.
Full procedural generation is phase 4 — do not build it yet.
- start() must initialize to the TITLE screen. Expose window.GAME per the contract.
Finish by running: node verify.js 1 (must exit 0).
-22
View File
@@ -1,22 +0,0 @@
Implement PHASE 2 ONLY (possession + first 3 enemies). Preserve all of phase 1.
- Possession: SPACE on an orthogonally adjacent enemy -> state becomes 'possessed';
the player takes that host's hp/stats/attack and occupies its tile. Adjacency test
must also accept a diagonally-adjacent enemy (use Chebyshev distance in the fallback).
- Voluntary ABANDON: press X while possessed -> return to ghost (state playing), host
SURVIVES at its current HP and stays in the enemy list, pacified for 2 turns with a
2-turn re-possess LOCKOUT (so input('Space') right after abandon must NOT re-possess).
The ghost timer RESUMES from where it paused — it is NOT reset to 15.
- Brute: enemy maxHp 8, damage 3, slow chase every 2 turns via A*/BFS. Player kit high
HP / slow / 3 dmg.
- Skitterer: maxHp 2, damage 1, moves every 2 turns, loose swarm + flank. Player kit
low HP / fast / 1 dmg/turn.
- Sentinel: maxHp 4, ranged. Fires a BURST of 3 shots (toward the player, projectiles
hit PLAYER only) then OVERHEATS for 3 turns (cannot fire, repositions slowly). Keeps
distance. No melee. Player kit same burst/overheat rhythm, shoot in facing, no melee.
- A*/BFS pathfinding: enemies navigate AROUND walls toward the ghost.
- Essence: when YOUR host kills an enemy, essence increases (values per AGENTS.md) and
accumulates in G.essence.
- Host death: check host hp <= 0 EVERY tick; when it dies, eject the ghost with a FRESH
timer (15, or 20 with Ghost T1). If ejection happens during a tick, do NOT decrement
that fresh timer on the same step.
Finish by running: node verify.js 1 && node verify.js 2 (both must exit 0).
-31
View File
@@ -1,31 +0,0 @@
Implement PHASE 3 ONLY (the remaining 9 enemies). Each needs full enemy AI + player
kit, with stats distinct from every other enemy. Preserve phases 1-2.
- Shielder (maxHp 5): frontal shield blocks damage from facing; Q/E rotate. Enemy slow
chase; player must rotate to face threats.
- Bomber (maxHp 3): ENEMY chases when aggroed and explodes 3x3 AoE 3 dmg to the PLAYER
ONLY on death or when adjacent (never other enemies). HOST: SPACE detonates (suicide,
3x3 AoE 4 dmg) and ejects you as ghost.
- Healer (maxHp 3): ENEMY stays near other enemies, heals nearby enemies +1/turn within
3 tiles, flees the player. HOST: SPACE AoE heal pulse (self +2, allies +1 within 3).
- Phaser (maxHp 4): ENEMY teleports toward the player every 3 turns (within LOS),
materializes/attacks/dematerializes. HOST: SPACE blink 5 tiles in facing (through
walls), 2-turn cooldown.
- Turret (maxHp 4): ENEMY stationary, fires a BURST (3 shots, 1 every 2 turns) at an
aggroed player then OVERHEATS 3 turns (fully silenced + vulnerable) — projectiles hit
PLAYER only, never enemies. HOST: rooted, SPACE fires in facing (Q/E rotate), same
overheat rhythm so it cannot fire forever.
- Charger (maxHp 5): ENEMY telegraphs 1 turn, then charges straight toward the player's
telegraphed position; collision with player = 3 dmg to PLAYER only; hits a wall =
stunned 2 turns; the charge does NOT damage other enemies. HOST: SPACE dash-charge 4
tiles in facing, 2 dmg per enemy hit in path.
- Siren (maxHp 3): ENEMY slow drift, emits pull field (drags player 1 tile/turn within 5)
+ weak melee. HOST: SPACE pulls all enemies within 4 one tile toward you.
- Mimic (maxHp 4): ENEMY disguised as a chest; when the player is adjacent it reveals
and bursts 2 dmg in a cross. HOST: passive (enemies don't aggro you while disguised);
SPACE surprise burst (2 dmg 3x3 cross).
- Leech (maxHp 4): ENEMY slow chase; on hit drains 1 from the player and heals self +1.
HOST: every hit deals 1 and heals you +1.
Re-enforce: enemy Bomber blast, enemy Charger charge, and enemy Turret shots damage the
PLAYER only and never reduce other enemies' HP (verify.js checks each). Pathfinder must
route around walls, never through them.
Finish by running: node verify.js 1 && node verify.js 2 && node verify.js 3 (all 0).
-22
View File
@@ -1,22 +0,0 @@
Implement PHASE 4 ONLY (procgen + progression + shop + save/load). Preserve 1-3.
- Procedural dungeon: random walk + room carving. Per floor: 5-8 rooms (4x4 to 8x6),
L-shaped 1-wide corridors (never diagonal), exit stairs in the FARthest room from
spawn, shop pad on floors 3/5/7/9, enemies scale 4+N per floor, 1-2 chests. Layouts
MUST differ across runs (Math.random-based) — verify.js generates 3 and compares wall
positions. Difficulty scaling per AGENTS.md (which enemy types appear on which floors).
- 10 floors with escalating enemy variety.
- Between-floor shop: after every floor exit (descend), show a shop with 3 random
upgrade choices BEFORE the next floor. All 11 upgrades across Ghost/Body/Meta trees
with per-tree prerequisites (T1->T2->T3->T4) and the essence costs in AGENTS.md.
- Save/load via localStorage key 'bodysnatcher_save'. Autosave on floor transition,
shop purchase, possession change. Save floor, essence, upgrades, player state (incl.
the possessed host), and the current floor layout. load() MUST validate/normalize the
stored data (treat it as untrusted/malformed), re-link player.host/body to the
restored host object, and restore G._exit by scanning the grid. Because verify.js may
overwrite the exit tile TYPE during other tests, ALSO trigger descend when the player
stands on the recorded G._exit coordinates during step().
- Shop API: openShop() (debug) sets state 'shop' AND grants essence>=30 so buy(0) works;
the between-floor shop uses earned essence; buy() hard-blocks insufficient essence and
enforces prereqs; expose the 3 choices on G.choices.
Finish by running (procgen is randomized, so run it a few times):
for i in 1 2 3 4 5; do node verify.js $i || break; done (all must exit 0).
-16
View File
@@ -1,16 +0,0 @@
Implement PHASE 5 ONLY (polish + audio + achievements + win/lose). Preserve everything.
- Web Audio API procedural sounds (hit, possess, death, pickup, explosion) via simple
oscillators — no audio files. Guard if AudioContext is unavailable/mock.
- Game feel: screen shake on explosions/big hits, particles on death/possession/essence
pickup, hit flash (white ~100ms), smooth movement interpolation (150ms ease). NONE of
this may break the deterministic tick.
- All 8 achievements, tracked in G.achievements and localStorage: First Possession,
Body Hopper (5 different enemy types one run), Pacifist Ghost (reach floor 3 with no
host damage), Essence Hoarder (>=30), Deep Diver (floor 7), Escape Artist (win),
Bomberman (3 kills in one Bomber blast), Dual Wield (unlock Body T3).
- Win state: reach the floor-10 exit -> state 'won' victory screen.
- Lose state: ghost timer hits 0 -> state 'lost' with run stats.
- Pause menu (ESC) with Save + Quit, controls, and the bestiary reachable from it.
- Complete contextual controls on title, HUD, shop, and pause screens.
Finish by running: for i in 1 2 3 4 5; do node verify.js $i || break; done (all 0),
and mentally stress a 200-tick session (the harness does this for you).
-15
View File
@@ -1,15 +0,0 @@
You are an adversarial QA reviewer for Body Snatcher. Read AGENTS.md and the COMPLETE
current index.html. Find bugs / missing features / spec violations and FIX them directly
in index.html (do not just report). Focus on:
- Any JS error or crash path (especially with mocked canvas/audio/localStorage).
- Enemies whose AI or player kit is broken; abilities that throw.
- Save/load edge cases (corrupt/missing/partial data) leaving bad state.
- Missing or untriggered achievements.
- Fog-of-war bugs.
- Base ghost timer below 15 steps.
- PACING VIOLATIONS (the most important): friendly fire between enemies; the whole floor
swarming on spawn instead of ~6-tile line-of-sight-gated aggro; Sentinel/Turret that
never overheat into a forced no-fire window.
- Missing controls text on title / HUD / shop / pause; missing bestiary.
After fixing, run and ensure ALL pass:
node verify.js 1 && node verify.js 2 && node verify.js 3 && node verify.js 4 && node verify.js 5
-18
View File
@@ -1,18 +0,0 @@
const fs=require('fs');
let acorn;
try{ acorn=require('acorn'); }catch(e){ try{ acorn=require('/opt/homebrew/lib/node_modules/eslint/node_modules/espree/node_modules/acorn'); }catch(e2){ try{acorn=require('/opt/homebrew/lib/node_modules/acorn')}catch(e3){ console.log('no acorn:',e3.message); process.exit(1);} } }
const src=fs.readFileSync('index.html','utf8');
const m=src.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);
const code=m[1];
const fileLineBase=src.slice(0,src.indexOf('<script')).split('\n').length;
try{
acorn.parse(code,{ecmaVersion:2022,sourceType:'script',allowReturnOutsideFunction:true});
console.log('PARSE OK');
}catch(e){
const fl=(e.loc? (e.loc.line+fileLineBase-1):'?');
console.log('ERROR: '+e.message+' at script-line '+(e.loc?e.loc.line:'?')+' col '+(e.loc?e.loc.column:'?')+' => FILE line '+fl);
// print context
const cl=code.split('\n');
const sl=e.loc?e.loc.line:null;
if(sl){ for(let k=Math.max(0,sl-4);k<=Math.min(cl.length-1,sl+1);k++) console.log((k+1===sl?'>>':' ')+(k+1)+'| '+cl[k]); }
}
-18
View File
@@ -1,18 +0,0 @@
const fs=require('fs'),vm=require('vm');
const src=fs.readFileSync('index.html','utf8');
const m=src.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);
const code=m[1];
const lines=code.split('\n');
function test(E){ // E = number of script lines kept; append close
const prefix=lines.slice(0,E).join('\n');
const full=prefix+'\n\n})();';
try{ new vm.Script(full); return {ok:true}; }
catch(e){ const ln=(e.stack.match(/(?:Object\.<anonymous>|g\.js):(\d+)/)||[])[1]; return {ok:false, line: ln?+ln:null, msg:e.message}; }
}
// coarse scan every 50 lines: classify
let prev=null;
for(let E=50; E<=lines.length; E+=50){
const r=test(E);
const cls = r.ok ? 'OK' : (r.line && r.line> E ? 'CLOSE-ERR(bug<=E)' : 'mid(err<=E line='+(r.line||'?')+')');
console.log('E='+E+' => '+cls+(r.ok?'':' "'+r.msg.slice(0,40)+'"'));
}
-30
View File
@@ -1,30 +0,0 @@
const fs=require('fs'),vm=require('vm');
const src=fs.readFileSync('index.html','utf8');
const m=src.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);
const code=m[1]; const lines=code.split('\n');
function test(E){
const full=lines.slice(0,E).join('\n')+'\n\n})();'; // close appended at line E+2
try{ new vm.Script(full,{filename:'g.js'}); return {ok:true}; }
catch(e){ const first=e.stack.split('\n')[0]; const lm=first.match(/g\.js:(\d+)/); return {ok:false, line: lm?+lm[1]:null, msg:e.message, first}; }
}
// fine scan: find smallest E (try every line near suspected region) where error line == E+2 (close error => bug at/before E)
// First, sample to find region: walk E, classify closeErr if line===E+2
let firstCloseErr=null, lastOk=null;
for(let E=100; E<=lines.length; E+=10){
const r=test(E);
if(r.ok){ lastOk=E; continue; }
if(r.line===E+2){ if(firstCloseErr===null) firstCloseErr=E; }
}
console.log('last balanced (OK) at E='+lastOk);
console.log('first close-error (bug at/before E) at E='+firstCloseErr);
// narrow between lastOk and firstCloseErr line by line
if(lastOk!==null && firstCloseErr!==null){
for(let E=lastOk; E<=firstCloseErr; E++){
const r=test(E);
if(!r.ok && r.line===E+2){ console.log('>>> unclosed brace introduced at/before script-line '+E+' (file line '+(E+17)+')');
// show context
for(let k=Math.max(0,E-3);k<=E;k++) console.log(' '+(k+1)+'|'+(lines[k]||''));
break;
}
}
}
-177
View File
@@ -1,177 +0,0 @@
=== Phase 1 (attempt 1/3) ===
Verification:
```bash
node verify.js 1
# Phase 1: PASS (8/8)
```
✓ index.html has <canvas> and <script>
✓ no external src= or import
✓ GAME.start() runs, valid state
✓ grid has wall and floor tiles
✓ ghost moves on input, blocked by wall
✓ title screen explains controls (WASD/arrows/SPACE/Q-E/ENTER/ESC)
✓ enemy legend (bestiary) reachable, lists enemies
✓ starting ghost timer >= 15s
Phase 1: PASS (8/8)
=== Phase 1 PASSED (gates 1..1 green) ===
=== Phase 2 (attempt 1/3) ===
Self-checks (per instructions) both pass:
```bash
node verify.js 1 && node verify.js 2
```
✓ index.html has <canvas> and <script>
✓ no external src= or import
✓ GAME.start() runs, valid state
✓ grid has wall and floor tiles
✓ ghost moves on input, blocked by wall
✓ title screen explains controls (WASD/arrows/SPACE/Q-E/ENTER/ESC)
✓ enemy legend (bestiary) reachable, lists enemies
✓ starting ghost timer >= 15s
Phase 1: PASS (8/8)
✓ SPACE on adjacent enemy -> possessed
✓ X abandons host: ghost returns, host survives, lockout
✓ Brute/Skitterer/Sentinel stats
✓ Sentinel fires a burst then OVERHEATS (no-fire window)
✓ enemies pathfind toward the ghost
✓ killing host ejects ghost with timer>0
✓ essence increases on kill
✓ no friendly fire: Sentinel projectiles never hit another enemy
Phase 2: PASS (8/8)
=== Phase 2 PASSED (gates 1..2 green) ===
=== Phase 3 (attempt 1/3) ===
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
✓ index.html has <canvas> and <script>
✓ no external src= or import
✓ GAME.start() runs, valid state
✓ grid has wall and floor tiles
✓ ghost moves on input, blocked by wall
✓ title screen explains controls (WASD/arrows/SPACE/Q-E/ENTER/ESC)
✓ enemy legend (bestiary) reachable, lists enemies
✓ starting ghost timer >= 15s
Phase 1: PASS (8/8)
✓ SPACE on adjacent enemy -> possessed
✓ X abandons host: ghost returns, host survives, lockout
✓ Brute/Skitterer/Sentinel stats
✓ Sentinel fires a burst then OVERHEATS (no-fire window)
✓ enemies pathfind toward the ghost
✓ killing host ejects ghost with timer>0
✓ essence increases on kill
✓ no friendly fire: Sentinel projectiles never hit another enemy
Phase 2: PASS (8/8)
✓ all 12 enemy types instantiate
✓ distinct hp+damage+speed tuples
✓ each special ability triggers without error
✓ pathfinder navigates around walls (not through)
✓ Bomber AoE damages player only, never other enemies
✓ Charger charge hits player only, never other enemies
✓ Turret shots hit player only, never other enemies
✓ Turret OVERHEATS after burst
Phase 3: PASS (8/8)
=== Phase 3 PASSED (gates 1..3 green) ===
=== Phase 4 (attempt 1/3) ===
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
✓ index.html has <canvas> and <script>
✓ no external src= or import
✓ GAME.start() runs, valid state
✓ grid has wall and floor tiles
✓ ghost moves on input, blocked by wall
✓ title screen explains controls (WASD/arrows/SPACE/Q-E/ENTER/ESC)
✓ enemy legend (bestiary) reachable, lists enemies
✓ starting ghost timer >= 15s
Phase 1: PASS (8/8)
✓ SPACE on adjacent enemy -> possessed
✓ X abandons host: ghost returns, host survives, lockout
✓ Brute/Skitterer/Sentinel stats
✓ Sentinel fires a burst then OVERHEATS (no-fire window)
✓ enemies pathfind toward the ghost
✓ killing host ejects ghost with timer>0
✓ essence increases on kill
✓ no friendly fire: Sentinel projectiles never hit another enemy
Phase 2: PASS (8/8)
✓ all 12 enemy types instantiate
✓ distinct hp+damage+speed tuples
✓ each special ability triggers without error
✗ pathfinder navigates around walls (not through) → did not navigate (d0=7,df=7)
✓ Bomber AoE damages player only, never other enemies
✓ Charger charge hits player only, never other enemies
✓ Turret shots hit player only, never other enemies
✓ Turret OVERHEATS after burst
Phase 3: FAIL (7 passed, 1 failed)
- pathfinder navigates around walls (not through) :: did not navigate (d0=7,df=7)
✓ procedural dungeons differ across runs
✓ exit tile exists on the floor
✓ shop appears on floor transition
✓ buying an upgrade changes GAME.upgrades
✓ save() writes to localStorage
✓ save/load round-trip persists floor+essence+upgrades
Phase 4: PASS (6/6)
=== Phase 4 gate FAILED (attempt 1) ===
✓ procedural dungeons differ across runs
✓ exit tile exists on the floor
✓ shop appears on floor transition
✓ buying an upgrade changes GAME.upgrades
✓ save() writes to localStorage
✓ save/load round-trip persists floor+essence+upgrades
Phase 4: PASS (6/6)
=== Phase 4 (attempt 2/3) ===
for i in 1 2 3 4 5; do node verify.js $i || exit 1; done
done
```
All phases 1–5 PASS.
✓ index.html has <canvas> and <script>
✓ no external src= or import
✓ GAME.start() runs, valid state
✓ grid has wall and floor tiles
✓ ghost moves on input, blocked by wall
✓ title screen explains controls (WASD/arrows/SPACE/Q-E/ENTER/ESC)
✓ enemy legend (bestiary) reachable, lists enemies
✓ starting ghost timer >= 15s
Phase 1: PASS (8/8)
✓ SPACE on adjacent enemy -> possessed
✓ X abandons host: ghost returns, host survives, lockout
✓ Brute/Skitterer/Sentinel stats
✓ Sentinel fires a burst then OVERHEATS (no-fire window)
✓ enemies pathfind toward the ghost
✓ killing host ejects ghost with timer>0
✓ essence increases on kill
✓ no friendly fire: Sentinel projectiles never hit another enemy
Phase 2: PASS (8/8)
✓ all 12 enemy types instantiate
✓ distinct hp+damage+speed tuples
✓ each special ability triggers without error
✓ pathfinder navigates around walls (not through)
✓ Bomber AoE damages player only, never other enemies
✓ Charger charge hits player only, never other enemies
✓ Turret shots hit player only, never other enemies
✓ Turret OVERHEATS after burst
Phase 3: PASS (8/8)
✓ procedural dungeons differ across runs
✓ exit tile exists on the floor
✓ shop appears on floor transition
✓ buying an upgrade changes GAME.upgrades
✓ save() writes to localStorage
✓ save/load round-trip persists floor+essence+upgrades
Phase 4: PASS (6/6)
=== Phase 4 PASSED (gates 1..4 green) ===
=== Phase 5 (attempt 1/3) ===
-16
View File
@@ -1,16 +0,0 @@
const fs=require('fs');
const espree=require('/opt/homebrew/lib/node_modules/eslint/node_modules/espree/dist/espree.cjs');
const src=fs.readFileSync('index.html','utf8');
const m=src.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);
const code=m[1];
const base=src.slice(0,src.indexOf('<script')).split('\n').length;
try{
espree.parse(code,{ecmaVersion:2022,sourceType:'script',allowReturnOutsideFunction:true});
console.log('PARSE OK');
}catch(e){
const sl=e.lineNumber||e.loc?.line; const col=e.column||e.loc?.column;
console.log('ERROR: '+e.message);
console.log(' script-line '+sl+' col '+col+' => FILE line '+(sl?(sl+base-1):'?'));
const cl=code.split('\n');
if(sl) for(let k=Math.max(0,sl-5);k<=Math.min(cl.length-1,sl+1);k++) console.log((k+1===sl?'>>':' ')+(k+1)+'| '+cl[k]);
}
-42
View File
@@ -1,42 +0,0 @@
=== Phase 1 (attempt 1/3) ===
Verification:
```bash
node verify.js 1
# Phase 1: PASS (8/8)
```
=== Phase 1 PASSED (gates 1..1 green) ===
=== Phase 2 (attempt 1/3) ===
Self-checks (per instructions) both pass:
```bash
node verify.js 1 && node verify.js 2
```
=== Phase 2 PASSED (gates 1..2 green) ===
=== Phase 3 (attempt 1/3) ===
build.sh: line 221: 12844 Killed: 9 pi -p -a $MODEL "$prompt" > "build/phase${phase}.attempt${attempt}.log" 2>&1
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
=== Phase 3 PASSED (gates 1..3 green) ===
=== Phase 4 (attempt 1/3) ===
build.sh: line 221: 62108 Killed: 9 pi -p -a $MODEL "$prompt" > "build/phase${phase}.attempt${attempt}.log" 2>&1
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
=== Phase 4 gate FAILED (attempt 1) ===
✓ procedural dungeons differ across runs
✓ exit tile exists on the floor
✓ shop appears on floor transition
✓ buying an upgrade changes GAME.upgrades
✓ save() writes to localStorage
✓ save/load round-trip persists floor+essence+upgrades
Phase 4: PASS (6/6)
=== Phase 4 (attempt 2/3) ===
for i in 1 2 3 4 5; do node verify.js $i || exit 1; done
done
```
All phases 1–5 PASS.
=== Phase 4 PASSED (gates 1..4 green) ===
=== Phase 5 (attempt 1/3) ===
-1
View File
@@ -1 +0,0 @@
79805
-43
View File
@@ -1,43 +0,0 @@
const fs=require('fs');
const src=fs.readFileSync('index.html','utf8');
const m=src.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);
let code=m[1];
let lines=code.split('\n');
let st='code'; // code,sq,dq,tmp,lc,bc
let depth={parens:0,brace:0,brack:0};
let openBraceStack=[]; // line numbers of unclosed {
let openParenStack=[];
let prevSignificant='';
for(let li=0; li<lines.length; li++){
let line=lines[li];
for(let i=0;i<line.length;i++){
let c=line[i], n=line[i+1];
if(st==='lc'){ if(c==='\n'){st='code';} continue; }
if(st==='bc'){ if(c==='*'&&n==='/'){st='code';i++;} continue; }
if(st==='sq'){ if(c==='\\'){i++;} else if(c==="'"){st='code';} continue; }
if(st==='dq'){ if(c==='\\'){i++;} else if(c==='"'){st='code';} continue; }
if(st==='tmp'){ if(c==='\\'){i++;} else if(c==='`'){st='code';} else if(c==='$'&&n==='{'){depth.brace++;openBraceStack.push(li+1);i++;} continue; }
// st==='code'
if(c==='/'&&n==='/'){ st='lc'; continue; }
if(c==='/'&&n==='*'){ st='bc'; i++; continue; }
if(c==="'"){ st='sq'; continue; }
if(c==='"'){ st='dq'; continue; }
if(c==='`'){ st='tmp'; continue; }
if(c==='('){ depth.parens++; openParenStack.push(li+1); }
else if(c===')'){ depth.parens--; if(openParenStack.length)openParenStack.pop(); }
else if(c==='{'){ depth.brace++; openBraceStack.push(li+1); }
else if(c==='}'){ depth.brace--; if(openBraceStack.length)openBraceStack.pop(); }
else if(c==='['){ depth.brack++; }
else if(c===']'){ depth.brack--; }
}
}
console.log('FINAL depth (should be 0/0/0 outside IIFE):', JSON.stringify(depth));
console.log('unclosed { openers (script-line, last 12):', openBraceStack.slice(-12));
console.log('unclosed ( openers (script-line, last 12):', openParenStack.slice(-12));
// map script line -> file line (script starts after <script>); find offset
const before=src.indexOf('<script');
const header=src.slice(0,before);
const fileLineOffset = header.split('\n').length;
console.log('script starts at file line:', fileLineOffset);
console.log('=> suspect unclosed { at FILE line:', openBraceStack.slice(-1).map(x=>x+fileLineOffset-1));
console.log('=> suspect unclosed ( at FILE line:', openParenStack.slice(-1).map(x=>x+fileLineOffset-1));
-45
View File
@@ -1,45 +0,0 @@
const fs=require('fs');
const src=fs.readFileSync('index.html','utf8');
const m=src.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);
const code=m[1];
const chars=[...code];
// mode stack: bottom is 'code'
let mode=['code'];
let braceStack=[]; // {line, kind:'brace'|'interp'}
let parenStack=[];
const fileOff = src.indexOf('<script');
const fileLineBase = src.slice(0,fileOff).split('\n').length;
function L(idx){ // 1-based file line from code char index
let n=1; for(let k=0;k<idx;k++) if(code[k]==='\n') n++; return n+fileLineBase-1; }
let i=0;
const N=chars.length;
let errs=[];
while(i<N){
const c=chars[i], n=chars[i+1];
const top=mode[mode.length-1];
if(top==='lc'){ if(c==='\n') mode.pop(); i++; continue; }
if(top==='bc'){ if(c==='*'&&n==='/'){mode.pop();i+=2;continue;} i++; continue; }
if(top==='sq'){ if(c==='\\'){i+=2;continue;} if(c==="'"){mode.pop();i++;continue;} i++; continue; }
if(top==='dq'){ if(c==='\\'){i+=2;continue;} if(c==='"'){mode.pop();i++;continue;} i++; continue; }
if(top==='tmp'){
if(c==='\\'){i+=2;continue;}
if(c==='`'){mode.pop();i++;continue;}
if(c==='$'&&n==='{'){ braceStack.push({line:L(i),kind:'interp'}); mode.push('code'); i+=2; continue; }
i++; continue;
}
// top==='code'
if(c==='/'&&n==='/'){ mode.push('lc'); i+=2; continue; }
if(c==='/'&&n==='*'){ mode.push('bc'); i+=2; continue; }
if(c==="'"){ mode.push('sq'); i++; continue; }
if(c==='"'){ mode.push('dq'); i++; continue; }
if(c==='`'){ mode.push('tmp'); i++; continue; }
if(c==='{'){ braceStack.push({line:L(i),kind:'brace'}); i++; continue; }
if(c==='}'){ if(!braceStack.length){errs.push('extra } at '+L(i));} else braceStack.pop(); i++; continue; }
if(c==='('){ parenStack.push(L(i)); i++; continue; }
if(c===')'){ if(parenStack.length)parenStack.pop(); else errs.push('extra ) at '+L(i)); i++; continue; }
i++;
}
console.log('mode stack leftover:', mode);
console.log('errs:', errs.slice(0,5));
console.log('unclosed {/interp (last 15):', braceStack.slice(-15).map(b=>b.kind+'@'+b.line));
console.log('unclosed ( (last 8):', parenStack.slice(-8));
-44
View File
@@ -1,44 +0,0 @@
const fs=require('fs');
const src=fs.readFileSync('index.html','utf8');
const m=src.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);
const code=m[1];
const fileOff=src.indexOf('<script');
const fileLineBase=src.slice(0,fileOff).split('\n').length;
function L(idx){let n=1;for(let k=0;k<idx;k++)if(code[k]==='\n')n++;return n+fileLineBase-1;}
let mode=['code']; let braceStack=[]; let parenStack=[]; let prevSig='';
const isIdentChar=c=>/[A-Za-z0-9_$]/.test(c);
const rePrevWords=new Set(['return','typeof','instanceof','in','of','new','delete','void','yield','else','do','case','throw','await','yield','if','while','for','switch']);
function prevIsRegexStart(prev){
if(prev==='')return true;
// last token
const m1=prev.match(/([A-Za-z_$][A-Za-z0-9_$]*)$/);
if(m1) return rePrevWords.has(m1[1]);
const last=prev[prev.length-1];
return '(,=:[!&|?{;}+-*%<>^~'.includes(last);
}
let i=0;const ch=[...code];const N=ch.length;
while(i<N){
const c=ch[i],n=ch[i+1];const top=mode[mode.length-1];
if(top==='lc'){if(c==='\n')mode.pop();i++;continue;}
if(top==='bc'){if(c==='*'&&n==='/'){mode.pop();i+=2;}else i++;continue;}
if(top==='sq'){if(c==='\\'){i+=2;continue;}if(c==="'"){mode.pop();}i++;continue;}
if(top==='dq'){if(c==='\\'){i+=2;continue;}if(c==='"'){mode.pop();}i++;continue;}
if(top==='tmp'){if(c==='\\'){i+=2;continue;}if(c==='`'){mode.pop();i++;continue;}if(c==='$'&&n==='{'){braceStack.push({line:L(i),kind:'interp'});mode.push('code');i+=2;continue;}i++;continue;}
if(top==='re'){if(c==='\\'){i+=2;continue;}if(c==='['){mode.push('recls');i++;continue;}if(c==='/'){mode.pop();i++;while(i<N&&/[a-z]/i.test(ch[i]))i++;continue;}i++;continue;}
if(top==='recls'){if(c==='\\'){i+=2;continue;}if(c===']'){mode.pop();}i++;continue;}
// code
if(c==='/'&&n==='/'){mode.push('lc');i+=2;continue;}
if(c==='/'&&n==='*'){mode.push('bc');i+=2;continue;}
if(c==='/'){ if(prevIsRegexStart(prevSig)){mode.push('re');i++;continue;} i++;continue; }
if(c==="'"){mode.push('sq');i++;continue;}
if(c==='"'){mode.push('dq');i++;continue;}
if(c==='`'){mode.push('tmp');i++;continue;}
if(c==='{'){braceStack.push({line:L(i),kind:'brace'});}
else if(c==='}'){if(braceStack.length)braceStack.pop();}
else if(c==='('){parenStack.push(L(i));}
else if(c===')'){if(parenStack.length)parenStack.pop();}
if(!/\s/.test(c))prevSig+=c;
i++;
}
console.log('unclosed braces/interps (last 12):', braceStack.slice(-12).map(b=>b.kind+'@L'+b.line));
console.log('unclosed parens (last 6):', parenStack.slice(-6));
-40
View File
@@ -1,40 +0,0 @@
const fs=require('fs');
const espree=require('/opt/homebrew/lib/node_modules/eslint/node_modules/espree/dist/espree.cjs');
const src=fs.readFileSync('index.html','utf8');
const m=src.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);
const code=m[1];
const base=src.slice(0,src.indexOf('<script')).split('\n').length;
const toks=espree.tokenize(code,{ecmaVersion:2022,loc:true});
function balanced(subset){
const st=[]; const open={')':'(',']':'[','}':'{'};
for(const t of subset){
const v=t.value;
if(v==='{'||v==='('||v==='[') st.push(v);
else if(v==='}'||v===')'||v===']'){ if(!st.length||st[st.length-1]!==open[v]) return false; st.pop(); }
}
return st.length===0;
}
// sanity: full set should NOT balance
console.log('full balances?', balanced(toks));
// find the { token whose removal balances everything; report candidates
const cand=[];
for(let i=0;i<toks.length;i++){
if(toks[i].value==='{'){
const sub=toks.slice(0,i).concat(toks.slice(i+1));
if(balanced(sub)){ cand.push({i, line:toks[i].loc.start.line, col:toks[i].loc.start.column}); }
}
}
console.log('removable { candidates (file line):');
const cl=code.split('\n');
for(const c of cand.slice(0,8)){
const fl=c.line+base-1;
console.log(' script-line '+c.line+' col '+c.col+' => FILE line '+fl+' : '+JSON.stringify(cl[c.line-1]));
}
// also test removing a '(' in case it's a paren issue
const pc=[];
for(let i=0;i<toks.length;i++){
if(toks[i].value==='('){
if(balanced(toks.slice(0,i).concat(toks.slice(i+1)))) pc.push({line:toks[i].loc.start.line,col:toks[i].loc.start.column});
}
}
if(pc.length) console.log('removable ( candidates:', pc.slice(0,4).map(p=>'L'+(p.line+base-1)));
-29
View File
@@ -1,29 +0,0 @@
const fs=require('fs');
const espree=require('/opt/homebrew/lib/node_modules/eslint/node_modules/espree/dist/espree.cjs');
const src=fs.readFileSync('index.html','utf8');
const m=src.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);
const code=m[1];
const base=src.slice(0,src.indexOf('<script')).split('\n').length;
const toks=espree.tokenize(code,{ecmaVersion:2022,loc:true});
function balanced(subset){const st=[];const open={')':'(',']':'[','}':'{'};for(const t of subset){const v=t.value;if(v==='{'||v==='('||v==='[')st.push(v);else if(v==='}'||v===')'||v===']'){if(!st.length||st[st.length-1]!==open[v])return false;st.pop();}}return st.length===0;}
const codeLines=code.split('\n');
function removeBraceAt(line,col){ // 1-based line, 0-based col in script
const nl=codeLines.slice();
nl[line-1]=nl[line-1].slice(0,col)+nl[line-1].slice(col+1);
return nl.join('\n');
}
function parses(c){try{espree.parse(c,{ecmaVersion:2022,sourceType:'script',allowReturnOutsideFunction:true});return true;}catch(e){return false;}}
// collect ALL { removal candidates that balance the count, then test-parse
let found=[];
for(let i=0;i<toks.length;i++){
if(toks[i].value==='{'){
if(balanced(toks.slice(0,i).concat(toks.slice(i+1)))){
const L=toks[i].loc.start.line, C=toks[i].loc.start.column;
const testCode=removeBraceAt(L,C);
if(parses(testCode)){ found.push({line:L,col:C,file:L+base-1}); }
}
}
}
console.log('=== { removals that make it PARSE (the culprit) ===');
for(const f of found){ console.log(' script-line '+f.line+' col '+f.col+' FILE line '+f.file+' : '+JSON.stringify(codeLines[f.line-1])); }
// Also try INSERTING a } before the final IIFE close (alternative fix): find where
-25
View File
@@ -1,25 +0,0 @@
const fs=require('fs');
const espree=require('/opt/homebrew/lib/node_modules/eslint/node_modules/espree/dist/espree.cjs');
const src=fs.readFileSync('index.html','utf8');
const m=src.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);
const code=m[1];
const base=src.slice(0,src.indexOf('<script')).split('\n').length;
const codeLines=code.split('\n');
function parses(c){try{espree.parse(c,{ecmaVersion:2022,sourceType:'script',allowReturnOutsideFunction:true});return true;}catch(e){return false;}}
// also test inserting } right before the final })(); (i.e., extra close for the IIFE body)
let hits=[];
for(let L=1;L<=codeLines.length;L++){
// insert '}' after end of line L
const mod=codeLines.slice(0,L).join('\n')+'\n}\n'+codeLines.slice(L).join('\n');
if(parses(mod)) hits.push({type:'}', line:L, file:L+base-1, ctx:codeLines[L-1]});
}
// test inserting ')' similarly (rare)
let phits=[];
for(let L=1;L<=codeLines.length;L++){
const mod=codeLines.slice(0,L).join('\n')+'\n)\n'+codeLines.slice(L).join('\n');
if(parses(mod)) phits.push({line:L, file:L+base-1, ctx:codeLines[L-1]});
}
console.log('} insertions that PARSE: '+hits.length);
for(const h of hits.slice(0,12)) console.log(' +} after FILE line '+h.file+' :: '+JSON.stringify(h.ctx));
console.log(') insertions that PARSE: '+phits.length);
for(const h of phits.slice(0,6)) console.log(' +) after FILE line '+h.file+' :: '+JSON.stringify(h.ctx));
-24
View File
@@ -1,24 +0,0 @@
const fs=require('fs');
const espree=require('/opt/homebrew/lib/node_modules/eslint/node_modules/espree/dist/espree.cjs');
const src=fs.readFileSync('index.html','utf8');
const m=src.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);
const code=m[1];
const base=src.slice(0,src.indexOf('<script')).split('\n').length;
const toks=espree.tokenize(code,{ecmaVersion:2022,loc:true});
const codeLines=code.split('\n');
function parses(c){try{espree.parse(c,{ecmaVersion:2022,sourceType:'script',allowReturnOutsideFunction:true});return true;}catch(e){return false;}}
// map each token to its absolute char offset in code, then remove that single char
// build offset index: line/col -> char index
const lineStarts=[0];
for(const ln of codeLines){ lineStarts.push(lineStarts[lineStarts.length-1]+ln.length+1); }
let hits=[];
for(const t of toks){
if(!'{([]}'.includes(t.value)) continue;
const off=lineStarts[t.loc.start.line-1]+t.loc.start.column;
const mod=code.slice(0,off)+code.slice(off+1);
if(parses(mod)){
hits.push({val:t.value, line:t.loc.start.line, col:t.loc.start.column, file:t.loc.start.line+base-1, ctx:codeLines[t.loc.start.line-1]});
}
}
console.log('bracket removals that PARSE: '+hits.length);
for(const h of hits) console.log(' remove '+h.val+' at FILE line '+h.file+' col '+h.col+' :: '+JSON.stringify(h.ctx));
-12
View File
@@ -1,12 +0,0 @@
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
Fixed: missing closing brace for the ghost-timer block in `stepOnce()`.
- **Change:** inserted a `}` to close `if (!ejectedThisStep && GAME.player && GAME.player.ghost){ ... }`
- **Location:** `index.html` **line 968** (right after the inner `if (GAME.player.timer <= 0){...}` block)
Verified (all exit 0):
```bash
node verify.js 1 && node verify.js 2 && node verify.js 3 && node verify.js 4 && node verify.js 5
```
-1
View File
@@ -1 +0,0 @@
11107
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-9
View File
@@ -1,9 +0,0 @@
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
Created `./index.html` implementing Phase 1 core engine only (canvas + HUD, deterministic `tick(n)` ghost timer, grid + walls + collision, fog-of-war, title screen controls + legend toggle `l`, `window.GAME` contract w/ safe stubs for later phases).
Verification:
```bash
node verify.js 1
# Phase 1: PASS (8/8)
```
-16
View File
@@ -1,16 +0,0 @@
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
Implemented Phase 2 incrementally in `index.html` (no rewrite):
- Possession: `Space` while ghost, adjacent enemy (orthogonal; diagonal via Chebyshev fallback) → `state='possessed'`, `player.host` set, player moved onto host tile
- Voluntary abandon: `x` while possessed → back to ghost (`state='playing'`), host returned to `enemies`, `pacify=2`, `lockout=2`, ghost timer resumes (not reset), immediate re-possess blocked
- Enemies implemented: **Brute**, **Skitterer**, **Sentinel** with required stats
- Deterministic `tick(n)` now advances AI + projectiles + ghost timer (paused while possessed); host death checked every tick; host death ejects with fresh timer and does **not** decrement that fresh timer in the same step
- BFS pathfinding around walls toward player for melee enemies
- Sentinel burst (3 shots) + overheat window (3 turns), projectiles damage **player only** (no friendly fire)
Self-checks (per instructions) both pass:
```bash
node verify.js 1 && node verify.js 2
```
-3
View File
@@ -1,3 +0,0 @@
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
-3
View File
@@ -1,3 +0,0 @@
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
-17
View File
@@ -1,17 +0,0 @@
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
Implemented Phase 4 systems (procgen/progression/shop/save-load) and fixed a Phase 3 regression that was breaking verify:
- AI aggro now uses **path distance** (so melee navigates around walls); **Sentinel/Turret still require LOS** before shooting (prevents stray ranged fire during tests).
- Enemy placement min spawn distance increased to **9** (keeps spawn area calm + prevents random test interference).
- Shop between floors + debug `openShop()` stipend + `G.choices` exposure already in place; save/load validates + restores `_exit` coords-based descend.
Tests run (multiple times due to procgen randomness):
```bash
for run in 1 2 3 4 5; do
for i in 1 2 3 4 5; do node verify.js $i || exit 1; done
done
```
All phases 1–5 PASS.
-1
View File
@@ -1 +0,0 @@
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
-1
View File
@@ -1 +0,0 @@
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
-1
View File
@@ -1 +0,0 @@
44170
-21
View File
@@ -1,21 +0,0 @@
const fs=require('fs');
const espree=require('/opt/homebrew/lib/node_modules/eslint/node_modules/espree/dist/espree.cjs');
const src=fs.readFileSync('index.html','utf8');
const m=src.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);
const code=m[1];
const base=src.slice(0,src.indexOf('<script')).split('\n').length;
const toks=espree.tokenize(code,{ecmaVersion:2022,loc:true});
const stack=[]; // {ch, line, col}
const open={'}':'{',']':'[',')':'('};
let extra=null;
for(const t of toks){
const v=t.value;
if(v==='{'||v==='('||v==='['){ stack.push({ch:v,line:t.loc.start.line,col:t.loc.start.column}); }
else if(v==='}'||v===')'||v===']'){
// pop until matching
if(stack.length && stack[stack.length-1].ch===open[v]){ stack.pop(); }
else { console.log('EXTRA close '+v+' at script-line '+t.loc.start.line+' (file '+(t.loc.start.line+base-1)+')'); extra=v; }
}
}
console.log('=== unmatched openers remaining (top = most recent) ===');
for(const s of stack.slice().reverse()){ console.log(s.ch+' at script-line '+s.line+' col '+s.col+' => FILE line '+(s.line+base-1)); }
@@ -26,6 +26,19 @@ Browser-based roguelike. You are a ghost with 1 HP and no attack. Possess enemie
- **Slow baseline:** most chasers move every 2 turns; Skitterer every 2 turns; Turret fires every 2 turns. The player chooses engagements.
- **Spawn safety:** the area around spawn is kept clear of enemies.
## Art Direction (high-polish vector art)
- Everything is drawn on `<canvas>` with layered primitives — gradients, beveled edges, highlights, outlines, soft drop shadows. NO external image/sprite/font assets (zero-dependency rule holds).
- Atmospheric dungeon: beveled cracked stone walls, lit floor flagstones, glowing runic exit stairs, ornate gilded chests, torch-light color grading, soft vignette. Smooth radial fog (gradient falloff, not a hard circle).
- Each entity is a detailed, personality-rich sprite (eyes tracking facing, equipment, idle bob, possession aura on the current host) — see AGENTS.md §Visual Style and each enemy's Sprite line. Never flat single-rect placeholders.
- Polished UI: bordered panels with icons and accent colors for title, HUD, shop, and pause — not bare text.
## Movement Feel (snappy)
- Movement interpolation is a quick ~85ms ease (down from 150ms); HOLD a direction to move continuously at the turn cadence.
- The real-time live loop advances turns at a brisk ~600ms cadence (down from 1000ms) so the dungeon feels alive.
- Presentation/cadence only — the core model stays one-tile-per-turn and `tick(n)` stays deterministic for the headless harness. Never tie game state to wall-clock.
## Player Guidance and Forgiveness
- The title screen explains every control before the player starts: WASD/arrows to move, SPACE to possess or attack, Q/E to face, X to abandon host, ENTER to confirm, and ESC to pause.
File diff suppressed because it is too large. Load diff
-316
View File
@@ -1,316 +0,0 @@
#!/usr/bin/env node
'use strict';
/*
verify.js — headless test harness for Body Snatcher (single index.html).
Uses only Node builtins: fs, vm, path.
Usage: node verify.js <phase> (phase 1..5). Exit 0 = pass, 1 = fail.
*/
const fs = require('fs');
const path = require('path');
const vm = require('vm');
const PHASE = parseInt(process.argv[2] || '1', 10);
const HTML = path.join(__dirname, 'index.html');
const SAVE_KEY = 'bodysnatcher_save';
const ENEMIES = ['Brute','Skitterer','Sentinel','Shielder','Bomber','Healer','Phaser','Turret','Charger','Siren','Mimic','Leech'];
const VALID_STATES = ['title','playing','possessed','shop','paused','won','lost'];
function fail(msg){ const e = new Error(msg || 'assertion failed'); e._assert = true; throw e; }
function assert(c, m){ if (!c) fail(m || 'assertion failed'); }
// ---------------------------------------------------------------- read source
if (!fs.existsSync(HTML)) { console.error(`FAIL: index.html not found`); process.exit(1); }
const SRC = fs.readFileSync(HTML, 'utf8');
const scriptRe = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi;
let mm, SCRIPT = '', externalSrc = false;
while ((mm = scriptRe.exec(SRC))) {
if (/\bsrc\s*=/.test(mm[1] || '')) externalSrc = true;
SCRIPT += '\n' + (mm[2] || '');
}
if (!SCRIPT.trim()) { /* maybe the game is all inline anyway; keep going */ }
// ----------------------------------------------------------------- mocks
function noop(){ return undefined; }
const grad = { addColorStop: noop, addColorStop: noop };
const texts = [];
function makeCtx(canvas){
const base = {
canvas,
fillStyle:'#000', strokeStyle:'#000', shadowColor:'#000', font:'10px sans-serif',
textAlign:'left', textBaseline:'alphabetic', globalAlpha:1, lineWidth:1, lineCap:'butt',
lineJoin:'miter', miterLimit:10, shadowBlur:0, shadowOffsetX:0, shadowOffsetY:0,
globalCompositeOperation:'source-over', imageSmoothingEnabled:true, lineDashOffset:0,
save:noop, restore:noop, scale:noop, rotate:noop, translate:noop, transform:noop,
setTransform:noop, resetTransform:noop,
beginPath:noop, closePath:noop, moveTo:noop, lineTo:noop, bezierCurveTo:noop,
quadraticCurveTo:noop, arc:noop, arcTo:noop, rect:noop, ellipse:noop, fill:noop,
stroke:noop, clip:noop, isPointInPath:()=>false,
clearRect:noop, fillRect:noop, strokeRect:noop, drawImage:noop,
fillText:(t)=>{ texts.push(String(t)); }, strokeText:(t)=>{ texts.push(String(t)); },
measureText:(s)=>({ width: ((String(s)||'').length*7)+2 }),
getImageData:(x,y,w,h)=>({ data: new Uint8ClampedArray(Math.max(1,(w||1))*(h||1)*4) }),
putImageData:noop, createImageData:(w,h)=>({ data: new Uint8ClampedArray((w||1)*(h||1)*4) }),
createLinearGradient:()=>({addColorStop:noop}), createRadialGradient:()=>({addColorStop:noop}),
createPattern:()=>({}), setLineDash:noop, getLineDash:()=>[], drawFocusIfNeeded:noop,
};
return new Proxy(base, {
get(t,p){ return (p in t) ? t[p] : noop; },
set(t,p,v){ t[p]=v; return true; },
});
}
function makeCanvas(id){
const canvas = { id, width:800, height:640, clientWidth:800, clientHeight:640,
style:{}, tabindex:0, addEventListener:noop, removeEventListener:noop, focus:noop, blur:noop,
getBoundingClientRect:()=>({left:0,top:0,right:800,bottom:640,width:800,height:640,x:0,y:0}) };
const ctx = makeCtx(canvas);
canvas.getContext = (type)=> (/2d/i.test(String(type)) ? ctx : {});
return canvas;
}
const els = {};
['game','canvas','screen','board','c','main','stage','view','bg','overlay','hud'].forEach(id=>{ els[id] = makeCanvas(id); });
function genericEl(){
return { style:{}, addEventListener:noop, removeEventListener:noop, appendChild:noop,
removeChild:noop, setAttribute:noop, getAttribute:()=>null, getContext:()=>({}),
innerHTML:'', textContent:'', firstChild:null, lastChild:null, childNodes:[], children:[],
parentElement:null, focus:noop, click:noop, blur:noop,
classList:{add:noop,remove:noop,toggle:noop,contains:()=>false}, dataset:{}, append:noop,
prepend:noop, insertBefore:noop, replaceChild:noop };
}
const keyHandlers = [];
const loadHandlers = [];
const documentMock = {
getElementById:(id)=> (els[id] !== undefined ? els[id] : null),
createElement:(tag)=> (String(tag).toLowerCase()==='canvas' ? makeCanvas() : genericEl()),
createElementNS:(_n,tag)=> documentMock.createElement(tag),
createTextNode:(t)=>({ textContent:String(t), nodeType:3 }),
addEventListener:(ev,cb)=>{ if (/key/i.test(ev)) keyHandlers.push(cb); if (/load|domcontent/i.test(ev)) loadHandlers.push(cb); },
removeEventListener:noop,
body: Object.assign(genericEl(), { addEventListener:noop }),
documentElement: Object.assign(genericEl(), { clientWidth:800, clientHeight:640, addEventListener:noop }),
head: genericEl(),
readyState:'complete', querySelector:()=>null, querySelectorAll:()=>[],
getElementsByTagName:()=>[], getElementsByClassName:()=>[],
createEvent:()=>({ initEvent:noop, initCustomEvent:noop }),
title:'', hidden:false, visibilityState:'visible', hasFocus:()=>true,
};
const store = {};
const setItemCalls = [];
const localStorageMock = {
getItem:(k)=> Object.prototype.hasOwnProperty.call(store,k) ? store[k] : null,
setItem:(k,v)=>{ store[k]=String(v); setItemCalls.push(String(k)); },
removeItem:(k)=>{ delete store[k]; },
clear:()=>{ Object.keys(store).forEach(k=>delete store[k]); },
key:(i)=> Object.keys(store)[i] || null,
get length(){ return Object.keys(store).length; },
};
const audioMethods = {};
let audioCreated = 0;
function makeAudioNode(){ return {
connect:()=>({}), disconnect:noop, start:noop, stop:noop, frequency:{value:440,setValueAtTime:noop,linearRampToValueAtTime:noop,exponentialRampToValueAtTime:noop},
gain:{value:1,setValueAtTime:noop,linearRampToValueAtTime:noop,exponentialRampToValueAtTime:noop},
detune:{value:0,setValueAtTime:noop}, type:'', playbackRate:{value:1,setValueAtTime:noop},
Q:{value:1,setValueAtTime:noop}, buffer:null, loop:false, destination:{}
}; }
class MockAudioContext {
constructor(){ audioCreated++; this.currentTime=0; this.state='running'; this.sampleRate=44100;
this.destination={ connect:()=>({}) }; this.listener={}; }
createOscillator(){ audioMethods.createOscillator=1; return makeAudioNode(); }
createGain(){ audioMethods.createGain=1; return makeAudioNode(); }
createBufferSource(){ audioMethods.createBufferSource=1; return makeAudioNode(); }
createDynamicsCompressor(){ return makeAudioNode(); }
createAnalyser(){ return makeAudioNode(); }
createBiquadFilter(){ return makeAudioNode(); }
createDelay(){ return makeAudioNode(); }
createBuffer(){ return { getChannelData:()=>new Float32Array(1024) }; }
decodeAudioData(){ return Promise.resolve({}); }
resume(){ audioMethods.resume=1; return Promise.resolve(); }
suspend(){ return Promise.resolve(); }
close(){ return Promise.resolve(); }
}
let perfNow = 0;
const sb = {};
sb.setTimeout = (fn)=>{ const id=Math.random(); return id; }; // no-op (deterministic loop via tick)
sb.clearTimeout = noop; sb.setInterval = ()=>1; sb.clearInterval = noop;
sb.queueMicrotask = (fn)=>{ Promise.resolve().then(fn); };
sb.requestAnimationFrame = ()=>1; sb.cancelAnimationFrame = noop;
sb.requestIdleCallback = ()=>1; sb.cancelIdleCallback = noop;
sb.performance = { now:()=>(perfNow+=16), timeOrigin:0, mark:noop, measure:noop };
sb.Date = Date;
sb.localStorage = localStorageMock;
sb.AudioContext = MockAudioContext; sb.webkitAudioContext = MockAudioContext;
sb.document = documentMock;
sb.console = { log:noop, debug:noop, info:noop, trace:noop,
warn:(...a)=>process.stderr.write('[game.warn] '+a.map(String).join(' ')+'\n'),
error:(...a)=>process.stderr.write('[game.err] '+a.map(String).join(' ')+'\n') };
sb.navigator = { userAgent:'node.js', platform:process.platform, language:'en' };
sb.location = { href:'file:///', reload:noop };
sb.screen = { width:800, height:640 };
sb.matchMedia = ()=>({ matches:false, addListener:noop, removeListener:noop, addEventListener:noop, removeEventListener:noop });
sb.innerWidth = 800; sb.innerHeight = 640; sb.devicePixelRatio = 1;
['Math','JSON','Object','Array','String','Number','Boolean','RegExp','Map','Set','WeakMap','WeakSet','Symbol','Error','TypeError','RangeError','SyntaxError','Promise','Reflect','Proxy','Uint8Array','Uint8ClampedArray','Int8Array','Int16Array','Uint16Array','Int32Array','Uint32Array','Float32Array','Float64Array','ArrayBuffer','DataView','Number','parseInt','parseFloat','isNaN','isFinite','encodeURIComponent','decodeURIComponent','encodeURI','decodeURI'].forEach(k=>{ if (global[k]!==undefined) sb[k]=global[k]; });
sb.btoa = (s)=> Buffer.from(s,'binary').toString('base64');
sb.atob = (s)=> Buffer.from(s,'base64').toString('binary');
sb.window = sb; sb.self = sb; sb.globalThis = sb;
// ----------------------------------------------------------------- run script
vm.createContext(sb);
try {
vm.runInContext(SCRIPT, sb, { filename:'index.html-inline', timeout:8000 });
} catch (e) {
console.error('FAIL: index.html inline script threw on load:\n' + (e && e.stack || e));
process.exit(1);
}
for (const h of loadHandlers) { try { h({type:'load'}); } catch(_){} }
const G = sb.GAME;
if (!G) { console.error('FAIL: window.GAME is not defined after load'); process.exit(1); }
// ----------------------------------------------------------------- helpers
const H = {};
H.inBounds = (x,y)=>{ const g=G.grid; return !!(g && y>=0 && y<g.length && x>=0 && x<g[y].length); };
H.tileType = (x,y)=>{ if(!H.inBounds(x,y)) return -1; const t=G.grid[y][x]; return (t && typeof t==='object') ? (t.type!==undefined?t.type:0) : t; };
H.isWall = (x,y)=>{ if(H.tileType(x,y)===1) return true; const t=G.grid && G.grid[y] && G.grid[y][x]; return !!(t && typeof t==='object' && t.solid); };
H.setTile = (x,y,type,solid)=>{ if(!H.inBounds(x,y)) return; const cur=G.grid[y][x]; const sol = solid!==undefined?solid:(type===1);
if (cur && typeof cur==='object') { cur.type=type; cur.solid=sol; } else { G.grid[y][x]=type; } };
H.floor = (x,y)=> H.setTile(x,y,0,false);
H.wall = (x,y)=> H.setTile(x,y,1,true);
H.clearRow = (y,x1,x2)=>{ for(let x=x1;x<=x2;x++) if(H.inBounds(x,y)) H.floor(x,y); };
H.clearCol = (x,y1,y2)=>{ for(let y=y1;y<=y2;y++) if(H.inBounds(x,y)) H.floor(x,y); };
H.manhattan = (a,b)=> Math.abs(a.x-b.x)+Math.abs(a.y-b.y);
H.cheby = (a,b)=> Math.max(Math.abs(a.x-b.x),Math.abs(a.y-b.y));
H.ppos = ()=> ({ x:G.player.x, y:G.player.y });
H.start = ()=>{ if (typeof G.start==='function') G.start(); };
H.newRun = ()=>{ if (typeof G.newRun==='function') { G.newRun(); } else { if(typeof G.start==='function')G.start(); G.input('Enter'); } };
H.findExit = ()=>{ if (G._exit && G._exit.x!==undefined) return {x:G._exit.x,y:G._exit.y};
const g=G.grid; for(let y=0;y<g.length;y++) for(let x=0;x<g[y].length;x++) if(H.tileType(x,y)===3) return {x,y}; return null; };
H.findFreeNear = (x,y,r)=>{ for(let rad=0;rad<=(r||6);rad++) for(let dy=-rad;dy<=rad;dy++) for(let dx=-rad;dx<=rad;dx++){ const nx=x+dx,ny=y+dy; if(H.inBounds(nx,ny)&&!H.isWall(nx,ny)) return {x:nx,y:ny}; } return null; };
H.spawnAt = (type,x,y)=>{ if(H.inBounds(x,y)) H.floor(x,y); return G.spawn(type,x,y); };
H.maxHp = (e)=> e && (e.maxHp!==undefined?e.maxHp:e.hp);
H.statVal = (e,keys)=>{ for(const k of keys) if(e && e[k]!==undefined) return e[k]; return undefined; };
H.countAch = ()=>{ const a=G.achievements; if(!a) return 0;
if(Array.isArray(a)) return a.filter(x=>x && (x.unlocked||x.done||x.unlockedAt)).length;
return Object.values(a).filter(v=> v===true || (v && v.unlocked)).length; };
H.descend = ()=>{ // step the player onto the exit tile; returns resulting state
const ex = H.findExit(); if(!ex) return null;
// place player on a floor neighbour of the exit
const neigh=[[-1,0],[1,0],[0,-1],[0,1]].find(([dx,dy])=>H.inBounds(ex.x+dx,ex.y+dy));
if(!neigh) return G.state;
const sx=ex.x+neigh[0], sy=ex.y+neigh[1]; H.floor(sx,sy);
G.player.x=sx; G.player.y=sy;
// move onto exit
if(ex.x>sx) G.input('ArrowRight'); else if(ex.x<sx) G.input('ArrowLeft');
else if(ex.y>sy) G.input('ArrowDown'); else G.input('ArrowUp');
return G.state;
};
H.projectilesAt = ()=> (Array.isArray(G.projectiles)?G.projectiles.length:(G.projectiles?Object.keys(G.projectiles).length:0));
H.tankHost = ()=>{ const h=G.player&&G.player.host; if(h){ h.hp=999; if(h.maxHp!==undefined)h.maxHp=999; } };
// ----------------------------------------------------------------- phase defs
function p1(){
const checks = [];
checks.push(['index.html has <canvas> and <script>', ()=>{ assert(/<canvas/i.test(SRC), 'no <canvas>'); assert(/<script/i.test(SRC), 'no <script>'); }]);
checks.push(['no external src= or import', ()=>{ assert(!externalSrc, 'external <script src=> found'); assert(!/^\s*import\s/m.test(SCRIPT) && !/\bimport\s*["']/m.test(SCRIPT), 'ES import found'); }]);
checks.push(['GAME.start() runs, valid state', ()=>{ H.start(); assert(VALID_STATES.includes(G.state), 'invalid state: '+G.state); }]);
checks.push(['grid has wall and floor tiles', ()=>{ const g=G.grid; assert(g && g.length, 'no grid'); let w=0,f=0; for(let y=0;y<g.length;y++) for(let x=0;x<g[y].length;x++){ const t=H.tileType(x,y); if(t===1)w++; else if(t===0)f++; } assert(w>0,'no walls'); assert(f>0,'no floor'); }]);
checks.push(['ghost moves on input, blocked by wall', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y);
// choose an in-bounds horizontal direction
let dir='ArrowRight', nx=p.x+1; if(!H.inBounds(p.x+1,p.y)){ dir='ArrowLeft'; nx=p.x-1; }
H.wall(nx,p.y); G.input(dir); assert(G.player.x===p.x, 'ghost moved into wall');
H.floor(nx,p.y); G.input(dir); assert(G.player.x===nx, 'ghost did not move onto floor');
}]);
checks.push(['title screen explains controls (WASD/arrows/SPACE/Q-E/ENTER/ESC)', ()=>{ assert(/WASD/i.test(SRC), 'WASD missing'); assert(/arrow/i.test(SRC), 'arrows missing'); assert(/space/i.test(SRC), 'SPACE missing'); assert(/enter/i.test(SRC), 'ENTER missing'); assert(/esc|escape|pause/i.test(SRC), 'ESC/pause missing'); assert(/facing|rotate|\bQ\b.*\bE\b|\bQ\/E\b|Q\/E/i.test(SRC), 'Q/E facing missing'); }]);
checks.push(['enemy legend (bestiary) reachable, lists enemies', ()=>{ assert(/legend|bestiary/i.test(SRC), 'no legend/bestiary panel'); let names=0; for(const n of ENEMIES) if(new RegExp(n,'i').test(SRC)) names++; assert(names>=6, 'only '+names+' enemy names in source'); H.start(); assert(typeof G.input==='function'); let ok=true; try { G.input('l'); } catch(e){ ok=false; } assert(ok, "input('l') threw"); }]);
checks.push(['starting ghost timer >= 15s', ()=>{ H.newRun(); assert(G.player && (G.player.timer||0)>=15, 'timer='+(G.player&&G.player.timer)); }]);
return checks;
}
function p2(){
const checks = [];
checks.push(['SPACE on adjacent enemy -> possessed', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); const e=H.spawnAt('Brute', p.x+1, p.y); assert(e, 'spawn failed'); G.input('Space'); assert(G.state==='possessed', 'state='+G.state); assert(!!G.player.host, 'no host'); }]);
checks.push(['X abandons host: ghost returns, host survives, lockout', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); H.spawnAt('Brute', p.x+1, p.y); G.input('Space'); assert(G.state==='possessed'); const hostId = G.player.host && (G.player.host.id||G.player.host._id); const before = (G.enemies||[]).length; G.input('x'); assert(G.state!=='possessed', 'still possessed after X'); assert(!G.player.host, 'host still set'); assert(G.player.ghost===true, 'not ghost'); assert((G.player.timer||0)>0, 'timer<=0 after abandon'); assert((G.enemies||[]).length>=before, 'host disappeared from enemies'); // lockout: immediate re-possess must fail
G.input('Space'); assert(G.state!=='possessed', 're-possessed immediately (no lockout)'); }]);
checks.push(['Brute/Skitterer/Sentinel stats', ()=>{ for(const [t,hp,dmg] of [['Brute',8,3],['Skitterer',2,1],['Sentinel',4,null]]){ const p=H.ppos?H.ppos():{x:5,y:5}; H.newRun(); const pp=H.ppos(); H.floor(pp.x,pp.y); const e=H.spawnAt(t, pp.x+1, pp.y); assert(e, t+' spawn failed'); assert(H.maxHp(e)===hp, t+' maxHp='+H.maxHp(e)+' want '+hp); if(dmg!==null) assert(H.statVal(e,['damage','dmg','attack','atk'])===dmg, t+' damage mismatch'); } }]);
checks.push(['Sentinel fires a burst then OVERHEATS (no-fire window)', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); H.clearRow(p.y,0,24); const brute=H.spawnAt('Brute', p.x+1, p.y); G.input('Space'); assert(G.state==='possessed','need possessed host'); const hp=H.ppos(); H.tankHost(); const sx=Math.max(1,hp.x-5); H.clearRow(hp.y,sx,hp.x); const sen=H.spawnAt('Sentinel', sx, hp.y); assert(sen,'sentinel spawn'); let ohMax=0,fired=false; for(let i=0;i<22;i++){ const b=H.projectilesAt(); const bl0=sen.burstLeft; G.tick(1); if(H.projectilesAt()>b||sen.burstLeft<bl0) fired=true; ohMax=Math.max(ohMax, sen.overheatLeft||0); } assert(fired,'sentinel never fired (setup/aggro issue)'); assert(ohMax>=3,'sentinel never entered a 3-turn overheat (ohMax='+ohMax+')'); }]);
checks.push(['enemies pathfind toward the ghost', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); H.clearRow(p.y,0,24); const ex=Math.max(1,p.x-5); H.clearRow(p.y,ex,p.x); const e=H.spawnAt('Brute', ex, p.y); assert(e); const d0=H.manhattan({x:ex,y:p.y},p); let moved=false; for(let i=0;i<14;i++){ G.tick(1); } const df=H.manhattan({x:e.x,y:e.y},p); assert(df<d0, 'enemy did not approach (d0='+d0+', df='+df+')'); }]);
checks.push(['killing host ejects ghost with timer>0', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); H.spawnAt('Skitterer', p.x+1, p.y); G.input('Space'); assert(G.state==='possessed'); const host=G.player.host; assert(host,'no host'); host.hp=0; G.tick(1); assert(G.player.ghost===true,'not ghost after host death'); assert(!G.player.host,'host still set'); assert((G.player.timer||0)>0,'timer<=0'); }]);
checks.push(['essence increases on kill', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); H.spawnAt('Brute', p.x+1, p.y); G.input('Space'); assert(G.state==='possessed'); const target=H.spawnAt('Skitterer', p.x+2, p.y); H.floor(p.x+2,p.y); const e0=G.essence||0; let got=false; for(let i=0;i<8;i++){ G.input('Space'); if((G.essence||0)>e0){got=true;break;} G.input('e'); G.input('q'); } assert(got,'essence did not increase after kill (e0='+e0+', e='+G.essence+')'); }]);
checks.push(['no friendly fire: Sentinel projectiles never hit another enemy', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); H.clearRow(p.y,0,24); const brute=H.spawnAt('Brute', p.x+1, p.y); G.input('Space'); const hp=H.ppos(); H.tankHost(); const sx=Math.max(1,hp.x-5); H.clearRow(hp.y,sx,hp.x); const mid=Math.round((sx+hp.x)/2); H.floor(mid,hp.y); const meat=H.spawnAt('Skitterer', mid, hp.y); assert(meat); const sen=H.spawnAt('Sentinel', sx, hp.y); assert(sen); const meatHp0=H.maxHp(meat); let fired=0; for(let i=0;i<16;i++){ const b=H.projectilesAt(); G.tick(1); if(H.projectilesAt()-b>0) fired++; } assert(fired>=2,'sentinel did not fire (fired='+fired+')'); assert((meat.hp||0)===meatHp0 || H.maxHp(meat)===meatHp0, 'friendly fire: meat enemy lost HP ('+meatHp0+'->'+(meat.hp)+')'); }]);
return checks;
}
function p3(){
const checks = [];
checks.push(['all 12 enemy types instantiate', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); for(const t of ENEMIES){ const spot=H.findFreeNear(p.x,p.y,8); const e=G.spawn(t, spot.x, spot.y); assert(e, t+' spawn returned falsy'); assert(e && (e.type===t || (e.type||'').toLowerCase()===t.toLowerCase() || e.kind===t), t+' wrong type'); } }]);
checks.push(['distinct hp+damage+speed tuples', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); const seen=new Set(); let i=0; for(const t of ENEMIES){ const spot=H.findFreeNear(p.x,p.y,10); const e=G.spawn(t, spot.x, spot.y); const hp=H.maxHp(e), dmg=H.statVal(e,['damage','dmg','attack','atk'])??'?'; const sp=H.statVal(e,['speed','moveInterval','moveEvery','moveCd'])??'?'; const key=t+'|'+hp+'|'+dmg+'|'+sp; seen.add(key); i++; } // at least 10 of 12 distinct combinations
assert(seen.size>=10, 'only '+seen.size+' distinct stat tuples'); }]);
checks.push(['each special ability triggers without error', ()=>{ for(const t of ENEMIES){ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); H.clearRow(p.y,0,24); const e=H.spawnAt(t, p.x+1, p.y); G.input('Space'); // possess (some types may need LOS/adjacency; best effort)
let threw=false; try { if(G.state==='possessed'){ G.input('e'); G.input('Space'); G.input('q'); G.input('Space'); } } catch(err){ threw=true; } assert(!threw, t+' ability threw'); } }]);
checks.push(['pathfinder navigates around walls (not through)', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y);
// clear a room (remove procgen interference), then a wall column with a DOOR on the player's row so LOS stays clear and the Brute aggros; it must reach the player via the door without clipping walls
for(let yy=p.y-6;yy<=p.y+6;yy++) for(let xx=p.x-9;xx<=p.x+4;xx++) if(H.inBounds(xx,yy)) H.floor(xx,yy);
const wx=p.x-3; for(let yy=p.y-3;yy<=p.y+3;yy++) if(yy!==p.y) H.wall(wx,yy); H.floor(wx,p.y);
const ex=p.x-5; H.floor(ex,p.y); const e=H.spawnAt('Brute', ex, p.y); assert(e,'brute spawn'); const d0=H.manhattan({x:ex,y:p.y},p);
for(let i=0;i<44;i++) G.tick(1); const df=H.manhattan({x:e.x,y:e.y},p); assert(df<=2,'did not navigate to player through the door (d0='+d0+',df='+df+')'); }]);
checks.push(['Bomber AoE damages player only, never other enemies', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); H.clearRow(p.y,0,24); const b=H.spawnAt('Bomber', p.x+1, p.y); const meat=H.spawnAt('Skitterer', p.x+2, p.y); H.floor(p.x+2,p.y); const m0=meat.hp; let exploded=false; for(let i=0;i<14;i++){ const ben=(G.enemies||[]).find(x=>x===b||x.type==='Bomber'); G.tick(1); if(!ben || (b.hp!==undefined && b.hp<=0) || !(G.enemies||[]).includes(b)){ exploded=true; break; } } assert(exploded,'bomber never exploded'); assert((meat.hp||0)>=m0 || !((G.enemies||[]).includes(meat) && meat.hp<m0), 'friendly fire: meat lost HP ('+m0+'->'+(meat.hp)+')'); }]);
checks.push(['Charger charge hits player only, never other enemies', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); H.clearRow(p.y,0,24); const cx=Math.max(1,p.x-5); const meat=H.spawnAt('Skitterer', p.x-3, p.y); H.floor(p.x-3,p.y); const ch=H.spawnAt('Charger', cx, p.y); assert(ch); const m0=meat.hp; for(let i=0;i<16;i++) G.tick(1); assert((meat.hp||0)===m0 || !(G.enemies||[]).includes(meat), 'friendly fire: charger damaged meat ('+m0+'->'+(meat.hp)+')'); }]);
checks.push(['Turret shots hit player only, never other enemies', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); H.clearRow(p.y,0,24); const brute=H.spawnAt('Brute', p.x+1,p.y); G.input('Space'); const hp=H.ppos(); H.tankHost(); const cx=Math.max(1,hp.x-5); H.clearRow(hp.y,cx,hp.x); const meat=H.spawnAt('Skitterer', hp.x-3, hp.y); H.floor(hp.x-3,hp.y); const tur=H.spawnAt('Turret', cx, hp.y); assert(tur); const m0=meat.hp; let fired=0; for(let i=0;i<14;i++){ const b=H.projectilesAt(); G.tick(1); if(H.projectilesAt()-b>0) fired++; } assert(fired>=2,'turret did not fire'); assert((meat.hp||0)===m0,'friendly fire: turret shot meat ('+m0+'->'+(meat.hp)+')'); }]);
checks.push(['Turret OVERHEATS after burst', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); H.clearRow(p.y,0,24); const brute=H.spawnAt('Brute', p.x+1,p.y); G.input('Space'); const hp=H.ppos(); H.tankHost(); const cx=Math.max(1,hp.x-5); H.clearRow(hp.y,cx,hp.x); const tur=H.spawnAt('Turret', cx, hp.y); assert(tur); let ohMax=0,fired=false; for(let i=0;i<22;i++){ const b=H.projectilesAt(); const bl0=tur.burstLeft; G.tick(1); if(H.projectilesAt()>b||tur.burstLeft<bl0) fired=true; ohMax=Math.max(ohMax, tur.overheatLeft||0); } assert(fired,'turret never fired (setup/aggro issue)'); assert(ohMax>=3,'turret never entered a 3-turn overheat (ohMax='+ohMax+')'); }]);
return checks;
}
function p4(){
const checks = [];
checks.push(['procedural dungeons differ across runs', ()=>{ const snaps=[]; for(let r=0;r<3;r++){ H.newRun(); const g=G.grid; let s=''; for(let y=0;y<g.length;y++){ let row=''; for(let x=0;x<g[y].length;x++) row += H.isWall(x,y)?'1':'0'; s+=row+'\n'; } snaps.push(s); } const uniq=new Set(snaps); assert(uniq.size>=2,'all 3 layouts identical'); }]);
checks.push(['exit tile exists on the floor', ()=>{ H.newRun(); const ex=H.findExit(); assert(ex,'no exit tile / G._exit'); }]);
checks.push(['shop appears on floor transition', ()=>{ H.newRun(); const st=H.descend(); assert(st==='shop','state='+st+' after descending (expected shop)'); }]);
checks.push(['buying an upgrade changes GAME.upgrades', ()=>{ H.newRun(); if(typeof G.openShop!=='function') fail('no openShop'); G.openShop(); assert(G.state==='shop','openShop state='+G.state); const choices=G.choices||G.shopChoices||G.upgradeChoices; assert(choices && choices.length>=3,'choices<3 ('+(choices?choices.length:0)+')'); const before=JSON.stringify(G.upgrades||{}); let bought=false; for(let idx=0;idx<(choices?choices.length:3);idx++){ const ess=G.essence; try { G.buy(idx); } catch(e){ continue; } if(JSON.stringify(G.upgrades||{})!==before){ bought=true; break; } } assert(bought,'no buy() changed upgrades'); }]);
checks.push(['save() writes to localStorage', ()=>{ setItemCalls.length=0; store[SAVE_KEY] && delete store[SAVE_KEY]; assert(typeof G.save==='function'); G.save(); assert(setItemCalls.indexOf(SAVE_KEY)>=0,'save() did not call setItem("'+SAVE_KEY+'")'); }]);
checks.push(['save/load round-trip persists floor+essence+upgrades', ()=>{ H.newRun(); // establish some state
const st=H.descend(); if(st==='shop'){ try{G.buy(0);}catch(_){} try{G.input('Enter');}catch(_){} } if(typeof G.setFloor==='function'){ try{G.setFloor(3);}catch(_){} } G.essence=42; const upBefore=JSON.stringify(G.upgrades||{}); const fl=(G.floor||1); const ess=(G.essence||0); G.save(); assert(store[SAVE_KEY],'no save data written'); if(typeof G.load!=='function') fail('no load()'); H.newRun(); G.load(); assert((G.floor||1)===fl,'floor not restored ('+G.floor+' vs '+fl+')'); assert((G.essence||0)===ess,'essence not restored ('+G.essence+' vs '+ess+')'); assert(JSON.stringify(G.upgrades||{})===upBefore,'upgrades not restored'); }]);
return checks;
}
function p5(){
const checks = [];
checks.push(['can reach WON (floor 10 exit)', ()=>{ if(typeof G.setFloor!=='function') fail('no setFloor'); G.setFloor(10); assert(G.floor===10 || G.floor===9,'setFloor(10) -> floor='+G.floor); const st=H.descend(); assert(G.state==='won','state='+st+' (expected won)'); }]);
checks.push(['can reach LOST (ghost timer expires)', ()=>{ H.newRun(); assert(G.player.ghost===true); G.player.timer=1; for(let i=0;i<5;i++){ G.tick(1); if(G.state==='lost') break; } assert(G.state==='lost','state='+G.state); }]);
checks.push(['at least 3 achievements trigger', ()=>{ // fresh: first possession, deep diver, essence hoarder
H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); H.spawnAt('Brute', p.x+1, p.y); G.input('Space'); // First Possession
try{ if(typeof G.setFloor==='function') G.setFloor(7); }catch(_){} // Deep Diver
G.essence=29; // one more -> 30 for hoarder
const tg=H.findFreeNear(p.x,p.y,6); if(tg && G.state!=='possessed'){ H.spawnAt('Brute',p.x+1,p.y); G.input('Space'); } const target=H.findFreeNear(G.player.x,G.player.y,4); if(target){ H.spawnAt('Skitterer', target.x, target.y); for(let i=0;i<8;i++){ G.input('Space'); if((G.essence||0)>=30) break; G.input('e'); } } try{ G.tick(1); }catch(_){} const n=H.countAch(); assert(n>=3,'only '+n+' achievements unlocked'); }]);
checks.push(['audio system initialised and used', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); H.spawnAt('Brute', p.x+1, p.y); G.input('Space'); G.input('x'); assert(audioCreated>0,'AudioContext never constructed'); assert(audioMethods.createOscillator||audioMethods.createGain||audioMethods.createBufferSource||audioMethods.resume,'no audio methods called'); }]);
checks.push(['no errors during 200-tick stress (move/possess/attack/descend)', ()=>{ H.newRun(); const keys=['ArrowUp','ArrowDown','ArrowLeft','ArrowRight','Space','x','q','e']; let err=null; try { for(let i=0;i<200;i++){ const k=keys[i%keys.length]; G.input(k); if(i%50===49){ // descend a floor where possible
try{ H.descend(); if(G.state==='shop'){ G.input('Enter'); } }catch(_){} } G.tick(1); if(G.state==='lost'||G.state==='won'){ H.newRun(); } } } catch(e){ err=e; } assert(!err,'threw during stress: '+(err&&err.message)); }]);
return checks;
}
const PHASES = { 1:p1, 2:p2, 3:p3, 4:p4, 5:p5 };
const fn = PHASES[PHASE];
if (!fn) { console.error('FAIL: unknown phase '+PHASE+' (use 1..5)'); process.exit(1); }
// ----------------------------------------------------------------- run checks
let checks;
try { checks = fn(); }
catch (e) { console.error('FAIL: phase '+PHASE+' setup threw: '+(e&&e.stack||e)); process.exit(1); }
let pass=0, failCount=0;
const failures=[];
for (const [name, c] of checks){
try { c(); pass++; console.log(' ✓ '+name); }
catch (e){ failCount++; failures.push(name+' :: '+(e&&e.message||e)); console.log(' ✗ '+name+' → '+(e&&e.message||e)); }
}
console.log('');
if (failCount===0){ console.log(`Phase ${PHASE}: PASS (${pass}/${pass})`); process.exit(0); }
console.log(`Phase ${PHASE}: FAIL (${pass} passed, ${failCount} failed)`);
for (const f of failures) console.log(' - '+f);
process.exit(1);