Chapter 2 lab Chapter 3 lab Chapter 4 lab Chapter 5 lab Chapter 6 lab Chapter 7 lab Chapter 8 lab Chapter 9 lab Chapter 10 lab Chapter 12 lab Chapter 13 lab
Chapter 7 · Lab

Lab 7: Object-Oriented Programming Using JavaScript

Build a simple Tower Defense game in five stages using classes, objects, arrays and the requestAnimationFrame game loop. Each task replaces script.js with a more complete version.

Learning outcomes

  • Create classes and objects in JavaScript
  • Build an animation / game loop with requestAnimationFrame()
  • Manage multiple object instances in arrays
  • Detect collisions between rectangles
  • Handle mouse and click events on a canvas

Your progress

Tasks completed 0/5

Log in to save your lab progress. Log in

1

Exercise 7.1 — Creating the game grid

This stage sets up the foundation: a canvas, a Cell class, and a game loop. The createGrid() function fills the gameGrid array with a Cell object for every square on the board, and handleGameGrid() draws them.

Run it to see the empty grid with a blue controls bar at the top.

Code

TowerDefense.html
<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tower Defense</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
  <canvas id="myCanvas"></canvas>
  <script src="script.js"></script>
</body>
</html>
style.css
body {
  background: black;
  margin: 0;
}

#myCanvas {
  display: block;
  width: 100%;
  max-width: 900px;
  height: auto;
  margin: 0 auto;
  background: white;
}
script.js
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
canvas.width = 900;
canvas.height = 600;

// Global variables
const cellSize = 100;
const cellGap = 3;
const gameGrid = [];   // the game board

const controlsBar = {
  width: canvas.width,
  height: cellSize
};

class Cell {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.width = cellSize;
    this.height = cellSize;
  }

  draw() {
    ctx.strokeStyle = 'black';
    ctx.strokeRect(this.x, this.y, this.width, this.height);
  }
}

function createGrid() {
  for (let y = 0; y < canvas.height; y += cellSize) {
    for (let x = 0; x < canvas.width; x += cellSize) {
      gameGrid.push(new Cell(x, y));
    }
  }
}
createGrid();

function handleGameGrid() {
  for (let i = 0; i < gameGrid.length; i++) {
    gameGrid[i].draw();
  }
}

function animate() {
  ctx.fillStyle = 'blue';
  ctx.fillRect(0, 0, controlsBar.width, controlsBar.height);
  handleGameGrid();
  requestAnimationFrame(animate);
}
animate();

Try it

TowerDefense.html
style.css
script.js
2

Exercise 7.2 — Collision detection between 2 rectangles

Now the game tracks the mouse. The collision() function checks whether two rectangles overlap; if the mouse is over a cell, that cell is outlined. animate() also clears the canvas each frame.

Move your mouse over the board to highlight cells.

Code

TowerDefense.html
<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tower Defense</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
  <canvas id="myCanvas"></canvas>
  <script src="script.js"></script>
</body>
</html>
style.css
body {
  background: black;
  margin: 0;
}

#myCanvas {
  display: block;
  width: 100%;
  max-width: 900px;
  height: auto;
  margin: 0 auto;
  background: white;
}
script.js
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
canvas.width = 900;
canvas.height = 600;

const cellSize = 100;
const cellGap = 3;
const gameGrid = [];

const controlsBar = { width: canvas.width, height: cellSize };

// Mouse
const mouse = { x: 10, y: 10, width: 0.1, height: 0.1 };

canvas.addEventListener('mousemove', function (e) {
  const rect = canvas.getBoundingClientRect();
  mouse.x = (e.clientX - rect.left) * (canvas.width / rect.width);
  mouse.y = (e.clientY - rect.top) * (canvas.height / rect.height);
});

canvas.addEventListener('mouseleave', function () {
  mouse.x = undefined;
  mouse.y = undefined;
});

class Cell {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.width = cellSize;
    this.height = cellSize;
  }

  draw() {
    if (mouse.x && mouse.y && collision(this, mouse)) {
      ctx.strokeStyle = 'black';
      ctx.strokeRect(this.x, this.y, this.width, this.height);
    }
  }
}

