TExcelTAD
Home › 2D Games with JavaScript & Canvas › Canvas Games Exercises

Canvas Games Exercises

Time to practise the logic that every game in this course rests on. Most exercises are pure functions: collisions, timers, pools, tiles, easing. They are easy to test in the console and they are where most game bugs hide. Each one has a starter playground with the tests already written; complete the code marked TODO until the output matches. The last exercise is a playable one.

Tip: Run the starter first. It prints wrong answers (undefined, false, zeros), which shows you what the tests expect. Change the code, press Ctrl+Enter, repeat. Try for a while before opening the solution.

Exercise 1: AABB overlap

Topics: Collision Detection, axis-aligned boxes

Write overlaps(a, b) for two boxes { x, y, w, h } (top-left corner plus size). Boxes that only touch along an edge do not overlap.

js · try it yourself
function overlaps(a, b) {
  // TODO: true when the boxes overlap on both the x and the y axis
}

const player = { x: 10, y: 10, w: 20, h: 20 };
console.log(overlaps(player, { x: 25, y: 25, w: 10, h: 10 }));  // corners overlap
console.log(overlaps(player, { x: 30, y: 10, w: 10, h: 10 }));  // touching edges only
console.log(overlaps(player, { x: 0, y: 40, w: 50, h: 5 }));    // below
console.log(overlaps(player, { x: 15, y: 15, w: 2, h: 2 }));    // fully inside

Expected output:

text
true
false
false
true
Show solution
js
function overlaps(a, b) {
  return a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;
}

const player = { x: 10, y: 10, w: 20, h: 20 };
console.log(overlaps(player, { x: 25, y: 25, w: 10, h: 10 }));  // corners overlap
console.log(overlaps(player, { x: 30, y: 10, w: 10, h: 10 }));  // touching edges only
console.log(overlaps(player, { x: 0, y: 40, w: 50, h: 5 }));    // below
console.log(overlaps(player, { x: 15, y: 15, w: 2, h: 2 }));    // fully inside

Exercise 2: Circle vs rectangle

Topics: collision, Math.min/Math.max clamping

A ball { x, y, r } hits a brick { x, y, w, h } when the nearest point of the rectangle to the ball's centre is closer than the radius. Clamp the centre into the rectangle to find that point, then compare squared distances (no Math.sqrt needed).

js · try it yourself
function circleRect(c, r) {
  // TODO: clamp c.x and c.y into the rectangle, then compare the squared distance with c.r²
}

const brick = { x: 100, y: 50, w: 60, h: 20 };
console.log(circleRect({ x: 130, y: 45, r: 6 }, brick));   // just above the top edge
console.log(circleRect({ x: 130, y: 40, r: 6 }, brick));   // 10 px above: miss
console.log(circleRect({ x: 96, y: 46, r: 6 }, brick));    // near the top-left corner
console.log(circleRect({ x: 94, y: 44, r: 6 }, brick));    // outside the corner (distance 8.49)

Expected output:

text
true
false
true
false
Show solution
js
function circleRect(c, r) {
  const nearestX = Math.max(r.x, Math.min(c.x, r.x + r.w));
  const nearestY = Math.max(r.y, Math.min(c.y, r.y + r.h));
  const dx = c.x - nearestX, dy = c.y - nearestY;
  return dx * dx + dy * dy < c.r * c.r;
}

const brick = { x: 100, y: 50, w: 60, h: 20 };
console.log(circleRect({ x: 130, y: 45, r: 6 }, brick));   // just above the top edge
console.log(circleRect({ x: 130, y: 40, r: 6 }, brick));   // 10 px above: miss
console.log(circleRect({ x: 96, y: 46, r: 6 }, brick));    // near the top-left corner
console.log(circleRect({ x: 94, y: 44, r: 6 }, brick));    // outside the corner (distance 8.49)

Exercise 3: The fixed-step accumulator

Topics: The Fixed-Step Loop, clamping dt

Given a list of frame times in seconds, simulate the accumulator loop: add each (clamped) frame time to acc, then run as many step-sized updates as fit. Return the total number of updates, the number per frame and alpha, the leftover fraction of a step (rounded to 2 decimals) used for interpolation.

js · try it yourself
function simulateFrames(frameTimes, step = 1 / 60, maxDt = 0.1) {
  let acc = 0, updates = 0;
  const perFrame = [];
  for (const dt of frameTimes) {
    // TODO: add the clamped dt, count how many steps fit, subtract them
    perFrame.push(0);
  }
  return { updates, perFrame, alpha: +(acc / step).toFixed(2) };
}

