TExcelTAD
Home › 2D Games with JavaScript & Canvas › Breakout 3: Levels, Lives, Win & Lose

Breakout 3: Levels, Lives, Win & Lose

One wall of bricks is a demo; a sequence of walls is a game. In this step we describe levels as data (short strings anyone can edit), add bricks that take two hits and steel bricks that never break, give the player three lives, and wrap everything in win and lose screens.

Levels as strings

Hand-placing bricks in code doesn't scale. Instead, draw each level as text, one string per row, one character per brick:

Character Brick
. empty
1 normal, breaks in one hit
2 tough, takes two hits
# steel, never breaks
js
const LEVELS = [
  ['1111111111',
   '1111111111',
   '1111111111'],
  ['..222222..',
   '.21111112.',
   '2111111112',
   '.21111112.',
   '..222222..'],
];

This is exactly how many real games store levels: a tilemap made of characters or numbers. A designer can change a level without touching any logic, and you'll use the same idea for the platformer in Platformer 2.

Parsing a level

A parser walks the strings and turns every non-empty character into a brick object. It also counts the bricks that can break, because steel bricks must not stop the level from being cleared:

js · try it yourself
const BRICK_W = 44, BRICK_H = 12, GAP = 2, LEFT = 11, TOP = 30;
const TYPES = { '1': { hp: 1 }, '2': { hp: 2 }, '#': { hp: Infinity } };

function parseLevel(rows) {
  const bricks = [];
  rows.forEach((line, row) => {
    [...line].forEach((ch, col) => {
      if (!TYPES[ch]) return;                       // '.' and unknown characters: no brick
      bricks.push({ x: LEFT + col * (BRICK_W + GAP), y: TOP + row * (BRICK_H + GAP), type: ch, hp: TYPES[ch].hp });
    });
  });
  const breakable = bricks.filter((b) => b.hp !== Infinity).length;
  return { bricks, breakable };
}

const level = parseLevel([
  '#..2..#',
  '.11111.',
]);
console.log("bricks:", level.bricks.length, "breakable:", level.breakable);
console.log(level.bricks[0]);
console.log(level.bricks[1]);
console.log("types:", level.bricks.map((b) => b.type).join(''));
bricks: 8 breakable: 6
{ x: 11, y: 30, type: '#', hp: Infinity }
{ x: 149, y: 30, type: '2', hp: 2 }
types: #2#11111

A brick with hp: Infinity can be hit forever: Infinity - 1 is still Infinity. Small trick, no special case.

Hit points instead of instant removal

Bricks now lose a hit point per hit and are removed when it reaches zero:

js
const brick = bricks[i];
brick.hp--;
if (brick.hp <= 0) { bricks.splice(i, 1); breakable--; score += 20; }
else if (brick.type !== '#') score += 5;

Lives and the game flow

The game has four states. stuck (the ball waiting on the paddle) is a detail inside the playing state:

State What happens Next
playing the game; losing the ball costs a life cleared when no breakable bricks are left, lost at 0 lives
cleared short pause, "Level 2" banner playing on the next level, or won after the last one
won / lost final score Enter or Space → a new game

Each level also makes the ball a little faster (BALL_SPEED * (1 + 0.12 * levelIndex)), the cheapest difficulty curve there is.

Step 3: the full game loop

Click, then ←/→ or A/D, Space to launch. Three levels, three lives:

html · try it yourself
<style>
  html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; }
  canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; outline: none; touch-action: none; }