function createGrid() {
  for (let y = 0; y < canvas.height; y += cellSize) {
    for (let x = 0; x < canvas.width; x += cellSize) {
      gameGrid.push(new Cell(x, y));
    }
  }
}
createGrid();

function handleGameGrid() {
  for (let i = 0; i < gameGrid.length; i++) {
    gameGrid[i].draw();
  }
}

function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = 'blue';
  ctx.fillRect(0, 0, controlsBar.width, controlsBar.height);
  handleGameGrid();
  requestAnimationFrame(animate);
}
animate();

function collision(first, second) {
  if (!(first.x > second.x + second.width ||
        first.x + first.width < second.x ||
        first.y > second.y + second.height ||
        first.y + first.height < second.y)) {
    return true;
  }
}

Try it

TowerDefense.html
style.css
script.js
3

Exercise 7.3 — Creating defenders

A Defender class is added. Click on the board to place a defender — each one costs 100 resources. You start with 300 resources, so you can place three defenders.

Notice how handleDefenders() draws every object in the defenders array.

Code

TowerDefense.html
<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tower Defense</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
  <canvas id="myCanvas"></canvas>
  <script src="script.js"></script>
</body>
</html>
style.css
body {
  background: black;
  margin: 0;
}

#myCanvas {
  display: block;
  width: 100%;
  max-width: 900px;
  height: auto;
  margin: 0 auto;
  background: white;
}
script.js
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
canvas.width = 900;
canvas.height = 600;

const cellSize = 100;
const cellGap = 3;
const gameGrid = [];
const defenders = [];
let numberOfResources = 300;

const controlsBar = { width: canvas.width, height: cellSize };

// Mouse
const mouse = { x: 10, y: 10, width: 0.1, height: 0.1 };

canvas.addEventListener('mousemove', function (e) {
  const rect = canvas.getBoundingClientRect();
  mouse.x = (e.clientX - rect.left) * (canvas.width / rect.width);
  mouse.y = (e.clientY - rect.top) * (canvas.height / rect.height);
});

canvas.addEventListener('mouseleave', function () {
  mouse.x = undefined;
  mouse.y = undefined;
});

class Cell {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.width = cellSize;
    this.height = cellSize;
  }

  draw() {
    if (mouse.x && mouse.y && collision(this, mouse)) {
      ctx.strokeStyle = 'black';
      ctx.strokeRect(this.x, this.y, this.width, this.height);
    }
  }
}

function createGrid() {
  for (let y = 0; y < canvas.height; y += cellSize) {
    for (let x = 0; x < canvas.width; x += cellSize) {
      gameGrid.push(new Cell(x, y));
    }
  }
}
createGrid();

function handleGameGrid() {
  for (let i = 0; i < gameGrid.length; i++) {
    gameGrid[i].draw();
  }
}

// Defenders
class Defender {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.width = cellSize;
    this.height = cellSize;
    this.shooting = false;
    this.health = 100;
    this.projectiles = [];
    this.timer = 0;
  }

  draw() {
    ctx.fillStyle = 'blue';
    ctx.fillRect(this.x, this.y, this.width, this.height);
    ctx.fillStyle = 'gold';
    ctx.font = '30px Arial';
    ctx.fillText(Math.floor(this.health), this.x + 15, this.y + 30);
  }
}

canvas.addEventListener('click', function () {
  if (!mouse.x || !mouse.y) return;
  const gridPositionX = mouse.x - (mouse.x % cellSize) + cellGap;
  const gridPositionY = mouse.y - (mouse.y % cellSize) + cellGap;
  if (gridPositionY < cellSize) return;   // top row is the controls bar

  for (let i = 0; i < defenders.length; i++) {
    if (defenders[i].x === gridPositionX && defenders[i].y === gridPositionY) return;
  }

  const defenderCost = 100;
  if (numberOfResources >= defenderCost) {
    defenders.push(new Defender(gridPositionX, gridPositionY));
    numberOfResources -= defenderCost;
  }
});

