Skip to main content

Getting Started with Worm

What is This Tutorial?

Learn to build a classic Worm game (also known as Snake) using p5.js! You'll create a game where a worm moves around the screen, eats food to grow longer, and must avoid running into walls or itself.

What You'll Build

  • A moving worm controlled with arrow keys
  • Food that appears randomly
  • Growth mechanics when eating food
  • Collision detection for walls and self-collision
  • Score tracking
  • Game over system
info

This is a basic tutorial designed as a starting point. Use it to learn the fundamentals, then add your own features and customizations!

What You'll Learn

Through this tutorial, you'll master:

  • Grid-based movement - Moving objects in discrete steps
  • Arrays and data structures - Managing the worm's body segments
  • Keyboard input - Responding to arrow key presses
  • Collision detection - Checking for overlaps and boundaries
  • Game state management - Handling play, game over, and restart states
  • Random positioning - Placing food at valid locations

Prerequisites

Knowledge Requirements

  • Basic JavaScript (variables, functions, arrays, loops)
  • Familiarity with p5.js setup() and draw() functions
  • Understanding of conditionals (if statements)

Setup

  1. Open the p5.js Web Editor: https://editor.p5js.org/
  2. You'll see a default sketch ready to go
  3. Clear the existing code - we'll build from scratch!

Verify Your Setup

Test that p5.js is working:

function setup() {
createCanvas(400, 400);
}

function draw() {
background(220);
fill(0, 255, 0);
rect(200, 200, 20, 20);
}

If you see a small green square, you're ready to start! ✅

Tutorial Structure

This tutorial has 6 steps:

  1. Basic Setup - Create the grid and worm
  2. Movement - Make the worm move automatically
  3. Controls - Add keyboard input
  4. Food & Growth - Add food and growing mechanics
  5. Collision Detection - Add game over conditions
  6. Complete Code - Full working game

Let's begin! 🐛