Currently, I am working on developing a maze generating algorithm known as recursive division. This algorithm is relatively straightforward to comprehend: Step 1 involves dividing the grid/chamber with a vertical line if the height is less than the width, and with a horizontal line if the height exceeds the width. Step 2 requires repeating Step 1 with the sub-chambers created by the lines until a maze is formed (when the width or height equals 1 unit).
However, an issue I am encountering with this algorithm is a RangeError in JavaScript, indicating that the maze creation function is being called excessively (as I am attempting to implement the algorithm using a recursive function). Is there any possible solution to avoid or prevent this error? Or is there a critical element missing from my code causing the algorithm to malfunction?
I have experimented with incorporating a trampoline function, yet due to my beginner status, I have struggled with fully grasping it to implement it effectively. Additionally, I have restarted my project approximately three times in the hopes of devising an alternate solution to this problem, but I consistently encounter the same error.
Below is a snippet of my code:
//leftCord = the furthest left x coordinate of my chamber/grid, upCord = the highest y coordinate of my grid, and so on.
//(0, 0) IS LOCATED AT THE UPPER LEFT NODE OF MY GRID
function createMaze(leftCord, rightCord, upCord, downCord) {
var height = Math.abs(downCord - upCord);
var width = Math.abs(rightCord - leftCord);
if (height < 2 || width < 2) {
//The maze is finished!
return;
} else {
if (height < width) {
//cut the chamber/grid vertically
//Obtaining an even random number and plotting the function x = 'random number' on the grid
var x = randomNum(leftCord / 2, rightCord / 2) * 2;
var lineX = [];
for (i = upCord; i < downCord; i++) {
lineX.push(grid[i][x]);
}
//Creating a random door/passage ensuring it's odd
var randomDoor = randomNum(0, lineX.length / 2) * 2 + 1;
lineX.splice(randomDoor, 1);
//Drawing the line
for (i = 0; i < lineX.length; i++) {
lineX[i].className = "wall";
}
//Repeating the process for the left and right sub-chambers created by the line
createMaze(leftCord, x, upCord, downCord);
createMaze(x, rightCord, upCord, downCord);
} else {
//cut the chamber/grid horizontally
//Obtaining an even random number and plotting the function y = 'random number' on the grid
var y = randomNum(0, downCord / 2) * 2;
var lineY = [];
for (i = leftCord; i < rightCord; i++) {
lineY.push(grid[y][i]);
}
//Creating a random door/passage ensuring it's odd
var randomDoor = randomNum(0, lineY.length / 2) * 2 + 1;
lineY.splice(randomDoor, 1);
//Drawing the line
for(i = 0; i < lineY.length; i++){
lineY[i].className = "wall";
}
//Repeating the process for the upper and lower-chambers created by the line
createMaze(leftCord, rightCord, upCord, y);
createMaze(leftCord, rightCord, y, downCord);
}
}
}