我目前正在研究一种称为递归除法的迷宫生成算法。该算法很容易理解:步骤1:如果腔室的高度小于宽度,则用垂直线划分网格/腔室。如果高度大于宽度,则用水平线划分腔室。步骤2:对由行创建的子腔室重复步骤1。您要重复这些步骤,直到迷宫为止(直到宽度或高度等于1个单位)。
这个算法的问题是JavaScript打印出RangeError,这意味着我多次调用创建迷宫的函数(我正在尝试使用递归函数来实现该算法)。有什么方法可以避免/防止这种情况的发生?还是我的代码中缺少使算法无法正常工作的重要信息?
我已经尝试实现蹦床功能,但是由于我是初学者,所以我对它的理解不足以实现自己的自我。我也大约重新启动了我的整个项目3次,希望我能针对此问题提出不同的方法,但是每次都会遇到相同的错误。
我的代码在这里:
//leftCord = the left most x coordinate of my chamber/grid, upCord = the upmost y coordinate of my
grid etc.
//(0, 0) IS POSITIONED IN THE LEFT TOP 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 completed!
return;
} else {
if (height < width) {
//cut the chamber/grid vertically
//Getting a random number that's EVEN and drawing 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]);
}
//Making a random door/passage and making sure 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";
}
//Making the same thing again, but with the left and right sub-chambers that were created by the line
createMaze(leftCord, x, upCord, downCord);
createMaze(x, rightCord, upCord, downCord);
} else {
//cut the chamber/grid horizontally
//Getting a random number that's EVEN and drawing 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]);
}
//Making a random door/passage and making sure 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";
}
//Making the same thing again, but with the upper and lower-chambers that were created by the line
createMaze(leftCord, rightCord, upCord, y);
createMaze(leftCord, rightCord, y, downCord);
}
}
}
最佳答案
发生这种情况是因为您从未用i
初始化var
-它被发送到全局范围并覆盖每个函数调用。
关于javascript - 如何避免出现“RangeError:超出最大调用堆栈大小”错误?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59399260/