function handleDefenders() {
  for (let i = 0; i < defenders.length; i++) {
    defenders[i].draw();
  }
}

function handleGameStatus() {
  ctx.fillStyle = 'gold';
  ctx.font = '30px Arial';
  ctx.fillText('Resources: ' + numberOfResources, 20, 55);
}

function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = 'blue';
  ctx.fillRect(0, 0, controlsBar.width, controlsBar.height);
  handleGameGrid();
  handleDefenders();
  handleGameStatus();
  requestAnimationFrame(animate);
}
animate();

function collision(first, second) {
  if (!(first.x > second.x + second.width ||
        first.x + first.width < second.x ||
        first.y > second.y + second.height ||
        first.y + first.height < second.y)) {
    return true;
  }
}

Try it

TowerDefense.html
style.css
script.js
4

Exercise 7.4 — Creating and handling enemies

An Enemy class is added. Enemies spawn on the right and move left at random speeds; if one reaches the left edge, the game is over. Each enemy has health and maxHealth.

Watch the enemies march across the board and the "GAME OVER" message if one gets through.

Code

TowerDefense.html
<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tower Defense</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
  <canvas id="myCanvas"></canvas>
  <script src="script.js"></script>
</body>
</html>
style.css
body {
  background: black;
  margin: 0;
}

#myCanvas {
  display: block;
  width: 100%;
  max-width: 900px;
  height: auto;
  margin: 0 auto;
  background: white;
}
script.js
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
canvas.width = 900;
canvas.height = 600;

const cellSize = 100;
const cellGap = 3;
const gameGrid = [];
const defenders = [];
let numberOfResources = 300;
const enemies = [];
const enemyPositions = [];
let enemiesInterval = 600;
let frame = 0;
let gameOver = false;

const controlsBar = { width: canvas.width, height: cellSize };

// Mouse
const mouse = { x: 10, y: 10, width: 0.1, height: 0.1 };

canvas.addEventListener('mousemove', function (e) {
  const rect = canvas.getBoundingClientRect();
  mouse.x = (e.clientX - rect.left) * (canvas.width / rect.width);
  mouse.y = (e.clientY - rect.top) * (canvas.height / rect.height);
});

canvas.addEventListener('mouseleave', function () {
  mouse.x = undefined;
  mouse.y = undefined;
});

class Cell {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.width = cellSize;
    this.height = cellSize;
  }

  draw() {
    if (mouse.x && mouse.y && collision(this, mouse)) {
      ctx.strokeStyle = 'black';
      ctx.strokeRect(this.x, this.y, this.width, this.height);
    }
  }
}

function createGrid() {
  for (let y = 0; y < canvas.height; y += cellSize) {
    for (let x = 0; x < canvas.width; x += cellSize) {
      gameGrid.push(new Cell(x, y));
    }
  }
}
createGrid();

function handleGameGrid() {
  for (let i = 0; i < gameGrid.length; i++) {
    gameGrid[i].draw();
  }
}

// Defenders
class Defender {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.width = cellSize;
    this.height = cellSize;
    this.shooting = false;
    this.health = 100;
    this.projectiles = [];
    this.timer = 0;
  }

  draw() {
    ctx.fillStyle = 'blue';
    ctx.fillRect(this.x, this.y, this.width, this.height);
    ctx.fillStyle = 'gold';
    ctx.font = '30px Arial';
    ctx.fillText(Math.floor(this.health), this.x + 15, this.y + 30);
  }
}

canvas.addEventListener('click', function () {
  if (!mouse.x || !mouse.y) return;
  const gridPositionX = mouse.x - (mouse.x % cellSize) + cellGap;
  const gridPositionY = mouse.y - (mouse.y % cellSize) + cellGap;
  if (gridPositionY < cellSize) return;

  for (let i = 0; i < defenders.length; i++) {
    if (defenders[i].x === gridPositionX && defenders[i].y === gridPositionY) return;
  }

  const defenderCost = 100;
  if (numberOfResources >= defenderCost) {
    defenders.push(new Defender(gridPositionX, gridPositionY));
    numberOfResources -= defenderCost;
  }
});

