## A Maze Generator

Wikipedia defines 8 steps in total for the algorithm. And it really is not more. Most of the code I programmed is for displaying things. But first things first.

To draw a grid I created a class called MazeCell. Its constructor excpects 4 parameters:

• x and y which are the objects position in the grid array, i.e. its array indices. The values are stored in i and j
• w and h which are the objects width and height.
The constructor calculates the x and y position of the object on the canvas based on the indices and w and h.
Besides that a flag is defined which tells if the object was visited or not.
We also need an array to store the neighbors of the object in as well as 4 flags which define which of the four outlines (top, right, bottom, left) of the cell should be drawn.

constructor(x, y, w, h) {
this.i = x;
this.j = y;
this.width = w;
this.height = h;
this.x = x * this.width;
this.y = y * this.height;
this.visited = false;
this.neighbors = [];
this.top = true;
this.right = true;
this.bottom = true;
this.left = true;
}

In my setup function I first create a two dimensional array representing a grid of MazeCell objects. In the second for-loop I teach every cell who its neighbors are. Once this is done I do the first step of the algorithm: Make the first cell the current cell and set it to visited. Then put it on the stack.

function setup() {
var myCanvas = createCanvas(width, height);
myCanvas.parent("p5_div");

cells = new Array(cols);
for(let i=0; i < cols; i++) {
cells[i] = new Array(rows);
}

for(let i = 0 ; i < cols; i++) {
for(let j = 0 ; j < rows; j++) {
cells[i][j] = new MazeCell(i, j, width/cols, height/rows);
}
}

for(let i = 0 ; i < cols; i++) {
for(let j = 0 ; j < rows; j++) {
}
}

// STEP 1
current = cells;
current.visited = true;
stack.push(current);
}

In my draw function I do the second step of the algorithm once all cells are drawn: While the stack is not empty, pop a cell from the stack and make it a current cell. If the current cell has any neighbours which have not been visited. Push the current cell to the stack and choose one of the unvisited neighbours. Remove the wall between the current cell and the chosen cell and mark the chosen cell as visited and push it to the stack

function draw() {
for(let i = 0 ; i < cols; i++) {
for(let j = 0 ; j < rows; j++) {
cells[i][j].show();
}
}

// STEP 2
if(stack.length>0) {
var current = stack.pop();
var next = current.checkNeighbors();

if(next) {
stack.push(current);
removeWall(next, current);
next.visited=true;
stack.push(next);
}
} else {
noLoop();
}
}

Last edit: 2022-12-18