// 120 Hz screen, a 40 ms hitch, then a 2-second tab switch.
console.log(simulateFrames([1 / 120, 1 / 120, 1 / 120, 1 / 120]));
console.log(simulateFrames([0.04]));
console.log(simulateFrames([2]));

Expected output:

text
{ updates: 2, perFrame: [ 0, 1, 0, 1 ], alpha: 0 }
{ updates: 2, perFrame: [ 2 ], alpha: 0.4 }
{ updates: 6, perFrame: [ 6 ], alpha: 0 }

Note the last line: without the maxDt clamp, a two-second pause would run 120 updates in one frame.

Show solution
js
function simulateFrames(frameTimes, step = 1 / 60, maxDt = 0.1) {
  let acc = 0, updates = 0;
  const perFrame = [];
  for (const dt of frameTimes) {
    acc += Math.min(dt, maxDt);
    let n = 0;
    while (acc >= step) { acc -= step; n++; }
    updates += n;
    perFrame.push(n);
  }
  return { updates, perFrame, alpha: +(acc / step).toFixed(2) };
}

// 120 Hz screen, a 40 ms hitch, then a 2-second tab switch.
console.log(simulateFrames([1 / 120, 1 / 120, 1 / 120, 1 / 120]));
console.log(simulateFrames([0.04]));
console.log(simulateFrames([2]));

Exercise 4: Weapon cooldown

Topics: Shooter 2: Projectiles & Cooldowns, closures

