Game making in JavaScript

Balloon Pop

Pop the balloons before they float away: your first game, drawn and animated on a canvas.

Day 1 45 to 60 minutes 7 steps Key Stage 3
Start step 1
balloon-pop/index.html

Balloons drift up from the bottom of the sky. Click one to pop it and score a point, but let five get away and the game is over. Along the way you will learn the idea at the heart of every video game: the game loop, which moves everything a little and draws it again, sixty times a second.

You will learn

  • Draw shapes on a canvas with JavaScript
  • Animate them with a game loop
  • Keep lots of things in an array of objects
  • Hit test a mouse click, and keep score

You will need

  • A computer with a web browser
  • The Web Studio, or Notepad
  • A mouse makes popping easier than a touchpad

Words to know

canvas
A box on a web page that JavaScript can draw on.
game loop
Code that clears the screen, moves everything and draws it again, many times a second.
object
Several values kept together, such as a balloon's x, y, speed and colour.
array
A list. balloons holds every balloon in the sky.

Step by step

  1. Step 1: A sky to play in

    Open the Web Studio and choose Day 1: Balloon Pop under Games. The page has a <canvas>: a box 480 pixels wide and 360 high that JavaScript can draw on. The CSS colours it sky blue.

    In script.js, getContext("2d") gives you ctx, the pen that draws on the canvas.

    index.htmlHTML
    <!DOCTYPE html><html>  <head>    <meta charset="utf-8">    <title>Balloon Pop</title>    <link rel="stylesheet" href="style.css">  </head>  <body>    <h1>Balloon Pop</h1>    <canvas id="game" width="480" height="360"></canvas>    <script src="script.js"></script>  </body></html>
    style.cssCSS
    body {  font-family: Arial, sans-serif;  text-align: center;  background: #1d2b53;  color: white;} canvas {  background: #8fd3ff;  border-radius: 12px;  max-width: 100%;  cursor: crosshair;}
    script.jsJavaScript
    // the canvas, and the pen that draws on itconst canvas = document.getElementById("game");const ctx = canvas.getContext("2d"); 
    balloon-pop/index.html
    An empty blue sky.
  2. Step 2: Draw a balloon

    A function draws a balloon anywhere you like. arc draws a circle: the middle's x and y, the radius, then where to start and end, all the way round from 0 to Math.PI * 2. On a canvas, x counts across from the left and y counts down from the top.

    New: lines 5 to 21.

    script.jsJavaScript
    // the canvas, and the pen that draws on itconst canvas = document.getElementById("game");const ctx = canvas.getContext("2d"); function drawBalloon(x, y, colour) {  // the string  ctx.strokeStyle = "white";  ctx.beginPath();  ctx.moveTo(x, y + 30);  ctx.lineTo(x, y + 70);  ctx.stroke();  // the balloon  ctx.fillStyle = colour;  ctx.beginPath();  ctx.arc(x, y, 30, 0, Math.PI * 2);  ctx.fill();} drawBalloon(240, 160, "red");drawBalloon(150, 200, "gold");drawBalloon(330, 220, "hotpink");
    balloon-pop/index.html
    Three balloons, each drawn by the same function.
  3. Step 3: Float away

    A balloon is now an object, with its x, its y, its speed and its colour together. loop clears the canvas, moves the balloon up a little, and draws it again. requestAnimationFrame(loop) asks the browser to run loop again for the next frame, about sixty times a second. When the balloon leaves the top, it starts again at the bottom, somewhere new.

    New: lines 19 to 32.

    script.jsJavaScript
    // the canvas, and the pen that draws on itconst canvas = document.getElementById("game");const ctx = canvas.getContext("2d"); function drawBalloon(x, y, colour) {  // the string  ctx.strokeStyle = "white";  ctx.beginPath();  ctx.moveTo(x, y + 30);  ctx.lineTo(x, y + 70);  ctx.stroke();  // the balloon  ctx.fillStyle = colour;  ctx.beginPath();  ctx.arc(x, y, 30, 0, Math.PI * 2);  ctx.fill();} let balloon = { x: 240, y: 420, speed: 2, colour: "red" }; function loop() {  ctx.clearRect(0, 0, canvas.width, canvas.height);  balloon.y = balloon.y - balloon.speed;  if (balloon.y < -80) {    balloon.y = 420;    balloon.x = Math.random() * 400 + 40;  }  drawBalloon(balloon.x, balloon.y, balloon.colour);  requestAnimationFrame(loop);} loop();
    balloon-pop/index.html
    One balloon floats up, again and again.
    Tip balloon.y - balloon.speed moves it up, because y counts down from the top.
  4. Step 4: A sky full of balloons

    Now keep many balloons in an array. newBalloon makes one with a random place, speed and colour. frames counts the frames, and every 50th frame, nearly a second, a new balloon is pushed into the array. Balloons that float off the top are marked gone, and filter keeps only the ones that are not.

    New: lines 4 to 7, 23 to 31, 35 to 37 and 39 to 50.

    script.jsJavaScript
    // the canvas, and the pen that draws on itconst canvas = document.getElementById("game");const ctx = canvas.getContext("2d"); const colours = ["red", "gold", "hotpink", "limegreen", "orange", "purple"];let balloons = [];let frames = 0; function drawBalloon(x, y, colour) {  // the string  ctx.strokeStyle = "white";  ctx.beginPath();  ctx.moveTo(x, y + 30);  ctx.lineTo(x, y + 70);  ctx.stroke();  // the balloon  ctx.fillStyle = colour;  ctx.beginPath();  ctx.arc(x, y, 30, 0, Math.PI * 2);  ctx.fill();} function newBalloon() {  return {    x: Math.random() * 400 + 40,    y: 420,    speed: Math.random() * 1.5 + 1,    colour: colours[Math.floor(Math.random() * colours.length)],    gone: false  };} function loop() {  ctx.clearRect(0, 0, canvas.width, canvas.height);  frames = frames + 1;  if (frames % 50 === 0) {    balloons.push(newBalloon());  }  for (const b of balloons) {    b.y = b.y - b.speed;    if (b.y < -80) {      b.gone = true;    }  }  balloons = balloons.filter(function (b) {    return !b.gone;  });  for (const b of balloons) {    drawBalloon(b.x, b.y, b.colour);  }  requestAnimationFrame(loop);} loop();
    balloon-pop/index.html
    Balloons of every colour, at every speed.
  5. Step 5: Pop!

    When the canvas is clicked, work out where, in the canvas's own pixels, then check every balloon. The distance from the click to the balloon's middle comes from Pythagoras: if it is less than the radius, 30, the click was inside, so the balloon is popped and the score goes up. write puts the score at the top.

    New: lines 8, 34 to 55 and 74.

    script.jsJavaScript
    // the canvas, and the pen that draws on itconst canvas = document.getElementById("game");const ctx = canvas.getContext("2d"); const colours = ["red", "gold", "hotpink", "limegreen", "orange", "purple"];let balloons = [];let frames = 0;let score = 0; function drawBalloon(x, y, colour) {  // the string  ctx.strokeStyle = "white";  ctx.beginPath();  ctx.moveTo(x, y + 30);  ctx.lineTo(x, y + 70);  ctx.stroke();  // the balloon  ctx.fillStyle = colour;  ctx.beginPath();  ctx.arc(x, y, 30, 0, Math.PI * 2);  ctx.fill();} function newBalloon() {  return {    x: Math.random() * 400 + 40,    y: 420,    speed: Math.random() * 1.5 + 1,    colour: colours[Math.floor(Math.random() * colours.length)],    gone: false  };} function write(text, x, y, size) {  ctx.fillStyle = "#1d2b53";  ctx.font = "bold " + size + "px Arial";  ctx.textAlign = "center";  ctx.fillText(text, x, y);} canvas.addEventListener("click", function (event) {  // where the click was, in the canvas's own pixels  const box = canvas.getBoundingClientRect();  const x = (event.clientX - box.left) * canvas.width / box.width;  const y = (event.clientY - box.top) * canvas.height / box.height;  for (const b of balloons) {    const dx = x - b.x;    const dy = y - b.y;    if (Math.sqrt(dx * dx + dy * dy) < 30) {      b.gone = true;      score = score + 1;    }  }}); function loop() {  ctx.clearRect(0, 0, canvas.width, canvas.height);  frames = frames + 1;  if (frames % 50 === 0) {    balloons.push(newBalloon());  }  for (const b of balloons) {    b.y = b.y - b.speed;    if (b.y < -80) {      b.gone = true;    }  }  balloons = balloons.filter(function (b) {    return !b.gone;  });  for (const b of balloons) {    drawBalloon(b.x, b.y, b.colour);  }  write("Score: " + score, 240, 34, 24);  requestAnimationFrame(loop);} loop();
    balloon-pop/index.html
    Click the balloons in the game above to pop them.
  6. Step 6: Don't let them get away

    Count the balloons that escape off the top. At five, the game stops: loop writes Game over and returns without asking for another frame, so nothing moves. A click then calls start, which resets everything and starts the loop again.

    New: lines 9, 10, 44 to 47, 62 to 70, 81, 90 to 96 and 100.

    script.jsJavaScript
    // the canvas, and the pen that draws on itconst canvas = document.getElementById("game");const ctx = canvas.getContext("2d"); const colours = ["red", "gold", "hotpink", "limegreen", "orange", "purple"];let balloons = [];let frames = 0;let score = 0;let escaped = 0;let playing = true; function drawBalloon(x, y, colour) {  // the string  ctx.strokeStyle = "white";  ctx.beginPath();  ctx.moveTo(x, y + 30);  ctx.lineTo(x, y + 70);  ctx.stroke();  // the balloon  ctx.fillStyle = colour;  ctx.beginPath();  ctx.arc(x, y, 30, 0, Math.PI * 2);  ctx.fill();} function newBalloon() {  return {    x: Math.random() * 400 + 40,    y: 420,    speed: Math.random() * 1.5 + 1,    colour: colours[Math.floor(Math.random() * colours.length)],    gone: false  };} function write(text, x, y, size) {  ctx.fillStyle = "#1d2b53";  ctx.font = "bold " + size + "px Arial";  ctx.textAlign = "center";  ctx.fillText(text, x, y);} canvas.addEventListener("click", function (event) {  if (!playing) {    start();    return;  }  // where the click was, in the canvas's own pixels  const box = canvas.getBoundingClientRect();  const x = (event.clientX - box.left) * canvas.width / box.width;  const y = (event.clientY - box.top) * canvas.height / box.height;  for (const b of balloons) {    const dx = x - b.x;    const dy = y - b.y;    if (Math.sqrt(dx * dx + dy * dy) < 30) {      b.gone = true;      score = score + 1;    }  }}); function start() {  balloons = [];  frames = 0;  score = 0;  escaped = 0;  playing = true;  loop();} function loop() {  ctx.clearRect(0, 0, canvas.width, canvas.height);  frames = frames + 1;  if (frames % 50 === 0) {    balloons.push(newBalloon());  }  for (const b of balloons) {    b.y = b.y - b.speed;    if (b.y < -80) {      b.gone = true;      escaped = escaped + 1;    }  }  balloons = balloons.filter(function (b) {    return !b.gone;  });  for (const b of balloons) {    drawBalloon(b.x, b.y, b.colour);  }  write("Score: " + score + "   Missed: " + escaped, 240, 34, 22);  if (escaped >= 5) {    playing = false;    write("Game over!", 240, 170, 44);    write("Click to play again", 240, 215, 22);    return;  }  requestAnimationFrame(loop);} start();
    balloon-pop/index.html
    Five balloons escape, and it is game over. Click to play again.
  7. Step 7: Start screen, and faster

    Begin with a start screen, so the game waits for the player. Then make it harder as you get better: the gap between balloons shrinks as the score goes up, down to 15 frames, and every balloon floats a little faster.

    New: lines 10, 30, 74 to 76 and 102 to 106.

    script.jsJavaScript
    // the canvas, and the pen that draws on itconst canvas = document.getElementById("game");const ctx = canvas.getContext("2d"); const colours = ["red", "gold", "hotpink", "limegreen", "orange", "purple"];let balloons = [];let frames = 0;let score = 0;let escaped = 0;let playing = false; function drawBalloon(x, y, colour) {  // the string  ctx.strokeStyle = "white";  ctx.beginPath();  ctx.moveTo(x, y + 30);  ctx.lineTo(x, y + 70);  ctx.stroke();  // the balloon  ctx.fillStyle = colour;  ctx.beginPath();  ctx.arc(x, y, 30, 0, Math.PI * 2);  ctx.fill();} function newBalloon() {  return {    x: Math.random() * 400 + 40,    y: 420,    speed: Math.random() * 1.5 + 1 + score / 20,    colour: colours[Math.floor(Math.random() * colours.length)],    gone: false  };} function write(text, x, y, size) {  ctx.fillStyle = "#1d2b53";  ctx.font = "bold " + size + "px Arial";  ctx.textAlign = "center";  ctx.fillText(text, x, y);} canvas.addEventListener("click", function (event) {  if (!playing) {    start();    return;  }  // where the click was, in the canvas's own pixels  const box = canvas.getBoundingClientRect();  const x = (event.clientX - box.left) * canvas.width / box.width;  const y = (event.clientY - box.top) * canvas.height / box.height;  for (const b of balloons) {    const dx = x - b.x;    const dy = y - b.y;    if (Math.sqrt(dx * dx + dy * dy) < 30) {      b.gone = true;      score = score + 1;    }  }}); function start() {  balloons = [];  frames = 0;  score = 0;  escaped = 0;  playing = true;  loop();} function loop() {  ctx.clearRect(0, 0, canvas.width, canvas.height);  frames = frames + 1;  // balloons come faster as the score goes up  const gap = Math.max(15, 50 - score);  if (frames % gap === 0) {    balloons.push(newBalloon());  }  for (const b of balloons) {    b.y = b.y - b.speed;    if (b.y < -80) {      b.gone = true;      escaped = escaped + 1;    }  }  balloons = balloons.filter(function (b) {    return !b.gone;  });  for (const b of balloons) {    drawBalloon(b.x, b.y, b.colour);  }  write("Score: " + score + "   Missed: " + escaped, 240, 34, 22);  if (escaped >= 5) {    playing = false;    write("Game over!", 240, 170, 44);    write("Click to play again", 240, 215, 22);    return;  }  requestAnimationFrame(loop);} // the start screendrawBalloon(140, 230, "gold");drawBalloon(340, 210, "hotpink");write("Balloon Pop", 240, 150, 44);write("Click to start", 240, 195, 22);
    balloon-pop/index.html
    The finished Balloon Pop. Click to start!

Test it

Tick each one when it works. If one does not, look back at the step it comes from.

Stretch challenges

Finished early? Try these. Each one has a hint if you get stuck.

  1. Golden balloons

    Make one balloon in ten gold, worth five points.

    Show a hint

    In newBalloon, use Math.random() < 0.1 to decide whether it is golden. Give the object points: 5 or points: 1, and add b.points to the score when it is popped.

  2. Pop sound

    Make a pop sound with the browser's own sound maker.

    Show a hint

    Make one const sound = new AudioContext(); at the top. To pop, make an oscillator with sound.createOscillator(), connect it to sound.destination, start it, and stop it 0.05 seconds later.

  3. Bombs

    Add black balloons that end the game if you pop one.

    Show a hint

    Give each balloon a bomb property that is true one time in eight. In the click handler, if the balloon is a bomb, set escaped to 5.

The finished code

Show the whole game
index.htmlHTML
<!DOCTYPE html><html>  <head>    <meta charset="utf-8">    <title>Balloon Pop</title>    <link rel="stylesheet" href="style.css">  </head>  <body>    <h1>Balloon Pop</h1>    <canvas id="game" width="480" height="360"></canvas>    <script src="script.js"></script>  </body></html>
style.cssCSS
body {  font-family: Arial, sans-serif;  text-align: center;  background: #1d2b53;  color: white;} canvas {  background: #8fd3ff;  border-radius: 12px;  max-width: 100%;  cursor: crosshair;}
script.jsJavaScript
// the canvas, and the pen that draws on itconst canvas = document.getElementById("game");const ctx = canvas.getContext("2d"); const colours = ["red", "gold", "hotpink", "limegreen", "orange", "purple"];let balloons = [];let frames = 0;let score = 0;let escaped = 0;let playing = false; function drawBalloon(x, y, colour) {  // the string  ctx.strokeStyle = "white";  ctx.beginPath();  ctx.moveTo(x, y + 30);  ctx.lineTo(x, y + 70);  ctx.stroke();  // the balloon  ctx.fillStyle = colour;  ctx.beginPath();  ctx.arc(x, y, 30, 0, Math.PI * 2);  ctx.fill();} function newBalloon() {  return {    x: Math.random() * 400 + 40,    y: 420,    speed: Math.random() * 1.5 + 1 + score / 20,    colour: colours[Math.floor(Math.random() * colours.length)],    gone: false  };} function write(text, x, y, size) {  ctx.fillStyle = "#1d2b53";  ctx.font = "bold " + size + "px Arial";  ctx.textAlign = "center";  ctx.fillText(text, x, y);} canvas.addEventListener("click", function (event) {  if (!playing) {    start();    return;  }  // where the click was, in the canvas's own pixels  const box = canvas.getBoundingClientRect();  const x = (event.clientX - box.left) * canvas.width / box.width;  const y = (event.clientY - box.top) * canvas.height / box.height;  for (const b of balloons) {    const dx = x - b.x;    const dy = y - b.y;    if (Math.sqrt(dx * dx + dy * dy) < 30) {      b.gone = true;      score = score + 1;    }  }}); function start() {  balloons = [];  frames = 0;  score = 0;  escaped = 0;  playing = true;  loop();} function loop() {  ctx.clearRect(0, 0, canvas.width, canvas.height);  frames = frames + 1;  // balloons come faster as the score goes up  const gap = Math.max(15, 50 - score);  if (frames % gap === 0) {    balloons.push(newBalloon());  }  for (const b of balloons) {    b.y = b.y - b.speed;    if (b.y < -80) {      b.gone = true;      escaped = escaped + 1;    }  }  balloons = balloons.filter(function (b) {    return !b.gone;  });  for (const b of balloons) {    drawBalloon(b.x, b.y, b.colour);  }  write("Score: " + score + "   Missed: " + escaped, 240, 34, 22);  if (escaped >= 5) {    playing = false;    write("Game over!", 240, 170, 44);    write("Click to play again", 240, 215, 22);    return;  }  requestAnimationFrame(loop);} // the start screendrawBalloon(140, 230, "gold");drawBalloon(340, 210, "hotpink");write("Balloon Pop", 240, 150, 44);write("Click to start", 240, 195, 22);
Notes for the teacher

Timing

  1. 10 minutes: steps 1 and 2. Draw the canvas's coordinates on the board: x across, y down, which surprises everyone.
  2. 20 minutes: steps 3 and 4. The game loop is the big idea of the whole track: clear, move, draw, repeat.
  3. 20 minutes: steps 5 to 7, then high score battles.

Mistakes to look out for

  1. getcontext or GetContext: JavaScript is case sensitive, so nothing draws. Press F12 in the browser and look at the Console for the error.
  2. A missing } at the end of loop: everything after it stops working.
  3. Forgetting ctx.beginPath(): every balloon joins up with the last one.
  4. A balloon that goes down, not up: + instead of - when moving.

Going further

The distance check is Pythagoras' theorem, which most students meet in Year 8 or 9 maths. It is worth pointing out: games are full of maths.