The user is asking for a single HTML file containing a snake game with AI autoplay on load, and manual operation via arrow keys. Let's write a polished implementation. Features: - Canvas grid-based snake - Arrow keys for control, WASD too if possible - Score display, high score via localStorage - Speed increases as score grows - Game over overlay, restart with Space - On load, AI (BFS pathfinding toward food, safe-move check) autoplays until arrow key is pressed - Polished styling AI: BFS from head to food, pick the move that reduces distance. But avoid collisions with walls/self. If BFS fails, pick a safe move that maximizes survival (e.g. prefer the move with the longest flood-fill space). Simple but decent enough. Implementation details: - Grid is 24x24, cell size around 24px, canvas 576? Make it responsive-ish. Use grid 24, cell 24 => 576px. - Game loop uses setTimeout, interval decreases with score. - AI tick: run BFS every step. Let's write compact but polished code. Edge cases: restart with Space; when AI dies, respawn food, and maybe resume AI? Spec: "When the page loads, autoplay until a key is pressed." So after death during AI mode... probably show game over, restart with Space, but keep it? Restart with Space, and if the user hasn't pressed a key yet, go back to AI. Simpler: restart with Space returns to normal play mode. Actually let's do this: on game over, show overlay; restart with Space. If AI mode was active, resume AI after restart. Track a manualControlled flag that gets set on arrow key press. AI move selection: - Compute reachable safe cells with BFS from head to food. - If path exists, take the first step; avoid moves that make the snake's body... but simple BFS ignores self-collision risk (it might trap itself). Add a safety check: after the candidate move, flood-fill from the new head; if free space is less than snake length + 1, penalize. Among valid moves, pick the one that minimizes BFS distance to food; if none valid, pick any safe move; if no safe move, just move forward and die. Simpler approach: generate safe moves (not wall, not body). For each safe move, BFS distance to food. Prefer the move that maximizes free space, then minimizes distance. Let's implement it: function aiMove(): safe = list of directions where next cell is in range and not body (excluding tail since tail moves? Keep it simple: exclude all body cells except tail tip when not growing). If none: return current direction (die). For each safe move, compute floodFill size from new head (count free cells reachable via BFS through empty cells). Score = floodSize; prefer distance to food as a tiebreaker? Actually prefer the move that minimizes distance while floodSize >= snake.length + 2. If none, pick the one with maximum floodSize. Distance: BFS distance from new head to food through empty cells. Use one BFS from head to food that computes distances, but safety check is separate. Keep it simple: for each safe move, do a BFS flood counting reachable empty cells; if flood >= snakeLen + 1, it's a "good" move; among good moves pick min Manhattan+... hmm, distance to food matters. Use a single BFS from head that computes distance to food and parents; then pick the neighbor of head along the path; then verify the safety of that neighbor with flood size; if unsafe try other safe neighbors in order of distance. Implementation: BFS from head over free cells (cells not occupied by body, excluding tail cell since it will be vacated). Get dist map and find the shortest path to food. Then step. Also check flood size of the chosen cell; if flood size < snake.length, try other safe neighbors in order of distance. That should be enough. Speed: base interval 140ms, decrease with score: interval = max(60, 140 - score*2). Food might give 10 points per eating. UI: header with score/high score, overlay div for game over and "AI playing" badge. Neon-ish dark theme. Direction queue to prevent 180-degree reversal from double-press within a single tick. Let's write the file. Canvas size: 24 cells * 24px = 576. Scale by devicePixelRatio for crispness? Keep it simple: fixed size, CSS max-width. Code: const COLS=24, ROWS=24, CELL=24; State: snake array of {x,y}, dir, nextDirQueue, food, score, mode ('ai'/'manual'), alive, timer. Loop with setTimeout(step, interval). step(): if mode==='ai' aiDecide(); apply queued direction (for manual) — actually for AI just set dir directly. move head, check collision -> gameOver. eat food -> score++, speed up, spawn food. draw. Draw: subtle checkerboard background, rounded snake with gradient head, glowing food. Game over overlay: show score, high score, "Press Space." Key handling: ArrowLeft etc. set manual mode on first press (unless dead? if dead Space restarts). preventDefault for arrow keys and Space. High score: localStorage 'snakeHighScore'. Write it all out. AI details in code: function aiDecide(){ const head = snake[0]; const opts = []; for each direction d in dirs: nx,ny; skip if outside; skip if occupied by body (excluding tail cell since tail moves unless growing). Collect as candidate. If candidates empty: return (die). // BFS distance from head to food over free cells Compute BFS to get distance to food and order candidates by Manhattan distance to food ascending? Better: BFS distance. Compute distMap via BFS from head. For each candidate compute distToFood = distMap[key(nx,ny)] if reached; else Infinity. // Safety: flood size from candidate For each candidate compute floodSize. Sort candidates by (floodSize >= snake.length ? 0 : 1, distToFood). Pick first. } Flood size BFS per candidate is O(4 candidates * 576) per tick — trivial. Occupancy check: body cells; tail cell (last) is fine because it moves, but if we eat this tick the tail doesn't move — check food position first: if candidate is on food, tail stays. Handling: occupied set = body cells except the last; if food is between head and..., just include tail as occupied unless candidate is the food cell. OK. Spawn food randomly in empty cell; if none -> win/game over (basically unreachable). Draw snake with rounded rectangles; head slightly different color; maybe draw eyes. Keep it clean. Also show a subtle "AI playing — press arrow key to take control" indicator, hide when manual. OK let's write the final HTML. CSS: dark gradient background, centered, monospace/score font. Overlay with blur. Speed display probably unnecessary. Write code carefully. Key handling: document.addEventListener('keydown', e=>{ const k=e.key; if(k===' '){ if(!alive){startGame();} e.preventDefault(); return;} const d = dirFromKey(k); if(d){ e.preventDefault(); if(mode==='ai'){mode='manual'; hide badge;} queue direction if not reverse; } }); Direction queue: array; in step, shift from queue: take first valid non-reverse direction. startGame(): reset snake to center length 3, dir right, score 0, spawn food, alive true, mode: keep? After Space restart, mode stays as-is (if user hasn't pressed key, keep AI). OK. gameOver(): alive=false; update high score; show overlay. Interval: base 140, min 60: interval = Math.max(60, 140 - Math.floor(score/10)*8)? Score +10 per food. Speed level = floor(score/50)? Let's do: speed increases every 3 foods. Keep: interval = Math.max(60, 140 - foodsEaten*3). Draw function with checkerboard: fill cell if (x+y)%2. Let's write it.