function handleDefenders() {
  for (let i = 0; i < defenders.length; i++) {
    defenders[i].draw();
  }
}

// Enemies
class Enemy {
  constructor(verticalPosition) {
    this.x = canvas.width;
    this.y = verticalPosition;
    this.width = cellSize;
    this.height = cellSize;
    this.speed = Math.random() * 0.2 + 0.4;
    this.movement = this.speed;
    this.health = 100;
    this.maxHealth = this.health;
  }

  update() {
    this.x -= this.movement;
  }

  draw() {
    ctx.fillStyle = 'red';
    ctx.fillRect(this.x, this.y, this.width, this.height);
    ctx.fillStyle = 'black';
    ctx.font = '30px Arial';
    ctx.fillText(Math.floor(this.health), this.x + 15, this.y + 30);
  }
}

function handleEnemies() {
  for (let i = 0; i < enemies.length; i++) {
    enemies[i].update();
    enemies[i].draw();

    if (enemies[i].x < 0) {
      gameOver = true;
    }
  }

  if (frame % enemiesInterval === 0) {
    const verticalPosition = Math.floor(Math.random() * 5 + 1) * cellSize + cellGap;
    enemies.push(new Enemy(verticalPosition));
    enemyPositions.push(verticalPosition);
    if (enemiesInterval > 120) enemiesInterval -= 50;
  }
}

// Utilities
function handleGameStatus() {
  ctx.fillStyle = 'gold';
  ctx.font = '30px Arial';
  ctx.fillText('Resources: ' + numberOfResources, 20, 55);

  if (gameOver) {
    ctx.fillStyle = 'black';
    ctx.font = '60px Arial';
    ctx.fillText('GAME OVER', 135, 330);
  }
}

function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = 'blue';
  ctx.fillRect(0, 0, controlsBar.width, controlsBar.height);
  handleGameGrid();
  handleDefenders();
  handleEnemies();
  handleGameStatus();
  frame++;
  if (!gameOver) requestAnimationFrame(animate);
}
animate();

function collision(first, second) {
  if (!(first.x > second.x + second.width ||
        first.x + first.width < second.x ||
        first.y > second.y + second.height ||
        first.y + first.height < second.y)) {
    return true;
  }
}

Try it

TowerDefense.html
style.css
script.js
5

Exercise 7.5 — Projectiles, resources & utilities

The final stage adds Projectile and Resource classes, a score, and a winning condition. Defenders shoot when an enemy is in their row; projectiles damage enemies; defeated enemies give resources and score.

  1. Place defenders by clicking on the board.
  2. Click the yellow resource boxes to collect them.
  3. Reach 50 points to win — "LEVEL COMPLETE".
  4. If an enemy reaches the left edge, it is "GAME OVER".

Code

TowerDefense.html
<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tower Defense</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
  <canvas id="myCanvas"></canvas>
  <script src="script.js"></script>
</body>
</html>
style.css
body {
  background: black;
  margin: 0;
}

#myCanvas {
  display: block;
  width: 100%;
  max-width: 900px;
  height: auto;
  margin: 0 auto;
  background: white;
}
script.js
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
canvas.width = 900;
canvas.height = 600;

// Global variables
const cellSize = 100;
const cellGap = 3;   // to avoid defender/enemy collision, make them smaller
let numberOfResources = 300;
let enemiesInterval = 600;
let frame = 0;
let gameOver = false;
let score = 0;
const winningScore = 50;

const gameGrid = [];
const defenders = [];
const enemies = [];
const enemyPositions = [];
const projectiles = [];
const resources = [];

const controlsBar = { width: canvas.width, height: cellSize };

// Mouse
const mouse = { x: 10, y: 10, width: 0.1, height: 0.1 };

canvas.addEventListener('mousemove', function (e) {
  const rect = canvas.getBoundingClientRect();
  mouse.x = (e.clientX - rect.left) * (canvas.width / rect.width);
  mouse.y = (e.clientY - rect.top) * (canvas.height / rect.height);
});