makeCooldown(seconds) returns an object with tick(dt) (counts the remaining time down, never below 0) and tryFire() (returns true and restarts the cooldown when it's ready, otherwise false). With the trigger held, a 0.25 s cooldown at 60 updates per second fires every 15 updates.

js · try it yourself
function makeCooldown(seconds) {
  let remaining = 0;
  return {
    tick(dt) {
      // TODO: count down
    },
    tryFire() {
      // TODO: fire only when the cooldown has run out
      return true;
    },
  };
}

const gun = makeCooldown(0.25);
const shots = [];
for (let step = 0; step < 40; step++) {   // 40 updates of 1/60 s with the trigger held
  gun.tick(1 / 60);
  if (gun.tryFire()) shots.push(step);
}
console.log('shots on steps:', shots.join(', '));

Expected output:

text
shots on steps: 0, 15, 30
Show solution
js
function makeCooldown(seconds) {
  let remaining = 0;
  return {
    tick(dt) { remaining = Math.max(0, remaining - dt); },
    tryFire() {
      if (remaining > 1e-9) return false;   // tiny epsilon: 15 × (1/60) is not exactly 0.25 in floating point
      remaining = seconds;
      return true;
    },
  };
}

const gun = makeCooldown(0.25);
const shots = [];
for (let step = 0; step < 40; step++) {   // 40 updates of 1/60 s with the trigger held
  gun.tick(1 / 60);
  if (gun.tryFire()) shots.push(step);
}
console.log('shots on steps:', shots.join(', '));

Fifteen additions of 1/60 don't give exactly 0.25 in floating point, so a strict remaining > 0 check fires one step late. Comparing with a tiny epsilon (or counting cooldowns in whole update steps) fixes it.

Exercise 5: An object pool

Topics: Shooter 4: Object Pooling, classes

Complete the pool so acquire() reuses a released object when one is free and only calls create() when the free list is empty. Three waves of 5 bullets should create just 5 objects in total.

js · try it yourself
class Pool {
  constructor(create) {
    this.create = create;
    this.free = [];
    this.created = 0;
  }
  acquire() {
    // TODO: reuse a free object if there is one
    this.created++;
    return this.create();
  }
  release(obj) {
    // TODO: keep the object for later
  }
}

const pool = new Pool(() => ({ x: 0, y: 0, alive: false }));
const live = [];
for (let wave = 1; wave <= 3; wave++) {
  for (let i = 0; i < 5; i++) {
    const b = pool.acquire();
    b.alive = true;
    live.push(b);
  }
  while (live.length) pool.release(live.pop());   // the wave ends: all bullets return
  console.log(`after wave ${wave}: created ${pool.created}, free ${pool.free.length}`);
}

Expected output:

text
after wave 1: created 5, free 5
after wave 2: created 5, free 5
after wave 3: created 5, free 5
Show solution
js
class Pool {
  constructor(create) {
    this.create = create;
    this.free = [];
    this.created = 0;
  }
  acquire() {
    if (this.free.length > 0) return this.free.pop();
    this.created++;
    return this.create();
  }
  release(obj) {
    this.free.push(obj);
  }
}

const pool = new Pool(() => ({ x: 0, y: 0, alive: false }));
const live = [];
for (let wave = 1; wave <= 3; wave++) {
  for (let i = 0; i < 5; i++) {
    const b = pool.acquire();
    b.alive = true;
    live.push(b);
  }
  while (live.length) pool.release(live.pop());   // the wave ends: all bullets return
  console.log(`after wave ${wave}: created ${pool.created}, free ${pool.free.length}`);
}

Exercise 6: Tile lookups

Topics: Platformer 2: Tilemaps & Tile Collision

The level is an array of strings, one character per 16×16 tile (# is solid). Write tileAt(px, py), which converts a pixel position to a tile and treats everything outside the map as solid, and boxHitsSolid(box), which checks every tile the box covers. Use x + w - 1 for the right edge so a box that ends exactly on a tile border doesn't count the next tile.

js · try it yourself
const TILE = 16;
const map = [
  '..........',
  '..........',
  '....##....',
  '##########',
];

function tileAt(px, py) {
  // TODO: pixel -> column/row; outside the map counts as '#'
}

function boxHitsSolid(box) {
  // TODO: loop over the columns and rows the box covers
  return false;
}

console.log(tileAt(70, 40), tileAt(10, 40), tileAt(-5, 10));
console.log(boxHitsSolid({ x: 20, y: 30, w: 12, h: 14 }));   // standing on air above the floor
console.log(boxHitsSolid({ x: 20, y: 36, w: 12, h: 14 }));   // sunk into the floor
console.log(boxHitsSolid({ x: 50, y: 20, w: 12, h: 12 }));   // next to the bump, not inside it

Expected output:

text
# . #
false
true
false
Show solution
js
const TILE = 16;
const map = [
  '..........',
  '..........',
  '....##....',
  '##########',
];

function tileAt(px, py) {
  const col = Math.floor(px / TILE), row = Math.floor(py / TILE);
  if (row < 0 || row >= map.length || col < 0 || col >= map[0].length) return '#';
  return map[row][col];
}

function boxHitsSolid(box) {
  const c0 = Math.floor(box.x / TILE), c1 = Math.floor((box.x + box.w - 1) / TILE);
  const r0 = Math.floor(box.y / TILE), r1 = Math.floor((box.y + box.h - 1) / TILE);
  for (let r = r0; r <= r1; r++) {
    for (let c = c0; c <= c1; c++) {
      if (tileAt(c * TILE, r * TILE) === '#') return true;
    }
  }
  return false;
}

console.log(tileAt(70, 40), tileAt(10, 40), tileAt(-5, 10));
console.log(boxHitsSolid({ x: 20, y: 30, w: 12, h: 14 }));   // standing on air above the floor
console.log(boxHitsSolid({ x: 20, y: 36, w: 12, h: 14 }));   // sunk into the floor
console.log(boxHitsSolid({ x: 50, y: 20, w: 12, h: 12 }));   // next to the bump, not inside it

Exercise 7: Easing a tween

Topics: Tweening & Easing

tween samples a value moving from from to to over duration seconds. Write easeOutQuad(t), which starts fast and slows down at the end: 1 - (1 - t)². The sample times go past the end (0.6 s) to check that the tween stops at its target.

js · try it yourself
const lerp = (a, b, t) => a + (b - a) * t;
const easeOutQuad = (t) => t; // TODO: ease out

function tween(from, to, duration, ease, times) {
  return times.map((time) => {
    const t = Math.min(1, Math.max(0, time / duration));
    return Math.round(lerp(from, to, ease(t)));
  });
}

const times = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6];
console.log('linear  ', tween(0, 200, 0.5, (t) => t, times).join(' '));
console.log('easeOut ', tween(0, 200, 0.5, easeOutQuad, times).join(' '));

Expected output:

text
linear   0 40 80 120 160 200 200
easeOut  0 72 128 168 192 200 200
Show solution
js
const lerp = (a, b, t) => a + (b - a) * t;
const easeOutQuad = (t) => 1 - (1 - t) * (1 - t);

function tween(from, to, duration, ease, times) {
  return times.map((time) => {
    const t = Math.min(1, Math.max(0, time / duration));
    return Math.round(lerp(from, to, ease(t)));
  });
}

const times = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6];
console.log('linear  ', tween(0, 200, 0.5, (t) => t, times).join(' '));
console.log('easeOut ', tween(0, 200, 0.5, easeOutQuad, times).join(' '));

Exercise 8: Paddle bounce angle

