xxxxxxxxxx
113
class Cell {
constructor(id, x, y, cellSize) {
this.id = id;
this.x = x;
this.y = y;
this.cellSize = cellSize;
this.visited = false;
this.neighbors = [];
}
show() {
let x = this.x * this.cellSize;
let y = this.y * this.cellSize;
stroke(255);
if (this.walls.top) line(x, y, x + this.cellSize, y);
if (this.walls.right) line(x + this.cellSize, y, x + this.cellSize, y + this.cellSize);
if (this.walls.bottom) line(x, y + this.cellSize, x + this.cellSize, y + this.cellSize);
if (this.walls.left) line(x, y, x, y + this.cellSize);
if (this.visited) {
noStroke();
fill(0, 0, 255, 100);
rect(x, y, this.cellSize, this.cellSize);
}
}
}
class Maze {
constructor(rows, cols) {
this.rows = rows;
this.cols = cols;
this.cells = [];
this.stack = [];
this.current = null;
this.cellSize = 0; // Add this line to declare cellSize
this.init();
}
init() {
this.cellSize = width / this.cols;
for (let y = 0; y < this.rows; y++) {
this.cells[y] = [];
for (let x = 0; x < this.cols; x++) {
this.cells[y][x] = new Cell(x, y, this.cellSize);
}
}
this.current = this.cells[0][0];
this.current.visited = true;
this.stack.push(this.current);
}
step() {
if (this.stack.length > 0) {
let neighbors = this.getUnvisitedNeighbors(this.current);
if (neighbors.length > 0) {
let next = random(neighbors);
this.removeWall(this.current, next);
this.stack.push(this.current);
this.current = next;
this.current.visited = true;
} else {
this.current = this.stack.pop();
}
}
}
show() {
for (let y = 0; y < this.rows; y++) {
for (let x = 0; x < this.cols; x++) {
this.cells[y][x].show();
}
}
}
getUnvisitedNeighbors(cell) {
let neighbors = [];
let top = cell.y - 1 >= 0 ? this.cells[cell.y - 1][cell.x] : null;
let right = cell.x + 1 < this.cols ? this.cells[cell.y][cell.x + 1] : null;
let bottom = cell.y + 1 < this.rows ? this.cells[cell.y + 1][cell.x] : null;
let left = cell.x - 1 >= 0 ? this.cells[cell.y][cell.x - 1] : null;
if (top && !top.visited) neighbors.push(top);
if (right && !right.visited) neighbors.push(right);
if (bottom && !bottom.visited) neighbors.push(bottom);
if (left && !left.visited) neighbors.push(left);
return neighbors;
}
removeWall(current, next) {
let dx = next.x - current.x;
let dy = next.y - current.y;
if (dx === 1) {
current.walls.right = false;
next.walls.left = false;
} else if (dx === -1) {
current.walls.left = false;
next.walls.right = false;
}
if (dy === 1) {
current.walls.bottom = false;
next.walls.top = false;
} else if (dy === -1) {
current.walls.top = false;
next.walls.bottom = false;
}
}
}