Game making in JavaScript
Paddle Rally
Keep a bouncing ball in play with a paddle. Hit it near the ends to send it flying off at an angle.
A ball races round a court, and your paddle is all that stops it escaping. Every hit scores a point and makes the ball a little faster. Where it hits the paddle matters: the middle sends it straight up, the ends send it off at an angle. Today's new idea is velocity: a ball's speed across and its speed down.
You will learn
- Move a ball with a speed across and a speed down
- Bounce off walls by changing direction
- Control a paddle with the mouse and the keyboard
- Change the angle of a bounce with a little maths
You will need
- A computer with a web browser and a mouse
- The Web Studio, or Notepad
- Days 1 and 2, for the game loop and the keyboard
Words to know
- velocity
- Speed in a direction: here a speed across,
dx, and a speed down,dy. - bounce
- Turning a speed round when something hits a wall.
- Math.abs
- Makes a number positive:
Math.abs(-3)is 3. - Math.min and Math.max
- Pick the smaller or the larger of two numbers, which keeps values in a range.
Step by step
Step 1: The court
Choose Day 3: Paddle Rally.
drawCourtdraws white lines withstrokeRect, a rectangle that is outlined instead of filled, and a line across the middle.rgbais a colour you can partly see through: here, white at 60%.1<!DOCTYPE html>2<html>3 <head>4 <meta charset="utf-8">5 <title>Paddle Rally</title>6 <link rel="stylesheet" href="style.css">7 </head>8 <body>9 <h1>Paddle Rally</h1>10 <canvas id="game" width="480" height="360"></canvas>11 <p>Move the mouse, or click the game and use the arrow keys.</p>12 <script src="script.js"></script>13 </body>14</html>1body {2 font-family: Arial, sans-serif;3 text-align: center;4 background: #073b2a;5 color: white;6}7 8canvas {9 background: #0b6e4f;10 border-radius: 10px;11 max-width: 100%;12}1const canvas = document.getElementById("game");2const ctx = canvas.getContext("2d");3 4function drawCourt() {5 ctx.strokeStyle = "rgba(255, 255, 255, 0.6)";6 ctx.lineWidth = 3;7 ctx.strokeRect(6, 6, canvas.width - 12, canvas.height - 12);8 ctx.beginPath();9 ctx.moveTo(6, canvas.height / 2);10 ctx.lineTo(canvas.width - 6, canvas.height / 2);11 ctx.stroke();12}13 14drawCourt();A green court with white lines. Step 2: A bouncing ball
The ball has a speed across,
dx, and a speed down,dy. Each frame it moves by both. When it reaches a wall, the speed towards that wall turns round:Math.absmakes a number positive, sodxbecomes positive, moving right, off the left wall, and negative off the right wall.New: lines 3 and 15 to 44.
1const canvas = document.getElementById("game");2const ctx = canvas.getContext("2d");3const ball = { x: 240, y: 120, dx: 3, dy: 3, r: 9 };4 5function drawCourt() {6 ctx.strokeStyle = "rgba(255, 255, 255, 0.6)";7 ctx.lineWidth = 3;8 ctx.strokeRect(6, 6, canvas.width - 12, canvas.height - 12);9 ctx.beginPath();10 ctx.moveTo(6, canvas.height / 2);11 ctx.lineTo(canvas.width - 6, canvas.height / 2);12 ctx.stroke();13}14 15function drawBall() {16 ctx.fillStyle = "yellow";17 ctx.beginPath();18 ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2);19 ctx.fill();20}21 22function loop() {23 ctx.clearRect(0, 0, canvas.width, canvas.height);24 drawCourt();25 ball.x = ball.x + ball.dx;26 ball.y = ball.y + ball.dy;27 // bounce off the walls28 if (ball.x < ball.r) {29 ball.dx = Math.abs(ball.dx);30 }31 if (ball.x > canvas.width - ball.r) {32 ball.dx = -Math.abs(ball.dx);33 }34 if (ball.y < ball.r) {35 ball.dy = Math.abs(ball.dy);36 }37 if (ball.y > canvas.height - ball.r) {38 ball.dy = -Math.abs(ball.dy);39 }40 drawBall();41 requestAnimationFrame(loop);42}43 44loop();The ball bounces round all four walls. Step 3: A paddle
The paddle follows the mouse across the canvas.
mousemovehappens every time the mouse moves, and the paddle's middle goes to the mouse's x.New: lines 4, 22 to 32 and 53.
1const canvas = document.getElementById("game");2const ctx = canvas.getContext("2d");3const ball = { x: 240, y: 120, dx: 3, dy: 3, r: 9 };4const paddle = { x: 195, y: 330, w: 90, h: 12 };5 6function drawCourt() {7 ctx.strokeStyle = "rgba(255, 255, 255, 0.6)";8 ctx.lineWidth = 3;9 ctx.strokeRect(6, 6, canvas.width - 12, canvas.height - 12);10 ctx.beginPath();11 ctx.moveTo(6, canvas.height / 2);12 ctx.lineTo(canvas.width - 6, canvas.height / 2);13 ctx.stroke();14}15 16function drawBall() {17 ctx.fillStyle = "yellow";18 ctx.beginPath();19 ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2);20 ctx.fill();21}22 23function drawPaddle() {24 ctx.fillStyle = "white";25 ctx.fillRect(paddle.x, paddle.y, paddle.w, paddle.h);26}27 28canvas.addEventListener("mousemove", function (event) {29 const box = canvas.getBoundingClientRect();30 const x = (event.clientX - box.left) * canvas.width / box.width;31 paddle.x = x - paddle.w / 2;32});33 34function loop() {35 ctx.clearRect(0, 0, canvas.width, canvas.height);36 drawCourt();37 ball.x = ball.x + ball.dx;38 ball.y = ball.y + ball.dy;39 // bounce off the walls40 if (ball.x < ball.r) {41 ball.dx = Math.abs(ball.dx);42 }43 if (ball.x > canvas.width - ball.r) {44 ball.dx = -Math.abs(ball.dx);45 }46 if (ball.y < ball.r) {47 ball.dy = Math.abs(ball.dy);48 }49 if (ball.y > canvas.height - ball.r) {50 ball.dy = -Math.abs(ball.dy);51 }52 drawBall();53 drawPaddle();54 requestAnimationFrame(loop);55}56 57loop();Move the mouse over the game: the paddle follows. Step 4: Bounce off the paddle
Remove the bounce off the bottom wall: that is where the paddle has to save the ball now. The ball bounces off the paddle if it is moving down and touching the paddle's top, between its two ends. If it falls off the bottom, it starts again at the top, heading a random way.
New: lines 34 to 40, 56 to 58 and 60 to 63.
1const canvas = document.getElementById("game");2const ctx = canvas.getContext("2d");3const ball = { x: 240, y: 120, dx: 3, dy: 3, r: 9 };4const paddle = { x: 195, y: 330, w: 90, h: 12 };5 6function drawCourt() {7 ctx.strokeStyle = "rgba(255, 255, 255, 0.6)";8 ctx.lineWidth = 3;9 ctx.strokeRect(6, 6, canvas.width - 12, canvas.height - 12);10 ctx.beginPath();11 ctx.moveTo(6, canvas.height / 2);12 ctx.lineTo(canvas.width - 6, canvas.height / 2);13 ctx.stroke();14}15 16function drawBall() {17 ctx.fillStyle = "yellow";18 ctx.beginPath();19 ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2);20 ctx.fill();21}22 23function drawPaddle() {24 ctx.fillStyle = "white";25 ctx.fillRect(paddle.x, paddle.y, paddle.w, paddle.h);26}27 28canvas.addEventListener("mousemove", function (event) {29 const box = canvas.getBoundingClientRect();30 const x = (event.clientX - box.left) * canvas.width / box.width;31 paddle.x = x - paddle.w / 2;32});33 34function resetBall() {35 ball.x = 240;36 ball.y = 120;37 ball.dx = Math.random() * 6 - 3;38 ball.dy = 3;39}40 41function loop() {42 ctx.clearRect(0, 0, canvas.width, canvas.height);43 drawCourt();44 ball.x = ball.x + ball.dx;45 ball.y = ball.y + ball.dy;46 // bounce off the walls47 if (ball.x < ball.r) {48 ball.dx = Math.abs(ball.dx);49 }50 if (ball.x > canvas.width - ball.r) {51 ball.dx = -Math.abs(ball.dx);52 }53 if (ball.y < ball.r) {54 ball.dy = Math.abs(ball.dy);55 }56 // bounce off the paddle57 if (ball.dy > 0 && ball.y + ball.r >= paddle.y && ball.y < paddle.y + paddle.h &&58 ball.x > paddle.x && ball.x < paddle.x + paddle.w) {59 ball.dy = -Math.abs(ball.dy);60 }61 // missed it62 if (ball.y > canvas.height + 20) {63 resetBall();64 }65 drawBall();66 drawPaddle();67 requestAnimationFrame(loop);68}69 70loop();Save the ball with the paddle, or it starts again. Step 5: Score, speed and angles
Each save scores a point and makes the ball 5% faster, up to a speed of 12. Then a little maths:
hitis how far from the middle of the paddle the ball landed, from minus 1 at the left end to 1 at the right end. Multiplying by 6 makes that the new speed across, so the ends send the ball off sideways.write, as in Meteor Dodge, shows the score in white.New: lines 5, 42 to 48, 67 to 72 and 80.
1const canvas = document.getElementById("game");2const ctx = canvas.getContext("2d");3const ball = { x: 240, y: 120, dx: 3, dy: 3, r: 9 };4const paddle = { x: 195, y: 330, w: 90, h: 12 };5let score = 0;6 7function drawCourt() {8 ctx.strokeStyle = "rgba(255, 255, 255, 0.6)";9 ctx.lineWidth = 3;10 ctx.strokeRect(6, 6, canvas.width - 12, canvas.height - 12);11 ctx.beginPath();12 ctx.moveTo(6, canvas.height / 2);13 ctx.lineTo(canvas.width - 6, canvas.height / 2);14 ctx.stroke();15}16 17function drawBall() {18 ctx.fillStyle = "yellow";19 ctx.beginPath();20 ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2);21 ctx.fill();22}23 24function drawPaddle() {25 ctx.fillStyle = "white";26 ctx.fillRect(paddle.x, paddle.y, paddle.w, paddle.h);27}28 29canvas.addEventListener("mousemove", function (event) {30 const box = canvas.getBoundingClientRect();31 const x = (event.clientX - box.left) * canvas.width / box.width;32 paddle.x = x - paddle.w / 2;33});34 35function resetBall() {36 ball.x = 240;37 ball.y = 120;38 ball.dx = Math.random() * 6 - 3;39 ball.dy = 3;40}41 42function write(text, x, y, size) {43 ctx.fillStyle = "white";44 ctx.font = "bold " + size + "px Arial";45 ctx.textAlign = "center";46 ctx.fillText(text, x, y);47}48 49function loop() {50 ctx.clearRect(0, 0, canvas.width, canvas.height);51 drawCourt();52 ball.x = ball.x + ball.dx;53 ball.y = ball.y + ball.dy;54 // bounce off the walls55 if (ball.x < ball.r) {56 ball.dx = Math.abs(ball.dx);57 }58 if (ball.x > canvas.width - ball.r) {59 ball.dx = -Math.abs(ball.dx);60 }61 if (ball.y < ball.r) {62 ball.dy = Math.abs(ball.dy);63 }64 // bounce off the paddle65 if (ball.dy > 0 && ball.y + ball.r >= paddle.y && ball.y < paddle.y + paddle.h &&66 ball.x > paddle.x && ball.x < paddle.x + paddle.w) {67 // a little faster every time, up to a limit68 ball.dy = -Math.min(12, Math.abs(ball.dy) * 1.05);69 // hitting near the ends sends the ball off at an angle70 const hit = (ball.x - (paddle.x + paddle.w / 2)) / (paddle.w / 2);71 ball.dx = hit * 6;72 score = score + 1;73 }74 // missed it75 if (ball.y > canvas.height + 20) {76 resetBall();77 }78 drawBall();79 drawPaddle();80 write("Score: " + score, canvas.width / 2, 40, 24);81 requestAnimationFrame(loop);82}83 84loop();Hit near the ends to aim the ball. Step 6: Lives, and the arrow keys
Three lives, then game over, and a start screen that waits for a click or Space. The arrow keys move the paddle as well as the mouse, and
Math.minandMath.maxkeep it on the court whichever way it moves.New: lines 5, 7, 8, 52 to 79, 83 to 91, 116, 121 to 127 and 131 to 134.
1const canvas = document.getElementById("game");2const ctx = canvas.getContext("2d");3const ball = { x: 240, y: 120, dx: 3, dy: 3, r: 9 };4const paddle = { x: 195, y: 330, w: 90, h: 12 };5const keys = {};6let score = 0;7let lives = 3;8let playing = false;9 10function drawCourt() {11 ctx.strokeStyle = "rgba(255, 255, 255, 0.6)";12 ctx.lineWidth = 3;13 ctx.strokeRect(6, 6, canvas.width - 12, canvas.height - 12);14 ctx.beginPath();15 ctx.moveTo(6, canvas.height / 2);16 ctx.lineTo(canvas.width - 6, canvas.height / 2);17 ctx.stroke();18}19 20function drawBall() {21 ctx.fillStyle = "yellow";22 ctx.beginPath();23 ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2);24 ctx.fill();25}26 27function drawPaddle() {28 ctx.fillStyle = "white";29 ctx.fillRect(paddle.x, paddle.y, paddle.w, paddle.h);30}31 32canvas.addEventListener("mousemove", function (event) {33 const box = canvas.getBoundingClientRect();34 const x = (event.clientX - box.left) * canvas.width / box.width;35 paddle.x = x - paddle.w / 2;36});37 38function resetBall() {39 ball.x = 240;40 ball.y = 120;41 ball.dx = Math.random() * 6 - 3;42 ball.dy = 3;43}44 45function write(text, x, y, size) {46 ctx.fillStyle = "white";47 ctx.font = "bold " + size + "px Arial";48 ctx.textAlign = "center";49 ctx.fillText(text, x, y);50}51 52document.addEventListener("keydown", function (event) {53 keys[event.key] = true;54 if (event.key === "ArrowLeft" || event.key === "ArrowRight" || event.key === " ") {55 event.preventDefault();56 }57 if (event.key === " " && !playing) {58 start();59 }60});61 62document.addEventListener("keyup", function (event) {63 keys[event.key] = false;64});65 66canvas.addEventListener("click", function () {67 if (!playing) {68 start();69 }70});71 72function start() {73 score = 0;74 lives = 3;75 resetBall();76 playing = true;77 loop();78}79 80function loop() {81 ctx.clearRect(0, 0, canvas.width, canvas.height);82 drawCourt();83 // the arrow keys move the paddle too84 if (keys.ArrowLeft) {85 paddle.x = paddle.x - 8;86 }87 if (keys.ArrowRight) {88 paddle.x = paddle.x + 8;89 }90 // keep the paddle on the court91 paddle.x = Math.max(0, Math.min(canvas.width - paddle.w, paddle.x));92 ball.x = ball.x + ball.dx;93 ball.y = ball.y + ball.dy;94 // bounce off the walls95 if (ball.x < ball.r) {96 ball.dx = Math.abs(ball.dx);97 }98 if (ball.x > canvas.width - ball.r) {99 ball.dx = -Math.abs(ball.dx);100 }101 if (ball.y < ball.r) {102 ball.dy = Math.abs(ball.dy);103 }104 // bounce off the paddle105 if (ball.dy > 0 && ball.y + ball.r >= paddle.y && ball.y < paddle.y + paddle.h &&106 ball.x > paddle.x && ball.x < paddle.x + paddle.w) {107 // a little faster every time, up to a limit108 ball.dy = -Math.min(12, Math.abs(ball.dy) * 1.05);109 // hitting near the ends sends the ball off at an angle110 const hit = (ball.x - (paddle.x + paddle.w / 2)) / (paddle.w / 2);111 ball.dx = hit * 6;112 score = score + 1;113 }114 // missed it115 if (ball.y > canvas.height + 20) {116 lives = lives - 1;117 resetBall();118 }119 drawBall();120 drawPaddle();121 write("Score: " + score + " Lives: " + lives, canvas.width / 2, 40, 22);122 if (lives <= 0) {123 playing = false;124 write("Game over!", canvas.width / 2, 170, 44);125 write("Click or press Space to play again", canvas.width / 2, 210, 18);126 return;127 }128 requestAnimationFrame(loop);129}130 131// the start screen132drawCourt();133write("Paddle Rally", canvas.width / 2, 160, 44);134write("Click or press Space to start", canvas.width / 2, 200, 18);The finished Paddle Rally. Click or press Space 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.
Two players
Turn it into a game for two: a second paddle at the top, moved with A and D.
Show a hint
Add
paddle2aty: 18. Checkkeys.aandkeys.dto move it, and copy the paddle bounce for the top, with the ball moving up. Each player scores when the other misses.Shrinking paddle
Make the paddle 2 pixels narrower with every save, down to 40.
Show a hint
After
score = score + 1, setpaddle.w = Math.max(40, paddle.w - 2).Bricks
Add a row of bricks at the top that break when the ball hits them.
Show a hint
Keep the bricks in an array of rectangles. Each frame, check whether the ball is inside each one. If it is, remove the brick and turn the ball round with
ball.dy = Math.abs(ball.dy).
The finished code
Show the whole game
1<!DOCTYPE html>2<html>3 <head>4 <meta charset="utf-8">5 <title>Paddle Rally</title>6 <link rel="stylesheet" href="style.css">7 </head>8 <body>9 <h1>Paddle Rally</h1>10 <canvas id="game" width="480" height="360"></canvas>11 <p>Move the mouse, or click the game and use the arrow keys.</p>12 <script src="script.js"></script>13 </body>14</html>1body {2 font-family: Arial, sans-serif;3 text-align: center;4 background: #073b2a;5 color: white;6}7 8canvas {9 background: #0b6e4f;10 border-radius: 10px;11 max-width: 100%;12}1const canvas = document.getElementById("game");2const ctx = canvas.getContext("2d");3const ball = { x: 240, y: 120, dx: 3, dy: 3, r: 9 };4const paddle = { x: 195, y: 330, w: 90, h: 12 };5const keys = {};6let score = 0;7let lives = 3;8let playing = false;9 10function drawCourt() {11 ctx.strokeStyle = "rgba(255, 255, 255, 0.6)";12 ctx.lineWidth = 3;13 ctx.strokeRect(6, 6, canvas.width - 12, canvas.height - 12);14 ctx.beginPath();15 ctx.moveTo(6, canvas.height / 2);16 ctx.lineTo(canvas.width - 6, canvas.height / 2);17 ctx.stroke();18}19 20function drawBall() {21 ctx.fillStyle = "yellow";22 ctx.beginPath();23 ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2);24 ctx.fill();25}26 27function drawPaddle() {28 ctx.fillStyle = "white";29 ctx.fillRect(paddle.x, paddle.y, paddle.w, paddle.h);30}31 32canvas.addEventListener("mousemove", function (event) {33 const box = canvas.getBoundingClientRect();34 const x = (event.clientX - box.left) * canvas.width / box.width;35 paddle.x = x - paddle.w / 2;36});37 38function resetBall() {39 ball.x = 240;40 ball.y = 120;41 ball.dx = Math.random() * 6 - 3;42 ball.dy = 3;43}44 45function write(text, x, y, size) {46 ctx.fillStyle = "white";47 ctx.font = "bold " + size + "px Arial";48 ctx.textAlign = "center";49 ctx.fillText(text, x, y);50}51 52document.addEventListener("keydown", function (event) {53 keys[event.key] = true;54 if (event.key === "ArrowLeft" || event.key === "ArrowRight" || event.key === " ") {55 event.preventDefault();56 }57 if (event.key === " " && !playing) {58 start();59 }60});61 62document.addEventListener("keyup", function (event) {63 keys[event.key] = false;64});65 66canvas.addEventListener("click", function () {67 if (!playing) {68 start();69 }70});71 72function start() {73 score = 0;74 lives = 3;75 resetBall();76 playing = true;77 loop();78}79 80function loop() {81 ctx.clearRect(0, 0, canvas.width, canvas.height);82 drawCourt();83 // the arrow keys move the paddle too84 if (keys.ArrowLeft) {85 paddle.x = paddle.x - 8;86 }87 if (keys.ArrowRight) {88 paddle.x = paddle.x + 8;89 }90 // keep the paddle on the court91 paddle.x = Math.max(0, Math.min(canvas.width - paddle.w, paddle.x));92 ball.x = ball.x + ball.dx;93 ball.y = ball.y + ball.dy;94 // bounce off the walls95 if (ball.x < ball.r) {96 ball.dx = Math.abs(ball.dx);97 }98 if (ball.x > canvas.width - ball.r) {99 ball.dx = -Math.abs(ball.dx);100 }101 if (ball.y < ball.r) {102 ball.dy = Math.abs(ball.dy);103 }104 // bounce off the paddle105 if (ball.dy > 0 && ball.y + ball.r >= paddle.y && ball.y < paddle.y + paddle.h &&106 ball.x > paddle.x && ball.x < paddle.x + paddle.w) {107 // a little faster every time, up to a limit108 ball.dy = -Math.min(12, Math.abs(ball.dy) * 1.05);109 // hitting near the ends sends the ball off at an angle110 const hit = (ball.x - (paddle.x + paddle.w / 2)) / (paddle.w / 2);111 ball.dx = hit * 6;112 score = score + 1;113 }114 // missed it115 if (ball.y > canvas.height + 20) {116 lives = lives - 1;117 resetBall();118 }119 drawBall();120 drawPaddle();121 write("Score: " + score + " Lives: " + lives, canvas.width / 2, 40, 22);122 if (lives <= 0) {123 playing = false;124 write("Game over!", canvas.width / 2, 170, 44);125 write("Click or press Space to play again", canvas.width / 2, 210, 18);126 return;127 }128 requestAnimationFrame(loop);129}130 131// the start screen132drawCourt();133write("Paddle Rally", canvas.width / 2, 160, 44);134write("Click or press Space to start", canvas.width / 2, 200, 18);Notes for the teacher
Timing
- 10 minutes: steps 1 and 2. Act out dx and dy with a student walking across the room.
- 20 minutes: steps 3 and 4.
- 20 minutes: steps 5 and 6, then a class rally record.
Mistakes to look out for
- A ball stuck juddering in a wall: using
ball.dx = -ball.dxinstead ofMath.abscan flip it back and forth every frame. The steps avoid this on purpose. - A paddle that ignores the mouse:
mousemovemust be added to the canvas, and the code needsgetBoundingClientRectto turn the mouse position into canvas pixels. - The ball passing through the paddle at high speed: the speed limit of 12 is less than the paddle's height plus the ball's radius, which stops this.
Going further
hit maps a position onto the range from minus one to one: the same idea as a percentage, and very common in games and graphics.