To create a maze generator and pathfinding visualizer using HTML5 canvas, we will break the task into several steps:
javascript Copy code
const canvas = document.getElementById('mazeCanvas');
const ctx = canvas.getContext('2d');
// Configuration
const cellSize = 20; // Size of each cell in pixels
const rows = 20; // Number of rows
const cols = 20; // Number of columns
canvas.width = cols * cellSize;
canvas.height = rows * cellSize;
let grid = [];
let stack = [];
let start = null;
let end = null;
// Generate the maze
function generateMaze() {
grid = [];
stack = [];
for (let r = 0; r < rows; r++) {
const row = [];
for (let c = 0; c < cols; c++) {
row.push({ x: c, y: r, walls: { top: true, right: true, bottom: true, left: true }, visited: false });
}
grid.push(row);
}
start = grid[0][0];
end = grid[rows - 1][cols - 1];
start.visited = true;
stack.push(start);
carvePassages();
}
// Carve passages using randomized DFS
function carvePassages() {
if (stack.length === 0) return;
const current = stack[stack.length - 1];
const neighbors = getUnvisitedNeighbors(current);
if (neighbors.length > 0) {
const next = neighbors[Math.floor(Math.random() * neighbors.length)];
removeWalls(current, next);
next.visited = true;
stack.push(next);
} else {
stack.pop();
}
setTimeout(carvePassages, 10); // Animate maze generation
}
// Get unvisited neighbors
function getUnvisitedNeighbors(cell) {
const neighbors = [];
const { x, y } = cell;
if (y > 0 && !grid[y - 1][x].visited) neighbors.push(grid[y - 1][x]); // Top
if (x < cols - 1 && !grid[y][x + 1].visited) neighbors.push(grid[y][x + 1]); // Right
if (y < rows - 1 && !grid[y + 1][x].visited) neighbors.push(grid[y + 1][x]); // Bottom
if (x > 0 && !grid[y][x - 1].visited) neighbors.push(grid[y][x - 1]); // Left
return neighbors;
}
// Remove walls between two cells
function removeWalls(a, b) {
const dx = a.x - b.x;
const dy = a.y - b.y;
if (dx === 1) {
a.walls.left = false;
b.walls.right = false;
} else if (dx === -1) {
a.walls.right = false;
b.walls.left = false;
}
if (dy === 1) {
a.walls.top = false;
b.walls.bottom = false;
} else if (dy === -1) {
a.walls.bottom = false;
b.walls.top = false;
}
}
// Draw the maze
function drawMaze() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
const cell = grid[r][c];
const x = cell.x * cellSize;
const y = cell.y * cellSize;
if (cell.walls.top) drawLine(x, y, x + cellSize, y);
if (cell.walls.right) drawLine(x + cellSize, y, x + cellSize, y + cellSize);
if (cell.walls.bottom) drawLine(x, y + cellSize, x + cellSize, y + cellSize);
if (cell.walls.left) drawLine(x, y, x, y + cellSize);
if (cell === start) fillCell(x, y, 'green');
if (cell === end) fillCell(x, y, 'red');
}
}
}
// Draw a line
function drawLine(x1, y1, x2, y2) {
ctx.strokeStyle = '#ecf0f1';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
// Fill a cell with a color
function fillCell(x, y, color) {
ctx.fillStyle = color;
ctx.fillRect(x + 1, y + 1, cellSize - 2, cellSize - 2);
}
// Pathfinding using A*
function solveMaze() {
const openSet = [start];
const closedSet = [];
while (openSet.length > 0) {
let current = openSet.reduce((a, b) => (a.f < b.f ? a : b));
if (current === end) {
reconstructPath(current);
return;
}
openSet.splice(openSet.indexOf(current), 1);
closedSet.push(current);
const neighbors = getNeighbors(current);
for (const neighbor of neighbors) {
if (closedSet.includes(neighbor)) continue;
const tentativeG = current.g + 1;
if (!openSet.includes(neighbor)) {
openSet.push(neighbor);
} else if (tentativeG >= neighbor.g) {
continue;
}
neighbor.parent = current;
neighbor.g = tentativeG;
neighbor.h = heuristic(neighbor, end);
neighbor.f = neighbor.g + neighbor.h;
}
drawMaze();
highlightPath(current, closedSet);
requestAnimationFrame(() => {}); // Animate step by step
}
}
// Get valid neighbors for A*
function getNeighbors(cell) {
const neighbors = [];
const { x, y } = cell;
if (y > 0 && !cell.walls.top) neighbors.push(grid[y - 1][x]);
if (x < cols - 1 && !cell.walls.right) neighbors.push(grid[y][x + 1]);
if (y < rows - 1 && !cell.walls.bottom) neighbors.push(grid[y + 1][x]);
if (x > 0 && !cell.walls.left) neighbors.push(grid[y][x - 1]);
return neighbors;
}
// Heuristic function (Manhattan distance)
function heuristic(a, b) {
return Math.abs(a.x - b.x) + Math.abs(a.y - b.y);
}
// Reconstruct and visualize the path
function reconstructPath(node) {
const path = [];
let current = node;
while (current.parent) {
path.push(current);
current = current.parent;
}
path.forEach((cell) => {
const x = cell.x * cellSize;
const y = cell.y * cellSize;
fillCell(x, y, 'yellow');
});
}
// Highlight the current cell and explored cells
function highlightPath(current, closedSet) {
const x = current.x * cellSize;
const y = current.y * cellSize;
fillCell(x, y, 'blue');
closedSet.forEach((cell) => {
const cx = cell.x * cellSize;
const cy = cell.y * cellSize;
fillCell(cx, cy, 'rgba(255, 255, 255, 0.3)');
});
}
// Event listener for generating maze
document.getElementById('generate').addEventListener('click', () => {
generateMaze();
drawMaze();
setTimeout(() => solveMaze(), 1000); // Start solving after maze generation
});
This implementation is visually appealing, interactive, and demonstrates both maze generation and pathfinding effectively.