Complete Worm Game Code
Here's the complete, fully functional Worm game with all features. Copy this into your p5.js Web Editor at https://editor.p5js.org/
// Grid settings
let cellSize = 20;
let cols, rows;
// Worm
let worm = [];
let xSpeed = 1;
let ySpeed = 0;
// Food
let food;
// Score
let score = 0;
// Game state
let gameOver = false;
function setup() {
createCanvas(400, 400);
frameRate(10);
// Calculate grid dimensions
cols = width / cellSize;
rows = height / cellSize;
// Initialize worm in center
let startX = floor(cols / 2);
let startY = floor(rows / 2);
worm.push({x: startX, y: startY});
// Create first food
createFood();
}
function draw() {
background(50);
// Update game
updateWorm();
// Draw grid lines (optional - remove for cleaner look)
stroke(80);
strokeWeight(1);
for (let i = 0; i < cols; i++) {
line(i * cellSize, 0, i * cellSize, height);
}
for (let i = 0; i < rows; i++) {
line(0, i * cellSize, width, i * cellSize);
}
// Draw food
fill(255, 0, 0);
noStroke();
rect(food.x * cellSize, food.y * cellSize, cellSize, cellSize);
// Draw worm
fill(0, 255, 0);
for (let i = 0; i < worm.length; i++) {
let segment = worm[i];
rect(segment.x * cellSize, segment.y * cellSize, cellSize, cellSize);
}
// Draw score
fill(255);
textSize(20);
textAlign(LEFT);
text('Score: ' + score, 10, 25);
// Game over screen
if (gameOver) {
fill(0, 0, 0, 200);
rect(0, 0, width, height);
fill(255);
textSize(40);
textAlign(CENTER, CENTER);
text('GAME OVER', width/2, height/2 - 40);
textSize(20);
text('Final Score: ' + score, width/2, height/2 + 10);
text('Press ENTER to restart', width/2, height/2 + 40);
}
}
function updateWorm() {
// Don't update if game is over
if (gameOver) return;
// Get current head position
let head = worm[worm.length - 1];
// Calculate new head position
let newHead = {
x: head.x + xSpeed,
y: head.y + ySpeed
};
// Check wall collision
if (newHead.x < 0 || newHead.x >= cols ||
newHead.y < 0 || newHead.y >= rows) {
gameOver = true;
return;
}
// Check self-collision
for (let i = 0; i < worm.length; i++) {
if (newHead.x === worm[i].x && newHead.y === worm[i].y) {
gameOver = true;
return;
}
}
// Add new head
worm.push(newHead);
// Check if food was eaten
if (newHead.x === food.x && newHead.y === food.y) {
score++;
createFood();
// Don't remove tail - worm grows!
} else {
// Remove tail - normal movement
worm.shift();
}
}
function createFood() {
let validPosition = false;
// Keep trying until we find a spot not occupied by worm
while (!validPosition) {
food = {
x: floor(random(cols)),
y: floor(random(rows))
};
// Check if food overlaps with worm
validPosition = true;
for (let i = 0; i < worm.length; i++) {
if (food.x === worm[i].x && food.y === worm[i].y) {
validPosition = false;
break;
}
}
}
}
function resetGame() {
// Reset worm
worm = [];
let startX = floor(cols / 2);
let startY = floor(rows / 2);
worm.push({x: startX, y: startY});
// Reset direction
xSpeed = 1;
ySpeed = 0;
// Reset score
score = 0;
// Reset game state
gameOver = false;
// Create new food
createFood();
}
function keyPressed() {
// Restart game
if (keyCode === ENTER && gameOver) {
resetGame();
return;
}
// Don't change direction if game is over
if (gameOver) return;
// Right arrow
if (keyCode === RIGHT_ARROW && xSpeed !== -1) {
xSpeed = 1;
ySpeed = 0;
}
// Left arrow
else if (keyCode === LEFT_ARROW && xSpeed !== 1) {
xSpeed = -1;
ySpeed = 0;
}
// Down arrow
else if (keyCode === DOWN_ARROW && ySpeed !== -1) {
xSpeed = 0;
ySpeed = 1;
}
// Up arrow
else if (keyCode === UP_ARROW && ySpeed !== 1) {
xSpeed = 0;
ySpeed = -1;
}
}
Features Included
This complete code includes:
- ✅ Grid-based movement system
- ✅ Arrow key controls
- ✅ Food spawning at random locations
- ✅ Growth mechanics when eating food
- ✅ Score tracking
- ✅ Wall collision detection
- ✅ Self-collision detection
- ✅ Game over screen
- ✅ Restart functionality
- ✅ Food never spawns on worm
How to Use
- Go to https://editor.p5js.org/
- Delete the default code
- Copy and paste this complete code
- Click the ▶️ Play button
- Use arrow keys to play!
Game Controls
- Arrow Keys - Move the worm (up, down, left, right)
- Enter - Restart game after game over
Customization Ideas
Try modifying these values to change the game:
Difficulty
frameRate(10); // Try 5 (easier) or 15 (harder)
cellSize = 20; // Try 10 (faster) or 30 (slower)
Appearance
// In draw() - Change colors
fill(0, 255, 0); // Worm color (try 255, 255, 0 for yellow)
fill(255, 0, 0); // Food color (try 255, 165, 0 for orange)
background(50); // Background (try 30 for darker)
Canvas Size
createCanvas(400, 400); // Try 600, 600 for bigger arena
Enhancement Ideas
Want to add more features? Try these:
1. Different Food Values
// Add special food worth more points
let specialFood = {x: 10, y: 10, value: 5};
// Draw it in different color
fill(255, 255, 0); // Yellow for special food
2. Obstacles
let obstacles = [];
// Generate obstacles and check collision
3. Speed Increase
// In updateWorm() when eating food:
if (score % 5 === 0) {
frameRate(frameRate() + 1); // Speed up every 5 points
}
4. Sound Effects
// Add p5.sound library in index.html
let eatSound, gameOverSound;
function preload() {
eatSound = loadSound('eat.mp3');
gameOverSound = loadSound('gameover.mp3');
}
// Play sounds at appropriate times
eatSound.play();
5. High Score
let highScore = 0;
// In resetGame():
if (score > highScore) {
highScore = score;
}
// Display high score
text('High Score: ' + highScore, 10, 50);
6. Wrap Around Walls
// Instead of game over on wall hit:
if (newHead.x < 0) newHead.x = cols - 1;
if (newHead.x >= cols) newHead.x = 0;
if (newHead.y < 0) newHead.y = rows - 1;
if (newHead.y >= rows) newHead.y = 0;
7. Color Gradient Worm
// In draw() when drawing worm:
for (let i = 0; i < worm.length; i++) {
let greenValue = map(i, 0, worm.length, 100, 255);
fill(0, greenValue, 0);
// ... draw segment
}
8. Trail Effect
// Remove grid lines and make background semi-transparent
background(50, 25); // Creates trailing effect
Troubleshooting
Worm moves too fast:
- Decrease
frameRate()value insetup()
Game is too easy:
- Increase
frameRate()for faster gameplay - Make canvas bigger for more space to navigate
Food appears on worm:
- The
createFood()function should prevent this - Make sure you copied the complete
whileloop
Controls not working:
- Check that
keyPressed()function is present - Make sure you're using arrow keys, not WASD
Game won't restart:
- Verify
resetGame()function exists - Check that Enter key check uses
ENTERconstant
Congratulations! 🎉
You've built a complete Worm game from scratch! You've learned:
- Grid-based game systems
- Array manipulation for game logic
- Collision detection algorithms
- Game state management
- User input handling
- Game over and restart systems
Use this as a foundation to create your own unique games! 🐛🎮