Game making in JavaScript
Balloon Pop
Pop the balloons before they float away: your first game, drawn and animated on a canvas.
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.
balloonsholds every balloon in the sky.
Step by step
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 youctx, the pen that draws on the canvas.1<!DOCTYPE html>2<html>3 <head>4 <meta charset="utf-8">5 <title>Balloon Pop</title>6 <link rel="stylesheet" href="style.css">7 </head>8 <body>9 <h1>Balloon Pop</h1>10 <canvas id="game" width="480" height="360"></canvas>11 <script src="script.js"></script>12 </body>13</html>1body {2 font-family: Arial, sans-serif;3 text-align: center;4 background: #1d2b53;5 color: white;6}7 8canvas {9 background: #8fd3ff;10 border-radius: 12px;11 max-width: 100%;12 cursor: crosshair;13}1// the canvas, and the pen that draws on it2const canvas = document.getElementById("game");3const ctx = canvas.getContext("2d");4An empty blue sky. Step 2: Draw a balloon
A function draws a balloon anywhere you like.
arcdraws a circle: the middle's x and y, the radius, then where to start and end, all the way round from 0 toMath.PI * 2. On a canvas, x counts across from the left and y counts down from the top.New: lines 5 to 21.
1// the canvas, and the pen that draws on it2const canvas = document.getElementById("game");3const ctx = canvas.getContext("2d");4 5function drawBalloon(x, y, colour) {6 // the string7 ctx.strokeStyle = "white";8 ctx.beginPath();9 ctx.moveTo(x, y + 30);10 ctx.lineTo(x, y + 70);11 ctx.stroke();12 // the balloon13 ctx.fillStyle = colour;14 ctx.beginPath();15 ctx.arc(x, y, 30, 0, Math.PI * 2);16 ctx.fill();17}18 19drawBalloon(240, 160, "red");20drawBalloon(150, 200, "gold");21drawBalloon(330, 220, "hotpink");Three balloons, each drawn by the same function. Step 3: Float away
A balloon is now an object, with its x, its y, its speed and its colour together.
loopclears the canvas, moves the balloon up a little, and draws it again.requestAnimationFrame(loop)asks the browser to runloopagain 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.
1// the canvas, and the pen that draws on it2const canvas = document.getElementById("game");3const ctx = canvas.getContext("2d");4 5function drawBalloon(x, y, colour) {6 // the string7 ctx.strokeStyle = "white";8 ctx.beginPath();9 ctx.moveTo(x, y + 30);10 ctx.lineTo(x, y + 70);11 ctx.stroke();12 // the balloon13 ctx.fillStyle = colour;14 ctx.beginPath();15 ctx.arc(x, y, 30, 0, Math.PI * 2);16 ctx.fill();17}18 19let balloon = { x: 240, y: 420, speed: 2, colour: "red" };20 21function loop() {22 ctx.clearRect(0, 0, canvas.width, canvas.height);23 balloon.y = balloon.y - balloon.speed;24 if (balloon.y < -80) {25 balloon.y = 420;26 balloon.x = Math.random() * 400 + 40;27 }28 drawBalloon(balloon.x, balloon.y, balloon.colour);29 requestAnimationFrame(loop);30}31 32loop();One balloon floats up, again and again. Tipballoon.y - balloon.speedmoves it up, because y counts down from the top.Step 4: A sky full of balloons
Now keep many balloons in an array.
newBalloonmakes one with a random place, speed and colour.framescounts the frames, and every 50th frame, nearly a second, a new balloon is pushed into the array. Balloons that float off the top are markedgone, andfilterkeeps only the ones that are not.New: lines 4 to 7, 23 to 31, 35 to 37 and 39 to 50.
1// the canvas, and the pen that draws on it2const canvas = document.getElementById("game");3const ctx = canvas.getContext("2d");4 5const colours = ["red", "gold", "hotpink", "limegreen", "orange", "purple"];6let balloons = [];7let frames = 0;8 9function drawBalloon(x, y, colour) {10 // the string11 ctx.strokeStyle = "white";12 ctx.beginPath();13 ctx.moveTo(x, y + 30);14 ctx.lineTo(x, y + 70);15 ctx.stroke();16 // the balloon17 ctx.fillStyle = colour;18 ctx.beginPath();19 ctx.arc(x, y, 30, 0, Math.PI * 2);20 ctx.fill();21}22 23function newBalloon() {24 return {25 x: Math.random() * 400 + 40,26 y: 420,27 speed: Math.random() * 1.5 + 1,28 colour: colours[Math.floor(Math.random() * colours.length)],29 gone: false30 };31}32 33function loop() {34 ctx.clearRect(0, 0, canvas.width, canvas.height);35 frames = frames + 1;36 if (frames % 50 === 0) {37 balloons.push(newBalloon());38 }39 for (const b of balloons) {40 b.y = b.y - b.speed;41 if (b.y < -80) {42 b.gone = true;43 }44 }45 balloons = balloons.filter(function (b) {46 return !b.gone;47 });48 for (const b of balloons) {49 drawBalloon(b.x, b.y, b.colour);50 }51 requestAnimationFrame(loop);52}53 54loop();Balloons of every colour, at every speed. 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.
writeputs the score at the top.New: lines 8, 34 to 55 and 74.
1// the canvas, and the pen that draws on it2const canvas = document.getElementById("game");3const ctx = canvas.getContext("2d");4 5const colours = ["red", "gold", "hotpink", "limegreen", "orange", "purple"];6let balloons = [];7let frames = 0;8let score = 0;9 10function drawBalloon(x, y, colour) {11 // the string12 ctx.strokeStyle = "white";13 ctx.beginPath();14 ctx.moveTo(x, y + 30);15 ctx.lineTo(x, y + 70);16 ctx.stroke();17 // the balloon18 ctx.fillStyle = colour;19 ctx.beginPath();20 ctx.arc(x, y, 30, 0, Math.PI * 2);21 ctx.fill();22}23 24function newBalloon() {25 return {26 x: Math.random() * 400 + 40,27 y: 420,28 speed: Math.random() * 1.5 + 1,29 colour: colours[Math.floor(Math.random() * colours.length)],30 gone: false31 };32}33 34function write(text, x, y, size) {35 ctx.fillStyle = "#1d2b53";36 ctx.font = "bold " + size + "px Arial";37 ctx.textAlign = "center";38 ctx.fillText(text, x, y);39}40 41canvas.addEventListener("click", function (event) {42 // where the click was, in the canvas's own pixels43 const box = canvas.getBoundingClientRect();44 const x = (event.clientX - box.left) * canvas.width / box.width;45 const y = (event.clientY - box.top) * canvas.height / box.height;46 for (const b of balloons) {47 const dx = x - b.x;48 const dy = y - b.y;49 if (Math.sqrt(dx * dx + dy * dy) < 30) {50 b.gone = true;51 score = score + 1;52 }53 }54});55 56function loop() {57 ctx.clearRect(0, 0, canvas.width, canvas.height);58 frames = frames + 1;59 if (frames % 50 === 0) {60 balloons.push(newBalloon());61 }62 for (const b of balloons) {63 b.y = b.y - b.speed;64 if (b.y < -80) {65 b.gone = true;66 }67 }68 balloons = balloons.filter(function (b) {69 return !b.gone;70 });71 for (const b of balloons) {72 drawBalloon(b.x, b.y, b.colour);73 }74 write("Score: " + score, 240, 34, 24);75 requestAnimationFrame(loop);76}77 78loop();Click the balloons in the game above to pop them. Step 6: Don't let them get away
Count the balloons that escape off the top. At five, the game stops:
loopwrites Game over and returns without asking for another frame, so nothing moves. A click then callsstart, which resets everything and starts the loop again.New: lines 9, 10, 44 to 47, 62 to 70, 81, 90 to 96 and 100.
1// the canvas, and the pen that draws on it2const canvas = document.getElementById("game");3const ctx = canvas.getContext("2d");4 5const colours = ["red", "gold", "hotpink", "limegreen", "orange", "purple"];6let balloons = [];7let frames = 0;8let score = 0;9let escaped = 0;10let playing = true;11 12function drawBalloon(x, y, colour) {13 // the string14 ctx.strokeStyle = "white";15 ctx.beginPath();16 ctx.moveTo(x, y + 30);17 ctx.lineTo(x, y + 70);18 ctx.stroke();19 // the balloon20 ctx.fillStyle = colour;21 ctx.beginPath();22 ctx.arc(x, y, 30, 0, Math.PI * 2);23 ctx.fill();24}25 26function newBalloon() {27 return {28 x: Math.random() * 400 + 40,29 y: 420,30 speed: Math.random() * 1.5 + 1,31 colour: colours[Math.floor(Math.random() * colours.length)],32 gone: false33 };34}35 36function write(text, x, y, size) {37 ctx.fillStyle = "#1d2b53";38 ctx.font = "bold " + size + "px Arial";39 ctx.textAlign = "center";40 ctx.fillText(text, x, y);41}42 43canvas.addEventListener("click", function (event) {44 if (!playing) {45 start();46 return;47 }48 // where the click was, in the canvas's own pixels49 const box = canvas.getBoundingClientRect();50 const x = (event.clientX - box.left) * canvas.width / box.width;51 const y = (event.clientY - box.top) * canvas.height / box.height;52 for (const b of balloons) {53 const dx = x - b.x;54 const dy = y - b.y;55 if (Math.sqrt(dx * dx + dy * dy) < 30) {56 b.gone = true;57 score = score + 1;58 }59 }60});61 62function start() {63 balloons = [];64 frames = 0;65 score = 0;66 escaped = 0;67 playing = true;68 loop();69}70 71function loop() {72 ctx.clearRect(0, 0, canvas.width, canvas.height);73 frames = frames + 1;74 if (frames % 50 === 0) {75 balloons.push(newBalloon());76 }77 for (const b of balloons) {78 b.y = b.y - b.speed;79 if (b.y < -80) {80 b.gone = true;81 escaped = escaped + 1;82 }83 }84 balloons = balloons.filter(function (b) {85 return !b.gone;86 });87 for (const b of balloons) {88 drawBalloon(b.x, b.y, b.colour);89 }90 write("Score: " + score + " Missed: " + escaped, 240, 34, 22);91 if (escaped >= 5) {92 playing = false;93 write("Game over!", 240, 170, 44);94 write("Click to play again", 240, 215, 22);95 return;96 }97 requestAnimationFrame(loop);98}99 100start();Five balloons escape, and it is game over. Click to play again. 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.
1// the canvas, and the pen that draws on it2const canvas = document.getElementById("game");3const ctx = canvas.getContext("2d");4 5const colours = ["red", "gold", "hotpink", "limegreen", "orange", "purple"];6let balloons = [];7let frames = 0;8let score = 0;9let escaped = 0;10let playing = false;11 12function drawBalloon(x, y, colour) {13 // the string14 ctx.strokeStyle = "white";15 ctx.beginPath();16 ctx.moveTo(x, y + 30);17 ctx.lineTo(x, y + 70);18 ctx.stroke();19 // the balloon20 ctx.fillStyle = colour;21 ctx.beginPath();22 ctx.arc(x, y, 30, 0, Math.PI * 2);23 ctx.fill();24}25 26function newBalloon() {27 return {28 x: Math.random() * 400 + 40,29 y: 420,30 speed: Math.random() * 1.5 + 1 + score / 20,31 colour: colours[Math.floor(Math.random() * colours.length)],32 gone: false33 };34}35 36function write(text, x, y, size) {37 ctx.fillStyle = "#1d2b53";38 ctx.font = "bold " + size + "px Arial";39 ctx.textAlign = "center";40 ctx.fillText(text, x, y);41}42 43canvas.addEventListener("click", function (event) {44 if (!playing) {45 start();46 return;47 }48 // where the click was, in the canvas's own pixels49 const box = canvas.getBoundingClientRect();50 const x = (event.clientX - box.left) * canvas.width / box.width;51 const y = (event.clientY - box.top) * canvas.height / box.height;52 for (const b of balloons) {53 const dx = x - b.x;54 const dy = y - b.y;55 if (Math.sqrt(dx * dx + dy * dy) < 30) {56 b.gone = true;57 score = score + 1;58 }59 }60});61 62function start() {63 balloons = [];64 frames = 0;65 score = 0;66 escaped = 0;67 playing = true;68 loop();69}70 71function loop() {72 ctx.clearRect(0, 0, canvas.width, canvas.height);73 frames = frames + 1;74 // balloons come faster as the score goes up75 const gap = Math.max(15, 50 - score);76 if (frames % gap === 0) {77 balloons.push(newBalloon());78 }79 for (const b of balloons) {80 b.y = b.y - b.speed;81 if (b.y < -80) {82 b.gone = true;83 escaped = escaped + 1;84 }85 }86 balloons = balloons.filter(function (b) {87 return !b.gone;88 });89 for (const b of balloons) {90 drawBalloon(b.x, b.y, b.colour);91 }92 write("Score: " + score + " Missed: " + escaped, 240, 34, 22);93 if (escaped >= 5) {94 playing = false;95 write("Game over!", 240, 170, 44);96 write("Click to play again", 240, 215, 22);97 return;98 }99 requestAnimationFrame(loop);100}101 102// the start screen103drawBalloon(140, 230, "gold");104drawBalloon(340, 210, "hotpink");105write("Balloon Pop", 240, 150, 44);106write("Click to start", 240, 195, 22);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.
Golden balloons
Make one balloon in ten gold, worth five points.
Show a hint
In
newBalloon, useMath.random() < 0.1to decide whether it is golden. Give the objectpoints: 5orpoints: 1, and addb.pointsto the score when it is popped.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 withsound.createOscillator(), connect it tosound.destination, start it, and stop it 0.05 seconds later.Bombs
Add black balloons that end the game if you pop one.
Show a hint
Give each balloon a
bombproperty that is true one time in eight. In the click handler, if the balloon is a bomb, setescapedto 5.
The finished code
Show the whole game
1<!DOCTYPE html>2<html>3 <head>4 <meta charset="utf-8">5 <title>Balloon Pop</title>6 <link rel="stylesheet" href="style.css">7 </head>8 <body>9 <h1>Balloon Pop</h1>10 <canvas id="game" width="480" height="360"></canvas>11 <script src="script.js"></script>12 </body>13</html>1body {2 font-family: Arial, sans-serif;3 text-align: center;4 background: #1d2b53;5 color: white;6}7 8canvas {9 background: #8fd3ff;10 border-radius: 12px;11 max-width: 100%;12 cursor: crosshair;13}1// the canvas, and the pen that draws on it2const canvas = document.getElementById("game");3const ctx = canvas.getContext("2d");4 5const colours = ["red", "gold", "hotpink", "limegreen", "orange", "purple"];6let balloons = [];7let frames = 0;8let score = 0;9let escaped = 0;10let playing = false;11 12function drawBalloon(x, y, colour) {13 // the string14 ctx.strokeStyle = "white";15 ctx.beginPath();16 ctx.moveTo(x, y + 30);17 ctx.lineTo(x, y + 70);18 ctx.stroke();19 // the balloon20 ctx.fillStyle = colour;21 ctx.beginPath();22 ctx.arc(x, y, 30, 0, Math.PI * 2);23 ctx.fill();24}25 26function newBalloon() {27 return {28 x: Math.random() * 400 + 40,29 y: 420,30 speed: Math.random() * 1.5 + 1 + score / 20,31 colour: colours[Math.floor(Math.random() * colours.length)],32 gone: false33 };34}35 36function write(text, x, y, size) {37 ctx.fillStyle = "#1d2b53";38 ctx.font = "bold " + size + "px Arial";39 ctx.textAlign = "center";40 ctx.fillText(text, x, y);41}42 43canvas.addEventListener("click", function (event) {44 if (!playing) {45 start();46 return;47 }48 // where the click was, in the canvas's own pixels49 const box = canvas.getBoundingClientRect();50 const x = (event.clientX - box.left) * canvas.width / box.width;51 const y = (event.clientY - box.top) * canvas.height / box.height;52 for (const b of balloons) {53 const dx = x - b.x;54 const dy = y - b.y;55 if (Math.sqrt(dx * dx + dy * dy) < 30) {56 b.gone = true;57 score = score + 1;58 }59 }60});61 62function start() {63 balloons = [];64 frames = 0;65 score = 0;66 escaped = 0;67 playing = true;68 loop();69}70 71function loop() {72 ctx.clearRect(0, 0, canvas.width, canvas.height);73 frames = frames + 1;74 // balloons come faster as the score goes up75 const gap = Math.max(15, 50 - score);76 if (frames % gap === 0) {77 balloons.push(newBalloon());78 }79 for (const b of balloons) {80 b.y = b.y - b.speed;81 if (b.y < -80) {82 b.gone = true;83 escaped = escaped + 1;84 }85 }86 balloons = balloons.filter(function (b) {87 return !b.gone;88 });89 for (const b of balloons) {90 drawBalloon(b.x, b.y, b.colour);91 }92 write("Score: " + score + " Missed: " + escaped, 240, 34, 22);93 if (escaped >= 5) {94 playing = false;95 write("Game over!", 240, 170, 44);96 write("Click to play again", 240, 215, 22);97 return;98 }99 requestAnimationFrame(loop);100}101 102// the start screen103drawBalloon(140, 230, "gold");104drawBalloon(340, 210, "hotpink");105write("Balloon Pop", 240, 150, 44);106write("Click to start", 240, 195, 22);Notes for the teacher
Timing
- 10 minutes: steps 1 and 2. Draw the canvas's coordinates on the board: x across, y down, which surprises everyone.
- 20 minutes: steps 3 and 4. The game loop is the big idea of the whole track: clear, move, draw, repeat.
- 20 minutes: steps 5 to 7, then high score battles.
Mistakes to look out for
getcontextorGetContext: JavaScript is case sensitive, so nothing draws. Press F12 in the browser and look at the Console for the error.- A missing
}at the end ofloop: everything after it stops working. - Forgetting
ctx.beginPath(): every balloon joins up with the last one. - 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.