Initial commit: Snake game implementation

Co-Authored-By: Warp <agent@warp.dev>
This commit is contained in:
2026-02-03 14:57:13 +00:00
co-authored by Warp
commit aae8304ce4
4 changed files with 371 additions and 0 deletions
+52
View File
@@ -0,0 +1,52 @@
# AGENTS.md
This file provides guidance to WARP (warp.dev) when working with code in this repository.
## Project Overview
This is a Snake game implemented with vanilla JavaScript, HTML5 Canvas, and CSS. The project has no build system or dependencies - it runs directly in the browser.
## Running the Game
Open `index.html` directly in a web browser:
```bash
open index.html # macOS
```
Or use a simple HTTP server for development:
```bash
python3 -m http.server 8000
# Then visit http://localhost:8000
```
## Architecture
### Game State Management
The game uses an immutable state pattern managed in `script.js`:
- **State object**: Contains `snake` (array of segments), `dir` (current direction), `nextDir` (queued direction), `food` position, `score`, and `over` flag
- **Pure functions**: `step()` takes current state and returns new state without mutations
- **Game loop**: `setInterval` calls `step()` every 120ms, then `render()` updates canvas and DOM
### Key Game Logic
- **Direction handling**: Prevents 180-degree turns via `isOpposite()` check
- **Collision detection**: `outOfBounds()` and `hitSelf()` determine game over conditions
- **Food placement**: `placeFood()` finds random empty cells by excluding snake positions
- **Growth mechanism**: When snake eats food, tail segment isn't removed in next step
### Rendering Pipeline
1. `drawGrid()` - Clears and draws background grid
2. `drawFood()` - Renders food as a red circle
3. `drawSnake()` - Draws snake segments (darker green for head)
4. UI updates via direct DOM manipulation (`scoreEl`, `statusEl`)
### Input Handling
- Arrow keys and WASD mapped in `directions` object
- `nextDir` queues direction changes to prevent mid-tick direction updates
- Enter key restarts game when over
## Code Conventions
- Uses IIFE to avoid global scope pollution
- Functional approach for game logic (pure `step()` function)
- Grid coordinates: 20x20 grid, each cell is 20px
- Color scheme defined in CSS custom properties in `styles.css`