Game making in JavaScript

Treasure Maze

Build a maze from a few lines of text, then collect every coin to unlock the exit. Then design your own.

Day 5 50 to 60 minutes 7 steps Key Stage 3
Start step 1
treasure-maze/index.html

This maze is drawn from text: each # is a wall, each . is floor, C is a coin and E is the exit. Change the letters and you have a new level, which is exactly how many real games store theirs. Collect every coin to open the exit, in as few moves as you can.

You will learn

  • Build a level from a grid of characters
  • Use loops inside loops to draw a grid
  • Move a player one square at a time, with solid walls
  • Use game state to lock and unlock the exit

You will need

  • A computer with a web browser and a keyboard
  • The Web Studio, or Notepad
  • Day 2, for the keyboard

Words to know

grid
Rows and columns of squares, like a chess board.
nested loop
A loop inside another loop: for every row, visit every square in it.
tile
One square of the maze: a wall, floor, a coin or the exit.
level design
Planning a game's maps so they are fun, fair and possible.

Step by step

  1. Step 1: Draw the maze

    Choose Day 5: Treasure Maze. The level is a list of nine strings, twelve characters each: one string a row. Two loops, one inside the other, visit every square: y counts the rows and x the squares across each row. Walls are purple and floor is cream, 40 pixels a square, which makes a maze 480 by 360, the size of the canvas.

    index.htmlHTML
    <!DOCTYPE html><html>  <head>    <meta charset="utf-8">    <title>Treasure Maze</title>    <link rel="stylesheet" href="style.css">  </head>  <body>    <h1>Treasure Maze</h1>    <canvas id="game" width="480" height="360"></canvas>    <p id="info">Click the maze, then use the arrow keys.</p>    <script src="script.js"></script>  </body></html>
    style.cssCSS
    body {  font-family: Arial, sans-serif;  text-align: center;  background: #2b2d42;  color: white;} canvas {  border-radius: 8px;  max-width: 100%;}
    script.jsJavaScript
    const canvas = document.getElementById("game");const ctx = canvas.getContext("2d");const SIZE = 40; // # is a wall, . is floor, P is the player, C is a coin and E is the exitconst level = [  "############",  "#P...#....C#",  "#.##.#.##..#",  "#.#C...#.#.#",  "#.####.#.#.#",  "#......#...#",  "###.##.#.#.#",  "#C....#..#E#",  "############"]; function draw() {  for (let y = 0; y < level.length; y++) {    for (let x = 0; x < level[y].length; x++) {      if (level[y][x] === "#") {        ctx.fillStyle = "#3d348b";      } else {        ctx.fillStyle = "#f7ede2";      }      ctx.fillRect(x * SIZE, y * SIZE, SIZE, SIZE);    }  }} draw();
    treasure-maze/index.html
    The maze, drawn from the text.
  2. Step 2: Coins, an exit and you

    Strings cannot be changed, and coins will disappear as you collect them, so load turns each string into an array of single characters with split(""). It also finds P, remembers where the player is, and puts floor there. draw adds gold coins, a brown door and the player.

    New: lines 17 to 34, 37 to 40, 46 to 55, 58 to 62 and 65.

    script.jsJavaScript
    const canvas = document.getElementById("game");const ctx = canvas.getContext("2d");const SIZE = 40; // # is a wall, . is floor, P is the player, C is a coin and E is the exitconst level = [  "############",  "#P...#....C#",  "#.##.#.##..#",  "#.#C...#.#.#",  "#.####.#.#.#",  "#......#...#",  "###.##.#.#.#",  "#C....#..#E#",  "############"];let map = [];const player = { x: 0, y: 0 }; // turn the level into a grid of tiles we can change, and find the playerfunction load() {  map = [];  for (let y = 0; y < level.length; y++) {    const row = level[y].split("");    for (let x = 0; x < row.length; x++) {      if (row[x] === "P") {        player.x = x;        player.y = y;        row[x] = ".";      }    }    map.push(row);  }} function draw() {  for (let y = 0; y < map.length; y++) {    for (let x = 0; x < map[y].length; x++) {      const tile = map[y][x];      if (tile === "#") {        ctx.fillStyle = "#3d348b";      } else {        ctx.fillStyle = "#f7ede2";      }      ctx.fillRect(x * SIZE, y * SIZE, SIZE, SIZE);      if (tile === "C") {        ctx.fillStyle = "gold";        ctx.beginPath();        ctx.arc(x * SIZE + 20, y * SIZE + 20, 10, 0, Math.PI * 2);        ctx.fill();      }      if (tile === "E") {        ctx.fillStyle = "saddlebrown";        ctx.fillRect(x * SIZE + 8, y * SIZE + 4, 24, 32);      }    }  }  // the player  ctx.fillStyle = "tomato";  ctx.beginPath();  ctx.arc(player.x * SIZE + 20, player.y * SIZE + 20, 14, 0, Math.PI * 2);  ctx.fill();} load();draw();
    treasure-maze/index.html
    Gold coins, the brown exit, and the player in the top left.
  3. Step 3: Move with the arrow keys

    Each arrow key sets dx or dy to 1 or minus 1: which way to move across and down. The player moves one square, and the maze is drawn again. Try it: you can walk straight through the walls!

    New: lines 65 to 88.

    script.jsJavaScript
    const canvas = document.getElementById("game");const ctx = canvas.getContext("2d");const SIZE = 40; // # is a wall, . is floor, P is the player, C is a coin and E is the exitconst level = [  "############",  "#P...#....C#",  "#.##.#.##..#",  "#.#C...#.#.#",  "#.####.#.#.#",  "#......#...#",  "###.##.#.#.#",  "#C....#..#E#",  "############"];let map = [];const player = { x: 0, y: 0 }; // turn the level into a grid of tiles we can change, and find the playerfunction load() {  map = [];  for (let y = 0; y < level.length; y++) {    const row = level[y].split("");    for (let x = 0; x < row.length; x++) {      if (row[x] === "P") {        player.x = x;        player.y = y;        row[x] = ".";      }    }    map.push(row);  }} function draw() {  for (let y = 0; y < map.length; y++) {    for (let x = 0; x < map[y].length; x++) {      const tile = map[y][x];      if (tile === "#") {        ctx.fillStyle = "#3d348b";      } else {        ctx.fillStyle = "#f7ede2";      }      ctx.fillRect(x * SIZE, y * SIZE, SIZE, SIZE);      if (tile === "C") {        ctx.fillStyle = "gold";        ctx.beginPath();        ctx.arc(x * SIZE + 20, y * SIZE + 20, 10, 0, Math.PI * 2);        ctx.fill();      }      if (tile === "E") {        ctx.fillStyle = "saddlebrown";        ctx.fillRect(x * SIZE + 8, y * SIZE + 4, 24, 32);      }    }  }  // the player  ctx.fillStyle = "tomato";  ctx.beginPath();  ctx.arc(player.x * SIZE + 20, player.y * SIZE + 20, 14, 0, Math.PI * 2);  ctx.fill();} document.addEventListener("keydown", function (event) {  let dx = 0;  let dy = 0;  if (event.key === "ArrowLeft") {    dx = -1;  }  if (event.key === "ArrowRight") {    dx = 1;  }  if (event.key === "ArrowUp") {    dy = -1;  }  if (event.key === "ArrowDown") {    dy = 1;  }  if (dx === 0 && dy === 0) {    return;  }  event.preventDefault();  player.x = player.x + dx;  player.y = player.y + dy;  draw();}); load();draw();
    treasure-maze/index.html
    Click the maze and press the arrow keys. The walls do not stop you yet.
  4. Step 4: Solid walls

    Before moving, look at the square you are moving into: map[y][x] is the tile at row y, square x. If it is a wall, do nothing.

    New: lines 84 to 87.

    script.jsJavaScript
    const canvas = document.getElementById("game");const ctx = canvas.getContext("2d");const SIZE = 40; // # is a wall, . is floor, P is the player, C is a coin and E is the exitconst level = [  "############",  "#P...#....C#",  "#.##.#.##..#",  "#.#C...#.#.#",  "#.####.#.#.#",  "#......#...#",  "###.##.#.#.#",  "#C....#..#E#",  "############"];let map = [];const player = { x: 0, y: 0 }; // turn the level into a grid of tiles we can change, and find the playerfunction load() {  map = [];  for (let y = 0; y < level.length; y++) {    const row = level[y].split("");    for (let x = 0; x < row.length; x++) {      if (row[x] === "P") {        player.x = x;        player.y = y;        row[x] = ".";      }    }    map.push(row);  }} function draw() {  for (let y = 0; y < map.length; y++) {    for (let x = 0; x < map[y].length; x++) {      const tile = map[y][x];      if (tile === "#") {        ctx.fillStyle = "#3d348b";      } else {        ctx.fillStyle = "#f7ede2";      }      ctx.fillRect(x * SIZE, y * SIZE, SIZE, SIZE);      if (tile === "C") {        ctx.fillStyle = "gold";        ctx.beginPath();        ctx.arc(x * SIZE + 20, y * SIZE + 20, 10, 0, Math.PI * 2);        ctx.fill();      }      if (tile === "E") {        ctx.fillStyle = "saddlebrown";        ctx.fillRect(x * SIZE + 8, y * SIZE + 4, 24, 32);      }    }  }  // the player  ctx.fillStyle = "tomato";  ctx.beginPath();  ctx.arc(player.x * SIZE + 20, player.y * SIZE + 20, 14, 0, Math.PI * 2);  ctx.fill();} document.addEventListener("keydown", function (event) {  let dx = 0;  let dy = 0;  if (event.key === "ArrowLeft") {    dx = -1;  }  if (event.key === "ArrowRight") {    dx = 1;  }  if (event.key === "ArrowUp") {    dy = -1;  }  if (event.key === "ArrowDown") {    dy = 1;  }  if (dx === 0 && dy === 0) {    return;  }  event.preventDefault();  // walls are solid  if (map[player.y + dy][player.x + dx] === "#") {    return;  }  player.x = player.x + dx;  player.y = player.y + dy;  draw();}); load();draw();
    treasure-maze/index.html
    Now the walls are solid.
    Watch out It is map[y][x], the row first, then the square across. The other way round finds the wrong square.
  5. Step 5: Collect the coins

    Count the coins as the level loads. Stepping on a coin turns it into floor and takes one off the count. The exit stays shut while any coins are left: brown means locked, and it turns green when you have them all. The line under the maze shows the coins left and your moves.

    New: lines 19 to 21, 26, 34 to 36, 60 to 65, 75, 97 to 101 and 104 to 110.

    script.jsJavaScript
    const canvas = document.getElementById("game");const ctx = canvas.getContext("2d");const SIZE = 40; // # is a wall, . is floor, P is the player, C is a coin and E is the exitconst level = [  "############",  "#P...#....C#",  "#.##.#.##..#",  "#.#C...#.#.#",  "#.####.#.#.#",  "#......#...#",  "###.##.#.#.#",  "#C....#..#E#",  "############"];let map = [];const player = { x: 0, y: 0 };const info = document.getElementById("info");let coins = 0;let moves = 0; // turn the level into a grid of tiles we can change, and find the playerfunction load() {  map = [];  coins = 0;  for (let y = 0; y < level.length; y++) {    const row = level[y].split("");    for (let x = 0; x < row.length; x++) {      if (row[x] === "P") {        player.x = x;        player.y = y;        row[x] = ".";      }      if (row[x] === "C") {        coins = coins + 1;      }    }    map.push(row);  }} function draw() {  for (let y = 0; y < map.length; y++) {    for (let x = 0; x < map[y].length; x++) {      const tile = map[y][x];      if (tile === "#") {        ctx.fillStyle = "#3d348b";      } else {        ctx.fillStyle = "#f7ede2";      }      ctx.fillRect(x * SIZE, y * SIZE, SIZE, SIZE);      if (tile === "C") {        ctx.fillStyle = "gold";        ctx.beginPath();        ctx.arc(x * SIZE + 20, y * SIZE + 20, 10, 0, Math.PI * 2);        ctx.fill();      }      if (tile === "E") {        // the exit is locked, brown, until every coin is collected        if (coins > 0) {          ctx.fillStyle = "saddlebrown";        } else {          ctx.fillStyle = "limegreen";        }        ctx.fillRect(x * SIZE + 8, y * SIZE + 4, 24, 32);      }    }  }  // the player  ctx.fillStyle = "tomato";  ctx.beginPath();  ctx.arc(player.x * SIZE + 20, player.y * SIZE + 20, 14, 0, Math.PI * 2);  ctx.fill();  info.textContent = "Coins left: " + coins + ". Moves: " + moves + ".";} document.addEventListener("keydown", function (event) {  let dx = 0;  let dy = 0;  if (event.key === "ArrowLeft") {    dx = -1;  }  if (event.key === "ArrowRight") {    dx = 1;  }  if (event.key === "ArrowUp") {    dy = -1;  }  if (event.key === "ArrowDown") {    dy = 1;  }  if (dx === 0 && dy === 0) {    return;  }  event.preventDefault();  const nx = player.x + dx;  const ny = player.y + dy;  const tile = map[ny][nx];  // walls are solid, and the exit is locked while there are coins left  if (tile === "#" || (tile === "E" && coins > 0)) {    return;  }  player.x = nx;  player.y = ny;  moves = moves + 1;  if (tile === "C") {    map[ny][nx] = ".";    coins = coins - 1;  }  draw();}); load();draw();
    treasure-maze/index.html
    Collect all three coins, and the exit turns green.
  6. Step 6: Escape!

    Stepping onto the open exit wins. won stops the arrow keys, and draw darkens the maze and shows how many moves you took.

    New: lines 22, 77 to 87, 109 to 111 and 126 to 128.

    script.jsJavaScript
    const canvas = document.getElementById("game");const ctx = canvas.getContext("2d");const SIZE = 40; // # is a wall, . is floor, P is the player, C is a coin and E is the exitconst level = [  "############",  "#P...#....C#",  "#.##.#.##..#",  "#.#C...#.#.#",  "#.####.#.#.#",  "#......#...#",  "###.##.#.#.#",  "#C....#..#E#",  "############"];let map = [];const player = { x: 0, y: 0 };const info = document.getElementById("info");let coins = 0;let moves = 0;let won = false; // turn the level into a grid of tiles we can change, and find the playerfunction load() {  map = [];  coins = 0;  for (let y = 0; y < level.length; y++) {    const row = level[y].split("");    for (let x = 0; x < row.length; x++) {      if (row[x] === "P") {        player.x = x;        player.y = y;        row[x] = ".";      }      if (row[x] === "C") {        coins = coins + 1;      }    }    map.push(row);  }} function draw() {  for (let y = 0; y < map.length; y++) {    for (let x = 0; x < map[y].length; x++) {      const tile = map[y][x];      if (tile === "#") {        ctx.fillStyle = "#3d348b";      } else {        ctx.fillStyle = "#f7ede2";      }      ctx.fillRect(x * SIZE, y * SIZE, SIZE, SIZE);      if (tile === "C") {        ctx.fillStyle = "gold";        ctx.beginPath();        ctx.arc(x * SIZE + 20, y * SIZE + 20, 10, 0, Math.PI * 2);        ctx.fill();      }      if (tile === "E") {        // the exit is locked, brown, until every coin is collected        if (coins > 0) {          ctx.fillStyle = "saddlebrown";        } else {          ctx.fillStyle = "limegreen";        }        ctx.fillRect(x * SIZE + 8, y * SIZE + 4, 24, 32);      }    }  }  // the player  ctx.fillStyle = "tomato";  ctx.beginPath();  ctx.arc(player.x * SIZE + 20, player.y * SIZE + 20, 14, 0, Math.PI * 2);  ctx.fill();  info.textContent = "Coins left: " + coins + ". Moves: " + moves + ".";  if (won) {    ctx.fillStyle = "rgba(0, 0, 0, 0.6)";    ctx.fillRect(0, 0, canvas.width, canvas.height);    ctx.fillStyle = "white";    ctx.textAlign = "center";    ctx.font = "bold 44px Arial";    ctx.fillText("You escaped!", canvas.width / 2, 170);    ctx.font = "bold 22px Arial";    ctx.fillText("in " + moves + " moves", canvas.width / 2, 210);    info.textContent = "You escaped in " + moves + " moves.";  }} document.addEventListener("keydown", function (event) {  let dx = 0;  let dy = 0;  if (event.key === "ArrowLeft") {    dx = -1;  }  if (event.key === "ArrowRight") {    dx = 1;  }  if (event.key === "ArrowUp") {    dy = -1;  }  if (event.key === "ArrowDown") {    dy = 1;  }  if (dx === 0 && dy === 0) {    return;  }  event.preventDefault();  if (won) {    return;  }  const nx = player.x + dx;  const ny = player.y + dy;  const tile = map[ny][nx];  // walls are solid, and the exit is locked while there are coins left  if (tile === "#" || (tile === "E" && coins > 0)) {    return;  }  player.x = nx;  player.y = ny;  moves = moves + 1;  if (tile === "C") {    map[ny][nx] = ".";    coins = coins - 1;  }  if (tile === "E") {    won = true;  }  draw();}); load();draw();
    treasure-maze/index.html
    Reach the green exit to escape.
  7. Step 7: A second maze

    Put both mazes in a list called levels, and keep the number of the current one in level. The exit of the first maze loads the second, and the exit of the last one wins. Adding a third maze now takes no new code at all: just another nine strings.

    New: lines 6 to 28, 36, 39, 42, 43, 90, 97, 100, 141 to 146 and 151.

    script.jsJavaScript
    const canvas = document.getElementById("game");const ctx = canvas.getContext("2d");const SIZE = 40; // # is a wall, . is floor, P is the player, C is a coin and E is the exitconst levels = [  [    "############",    "#P...#....C#",    "#.##.#.##..#",    "#.#C...#.#.#",    "#.####.#.#.#",    "#......#...#",    "###.##.#.#.#",    "#C....#..#E#",    "############"  ],  [    "############",    "#P.#...#..C#",    "#..#.#.#.#.#",    "#.##.#...#.#",    "#....###.#.#",    "##.#...#...#",    "#C.#.#.#.###",    "#..#.#C...E#",    "############"  ]];let map = [];const player = { x: 0, y: 0 };const info = document.getElementById("info");let coins = 0;let moves = 0;let won = false;let level = 0; // turn the level into a grid of tiles we can change, and find the playerfunction load(n) {  map = [];  coins = 0;  for (let y = 0; y < levels[n].length; y++) {    const row = levels[n][y].split("");    for (let x = 0; x < row.length; x++) {      if (row[x] === "P") {        player.x = x;        player.y = y;        row[x] = ".";      }      if (row[x] === "C") {        coins = coins + 1;      }    }    map.push(row);  }} function draw() {  for (let y = 0; y < map.length; y++) {    for (let x = 0; x < map[y].length; x++) {      const tile = map[y][x];      if (tile === "#") {        ctx.fillStyle = "#3d348b";      } else {        ctx.fillStyle = "#f7ede2";      }      ctx.fillRect(x * SIZE, y * SIZE, SIZE, SIZE);      if (tile === "C") {        ctx.fillStyle = "gold";        ctx.beginPath();        ctx.arc(x * SIZE + 20, y * SIZE + 20, 10, 0, Math.PI * 2);        ctx.fill();      }      if (tile === "E") {        // the exit is locked, brown, until every coin is collected        if (coins > 0) {          ctx.fillStyle = "saddlebrown";        } else {          ctx.fillStyle = "limegreen";        }        ctx.fillRect(x * SIZE + 8, y * SIZE + 4, 24, 32);      }    }  }  // the player  ctx.fillStyle = "tomato";  ctx.beginPath();  ctx.arc(player.x * SIZE + 20, player.y * SIZE + 20, 14, 0, Math.PI * 2);  ctx.fill();  info.textContent = "Maze " + (level + 1) + ". Coins left: " + coins + ". Moves: " + moves + ".";  if (won) {    ctx.fillStyle = "rgba(0, 0, 0, 0.6)";    ctx.fillRect(0, 0, canvas.width, canvas.height);    ctx.fillStyle = "white";    ctx.textAlign = "center";    ctx.font = "bold 44px Arial";    ctx.fillText("You escaped both!", canvas.width / 2, 170);    ctx.font = "bold 22px Arial";    ctx.fillText("in " + moves + " moves", canvas.width / 2, 210);    info.textContent = "You escaped both mazes in " + moves + " moves.";  }} document.addEventListener("keydown", function (event) {  let dx = 0;  let dy = 0;  if (event.key === "ArrowLeft") {    dx = -1;  }  if (event.key === "ArrowRight") {    dx = 1;  }  if (event.key === "ArrowUp") {    dy = -1;  }  if (event.key === "ArrowDown") {    dy = 1;  }  if (dx === 0 && dy === 0) {    return;  }  event.preventDefault();  if (won) {    return;  }  const nx = player.x + dx;  const ny = player.y + dy;  const tile = map[ny][nx];  // walls are solid, and the exit is locked while there are coins left  if (tile === "#" || (tile === "E" && coins > 0)) {    return;  }  player.x = nx;  player.y = ny;  moves = moves + 1;  if (tile === "C") {    map[ny][nx] = ".";    coins = coins - 1;  }  if (tile === "E") {    if (level < levels.length - 1) {      level = level + 1;      load(level);    } else {      won = true;    }  }  draw();}); load(level);draw();
    treasure-maze/index.html
    The finished Treasure Maze: two mazes to escape.

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. Your own maze

    Design a third maze and add it to the list.

    Show a hint

    Plan it on squared paper first: 12 squares across and 9 down, with walls all round the edge, one P and one E. Every string must be exactly 12 characters long.

  2. Keys and doors

    Add a key, K, that opens locked doors, D.

    Show a hint

    Keep let hasKey = false;. Stepping on K sets it to true. A D square is solid while hasKey is false, just like the locked exit.

  3. Enemies

    Add a ghost, G, that moves one square towards the player after every move.

    Show a hint

    After the player moves, compare the ghost's x and y with the player's and move it one square closer, unless a wall is in the way. If it lands on the player, restart the level.

The finished code

Show the whole game
index.htmlHTML
<!DOCTYPE html><html>  <head>    <meta charset="utf-8">    <title>Treasure Maze</title>    <link rel="stylesheet" href="style.css">  </head>  <body>    <h1>Treasure Maze</h1>    <canvas id="game" width="480" height="360"></canvas>    <p id="info">Click the maze, then use the arrow keys.</p>    <script src="script.js"></script>  </body></html>
style.cssCSS
body {  font-family: Arial, sans-serif;  text-align: center;  background: #2b2d42;  color: white;} canvas {  border-radius: 8px;  max-width: 100%;}
script.jsJavaScript
const canvas = document.getElementById("game");const ctx = canvas.getContext("2d");const SIZE = 40; // # is a wall, . is floor, P is the player, C is a coin and E is the exitconst levels = [  [    "############",    "#P...#....C#",    "#.##.#.##..#",    "#.#C...#.#.#",    "#.####.#.#.#",    "#......#...#",    "###.##.#.#.#",    "#C....#..#E#",    "############"  ],  [    "############",    "#P.#...#..C#",    "#..#.#.#.#.#",    "#.##.#...#.#",    "#....###.#.#",    "##.#...#...#",    "#C.#.#.#.###",    "#..#.#C...E#",    "############"  ]];let map = [];const player = { x: 0, y: 0 };const info = document.getElementById("info");let coins = 0;let moves = 0;let won = false;let level = 0; // turn the level into a grid of tiles we can change, and find the playerfunction load(n) {  map = [];  coins = 0;  for (let y = 0; y < levels[n].length; y++) {    const row = levels[n][y].split("");    for (let x = 0; x < row.length; x++) {      if (row[x] === "P") {        player.x = x;        player.y = y;        row[x] = ".";      }      if (row[x] === "C") {        coins = coins + 1;      }    }    map.push(row);  }} function draw() {  for (let y = 0; y < map.length; y++) {    for (let x = 0; x < map[y].length; x++) {      const tile = map[y][x];      if (tile === "#") {        ctx.fillStyle = "#3d348b";      } else {        ctx.fillStyle = "#f7ede2";      }      ctx.fillRect(x * SIZE, y * SIZE, SIZE, SIZE);      if (tile === "C") {        ctx.fillStyle = "gold";        ctx.beginPath();        ctx.arc(x * SIZE + 20, y * SIZE + 20, 10, 0, Math.PI * 2);        ctx.fill();      }      if (tile === "E") {        // the exit is locked, brown, until every coin is collected        if (coins > 0) {          ctx.fillStyle = "saddlebrown";        } else {          ctx.fillStyle = "limegreen";        }        ctx.fillRect(x * SIZE + 8, y * SIZE + 4, 24, 32);      }    }  }  // the player  ctx.fillStyle = "tomato";  ctx.beginPath();  ctx.arc(player.x * SIZE + 20, player.y * SIZE + 20, 14, 0, Math.PI * 2);  ctx.fill();  info.textContent = "Maze " + (level + 1) + ". Coins left: " + coins + ". Moves: " + moves + ".";  if (won) {    ctx.fillStyle = "rgba(0, 0, 0, 0.6)";    ctx.fillRect(0, 0, canvas.width, canvas.height);    ctx.fillStyle = "white";    ctx.textAlign = "center";    ctx.font = "bold 44px Arial";    ctx.fillText("You escaped both!", canvas.width / 2, 170);    ctx.font = "bold 22px Arial";    ctx.fillText("in " + moves + " moves", canvas.width / 2, 210);    info.textContent = "You escaped both mazes in " + moves + " moves.";  }} document.addEventListener("keydown", function (event) {  let dx = 0;  let dy = 0;  if (event.key === "ArrowLeft") {    dx = -1;  }  if (event.key === "ArrowRight") {    dx = 1;  }  if (event.key === "ArrowUp") {    dy = -1;  }  if (event.key === "ArrowDown") {    dy = 1;  }  if (dx === 0 && dy === 0) {    return;  }  event.preventDefault();  if (won) {    return;  }  const nx = player.x + dx;  const ny = player.y + dy;  const tile = map[ny][nx];  // walls are solid, and the exit is locked while there are coins left  if (tile === "#" || (tile === "E" && coins > 0)) {    return;  }  player.x = nx;  player.y = ny;  moves = moves + 1;  if (tile === "C") {    map[ny][nx] = ".";    coins = coins - 1;  }  if (tile === "E") {    if (level < levels.length - 1) {      level = level + 1;      load(level);    } else {      won = true;    }  }  draw();}); load(level);draw();
Notes for the teacher

Timing

  1. 15 minutes: steps 1 and 2. Nested loops are the big idea: trace them on the board for a tiny 3 by 3 grid.
  2. 20 minutes: steps 3 to 5.
  3. 15 minutes: steps 6 and 7, then students design and swap mazes.

Mistakes to look out for

  1. A row with 11 or 13 characters: the maze draws crooked. Count them!
  2. map[x][y] instead of map[y][x].
  3. A coin the player can never reach. Ask students to check each other's mazes.
  4. The arrow keys scroll the page instead of moving the player: the game must be clicked first.

Going further

A level stored as text is data, kept apart from the code that plays it. Professional games load their levels from files in just this way, and some let players build and share their own.