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
<!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>
body {
background: black;
margin: 0;
}
#myCanvas {
display: block;
width: 100%;
max-width: 900px;
height: auto;
margin: 0 auto;
background: white;
}
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();