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.

Day 3 45 to 60 minutes 6 steps Key Stage 3
Start step 1
paddle-rally/index.html

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

  1. Step 1: The court

    Choose Day 3: Paddle Rally. drawCourt draws white lines with strokeRect, a rectangle that is outlined instead of filled, and a line across the middle. rgba is a colour you can partly see through: here, white at 60%.

    index.htmlHTML
    <!DOCTYPE html><html>  <head>    <meta charset="utf-8">    <title>Paddle Rally</title>    <link rel="stylesheet" href="style.css">  </head>  <body>    <h1>Paddle Rally</h1>    <canvas id="game" width="480" height="360"></canvas>    <p>Move the mouse, or click the game and use the arrow keys.</p>    <script src="script.js"></script>  </body></html>
    style.cssCSS
    body {  font-family: Arial, sans-serif;  text-align: center;  background: #073b2a;  color: white;} canvas {  background: #0b6e4f;  border-radius: 10px;  max-width: 100%;}
    script.jsJavaScript
    const canvas = document.getElementById("game");const ctx = canvas.getContext("2d"); function drawCourt() {  ctx.strokeStyle = "rgba(255, 255, 255, 0.6)";  ctx.lineWidth = 3;  ctx.strokeRect(6, 6, canvas.width - 12, canvas.height - 12);  ctx.beginPath();  ctx.moveTo(6, canvas.height / 2);  ctx.lineTo(canvas.width - 6, canvas.height / 2);  ctx.stroke();} drawCourt();
    paddle-rally/index.html
    A green court with white lines.
  2. 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.abs makes a number positive, so dx becomes positive, moving right, off the left wall, and negative off the right wall.

    New: lines 3 and 15 to 44.

    script.jsJavaScript
    const canvas = document.getElementById("game");const ctx = canvas.getContext("2d");const ball = { x: 240, y: 120, dx: 3, dy: 3, r: 9 }; function drawCourt() {  ctx.strokeStyle = "rgba(255, 255, 255, 0.6)";  ctx.lineWidth = 3;  ctx.strokeRect(6, 6, canvas.width - 12, canvas.height - 12);  ctx.beginPath();  ctx.moveTo(6, canvas.height / 2);  ctx.lineTo(canvas.width - 6, canvas.height / 2);  ctx.stroke();} function drawBall() {  ctx.fillStyle = "yellow";  ctx.beginPath();  ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2);  ctx.fill();} function loop() {  ctx.clearRect(0, 0, canvas.width, canvas.height);  drawCourt();  ball.x = ball.x + ball.dx;  ball.y = ball.y + ball.dy;  // bounce off the walls  if (ball.x < ball.r) {    ball.dx = Math.abs(ball.dx);  }  if (ball.x > canvas.width - ball.r) {    ball.dx = -Math.abs(ball.dx);  }  if (ball.y < ball.r) {    ball.dy = Math.abs(ball.dy);  }  if (ball.y > canvas.height - ball.r) {    ball.dy = -Math.abs(ball.dy);  }  drawBall();  requestAnimationFrame(loop);} loop();
    paddle-rally/index.html
    The ball bounces round all four walls.
  3. Step 3: A paddle

    The paddle follows the mouse across the canvas. mousemove happens every time the mouse moves, and the paddle's middle goes to the mouse's x.

    New: lines 4, 22 to 32 and 53.

    script.jsJavaScript
    const canvas = document.getElementById("game");const ctx = canvas.getContext("2d");const ball = { x: 240, y: 120, dx: 3, dy: 3, r: 9 };const paddle = { x: 195, y: 330, w: 90, h: 12 }; function drawCourt() {  ctx.strokeStyle = "rgba(255, 255, 255, 0.6)";  ctx.lineWidth = 3;  ctx.strokeRect(6, 6, canvas.width - 12, canvas.height - 12);  ctx.beginPath();  ctx.moveTo(6, canvas.height / 2);  ctx.lineTo(canvas.width - 6, canvas.height / 2);  ctx.stroke();} function drawBall() {  ctx.fillStyle = "yellow";  ctx.beginPath();  ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2);  ctx.fill();} function drawPaddle() {  ctx.fillStyle = "white";  ctx.fillRect(paddle.x, paddle.y, paddle.w, paddle.h);} canvas.addEventListener("mousemove", function (event) {  const box = canvas.getBoundingClientRect();  const x = (event.clientX - box.left) * canvas.width / box.width;  paddle.x = x - paddle.w / 2;}); function loop() {  ctx.clearRect(0, 0, canvas.width, canvas.height);  drawCourt();  ball.x = ball.x + ball.dx;  ball.y = ball.y + ball.dy;  // bounce off the walls  if (ball.x < ball.r) {    ball.dx = Math.abs(ball.dx);  }  if (ball.x > canvas.width - ball.r) {    ball.dx = -Math.abs(ball.dx);  }  if (ball.y < ball.r) {    ball.dy = Math.abs(ball.dy);  }  if (ball.y > canvas.height - ball.r) {    ball.dy = -Math.abs(ball.dy);  }  drawBall();  drawPaddle();  requestAnimationFrame(loop);} loop();
    paddle-rally/index.html
    Move the mouse over the game: the paddle follows.
  4. 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.

    script.jsJavaScript
    const canvas = document.getElementById("game");const ctx = canvas.getContext("2d");const ball = { x: 240, y: 120, dx: 3, dy: 3, r: 9 };const paddle = { x: 195, y: 330, w: 90, h: 12 }; function drawCourt() {  ctx.strokeStyle = "rgba(255, 255, 255, 0.6)";  ctx.lineWidth = 3;  ctx.strokeRect(6, 6, canvas.width - 12, canvas.height - 12);  ctx.beginPath();  ctx.moveTo(6, canvas.height / 2);  ctx.lineTo(canvas.width - 6, canvas.height / 2);  ctx.stroke();} function drawBall() {  ctx.fillStyle = "yellow";  ctx.beginPath();  ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2);  ctx.fill();} function drawPaddle() {  ctx.fillStyle = "white";  ctx.fillRect(paddle.x, paddle.y, paddle.w, paddle.h);} canvas.addEventListener("mousemove", function (event) {  const box = canvas.getBoundingClientRect();  const x = (event.clientX - box.left) * canvas.width / box.width;  paddle.x = x - paddle.w / 2;}); function resetBall() {  ball.x = 240;  ball.y = 120;  ball.dx = Math.random() * 6 - 3;  ball.dy = 3;} function loop() {  ctx.clearRect(0, 0, canvas.width, canvas.height);  drawCourt();  ball.x = ball.x + ball.dx;  ball.y = ball.y + ball.dy;  // bounce off the walls  if (ball.x < ball.r) {    ball.dx = Math.abs(ball.dx);  }  if (ball.x > canvas.width - ball.r) {    ball.dx = -Math.abs(ball.dx);  }  if (ball.y < ball.r) {    ball.dy = Math.abs(ball.dy);  }  // bounce off the paddle  if (ball.dy > 0 && ball.y + ball.r >= paddle.y && ball.y < paddle.y + paddle.h &&      ball.x > paddle.x && ball.x < paddle.x + paddle.w) {    ball.dy = -Math.abs(ball.dy);  }  // missed it  if (ball.y > canvas.height + 20) {    resetBall();  }  drawBall();  drawPaddle();  requestAnimationFrame(loop);} loop();
    paddle-rally/index.html
    Save the ball with the paddle, or it starts again.
  5. 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: hit is 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.

    script.jsJavaScript
    const canvas = document.getElementById("game");const ctx = canvas.getContext("2d");const ball = { x: 240, y: 120, dx: 3, dy: 3, r: 9 };const paddle = { x: 195, y: 330, w: 90, h: 12 };let score = 0; function drawCourt() {  ctx.strokeStyle = "rgba(255, 255, 255, 0.6)";  ctx.lineWidth = 3;  ctx.strokeRect(6, 6, canvas.width - 12, canvas.height - 12);  ctx.beginPath();  ctx.moveTo(6, canvas.height / 2);  ctx.lineTo(canvas.width - 6, canvas.height / 2);  ctx.stroke();} function drawBall() {  ctx.fillStyle = "yellow";  ctx.beginPath();  ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2);  ctx.fill();} function drawPaddle() {  ctx.fillStyle = "white";  ctx.fillRect(paddle.x, paddle.y, paddle.w, paddle.h);} canvas.addEventListener("mousemove", function (event) {  const box = canvas.getBoundingClientRect();  const x = (event.clientX - box.left) * canvas.width / box.width;  paddle.x = x - paddle.w / 2;}); function resetBall() {  ball.x = 240;  ball.y = 120;  ball.dx = Math.random() * 6 - 3;  ball.dy = 3;} function write(text, x, y, size) {  ctx.fillStyle = "white";  ctx.font = "bold " + size + "px Arial";  ctx.textAlign = "center";  ctx.fillText(text, x, y);} function loop() {  ctx.clearRect(0, 0, canvas.width, canvas.height);  drawCourt();  ball.x = ball.x + ball.dx;  ball.y = ball.y + ball.dy;  // bounce off the walls  if (ball.x < ball.r) {    ball.dx = Math.abs(ball.dx);  }  if (ball.x > canvas.width - ball.r) {    ball.dx = -Math.abs(ball.dx);  }  if (ball.y < ball.r) {    ball.dy = Math.abs(ball.dy);  }  // bounce off the paddle  if (ball.dy > 0 && ball.y + ball.r >= paddle.y && ball.y < paddle.y + paddle.h &&      ball.x > paddle.x && ball.x < paddle.x + paddle.w) {    // a little faster every time, up to a limit    ball.dy = -Math.min(12, Math.abs(ball.dy) * 1.05);    // hitting near the ends sends the ball off at an angle    const hit = (ball.x - (paddle.x + paddle.w / 2)) / (paddle.w / 2);    ball.dx = hit * 6;    score = score + 1;  }  // missed it  if (ball.y > canvas.height + 20) {    resetBall();  }  drawBall();  drawPaddle();  write("Score: " + score, canvas.width / 2, 40, 24);  requestAnimationFrame(loop);} loop();
    paddle-rally/index.html
    Hit near the ends to aim the ball.
  6. 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.min and Math.max keep 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.

    script.jsJavaScript
    const canvas = document.getElementById("game");const ctx = canvas.getContext("2d");const ball = { x: 240, y: 120, dx: 3, dy: 3, r: 9 };const paddle = { x: 195, y: 330, w: 90, h: 12 };const keys = {};let score = 0;let lives = 3;let playing = false; function drawCourt() {  ctx.strokeStyle = "rgba(255, 255, 255, 0.6)";  ctx.lineWidth = 3;  ctx.strokeRect(6, 6, canvas.width - 12, canvas.height - 12);  ctx.beginPath();  ctx.moveTo(6, canvas.height / 2);  ctx.lineTo(canvas.width - 6, canvas.height / 2);  ctx.stroke();} function drawBall() {  ctx.fillStyle = "yellow";  ctx.beginPath();  ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2);  ctx.fill();} function drawPaddle() {  ctx.fillStyle = "white";  ctx.fillRect(paddle.x, paddle.y, paddle.w, paddle.h);} canvas.addEventListener("mousemove", function (event) {  const box = canvas.getBoundingClientRect();  const x = (event.clientX - box.left) * canvas.width / box.width;  paddle.x = x - paddle.w / 2;}); function resetBall() {  ball.x = 240;  ball.y = 120;  ball.dx = Math.random() * 6 - 3;  ball.dy = 3;} function write(text, x, y, size) {  ctx.fillStyle = "white";  ctx.font = "bold " + size + "px Arial";  ctx.textAlign = "center";  ctx.fillText(text, x, y);} document.addEventListener("keydown", function (event) {  keys[event.key] = true;  if (event.key === "ArrowLeft" || event.key === "ArrowRight" || event.key === " ") {    event.preventDefault();  }  if (event.key === " " && !playing) {    start();  }}); document.addEventListener("keyup", function (event) {  keys[event.key] = false;}); canvas.addEventListener("click", function () {  if (!playing) {    start();  }}); function start() {  score = 0;  lives = 3;  resetBall();  playing = true;  loop();} function loop() {  ctx.clearRect(0, 0, canvas.width, canvas.height);  drawCourt();  // the arrow keys move the paddle too  if (keys.ArrowLeft) {    paddle.x = paddle.x - 8;  }  if (keys.ArrowRight) {    paddle.x = paddle.x + 8;  }  // keep the paddle on the court  paddle.x = Math.max(0, Math.min(canvas.width - paddle.w, paddle.x));  ball.x = ball.x + ball.dx;  ball.y = ball.y + ball.dy;  // bounce off the walls  if (ball.x < ball.r) {    ball.dx = Math.abs(ball.dx);  }  if (ball.x > canvas.width - ball.r) {    ball.dx = -Math.abs(ball.dx);  }  if (ball.y < ball.r) {    ball.dy = Math.abs(ball.dy);  }  // bounce off the paddle  if (ball.dy > 0 && ball.y + ball.r >= paddle.y && ball.y < paddle.y + paddle.h &&      ball.x > paddle.x && ball.x < paddle.x + paddle.w) {    // a little faster every time, up to a limit    ball.dy = -Math.min(12, Math.abs(ball.dy) * 1.05);    // hitting near the ends sends the ball off at an angle    const hit = (ball.x - (paddle.x + paddle.w / 2)) / (paddle.w / 2);    ball.dx = hit * 6;    score = score + 1;  }  // missed it  if (ball.y > canvas.height + 20) {    lives = lives - 1;    resetBall();  }  drawBall();  drawPaddle();  write("Score: " + score + "   Lives: " + lives, canvas.width / 2, 40, 22);  if (lives <= 0) {    playing = false;    write("Game over!", canvas.width / 2, 170, 44);    write("Click or press Space to play again", canvas.width / 2, 210, 18);    return;  }  requestAnimationFrame(loop);} // the start screendrawCourt();write("Paddle Rally", canvas.width / 2, 160, 44);write("Click or press Space to start", canvas.width / 2, 200, 18);
    paddle-rally/index.html
    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.

  1. Two players

    Turn it into a game for two: a second paddle at the top, moved with A and D.

    Show a hint

    Add paddle2 at y: 18. Check keys.a and keys.d to move it, and copy the paddle bounce for the top, with the ball moving up. Each player scores when the other misses.

  2. Shrinking paddle

    Make the paddle 2 pixels narrower with every save, down to 40.

    Show a hint

    After score = score + 1, set paddle.w = Math.max(40, paddle.w - 2).

  3. 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
index.htmlHTML
<!DOCTYPE html><html>  <head>    <meta charset="utf-8">    <title>Paddle Rally</title>    <link rel="stylesheet" href="style.css">  </head>  <body>    <h1>Paddle Rally</h1>    <canvas id="game" width="480" height="360"></canvas>    <p>Move the mouse, or click the game and use the arrow keys.</p>    <script src="script.js"></script>  </body></html>
style.cssCSS
body {  font-family: Arial, sans-serif;  text-align: center;  background: #073b2a;  color: white;} canvas {  background: #0b6e4f;  border-radius: 10px;  max-width: 100%;}
script.jsJavaScript
const canvas = document.getElementById("game");const ctx = canvas.getContext("2d");const ball = { x: 240, y: 120, dx: 3, dy: 3, r: 9 };const paddle = { x: 195, y: 330, w: 90, h: 12 };const keys = {};let score = 0;let lives = 3;let playing = false; function drawCourt() {  ctx.strokeStyle = "rgba(255, 255, 255, 0.6)";  ctx.lineWidth = 3;  ctx.strokeRect(6, 6, canvas.width - 12, canvas.height - 12);  ctx.beginPath();  ctx.moveTo(6, canvas.height / 2);  ctx.lineTo(canvas.width - 6, canvas.height / 2);  ctx.stroke();} function drawBall() {  ctx.fillStyle = "yellow";  ctx.beginPath();  ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2);  ctx.fill();} function drawPaddle() {  ctx.fillStyle = "white";  ctx.fillRect(paddle.x, paddle.y, paddle.w, paddle.h);} canvas.addEventListener("mousemove", function (event) {  const box = canvas.getBoundingClientRect();  const x = (event.clientX - box.left) * canvas.width / box.width;  paddle.x = x - paddle.w / 2;}); function resetBall() {  ball.x = 240;  ball.y = 120;  ball.dx = Math.random() * 6 - 3;  ball.dy = 3;} function write(text, x, y, size) {  ctx.fillStyle = "white";  ctx.font = "bold " + size + "px Arial";  ctx.textAlign = "center";  ctx.fillText(text, x, y);} document.addEventListener("keydown", function (event) {  keys[event.key] = true;  if (event.key === "ArrowLeft" || event.key === "ArrowRight" || event.key === " ") {    event.preventDefault();  }  if (event.key === " " && !playing) {    start();  }}); document.addEventListener("keyup", function (event) {  keys[event.key] = false;}); canvas.addEventListener("click", function () {  if (!playing) {    start();  }}); function start() {  score = 0;  lives = 3;  resetBall();  playing = true;  loop();} function loop() {  ctx.clearRect(0, 0, canvas.width, canvas.height);  drawCourt();  // the arrow keys move the paddle too  if (keys.ArrowLeft) {    paddle.x = paddle.x - 8;  }  if (keys.ArrowRight) {    paddle.x = paddle.x + 8;  }  // keep the paddle on the court  paddle.x = Math.max(0, Math.min(canvas.width - paddle.w, paddle.x));  ball.x = ball.x + ball.dx;  ball.y = ball.y + ball.dy;  // bounce off the walls  if (ball.x < ball.r) {    ball.dx = Math.abs(ball.dx);  }  if (ball.x > canvas.width - ball.r) {    ball.dx = -Math.abs(ball.dx);  }  if (ball.y < ball.r) {    ball.dy = Math.abs(ball.dy);  }  // bounce off the paddle  if (ball.dy > 0 && ball.y + ball.r >= paddle.y && ball.y < paddle.y + paddle.h &&      ball.x > paddle.x && ball.x < paddle.x + paddle.w) {    // a little faster every time, up to a limit    ball.dy = -Math.min(12, Math.abs(ball.dy) * 1.05);    // hitting near the ends sends the ball off at an angle    const hit = (ball.x - (paddle.x + paddle.w / 2)) / (paddle.w / 2);    ball.dx = hit * 6;    score = score + 1;  }  // missed it  if (ball.y > canvas.height + 20) {    lives = lives - 1;    resetBall();  }  drawBall();  drawPaddle();  write("Score: " + score + "   Lives: " + lives, canvas.width / 2, 40, 22);  if (lives <= 0) {    playing = false;    write("Game over!", canvas.width / 2, 170, 44);    write("Click or press Space to play again", canvas.width / 2, 210, 18);    return;  }  requestAnimationFrame(loop);} // the start screendrawCourt();write("Paddle Rally", canvas.width / 2, 160, 44);write("Click or press Space to start", canvas.width / 2, 200, 18);
Notes for the teacher

Timing

  1. 10 minutes: steps 1 and 2. Act out dx and dy with a student walking across the room.
  2. 20 minutes: steps 3 and 4.
  3. 20 minutes: steps 5 and 6, then a class rally record.

Mistakes to look out for

  1. A ball stuck juddering in a wall: using ball.dx = -ball.dx instead of Math.abs can flip it back and forth every frame. The steps avoid this on purpose.
  2. A paddle that ignores the mouse: mousemove must be added to the canvas, and the code needs getBoundingClientRect to turn the mouse position into canvas pixels.
  3. 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.