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.
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
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:
ycounts the rows andxthe 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.1<!DOCTYPE html>2<html>3 <head>4 <meta charset="utf-8">5 <title>Treasure Maze</title>6 <link rel="stylesheet" href="style.css">7 </head>8 <body>9 <h1>Treasure Maze</h1>10 <canvas id="game" width="480" height="360"></canvas>11 <p id="info">Click the maze, then use the arrow keys.</p>12 <script src="script.js"></script>13 </body>14</html>1body {2 font-family: Arial, sans-serif;3 text-align: center;4 background: #2b2d42;5 color: white;6}7 8canvas {9 border-radius: 8px;10 max-width: 100%;11}1const canvas = document.getElementById("game");2const ctx = canvas.getContext("2d");3const SIZE = 40;4 5// # is a wall, . is floor, P is the player, C is a coin and E is the exit6const level = [7 "############",8 "#P...#....C#",9 "#.##.#.##..#",10 "#.#C...#.#.#",11 "#.####.#.#.#",12 "#......#...#",13 "###.##.#.#.#",14 "#C....#..#E#",15 "############"16];17 18function draw() {19 for (let y = 0; y < level.length; y++) {20 for (let x = 0; x < level[y].length; x++) {21 if (level[y][x] === "#") {22 ctx.fillStyle = "#3d348b";23 } else {24 ctx.fillStyle = "#f7ede2";25 }26 ctx.fillRect(x * SIZE, y * SIZE, SIZE, SIZE);27 }28 }29}30 31draw();The maze, drawn from the text. Step 2: Coins, an exit and you
Strings cannot be changed, and coins will disappear as you collect them, so
loadturns each string into an array of single characters withsplit(""). It also findsP, remembers where the player is, and puts floor there.drawadds gold coins, a brown door and the player.New: lines 17 to 34, 37 to 40, 46 to 55, 58 to 62 and 65.
1const canvas = document.getElementById("game");2const ctx = canvas.getContext("2d");3const SIZE = 40;4 5// # is a wall, . is floor, P is the player, C is a coin and E is the exit6const level = [7 "############",8 "#P...#....C#",9 "#.##.#.##..#",10 "#.#C...#.#.#",11 "#.####.#.#.#",12 "#......#...#",13 "###.##.#.#.#",14 "#C....#..#E#",15 "############"16];17let map = [];18const player = { x: 0, y: 0 };19 20// turn the level into a grid of tiles we can change, and find the player21function load() {22 map = [];23 for (let y = 0; y < level.length; y++) {24 const row = level[y].split("");25 for (let x = 0; x < row.length; x++) {26 if (row[x] === "P") {27 player.x = x;28 player.y = y;29 row[x] = ".";30 }31 }32 map.push(row);33 }34}35 36function draw() {37 for (let y = 0; y < map.length; y++) {38 for (let x = 0; x < map[y].length; x++) {39 const tile = map[y][x];40 if (tile === "#") {41 ctx.fillStyle = "#3d348b";42 } else {43 ctx.fillStyle = "#f7ede2";44 }45 ctx.fillRect(x * SIZE, y * SIZE, SIZE, SIZE);46 if (tile === "C") {47 ctx.fillStyle = "gold";48 ctx.beginPath();49 ctx.arc(x * SIZE + 20, y * SIZE + 20, 10, 0, Math.PI * 2);50 ctx.fill();51 }52 if (tile === "E") {53 ctx.fillStyle = "saddlebrown";54 ctx.fillRect(x * SIZE + 8, y * SIZE + 4, 24, 32);55 }56 }57 }58 // the player59 ctx.fillStyle = "tomato";60 ctx.beginPath();61 ctx.arc(player.x * SIZE + 20, player.y * SIZE + 20, 14, 0, Math.PI * 2);62 ctx.fill();63}64 65load();66draw();Gold coins, the brown exit, and the player in the top left. Step 3: Move with the arrow keys
Each arrow key sets
dxordyto 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.
1const canvas = document.getElementById("game");2const ctx = canvas.getContext("2d");3const SIZE = 40;4 5// # is a wall, . is floor, P is the player, C is a coin and E is the exit6const level = [7 "############",8 "#P...#....C#",9 "#.##.#.##..#",10 "#.#C...#.#.#",11 "#.####.#.#.#",12 "#......#...#",13 "###.##.#.#.#",14 "#C....#..#E#",15 "############"16];17let map = [];18const player = { x: 0, y: 0 };19 20// turn the level into a grid of tiles we can change, and find the player21function load() {22 map = [];23 for (let y = 0; y < level.length; y++) {24 const row = level[y].split("");25 for (let x = 0; x < row.length; x++) {26 if (row[x] === "P") {27 player.x = x;28 player.y = y;29 row[x] = ".";30 }31 }32 map.push(row);33 }34}35 36function draw() {37 for (let y = 0; y < map.length; y++) {38 for (let x = 0; x < map[y].length; x++) {39 const tile = map[y][x];40 if (tile === "#") {41 ctx.fillStyle = "#3d348b";42 } else {43 ctx.fillStyle = "#f7ede2";44 }45 ctx.fillRect(x * SIZE, y * SIZE, SIZE, SIZE);46 if (tile === "C") {47 ctx.fillStyle = "gold";48 ctx.beginPath();49 ctx.arc(x * SIZE + 20, y * SIZE + 20, 10, 0, Math.PI * 2);50 ctx.fill();51 }52 if (tile === "E") {53 ctx.fillStyle = "saddlebrown";54 ctx.fillRect(x * SIZE + 8, y * SIZE + 4, 24, 32);55 }56 }57 }58 // the player59 ctx.fillStyle = "tomato";60 ctx.beginPath();61 ctx.arc(player.x * SIZE + 20, player.y * SIZE + 20, 14, 0, Math.PI * 2);62 ctx.fill();63}64 65document.addEventListener("keydown", function (event) {66 let dx = 0;67 let dy = 0;68 if (event.key === "ArrowLeft") {69 dx = -1;70 }71 if (event.key === "ArrowRight") {72 dx = 1;73 }74 if (event.key === "ArrowUp") {75 dy = -1;76 }77 if (event.key === "ArrowDown") {78 dy = 1;79 }80 if (dx === 0 && dy === 0) {81 return;82 }83 event.preventDefault();84 player.x = player.x + dx;85 player.y = player.y + dy;86 draw();87});88 89load();90draw();Click the maze and press the arrow keys. The walls do not stop you yet. Step 4: Solid walls
Before moving, look at the square you are moving into:
map[y][x]is the tile at rowy, squarex. If it is a wall, do nothing.New: lines 84 to 87.
1const canvas = document.getElementById("game");2const ctx = canvas.getContext("2d");3const SIZE = 40;4 5// # is a wall, . is floor, P is the player, C is a coin and E is the exit6const level = [7 "############",8 "#P...#....C#",9 "#.##.#.##..#",10 "#.#C...#.#.#",11 "#.####.#.#.#",12 "#......#...#",13 "###.##.#.#.#",14 "#C....#..#E#",15 "############"16];17let map = [];18const player = { x: 0, y: 0 };19 20// turn the level into a grid of tiles we can change, and find the player21function load() {22 map = [];23 for (let y = 0; y < level.length; y++) {24 const row = level[y].split("");25 for (let x = 0; x < row.length; x++) {26 if (row[x] === "P") {27 player.x = x;28 player.y = y;29 row[x] = ".";30 }31 }32 map.push(row);33 }34}35 36function draw() {37 for (let y = 0; y < map.length; y++) {38 for (let x = 0; x < map[y].length; x++) {39 const tile = map[y][x];40 if (tile === "#") {41 ctx.fillStyle = "#3d348b";42 } else {43 ctx.fillStyle = "#f7ede2";44 }45 ctx.fillRect(x * SIZE, y * SIZE, SIZE, SIZE);46 if (tile === "C") {47 ctx.fillStyle = "gold";48 ctx.beginPath();49 ctx.arc(x * SIZE + 20, y * SIZE + 20, 10, 0, Math.PI * 2);50 ctx.fill();51 }52 if (tile === "E") {53 ctx.fillStyle = "saddlebrown";54 ctx.fillRect(x * SIZE + 8, y * SIZE + 4, 24, 32);55 }56 }57 }58 // the player59 ctx.fillStyle = "tomato";60 ctx.beginPath();61 ctx.arc(player.x * SIZE + 20, player.y * SIZE + 20, 14, 0, Math.PI * 2);62 ctx.fill();63}64 65document.addEventListener("keydown", function (event) {66 let dx = 0;67 let dy = 0;68 if (event.key === "ArrowLeft") {69 dx = -1;70 }71 if (event.key === "ArrowRight") {72 dx = 1;73 }74 if (event.key === "ArrowUp") {75 dy = -1;76 }77 if (event.key === "ArrowDown") {78 dy = 1;79 }80 if (dx === 0 && dy === 0) {81 return;82 }83 event.preventDefault();84 // walls are solid85 if (map[player.y + dy][player.x + dx] === "#") {86 return;87 }88 player.x = player.x + dx;89 player.y = player.y + dy;90 draw();91});92 93load();94draw();Now the walls are solid. Watch out It ismap[y][x], the row first, then the square across. The other way round finds the wrong square.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.
1const canvas = document.getElementById("game");2const ctx = canvas.getContext("2d");3const SIZE = 40;4 5// # is a wall, . is floor, P is the player, C is a coin and E is the exit6const level = [7 "############",8 "#P...#....C#",9 "#.##.#.##..#",10 "#.#C...#.#.#",11 "#.####.#.#.#",12 "#......#...#",13 "###.##.#.#.#",14 "#C....#..#E#",15 "############"16];17let map = [];18const player = { x: 0, y: 0 };19const info = document.getElementById("info");20let coins = 0;21let moves = 0;22 23// turn the level into a grid of tiles we can change, and find the player24function load() {25 map = [];26 coins = 0;27 for (let y = 0; y < level.length; y++) {28 const row = level[y].split("");29 for (let x = 0; x < row.length; x++) {30 if (row[x] === "P") {31 player.x = x;32 player.y = y;33 row[x] = ".";34 }35 if (row[x] === "C") {36 coins = coins + 1;37 }38 }39 map.push(row);40 }41}42 43function draw() {44 for (let y = 0; y < map.length; y++) {45 for (let x = 0; x < map[y].length; x++) {46 const tile = map[y][x];47 if (tile === "#") {48 ctx.fillStyle = "#3d348b";49 } else {50 ctx.fillStyle = "#f7ede2";51 }52 ctx.fillRect(x * SIZE, y * SIZE, SIZE, SIZE);53 if (tile === "C") {54 ctx.fillStyle = "gold";55 ctx.beginPath();56 ctx.arc(x * SIZE + 20, y * SIZE + 20, 10, 0, Math.PI * 2);57 ctx.fill();58 }59 if (tile === "E") {60 // the exit is locked, brown, until every coin is collected61 if (coins > 0) {62 ctx.fillStyle = "saddlebrown";63 } else {64 ctx.fillStyle = "limegreen";65 }66 ctx.fillRect(x * SIZE + 8, y * SIZE + 4, 24, 32);67 }68 }69 }70 // the player71 ctx.fillStyle = "tomato";72 ctx.beginPath();73 ctx.arc(player.x * SIZE + 20, player.y * SIZE + 20, 14, 0, Math.PI * 2);74 ctx.fill();75 info.textContent = "Coins left: " + coins + ". Moves: " + moves + ".";76}77 78document.addEventListener("keydown", function (event) {79 let dx = 0;80 let dy = 0;81 if (event.key === "ArrowLeft") {82 dx = -1;83 }84 if (event.key === "ArrowRight") {85 dx = 1;86 }87 if (event.key === "ArrowUp") {88 dy = -1;89 }90 if (event.key === "ArrowDown") {91 dy = 1;92 }93 if (dx === 0 && dy === 0) {94 return;95 }96 event.preventDefault();97 const nx = player.x + dx;98 const ny = player.y + dy;99 const tile = map[ny][nx];100 // walls are solid, and the exit is locked while there are coins left101 if (tile === "#" || (tile === "E" && coins > 0)) {102 return;103 }104 player.x = nx;105 player.y = ny;106 moves = moves + 1;107 if (tile === "C") {108 map[ny][nx] = ".";109 coins = coins - 1;110 }111 draw();112});113 114load();115draw();Collect all three coins, and the exit turns green. Step 6: Escape!
Stepping onto the open exit wins.
wonstops the arrow keys, anddrawdarkens the maze and shows how many moves you took.New: lines 22, 77 to 87, 109 to 111 and 126 to 128.
1const canvas = document.getElementById("game");2const ctx = canvas.getContext("2d");3const SIZE = 40;4 5// # is a wall, . is floor, P is the player, C is a coin and E is the exit6const level = [7 "############",8 "#P...#....C#",9 "#.##.#.##..#",10 "#.#C...#.#.#",11 "#.####.#.#.#",12 "#......#...#",13 "###.##.#.#.#",14 "#C....#..#E#",15 "############"16];17let map = [];18const player = { x: 0, y: 0 };19const info = document.getElementById("info");20let coins = 0;21let moves = 0;22let won = false;23 24// turn the level into a grid of tiles we can change, and find the player25function load() {26 map = [];27 coins = 0;28 for (let y = 0; y < level.length; y++) {29 const row = level[y].split("");30 for (let x = 0; x < row.length; x++) {31 if (row[x] === "P") {32 player.x = x;33 player.y = y;34 row[x] = ".";35 }36 if (row[x] === "C") {37 coins = coins + 1;38 }39 }40 map.push(row);41 }42}43 44function draw() {45 for (let y = 0; y < map.length; y++) {46 for (let x = 0; x < map[y].length; x++) {47 const tile = map[y][x];48 if (tile === "#") {49 ctx.fillStyle = "#3d348b";50 } else {51 ctx.fillStyle = "#f7ede2";52 }53 ctx.fillRect(x * SIZE, y * SIZE, SIZE, SIZE);54 if (tile === "C") {55 ctx.fillStyle = "gold";56 ctx.beginPath();57 ctx.arc(x * SIZE + 20, y * SIZE + 20, 10, 0, Math.PI * 2);58 ctx.fill();59 }60 if (tile === "E") {61 // the exit is locked, brown, until every coin is collected62 if (coins > 0) {63 ctx.fillStyle = "saddlebrown";64 } else {65 ctx.fillStyle = "limegreen";66 }67 ctx.fillRect(x * SIZE + 8, y * SIZE + 4, 24, 32);68 }69 }70 }71 // the player72 ctx.fillStyle = "tomato";73 ctx.beginPath();74 ctx.arc(player.x * SIZE + 20, player.y * SIZE + 20, 14, 0, Math.PI * 2);75 ctx.fill();76 info.textContent = "Coins left: " + coins + ". Moves: " + moves + ".";77 if (won) {78 ctx.fillStyle = "rgba(0, 0, 0, 0.6)";79 ctx.fillRect(0, 0, canvas.width, canvas.height);80 ctx.fillStyle = "white";81 ctx.textAlign = "center";82 ctx.font = "bold 44px Arial";83 ctx.fillText("You escaped!", canvas.width / 2, 170);84 ctx.font = "bold 22px Arial";85 ctx.fillText("in " + moves + " moves", canvas.width / 2, 210);86 info.textContent = "You escaped in " + moves + " moves.";87 }88}89 90document.addEventListener("keydown", function (event) {91 let dx = 0;92 let dy = 0;93 if (event.key === "ArrowLeft") {94 dx = -1;95 }96 if (event.key === "ArrowRight") {97 dx = 1;98 }99 if (event.key === "ArrowUp") {100 dy = -1;101 }102 if (event.key === "ArrowDown") {103 dy = 1;104 }105 if (dx === 0 && dy === 0) {106 return;107 }108 event.preventDefault();109 if (won) {110 return;111 }112 const nx = player.x + dx;113 const ny = player.y + dy;114 const tile = map[ny][nx];115 // walls are solid, and the exit is locked while there are coins left116 if (tile === "#" || (tile === "E" && coins > 0)) {117 return;118 }119 player.x = nx;120 player.y = ny;121 moves = moves + 1;122 if (tile === "C") {123 map[ny][nx] = ".";124 coins = coins - 1;125 }126 if (tile === "E") {127 won = true;128 }129 draw();130});131 132load();133draw();Reach the green exit to escape. Step 7: A second maze
Put both mazes in a list called
levels, and keep the number of the current one inlevel. 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.
1const canvas = document.getElementById("game");2const ctx = canvas.getContext("2d");3const SIZE = 40;4 5// # is a wall, . is floor, P is the player, C is a coin and E is the exit6const levels = [7 [8 "############",9 "#P...#....C#",10 "#.##.#.##..#",11 "#.#C...#.#.#",12 "#.####.#.#.#",13 "#......#...#",14 "###.##.#.#.#",15 "#C....#..#E#",16 "############"17 ],18 [19 "############",20 "#P.#...#..C#",21 "#..#.#.#.#.#",22 "#.##.#...#.#",23 "#....###.#.#",24 "##.#...#...#",25 "#C.#.#.#.###",26 "#..#.#C...E#",27 "############"28 ]29];30let map = [];31const player = { x: 0, y: 0 };32const info = document.getElementById("info");33let coins = 0;34let moves = 0;35let won = false;36let level = 0;37 38// turn the level into a grid of tiles we can change, and find the player39function load(n) {40 map = [];41 coins = 0;42 for (let y = 0; y < levels[n].length; y++) {43 const row = levels[n][y].split("");44 for (let x = 0; x < row.length; x++) {45 if (row[x] === "P") {46 player.x = x;47 player.y = y;48 row[x] = ".";49 }50 if (row[x] === "C") {51 coins = coins + 1;52 }53 }54 map.push(row);55 }56}57 58function draw() {59 for (let y = 0; y < map.length; y++) {60 for (let x = 0; x < map[y].length; x++) {61 const tile = map[y][x];62 if (tile === "#") {63 ctx.fillStyle = "#3d348b";64 } else {65 ctx.fillStyle = "#f7ede2";66 }67 ctx.fillRect(x * SIZE, y * SIZE, SIZE, SIZE);68 if (tile === "C") {69 ctx.fillStyle = "gold";70 ctx.beginPath();71 ctx.arc(x * SIZE + 20, y * SIZE + 20, 10, 0, Math.PI * 2);72 ctx.fill();73 }74 if (tile === "E") {75 // the exit is locked, brown, until every coin is collected76 if (coins > 0) {77 ctx.fillStyle = "saddlebrown";78 } else {79 ctx.fillStyle = "limegreen";80 }81 ctx.fillRect(x * SIZE + 8, y * SIZE + 4, 24, 32);82 }83 }84 }85 // the player86 ctx.fillStyle = "tomato";87 ctx.beginPath();88 ctx.arc(player.x * SIZE + 20, player.y * SIZE + 20, 14, 0, Math.PI * 2);89 ctx.fill();90 info.textContent = "Maze " + (level + 1) + ". Coins left: " + coins + ". Moves: " + moves + ".";91 if (won) {92 ctx.fillStyle = "rgba(0, 0, 0, 0.6)";93 ctx.fillRect(0, 0, canvas.width, canvas.height);94 ctx.fillStyle = "white";95 ctx.textAlign = "center";96 ctx.font = "bold 44px Arial";97 ctx.fillText("You escaped both!", canvas.width / 2, 170);98 ctx.font = "bold 22px Arial";99 ctx.fillText("in " + moves + " moves", canvas.width / 2, 210);100 info.textContent = "You escaped both mazes in " + moves + " moves.";101 }102}103 104document.addEventListener("keydown", function (event) {105 let dx = 0;106 let dy = 0;107 if (event.key === "ArrowLeft") {108 dx = -1;109 }110 if (event.key === "ArrowRight") {111 dx = 1;112 }113 if (event.key === "ArrowUp") {114 dy = -1;115 }116 if (event.key === "ArrowDown") {117 dy = 1;118 }119 if (dx === 0 && dy === 0) {120 return;121 }122 event.preventDefault();123 if (won) {124 return;125 }126 const nx = player.x + dx;127 const ny = player.y + dy;128 const tile = map[ny][nx];129 // walls are solid, and the exit is locked while there are coins left130 if (tile === "#" || (tile === "E" && coins > 0)) {131 return;132 }133 player.x = nx;134 player.y = ny;135 moves = moves + 1;136 if (tile === "C") {137 map[ny][nx] = ".";138 coins = coins - 1;139 }140 if (tile === "E") {141 if (level < levels.length - 1) {142 level = level + 1;143 load(level);144 } else {145 won = true;146 }147 }148 draw();149});150 151load(level);152draw();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.
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
Pand oneE. Every string must be exactly 12 characters long.Keys and doors
Add a key,
K, that opens locked doors,D.Show a hint
Keep
let hasKey = false;. Stepping onKsets it to true. ADsquare is solid whilehasKeyis false, just like the locked exit.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
1<!DOCTYPE html>2<html>3 <head>4 <meta charset="utf-8">5 <title>Treasure Maze</title>6 <link rel="stylesheet" href="style.css">7 </head>8 <body>9 <h1>Treasure Maze</h1>10 <canvas id="game" width="480" height="360"></canvas>11 <p id="info">Click the maze, then use the arrow keys.</p>12 <script src="script.js"></script>13 </body>14</html>1body {2 font-family: Arial, sans-serif;3 text-align: center;4 background: #2b2d42;5 color: white;6}7 8canvas {9 border-radius: 8px;10 max-width: 100%;11}1const canvas = document.getElementById("game");2const ctx = canvas.getContext("2d");3const SIZE = 40;4 5// # is a wall, . is floor, P is the player, C is a coin and E is the exit6const levels = [7 [8 "############",9 "#P...#....C#",10 "#.##.#.##..#",11 "#.#C...#.#.#",12 "#.####.#.#.#",13 "#......#...#",14 "###.##.#.#.#",15 "#C....#..#E#",16 "############"17 ],18 [19 "############",20 "#P.#...#..C#",21 "#..#.#.#.#.#",22 "#.##.#...#.#",23 "#....###.#.#",24 "##.#...#...#",25 "#C.#.#.#.###",26 "#..#.#C...E#",27 "############"28 ]29];30let map = [];31const player = { x: 0, y: 0 };32const info = document.getElementById("info");33let coins = 0;34let moves = 0;35let won = false;36let level = 0;37 38// turn the level into a grid of tiles we can change, and find the player39function load(n) {40 map = [];41 coins = 0;42 for (let y = 0; y < levels[n].length; y++) {43 const row = levels[n][y].split("");44 for (let x = 0; x < row.length; x++) {45 if (row[x] === "P") {46 player.x = x;47 player.y = y;48 row[x] = ".";49 }50 if (row[x] === "C") {51 coins = coins + 1;52 }53 }54 map.push(row);55 }56}57 58function draw() {59 for (let y = 0; y < map.length; y++) {60 for (let x = 0; x < map[y].length; x++) {61 const tile = map[y][x];62 if (tile === "#") {63 ctx.fillStyle = "#3d348b";64 } else {65 ctx.fillStyle = "#f7ede2";66 }67 ctx.fillRect(x * SIZE, y * SIZE, SIZE, SIZE);68 if (tile === "C") {69 ctx.fillStyle = "gold";70 ctx.beginPath();71 ctx.arc(x * SIZE + 20, y * SIZE + 20, 10, 0, Math.PI * 2);72 ctx.fill();73 }74 if (tile === "E") {75 // the exit is locked, brown, until every coin is collected76 if (coins > 0) {77 ctx.fillStyle = "saddlebrown";78 } else {79 ctx.fillStyle = "limegreen";80 }81 ctx.fillRect(x * SIZE + 8, y * SIZE + 4, 24, 32);82 }83 }84 }85 // the player86 ctx.fillStyle = "tomato";87 ctx.beginPath();88 ctx.arc(player.x * SIZE + 20, player.y * SIZE + 20, 14, 0, Math.PI * 2);89 ctx.fill();90 info.textContent = "Maze " + (level + 1) + ". Coins left: " + coins + ". Moves: " + moves + ".";91 if (won) {92 ctx.fillStyle = "rgba(0, 0, 0, 0.6)";93 ctx.fillRect(0, 0, canvas.width, canvas.height);94 ctx.fillStyle = "white";95 ctx.textAlign = "center";96 ctx.font = "bold 44px Arial";97 ctx.fillText("You escaped both!", canvas.width / 2, 170);98 ctx.font = "bold 22px Arial";99 ctx.fillText("in " + moves + " moves", canvas.width / 2, 210);100 info.textContent = "You escaped both mazes in " + moves + " moves.";101 }102}103 104document.addEventListener("keydown", function (event) {105 let dx = 0;106 let dy = 0;107 if (event.key === "ArrowLeft") {108 dx = -1;109 }110 if (event.key === "ArrowRight") {111 dx = 1;112 }113 if (event.key === "ArrowUp") {114 dy = -1;115 }116 if (event.key === "ArrowDown") {117 dy = 1;118 }119 if (dx === 0 && dy === 0) {120 return;121 }122 event.preventDefault();123 if (won) {124 return;125 }126 const nx = player.x + dx;127 const ny = player.y + dy;128 const tile = map[ny][nx];129 // walls are solid, and the exit is locked while there are coins left130 if (tile === "#" || (tile === "E" && coins > 0)) {131 return;132 }133 player.x = nx;134 player.y = ny;135 moves = moves + 1;136 if (tile === "C") {137 map[ny][nx] = ".";138 coins = coins - 1;139 }140 if (tile === "E") {141 if (level < levels.length - 1) {142 level = level + 1;143 load(level);144 } else {145 won = true;146 }147 }148 draw();149});150 151load(level);152draw();Notes for the teacher
Timing
- 15 minutes: steps 1 and 2. Nested loops are the big idea: trace them on the board for a tiny 3 by 3 grid.
- 20 minutes: steps 3 to 5.
- 15 minutes: steps 6 and 7, then students design and swap mazes.
Mistakes to look out for
- A row with 11 or 13 characters: the maze draws crooked. Count them!
map[x][y]instead ofmap[y][x].- A coin the player can never reach. Ask students to check each other's mazes.
- 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.