Lesson 5 of 5 — Final Lesson! 🎉

🎮 Functions & Your First Game

Put it all together to build a complete, playable game!

🏁 The Finish Line

You've learned so much! Drawing, animation, conditionals, loops... Now let's combine everything to build a real game.

But first, one more powerful tool: functions.

📦 Functions: Reusable Code

A function is a named block of code you can use over and over. You've already used functions like circle()!

🔑 Creating Your Own Function

function drawStar(x, y, size) {
  // Code to draw a star at x, y with given size
}

// Use it:
drawStar(100, 100, 50);
drawStar(200, 150, 30);

🖱️ Mouse Input

p5.js gives you the mouse position automatically:

Mouse Position

  • mouseX — horizontal position
  • mouseY — vertical position

Mouse Click

function mousePressed() {
  // Runs when clicked
}

💥 Collision Detection

To know if two objects touch, we calculate the distance between them. p5.js has a dist() function!

🔑 Distance Formula

let d = dist(x1, y1, x2, y2);

// If distance is less than the sum of radii, they're touching!
if (d < radius1 + radius2) {
  // Collision!
}

🏆 Keeping Score

Use a variable to track the score and text() to display it.

🎮 Building: Catch Game

Let's build a complete game where you catch falling objects with a paddle!

Step 1: Falling Object

Step 2: Add Catching & Score

🎮 Your Complete Game!

Here's the full game with multiple falling objects, lives, and game over! Study this code — you wrote everything in it!

🚀 What's Next?

Congratulations! You've completed all 5 lessons and built a real game! Here are some ideas to keep learning:

  • 🎮 Modify the game: Add power-ups, different object types, or a high score
  • 🎨 Make art: Create generative art with what you learned
  • 📚 Learn more: Check out p5js.org/learn
  • 🏆 Challenges: Try The Coding Train on YouTube

🎓 Everything You Learned

Lesson 1: Drawing

  • ✅ Coordinates (x, y)
  • ✅ Shapes: circle, rect, line, triangle
  • ✅ Colors: fill, stroke, background

Lesson 2: Animation

  • ✅ Variables store values
  • ✅ draw() loop = animation
  • ✅ Changing variables over time

Lesson 3: Conditionals

  • ✅ if statements
  • ✅ Comparisons: <, >, ===
  • ✅ Bouncing off edges

Lesson 4: Loops

  • ✅ for loops repeat code
  • ✅ Nested loops = grids
  • ✅ random() for variety

Lesson 5: Functions & Games

  • ✅ Creating functions
  • ✅ Mouse input: mouseX, mouseY
  • ✅ Collision detection with dist()
  • ✅ Keeping score
  • ✅ Game states (playing, game over)
🏆

Congratulations!

You completed all 5 coding lessons!

You are now a JavaScript Game Developer