JavaScript Project for Beginners: Maze Game
In this code, the maze is represented as a 2D array, where 0 is an empty space and 1 is a wall. The player starts at (1, 1) and the goal is at (3, 3). It is a fun javascript project for beginners and a handy source of javascript exercises for beginners. Read the code, play the live demo, then solve the practice exercises.
How the JavaScript Maze Game Works
The maze is a 2D array. The player’s starting position is set to (1, 1) and the goal position is set to (3, 3). The displayMaze() function prints the current state of the maze, with the player shown as P and the goal as G. The movePlayer() function handles movement, and a keydown listener connects the arrow keys to it.
If you are searching for a javascript project for beginners, javascript exercises for beginners, javascript tasks for practice or quick js exercises you can finish in one sitting, this maze game fits all three. The sections below cover the code, the HTML version, a playable demo with random mazes, and javascript practice exercises with solutions.
What the finished project does
- Stores the maze as a grid of numbers and draws it as text.
- Moves the player only into empty cells inside the boundaries.
- Detects the goal and congratulates the player.
- Runs in two places: in the browser console and on a web page.
alert() for every wall bump, which is annoying, so messages now appear on the page. The arrow keys also scrolled the page while you played, so the handler calls event.preventDefault(). In the console version, the keyboard code is wrapped in a check so the file does not crash in Node.js, where document does not exist.Step 1: Define the Maze and Display It
Define the maze grid, the player’s starting position and the goal position, then write displayMaze(). It loops through every row and column and builds a line of text: P for the player, G for the goal, # for a wall and a blank for an empty space. These variables (maze, playerPosition, goalPosition) also make a neat set of javascript variables exercises.
// Define the maze grid (1 = wall, 0 = empty space)
const maze = [
[1, 1, 1, 1, 1],
[1, 0, 0, 0, 1],
[1, 1, 1, 0, 1],
[1, 0, 0, 0, 1],
[1, 1, 1, 1, 1]
];
// Define the player's starting position
let playerPosition = {
x: 1,
y: 1
};
// Define the goal position
const goalPosition = {
x: 3,
y: 3
};
// Function to display the maze
function displayMaze() {
for (let i = 0; i < maze.length; i++) {
let row = '';
for (let j = 0; j < maze[i].length; j++) {
if (i === playerPosition.y && j === playerPosition.x) {
row += 'P '; // Display the player
} else if (i === goalPosition.y && j === goalPosition.x) {
row += 'G '; // Display the goal
} else if (maze[i][j] === 1) {
row += '# '; // Display walls
} else {
row += ' '; // Display empty spaces
}
}
console.log(row);
}
}Calling displayMaze() prints the starting board:
# # # # #
# P #
# # # #
# G #
# # # # # Step 2: The movePlayer() Function
The movePlayer() function is responsible for handling the player’s movement. It calculates the new position from the player’s current position and a direction parameter (up, down, left or right). It then checks that the new position is inside the maze’s boundaries and is not a wall. If the move is legitimate, the player’s position is updated, the maze is shown again, and the function determines whether the player has reached the goal. This is a perfect javascript function exercise.
// Function to move the player
function movePlayer(direction) {
let newPosition = {
x: playerPosition.x,
y: playerPosition.y
};
switch (direction) {
case 'up':
newPosition.y -= 1;
break;
case 'down':
newPosition.y += 1;
break;
case 'left':
newPosition.x -= 1;
break;
case 'right':
newPosition.x += 1;
break;
}
// Check if the new position is within the maze boundaries and not a wall
if (
newPosition.x >= 0 &&
newPosition.x < maze[0].length &&
newPosition.y >= 0 &&
newPosition.y < maze.length &&
maze[newPosition.y][newPosition.x] === 0
) {
playerPosition = newPosition;
displayMaze();
// Check if the player reached the goal
if (
playerPosition.x === goalPosition.x &&
playerPosition.y === goalPosition.y
) {
console.log('Congratulations! You reached the goal!');
}
} else {
console.log('Invalid move!');
}
}Step 3: Handle Keyboard Input and Run It
The keydown event listener handles user input in the final section of the code. It monitors the arrow keys and calls movePlayer() when necessary. Paste all three parts into your browser’s console, click the page, and press the arrow keys.
// Display the initial maze
displayMaze();
// Handle user input (this part needs a browser)
if (typeof document !== 'undefined') {
document.addEventListener('keydown', function (event) {
switch (event.key) {
case 'ArrowUp':
movePlayer('up');
break;
case 'ArrowDown':
movePlayer('down');
break;
case 'ArrowLeft':
movePlayer('left');
break;
case 'ArrowRight':
movePlayer('right');
break;
}
});
}You can also test the game logic without a keyboard, for example by calling movePlayer('right') twice, then movePlayer('down') twice, to reach the goal.
Step 4: Maze Game HTML Code + JavaScript
This code can be executed in a web browser console or in an HTML file that also contains JavaScript. The maze will be visible, and you can use the arrow keys to find your way out of it and accomplish your goal.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Maze Game</title>
<style>
pre { font-family: monospace; font-size: 1.5rem; }
</style>
</head>
<body>
<pre id="maze"></pre>
<p id="message">Use the arrow keys to reach G.</p>
<script>
// Define the maze grid
const maze = [
[1, 1, 1, 1, 1],
[1, 0, 0, 0, 1],
[1, 1, 1, 0, 1],
[1, 0, 0, 0, 1],
[1, 1, 1, 1, 1]
];
// Define the player's starting position
let playerPosition = { x: 1, y: 1 };
// Define the goal position
const goalPosition = { x: 3, y: 3 };
// Function to display the maze
function displayMaze() {
let mazeText = '';
for (let i = 0; i < maze.length; i++) {
let row = '';
for (let j = 0; j < maze[i].length; j++) {
if (i === playerPosition.y && j === playerPosition.x) {
row += 'P '; // Display the player
} else if (i === goalPosition.y && j === goalPosition.x) {
row += 'G '; // Display the goal
} else if (maze[i][j] === 1) {
row += '# '; // Display walls
} else {
row += ' '; // Display empty spaces
}
}
mazeText += row + '\n';
}
document.getElementById('maze').textContent = mazeText;
}
// Show a message on the page instead of an alert() pop-up
function setMessage(text) {
document.getElementById('message').textContent = text;
}
// Function to move the player
function movePlayer(direction) {
let newPosition = { x: playerPosition.x, y: playerPosition.y };
switch (direction) {
case 'up': newPosition.y -= 1; break;
case 'down': newPosition.y += 1; break;
case 'left': newPosition.x -= 1; break;
case 'right': newPosition.x += 1; break;
}
// Check if the new position is within the maze boundaries and not a wall
if (
newPosition.x >= 0 &&
newPosition.x < maze[0].length &&
newPosition.y >= 0 &&
newPosition.y < maze.length &&
maze[newPosition.y][newPosition.x] === 0
) {
playerPosition = newPosition;
displayMaze();
setMessage('Use the arrow keys to reach G.');
// Check if the player reached the goal
if (
playerPosition.x === goalPosition.x &&
playerPosition.y === goalPosition.y
) {
setMessage('Congratulations! You reached the goal!');
}
} else {
setMessage('Invalid move!');
}
}
// Display the initial maze
displayMaze();
// Handle user input
document.addEventListener('keydown', function (event) {
const keys = {
ArrowUp: 'up',
ArrowDown: 'down',
ArrowLeft: 'left',
ArrowRight: 'right'
};
if (keys[event.key]) {
event.preventDefault(); // stop the arrow keys from scrolling the page
movePlayer(keys[event.key]);
}
});
</script>
</body>
</html>Live Demo: Play the Maze Game
This demo uses the same movement logic as the code above, plus a move counter, a timer and random mazes from the Depth-First Search code in Step 5. Click the maze, then use the arrow keys or WASD, or tap the buttons on a phone.
Step 5: How to Create a Maze in JavaScript
So far the maze was typed by hand. To create a maze in JS, use the grid-based approach: represent the maze as a 2D grid of cells, start with all walls, and use Depth-First Search to carve a random path. The result is a maze with exactly one route between any two cells, so it is always solvable. The Random buttons in the demo use this function.
function generateMaze(cols, rows) { // cols and rows must be odd numbers
// Start with a grid that is all walls
const grid = Array.from({ length: rows }, () => Array(cols).fill(1));
const stack = [[1, 1]];
grid[1][1] = 0;
while (stack.length) {
const [x, y] = stack[stack.length - 1];
const dirs = [[2, 0], [-2, 0], [0, 2], [0, -2]].sort(() => Math.random() - 0.5);
let carved = false;
for (const [dx, dy] of dirs) {
const nx = x + dx;
const ny = y + dy;
if (nx > 0 && ny > 0 && nx < cols - 1 && ny < rows - 1 && grid[ny][nx] === 1) {
grid[y + dy / 2][x + dx / 2] = 0; // knock down the wall in between
grid[ny][nx] = 0;
stack.push([nx, ny]);
carved = true;
break;
}
}
if (!carved) stack.pop(); // dead end: backtrack
}
return grid;
}
// Example: an 11 x 11 maze, goal at the bottom-right corner
const maze = generateMaze(11, 11);
const goalPosition = { x: 9, y: 9 };The other main approach is raycasting, which simulates light rays travelling through the maze to draw a 3D-like perspective. Libraries like p5.js and Three.js can help, especially for 3D. The FAQ below explains maze code in more detail.
Keep Going: Turn the Maze into a Portfolio Piece
So, you’ve conquered the maze and emerged victorious (or maybe you enjoyed a scenic detour through every dead end). Congratulations! This JavaScript project has not only provided a fun and engaging challenge, but also honed your web development skills in building a classic game.
- Publish the code on GitHub with a README and a screenshot, and host the live demo on GitHub Pages.
- Add multiple difficulty levels by letting players choose the maze size.
- Add collectibles inside the maze, such as coins that increase a score.
- Add a timer for a fast-paced mode, and save the best time with
localStorage.
The possibilities are endless, so keep coding, keep experimenting and, most importantly, keep having fun. Happy maze-ing!
JavaScript Exercises and Solutions Based on the Maze Game
The maze game is a great source of javascript exercises because every part practices a core idea. If you want javascript practice exercises with solutions, try each task yourself first, then open the solution to compare. These js exercises build on each other, from variables to functions to game state.
Javascript variables exercises and function exercises
Begin with exercise 1 (variables) and exercise 2 (functions). They are classic javascript exercises for beginners and take only a few minutes each.
1. Variables: count the walls
A javascript variables exercise: store the maze in a variable and count how many cells are walls.
const maze = [[1, 1, 1], [1, 0, 1], [1, 1, 1]];
let walls = 0;
for (const row of maze) {
for (const cell of row) {
if (cell === 1) walls++;
}
}
console.log(walls); // 82. Function: is this cell a wall?
A javascript function exercise: write isWall(maze, x, y) that also treats cells outside the maze as walls.
function isWall(maze, x, y) {
return maze[y] === undefined || maze[y][x] !== 0;
}
const small = [[1, 1], [1, 0]];
console.log(isWall(small, 1, 1)); // false
console.log(isWall(small, 5, 5)); // true3. Task: play a list of moves
One of the quickest javascript tasks for practice: run the winning route automatically after loading the code from Step 2.
const route = ['right', 'right', 'down', 'down'];
route.forEach((step) => movePlayer(step));
// ends with: Congratulations! You reached the goal!4. Challenge: count the moves
A js exercise with state: add a counter that increases after every valid move.
let moves = 0;
// inside movePlayer(), right after playerPosition = newPosition;
moves++;
console.log('Moves: ' + moves);5. Challenge: distance to the goal
Return the number of steps in a straight line (Manhattan distance) between the player and the goal.
const distance = (a, b) => Math.abs(a.x - b.x) + Math.abs(a.y - b.y);
console.log(distance({ x: 1, y: 1 }, { x: 3, y: 3 })); // 4Looking for more javascript exercises and solutions? Browse our JavaScript projects and the free PDF practice sets.
Frequently Asked Questions About Maze Games in JavaScript
How to create a maze in JS?
There are two main approaches. The grid-based approach stores the maze as a 2D grid of cells, each a wall or a passage, and uses an algorithm such as Depth-First Search to carve random paths (Step 5 has the code). The raycasting approach simulates light rays travelling through the maze, so you can draw a 3D-like perspective. Libraries like p5.js or Three.js help, especially for 3D.
Can you make a 3D game in JavaScript?
Yes. JavaScript is not the traditional choice for high-performance 3D games, but Three.js handles the 3D math and rendering, so you can build games with 3D models, lighting effects and camera movement entirely in a browser. Expect a learning curve: you need 3D concepts such as vectors and rotations, the Three.js API, and core game development principles like game design, physics and user interaction.
Can you code a game in JavaScript?
Absolutely. JavaScript is versatile (from text adventures to complex interactive games), accessible (games run in any browser), supported by engines such as Phaser and Babylon.js that handle graphics, physics and audio, and backed by a large community with many tutorials and forums.
What is a maze code?
Maze code is the JavaScript that creates, displays and lets you interact with a maze. It typically covers maze generation (for example Depth-First Search to decide walls and passages), maze representation (a 2D array or a collection of objects), maze display (drawing walls on a canvas, in the DOM or in 3D) and user interaction (keyboard presses or mouse clicks that move a character).
Why do the arrow keys scroll the page while I play?
Arrow keys scroll the page by default. Call event.preventDefault() inside the keydown handler for the arrow keys, as the HTML version in Step 4 does.
How long does it take to learn JavaScript?
Most beginners learn the basics (variables, functions, loops, arrays) in a few weeks of regular practice, and become comfortable building projects after a few months.
Is JavaScript for beginners, and how hard is it?
Yes. You see results instantly in the browser, and the basics are easy. Game logic takes more practice, so start with small javascript exercises for beginners like this maze game.
JavaScript FAQ in Turkish, Spanish, German and Arabic
Many learners search for JavaScript project ideas in their own language, so here are short answers to the most common questions.
Türkçe: JavaScript projeleri
JavaScript ile neler yapılabilir?
JavaScript ile web siteleri, mobil uygulamalar, oyunlar, Node.js ile sunucu uygulamaları ve labirent oyunu gibi küçük projeler geliştirebilirsiniz.
JavaScript öğrenmek ne kadar sürer?
Temel konuları öğrenmek genellikle birkaç hafta, rahatça proje geliştirmek ise birkaç ay düzenli pratik gerektirir.
JavaScript hangi program?
JavaScript bir programlama dilidir. Tarayıcıda veya Node.js ile çalışır; kod yazmak için Visual Studio Code gibi bir editör yeterlidir.
JavaScript neden popüler?
Her tarayıcıda çalıştığı, öğrenmesi kolay olduğu ve hem ön yüzde hem arka yüzde kullanılabildiği için popülerdir.
Español: proyectos en JavaScript
¿Qué proyectos se pueden hacer con JavaScript?
Calculadoras, carritos de compra, juegos de laberinto, relojes despertadores, aplicaciones del clima y mucho más.
¿Qué es un proyecto en JavaScript?
Es un programa o página web escrito con JavaScript que combina variables, funciones y arrays para resolver un problema concreto.
¿Cómo empezar un proyecto de JavaScript?
Crea un archivo .js, escribe una función pequeña como movePlayer() y ejecútala en la consola del navegador.
¿Qué programas se han hecho con JavaScript?
Sitios web, aplicaciones web, juegos de navegador, servidores con Node.js y aplicaciones de escritorio con Electron.
Deutsch: JavaScript lernen
Wird JavaScript noch benötigt?
Ja. JavaScript ist die Standardsprache des Webs, läuft in jedem Browser und wird mit Node.js auch auf Servern breit eingesetzt.
Was kann man alles mit JavaScript machen?
Websites, Web-Apps, Spiele, Server-Anwendungen, mobile Apps und kleine Projekte wie ein Labyrinth-Spiel.
Ist JavaScript für Anfänger?
Ja. Man sieht Ergebnisse sofort im Browser, und kleine Projekte erleichtern den Einstieg.
Wie schwierig ist JavaScript?
Die Grundlagen sind leicht zu lernen. Fortgeschrittene Themen wie asynchrone Programmierung brauchen mehr Übung.
العربية: مشاريع جافا سكريبت
تبحث عن مشاريع جافا سكريبت للمبتدئين؟ لعبة المتاهة هذه مثال بسيط على مشروع جافا سكريبت يمكنك تجربته مباشرة وتعديل شيفرته. يمكنك أيضاً البحث عن مشاريع جافا سكريبت جاهزة pdf للحصول على شروحات مكتوبة، أو البحث عن مشروع جافا سكريبت github للعثور على شيفرات مفتوحة المصدر.
لست بحاجة إلى جافا سكريبت تحميل أو تحميل جافا سكريبت للاندرويد، فهي تعمل داخل المتصفح مباشرة، ويكفي تطبيق محرر أكواد إذا أردت الكتابة من الهاتف. أما تفعيل جافا سكريبت على الهاتف فيتم من إعدادات المتصفح إذا كانت معطّلة. وللتوسع جرّب مشاريع جافا للمبتدئين، مع ملاحظة أن جافا وجافا سكريبت لغتان مختلفتان.
Keep Building with JavaScript
You built a maze game with a 2D array, handled keyboard input, generated random mazes and practiced with javascript exercises and solutions. Use this source code as a launchpad for further exploration, with multiple difficulty levels, collectibles or a timer. Small javascript project ideas like this one are the fastest way to learn.