canvas.addEventListener('mouseleave', function () {
  mouse.x = undefined;
  mouse.y = undefined;
});

// Game board
class Cell {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.width = cellSize;
    this.height = cellSize;
  }

  draw() {
    if (mouse.x && mouse.y && collision(this, mouse)) {
      ctx.strokeStyle = 'black';
      ctx.strokeRect(this.x, this.y, this.width, this.height);
    }
  }
}

function createGrid() {
  for (let y = 0; y < canvas.height; y += cellSize) {
    for (let x = 0; x < canvas.width; x += cellSize) {
      gameGrid.push(new Cell(x, y));
    }
  }
}
createGrid();

function handleGameGrid() {
  for (let i = 0; i < gameGrid.length; i++) {
    gameGrid[i].draw();
  }
}

// Projectiles
class Projectile {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.width = 10;
    this.height = 10;
    this.power = 20;
    this.speed = 5;
  }

  update() {
    this.x += this.speed;
  }

  draw() {
    ctx.fillStyle = 'black';
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.width, 0, Math.PI * 2);
    ctx.fill();
  }
}

function handleProjectiles() {
  for (let i = projectiles.length - 1; i >= 0; i--) {
    projectiles[i].update();
    projectiles[i].draw();

    // check if the projectile collided with an enemy
    for (let j = enemies.length - 1; j >= 0; j--) {
      if (enemies[j] && projectiles[i] && collision(projectiles[i], enemies[j])) {
        enemies[j].health -= projectiles[i].power;
        projectiles.splice(i, 1);
        break;
      }
    }

    // remove the projectile if it reaches the last cell
    if (projectiles[i] && projectiles[i].x > canvas.width - cellSize) {
      projectiles.splice(i, 1);
    }
  }
}

// Defenders
class Defender {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.width = cellSize - cellGap * 2;
    this.height = cellSize - cellGap * 2;
    this.shooting = false;
    this.health = 100;
    this.projectiles = [];
    this.timer = 0;
  }

  draw() {
    ctx.fillStyle = 'blue';
    ctx.fillRect(this.x, this.y, this.width, this.height);
    ctx.fillStyle = 'gold';
    ctx.font = '30px Arial';
    ctx.fillText(Math.floor(this.health), this.x + 15, this.y + 30);
  }

  update() {
    if (this.shooting) {
      this.timer++;
      if (this.timer % 100 === 0) {   // insert a new projectile every 100 frames
        projectiles.push(new Projectile(this.x + 70, this.y + 50));
      }
    }
  }
}

canvas.addEventListener('click', function () {
  if (!mouse.x || !mouse.y) return;
  const gridPositionX = mouse.x - (mouse.x % cellSize) + cellGap;
  const gridPositionY = mouse.y - (mouse.y % cellSize) + cellGap;
  if (gridPositionY < cellSize) return;

  for (let i = 0; i < defenders.length; i++) {
    if (defenders[i].x === gridPositionX && defenders[i].y === gridPositionY) return;
  }

  const defenderCost = 100;
  if (numberOfResources >= defenderCost) {
    defenders.push(new Defender(gridPositionX, gridPositionY));
    numberOfResources -= defenderCost;
  }
});

function handleDefenders() {
  for (let i = defenders.length - 1; i >= 0; i--) {
    defenders[i].draw();
    defenders[i].update();

    // shoot if there is an enemy in this row
    if (enemyPositions.indexOf(defenders[i].y) !== -1) {
      defenders[i].shooting = true;
    } else {
      defenders[i].shooting = false;
    }

    for (let j = enemies.length - 1; j >= 0; j--) {
      if (defenders[i] && collision(defenders[i], enemies[j])) {
        enemies[j].movement = 0;
        defenders[i].health -= 1;
      }
      if (defenders[i] && defenders[i].health <= 0) {
        defenders.splice(i, 1);
        enemies[j].movement = enemies[j].speed;
        break;
      }
    }
  }
}

