TS, create a maze ith recursive backtracking, result should be matrix with 1 and 0,…
- User
TS, create a maze ith recursive backtracking, result should be matrix with 1 and 0, where 1 is a wall
- Assistant
TS, create a maze ith recursive backtracking, result should be matrix with 1 and 0, where 1 is a wall
Sure! Below is a TypeScript implementation of a maze generator using the Recursive Backtracking algorithm. The maze is represented as a 2D matrix where 1 denotes a wall and 0 denotes a path.
Maze Representation: The maze is represented as a grid where each cell can either be a wall (1) or a path (0). Typically, odd indices in both rows and columns represent cells, and even indices represent walls between them.
Recursive Backtracking Algorithm:
type Cell = [number, number];
class MazeGenerator {
width: number;
height: number;
maze: number[][];
visited: boolean[][];
constructor(width: number, height: number) {
// Ensure the dimensions are odd numbers
this.width = width % 2 === 0 ? width + 1 : width;
this.height = height % 2 === 0 ? height + 1 : height;
this.maze = this.initializeMaze();
this.visited = this.initializeVisited();
}
// Initialize the maze grid with walls
initializeMaze(): number[][] {
const maze: number[][] = [];
for (let y = 0; y < this.height; y++) {
const row: number[] = [];
for (let x = 0; x < this.width; x++) {
row.push(1); // 1 represents a wall
}
maze.push(row);
}
return maze;
}
// Initialize the visited grid
initializeVisited(): boolean[][] {
const visited: boolean[][] = [];
for (let y = 0; y < this.height; y++) {
const row: boolean[] = [];
for (let x = 0; x < this.width; x++) {
row.push(false);
}
visited.push(row);
}
return visited;
}
// Shuffle an array in-place (Fisher-Yates shuffle)
shuffleArray(array: any[]) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
// Generate the maze using recursive backtracking
generateMaze(x: number, y: number) {
this.visited[y][x] = true;
this.maze[y][x] = 0; // 0 represents a path
const directions: Cell[] = [
[0, -2], // North
[2, 0], // East
[0, 2], // South
[-2, 0] // West
];
this.shuffleArray(directions);
for (const [dx, dy] of directions) {
const newX = x + dx;
const newY = y + dy;
if (this.isInBounds(newX, newY) && !this.visited[newY][newX]) {
// Remove the wall between current cell and new cell
this.maze[y + dy / 2][x + dx / 2] = 0;
this.generateMaze(newX, newY);
}
}
}
// Check if the cell is within maze boundaries
isInBounds(x: number, y: number): boolean {
return x > 0 && x < this.width - 1 && y > 0 && y < this.height - 1;
}
// Public method to create the maze
createMaze(): number[][] {
// Start from a random odd cell
const startX = 1;
const startY = 1;
this.generateMaze(startX, startY);
return this.maze;
}
// Print the maze to the console
printMaze() {
for (let y = 0; y < this.height; y++) {
let row = '';
for (let x = 0; x < this.width; x++) {
row += this.maze[y][x] === 1 ? '█' : ' ';
}
console.log(row);
}
}
}
// Example usage:
function main() {
const width = 21; // Must be odd
const height = 21; // Must be odd
const generator = new MazeGenerator(width, height);
const maze = generator.createMaze();
// Optionally, print the maze to the console
generator.printMaze();
// If you want to see the maze matrix
console.log("Maze Matrix:");
console.log(maze);
}
main();
Maze Dimensions: The maze dimensions are adjusted to be odd numbers to ensure that the borders are walls and there's a proper path structure.
Maze Initialization:
initializeMaze method creates a grid filled with 1s, representing walls.initializeVisited method creates a grid to keep track of visited cells during the maze generation.Recursive Backtracking (generateMaze method):
0).0.generateMaze for the new cell.Utility Methods:
shuffleArray: Implements the Fisher-Yates shuffle algorithm to randomize the order of directions.isInBounds: Checks whether the new cell is within the maze boundaries.Visualization:
printMaze method prints the maze to the console using █ for walls and spaces for paths.main function demonstrates how to use the MazeGenerator. It generates a 21x21 maze, prints it, and also logs the matrix representation.Setup TypeScript Environment:
npm install -g typescript
Save the Code:
mazeGenerator.ts.Compile and Run:
tsc mazeGenerator.ts
mazeGenerator.js file.node mazeGenerator.js
You should see a maze printed in your console, along with the matrix representation.
█████████████████████
█ █ █ █ █ █
█ █ █ █ █ █ █ █ █ █ █
█ █ █ █ █ █ █
█ █ █ █ █ █ █ █ █ █ █
█ █ █ █ █ █ █
█ ███████ █████ █ █ █
█ █ █ █ █
█████ █████ ███ ███ █
█ █ █ █ █
█ █████ ███ █ █ █ █ █
█ █ █ █ █ █ █
█ █ █████ ███ █████ █
█ █ █ █ █
█ █████████ ███ █████
█ █ █
█████████████████████
Maze Matrix:
[
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
[1,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,1],
[1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1],
...
]
Note: The actual maze will vary each time you run the generator due to the random nature of the algorithm.
Maze Size: You can change the width and height variables in the main function to generate mazes of different sizes. Remember to keep them odd numbers for proper maze structure.
Entrance and Exit: Currently, the generator starts carving paths from the cell (1,1). You can modify the createMaze method to set entrances and exits at different positions if desired.
Feel free to integrate this maze generator into your projects or modify it further to suit your needs!
Not yet included in a published release.