</style>
<canvas width="480" height="270"></canvas>
<script>
// ---- play kit: click to focus, keep game keys inside the frame, fixed-step loop ----
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const keys = new Set(), pressed = new Set();   // keys held now / pressed since the last update
let active = false, idleDrawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; });
cv.addEventListener('blur', () => { active = false; idleDrawn = false; keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
  if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault(); // don't scroll the lesson
  if (!e.repeat) pressed.add(e.code);
  keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function banner(title, sub = '') {
  ctx.save();
  ctx.fillStyle = 'rgba(0,0,0,0.6)'; ctx.fillRect(0, 0, W, H);
  ctx.fillStyle = '#fff'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
  ctx.font = 'bold 22px system-ui, sans-serif'; ctx.fillText(title, W / 2, H / 2 - 10);
  ctx.font = '14px system-ui, sans-serif'; ctx.fillText(sub, W / 2, H / 2 + 18);
  ctx.restore();
}
function run(update, draw, help = '') {
  const STEP = 1 / 60;
  let acc = 0, last = performance.now();
  requestAnimationFrame(function frame(now) {
    const dt = Math.min((now - last) / 1000, 0.1);
    last = now;
    if (active) {
      acc += dt;
      while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
      draw();
    } else if (!idleDrawn) {
      draw(); banner('Click to play', help); idleDrawn = true;
    }
    requestAnimationFrame(frame);
  });
}
// ---- end of play kit ----

// ---- Breakout, step 3: levels, tough and steel bricks, lives, win and lose ----
const PADDLE_W = 64, PADDLE_H = 8, PADDLE_SPEED = 320, BALL_SPEED = 230, MAX_ANGLE = Math.PI / 3;
const BRICK_W = 44, BRICK_H = 12, GAP = 2, TOP = 30;
const ROW_COLORS = ['#ef5350', '#ffa726', '#ffee58', '#66bb6a', '#42a5f5', '#ab47bc'];
const TYPES = { '1': { hp: 1 }, '2': { hp: 2 }, '#': { hp: Infinity } };
const LEVELS = [
  ['1111111111',
   '1111111111',
   '1111111111'],
  ['..222222..',
   '.21111112.',
   '2111111112',
   '.21111112.',
   '..222222..'],
  ['##..11..##',
   '2222222222',
   '1#1#11#1#1',
   '1111111111',
   '..1....1..'],
];
const paddle = { x: W / 2 - PADDLE_W / 2, y: H - 20 };
const ball = { x: 0, y: 0, size: 6, vx: 0, vy: 0, stuck: true };
let bricks = [], breakable = 0, level = 0, lives = 3, score = 0;
let state = 'playing', stateTimer = 0;   // 'playing' | 'cleared' | 'won' | 'lost'

function loadLevel(n) {
  level = n;
  bricks = [];
  const rows = LEVELS[n];
  const left = (W - (rows[0].length * (BRICK_W + GAP) - GAP)) / 2;
  rows.forEach((line, row) => [...line].forEach((ch, col) => {
    if (TYPES[ch]) bricks.push({ x: left + col * (BRICK_W + GAP), y: TOP + row * (BRICK_H + GAP), w: BRICK_W, h: BRICK_H, row, type: ch, hp: TYPES[ch].hp });
  }));
  breakable = bricks.filter((b) => b.hp !== Infinity).length;
  ball.stuck = true;
}

function newGame() {
  lives = 3;
  score = 0;
  loadLevel(0);
  state = 'playing';
}
newGame();

function resolve(r) {
  const overlapX = Math.min(ball.x + ball.size - r.x, r.x + r.w - ball.x);
  const overlapY = Math.min(ball.y + ball.size - r.y, r.y + r.h - ball.y);
  if (overlapX <= 0 || overlapY <= 0) return false;
  if (overlapX < overlapY) {
    if (ball.x + ball.size / 2 < r.x + r.w / 2) { ball.x -= overlapX; ball.vx = -Math.abs(ball.vx); }
    else { ball.x += overlapX; ball.vx = Math.abs(ball.vx); }
  } else {
    if (ball.y + ball.size / 2 < r.y + r.h / 2) { ball.y -= overlapY; ball.vy = -Math.abs(ball.vy); }
    else { ball.y += overlapY; ball.vy = Math.abs(ball.vy); }
  }
  return true;
}

function launch(angle) {
  const speed = BALL_SPEED * (1 + 0.12 * level);
  ball.vx = speed * Math.sin(angle);
  ball.vy = -speed * Math.cos(angle);
}

function play(dt) {
  if (keys.has('ArrowLeft') || keys.has('KeyA')) paddle.x -= PADDLE_SPEED * dt;
  if (keys.has('ArrowRight') || keys.has('KeyD')) paddle.x += PADDLE_SPEED * dt;
  paddle.x = Math.max(0, Math.min(W - PADDLE_W, paddle.x));

  if (ball.stuck) {
    ball.x = paddle.x + PADDLE_W / 2 - ball.size / 2;
    ball.y = paddle.y - ball.size;
    if (pressed.has('Space')) { ball.stuck = false; launch(0.35); }
    return;
  }

  ball.x += ball.vx * dt;
  ball.y += ball.vy * dt;
  if (ball.x < 0) { ball.x = 0; ball.vx = Math.abs(ball.vx); }
  if (ball.x + ball.size > W) { ball.x = W - ball.size; ball.vx = -Math.abs(ball.vx); }
  if (ball.y < 0) { ball.y = 0; ball.vy = Math.abs(ball.vy); }

  if (ball.vy > 0 && ball.y + ball.size > paddle.y && ball.y < paddle.y + PADDLE_H &&
      ball.x + ball.size > paddle.x && ball.x < paddle.x + PADDLE_W) {
    ball.y = paddle.y - ball.size;
    const offset = (ball.x + ball.size / 2 - (paddle.x + PADDLE_W / 2)) / (PADDLE_W / 2);
    launch(Math.max(-1, Math.min(1, offset)) * MAX_ANGLE);
  }

  const i = bricks.findIndex((b) => resolve(b));
  if (i !== -1) {
    const brick = bricks[i];
    brick.hp--;
    if (brick.hp <= 0) { bricks.splice(i, 1); breakable--; score += 20; }
    else if (brick.type !== '#') score += 5;
    if (breakable === 0) { state = 'cleared'; stateTimer = 1.5; }
  }

  if (ball.y > H) {
    lives--;
    if (lives === 0) state = 'lost';
    else ball.stuck = true;
  }
}

function update(dt) {
  const confirm = pressed.has('Enter') || pressed.has('Space');
  if (state === 'playing') play(dt);
  else if (state === 'cleared') {
    stateTimer -= dt;
    if (stateTimer <= 0) {
      if (level + 1 < LEVELS.length) { loadLevel(level + 1); state = 'playing'; }
      else state = 'won';
    }
  } else if (confirm) newGame();          // 'won' or 'lost'
}

function brickColor(b) {
  if (b.type === '#') return '#78809a';
  if (b.type === '2') return b.hp === 2 ? '#e0e0e0' : '#9e9e9e';
  return ROW_COLORS[b.row % ROW_COLORS.length];
}

function draw() {
  ctx.fillStyle = '#0e1018';
  ctx.fillRect(0, 0, W, H);
  for (const b of bricks) {
    ctx.fillStyle = brickColor(b);
    ctx.fillRect(Math.round(b.x), Math.round(b.y), b.w, b.h);
  }
  ctx.fillStyle = '#e8eaf6';
  ctx.fillRect(Math.round(paddle.x), Math.round(paddle.y), PADDLE_W, PADDLE_H);
  if (state === 'playing') {
    ctx.fillStyle = '#ffffff';
    ctx.fillRect(Math.round(ball.x), Math.round(ball.y), ball.size, ball.size);
  }
  // HUD
  ctx.fillStyle = '#b0b6cc';
  ctx.font = '12px ui-monospace, monospace';
  ctx.textBaseline = 'top';
  ctx.textAlign = 'left';
  ctx.fillText(`SCORE ${score}`, 8, 8);
  ctx.textAlign = 'center';
  ctx.fillText(`LEVEL ${level + 1}/${LEVELS.length}`, W / 2, 8);
  ctx.textAlign = 'right';
  ctx.fillText('♥'.repeat(lives), W - 8, 8);
  if (state === 'playing' && ball.stuck) {
    ctx.fillStyle = '#5c6380';
    ctx.textAlign = 'center';
    ctx.fillText('Space to launch', W / 2, H - 46);
  }
  if (state === 'cleared') banner(`Level ${level + 1} cleared!`, level + 1 < LEVELS.length ? 'Get ready…' : '');
  if (state === 'won') banner('You win!', `Score ${score} · Enter to play again`);
  if (state === 'lost') banner('Game over', `Score ${score} · Enter to try again`);
}

run(update, draw, '←/→ or A/D · Space to launch');
</script>

Reading the code

  • loadLevel(n) is the only place that builds bricks, and newGame() is the only place that resets lives and score. Like Pong's startMatch, it means "play again" can't inherit leftovers.
  • The bricks are centred per level from the row length, so a level 8 bricks wide also looks right.
  • The cleared state uses a countdown, just like Pong's serve timer, to give the player a breather.
  • The HUD (score, level, hearts) is drawn last, on top of everything. You'll polish it in HUD & Menus.

Tip: Put a cheat key in while developing, for example if (pressed.has('KeyN')) breakable = 0; to skip a level. Testing level 3 shouldn't require beating levels 1 and 2 every time. Remove it (or hide it behind a debug flag) before you ship.

Test yourself

Why does the level parser count breakable bricks separately?

  1. To draw them in a different colour
  2. Steel bricks never break, so the level must be cleared when only they remain
  3. To save memory
  4. Because bricks.length is slow

What is the advantage of describing levels as arrays of strings?

  1. They run faster
  2. Levels become data that can be edited (even by non-programmers) without changing game logic
  3. Canvas can draw strings directly
  4. It is the only way to make levels

A brick has hp: Infinity. What happens after brick.hp--?

  1. It becomes NaN
  2. It stays Infinity, so the brick never breaks
  3. It throws a RangeError
  4. It becomes 0