// Enemies
class Enemy {
  constructor(verticalPosition) {
    this.x = canvas.width;
    this.y = verticalPosition;
    this.width = cellSize - cellGap * 2;
    this.height = cellSize - cellGap * 2;
    this.speed = Math.random() * 0.2 + 0.4;
    this.movement = this.speed;
    this.health = 100;
    this.maxHealth = this.health;
  }

  update() {
    this.x -= this.movement;
  }

  draw() {
    ctx.fillStyle = 'red';
    ctx.fillRect(this.x, this.y, this.width, this.height);
    ctx.fillStyle = 'black';
    ctx.font = '30px Arial';
    ctx.fillText(Math.floor(this.health), this.x + 15, this.y + 30);
  }
}

function handleEnemies() {
  for (let i = enemies.length - 1; i >= 0; i--) {
    enemies[i].update();
    enemies[i].draw();

    if (enemies[i].x < 0) {
      gameOver = true;
    }

    if (enemies[i].health <= 0) {
      const gainedResources = enemies[i].maxHealth / 10;
      numberOfResources += gainedResources;
      score += gainedResources;

      const findThisIndex = enemyPositions.indexOf(enemies[i].y);
      if (findThisIndex !== -1) enemyPositions.splice(findThisIndex, 1);
      enemies.splice(i, 1);
    }
  }

  if (frame % enemiesInterval === 0 && score < winningScore) {
    const verticalPosition = Math.floor(Math.random() * 5 + 1) * cellSize + cellGap;
    enemies.push(new Enemy(verticalPosition));
    enemyPositions.push(verticalPosition);
    if (enemiesInterval > 120) enemiesInterval -= 50;
  }
}

// Resources
const amounts = [20, 30, 40];

class Resource {
  constructor() {
    this.x = Math.random() * (canvas.width - cellSize);
    this.y = (Math.floor(Math.random() * 5) + 1) * cellSize + 25;
    this.width = cellSize * 0.6;
    this.height = cellSize * 0.6;
    this.amount = amounts[Math.floor(Math.random() * amounts.length)];
  }

  draw() {
    ctx.fillStyle = 'yellow';
    ctx.fillRect(this.x, this.y, this.width, this.height);
    ctx.fillStyle = 'black';
    ctx.font = '20px Arial';
    ctx.fillText(this.amount, this.x + 15, this.y + 25);
  }
}

function handleResources() {
  if (frame % 500 === 0 && score < winningScore) {
    resources.push(new Resource());
  }

  for (let i = resources.length - 1; i >= 0; i--) {
    resources[i].draw();

    if (mouse.x && mouse.y && collision(resources[i], mouse)) {
      numberOfResources += resources[i].amount;
      resources.splice(i, 1);
    }
  }
}

// Utilities
function handleGameStatus() {
  ctx.fillStyle = 'gold';
  ctx.font = '30px Arial';
  ctx.fillText('Score: ' + score, 20, 40);
  ctx.fillText('Resources: ' + numberOfResources, 20, 80);

  if (gameOver) {
    ctx.fillStyle = 'black';
    ctx.font = '90px Arial';
    ctx.fillText('GAME OVER', 135, 330);
  }

  if (score >= winningScore && enemies.length === 0) {
    ctx.fillStyle = 'black';
    ctx.font = '60px Arial';
    ctx.fillText('LEVEL COMPLETE', 130, 300);
    ctx.font = '30px Arial';
    ctx.fillText('You win with ' + score + ' points!', 134, 340);
  }
}

function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = 'blue';
  ctx.fillRect(0, 0, controlsBar.width, controlsBar.height);
  handleGameGrid();
  handleDefenders();
  handleResources();
  handleProjectiles();
  handleEnemies();
  handleGameStatus();
  frame++;
  if (!gameOver) requestAnimationFrame(animate);
}
animate();

function collision(first, second) {
  if (!(first.x > second.x + second.width ||
        first.x + first.width < second.x ||
        first.y > second.y + second.height ||
        first.y + first.height < second.y)) {
    return true;
  }
}

Try it

TowerDefense.html
style.css
script.js