Topics: Pong 2, Breakout 2, sin/cos

Pong and Breakout feel controllable because the ball leaves the paddle at an angle that depends on where it hit: straight up in the middle, up to 60° at the edges. Compute the hit offset from −1 (left edge) to 1 (right edge), clamp it, turn it into an angle and return a velocity with the same speed. Round both components.

js · try it yourself
function bounceOffPaddle(ball, paddle, speed, maxAngleDeg = 60) {
  // TODO: offset -1..1 -> angle -> { vx, vy } (vy is negative: the ball goes up)
  return { vx: 0, vy: -speed };
}

const paddle = { x: 200, w: 80 };
for (const x of [240, 260, 280, 200, 300]) {
  console.log(`hit at x=${x}:`, bounceOffPaddle({ x }, paddle, 300));
}

Expected output:

text
hit at x=240: { vx: 0, vy: -300 }
hit at x=260: { vx: 150, vy: -260 }
hit at x=280: { vx: 260, vy: -150 }
hit at x=200: { vx: -260, vy: -150 }
hit at x=300: { vx: 260, vy: -150 }
Show solution
js
function bounceOffPaddle(ball, paddle, speed, maxAngleDeg = 60) {
  const offset = (ball.x - (paddle.x + paddle.w / 2)) / (paddle.w / 2);   // -1 .. 1
  const clamped = Math.max(-1, Math.min(1, offset));
  const angle = clamped * maxAngleDeg * Math.PI / 180;
  return { vx: Math.round(speed * Math.sin(angle)), vy: Math.round(-speed * Math.cos(angle)) };
}

const paddle = { x: 200, w: 80 };
for (const x of [240, 260, 280, 200, 300]) {
  console.log(`hit at x=${x}:`, bounceOffPaddle({ x }, paddle, 300));
}

Exercise 9 (playable): Screen wrap

Topics: Keyboard Input, the play kit

This little ship drifts with momentum (arrow keys to thrust). Right now it flies off the screen and never comes back. Complete wrap(value, max) so that leaving one edge brings the ship back on the opposite edge, like in Asteroids. The starter runs as it is; click it to play.

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 ----

function wrap(value, max) {
  // TODO: below 0 -> add max; at or above max -> subtract max
  return value;
}

const ship = { x: W / 2, y: H / 2, vx: 0, vy: 0 };
const THRUST = 220, DRAG = 0.6;
function update(dt) {
  if (keys.has('ArrowLeft')) ship.vx -= THRUST * dt;
  if (keys.has('ArrowRight')) ship.vx += THRUST * dt;
  if (keys.has('ArrowUp')) ship.vy -= THRUST * dt;
  if (keys.has('ArrowDown')) ship.vy += THRUST * dt;
  ship.vx -= ship.vx * DRAG * dt;
  ship.vy -= ship.vy * DRAG * dt;
  ship.x = wrap(ship.x + ship.vx * dt, W);
  ship.y = wrap(ship.y + ship.vy * dt, H);
}
function draw() {
  ctx.fillStyle = '#0e1018'; ctx.fillRect(0, 0, W, H);
  ctx.fillStyle = '#ffb74d';
  ctx.beginPath();
  ctx.arc(ship.x, ship.y, 10, 0, Math.PI * 2);
  ctx.fill();
  ctx.fillStyle = '#9aa3b5'; ctx.font = '12px monospace'; ctx.textAlign = 'left';
  ctx.fillText(`x ${ship.x.toFixed(0)}  y ${ship.y.toFixed(0)}`, 8, 16);
}
run(update, draw, 'Arrow keys to thrust');
</script>
Show solution
js
function wrap(value, max) {
  if (value < 0) return value + max;
  if (value >= max) return value - max;
  return value;
}

For a ship that should appear half on each side while crossing, draw it a second time at x ± W (and y ± H) when it is near an edge.

Test yourself

Why do the tile checks use x + w - 1 for the right edge of a box?

  1. To make the box smaller for fairness
  2. A box ending exactly on a tile border would otherwise also count the next tile as touched
  3. Arrays start at 1
  4. It is required by Math.floor

In the circle-vs-rectangle test, what is the 'nearest point' of the rectangle?

  1. Its centre
  2. The ball's centre clamped into the rectangle's x and y ranges
  3. Its top-left corner
  4. The corner farthest from the ball

Three waves of 5 bullets went through the pool, and created stayed at 5. Why?

  1. The pool deletes old bullets
  2. Released bullets go to the free list and are reused by later acquire() calls
  3. JavaScript caches objects automatically
  4. Each wave uses the same variable