矩阵变量在javascript中不是未定义的



我正在使用回溯算法和p5.js库编写迷宫生成器,但是当我编写循环以设置迷宫中的随机位置时,我注意到javascript中的一个错误:">maze[(x - 2)] is undefined",但是这个变量是声明的!我试着阅读有关数据结构的书籍,但是我找不到解决这个问题的方法。

发生了什么事?

有人能帮帮我吗?

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset = "utf-8">
<title>Maze</title>
</head>
<body>
<script src = "https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.js"></script>
<script>
var width = 720;
var height = 400;
var x, y;
var maze = Array(39).fill(Array(71).fill(0));
function setup()
{
createCanvas(720, 400);
}
function draw()
{
//inicial position
x = 1;
y = 1;
maze[x][y] = 1;
//grid
strokeWeight(1);
stroke('BLACK');
for (x = 0; x <= 720; x += 10) line(x, 0, x, 400);
for (y = 0; y <= 400; y += 10) line(0, y, 720, y);
found = 0;
do
{
direction = Math.floor(Math.random() * 4);
if (direction == 0 && (y != width - 2 && maze[x][y + 2] == 0))
{
x2 = x;
y2 = y;
y += 2;
maze[x][y] = 1;
maze[x][y-1] = 1;
found = 1;
}
else if (direction == 1 && (x > 1 && maze[x - 2][y] == 0))
{
x2 = x;
y2 = y;
x -= 2;
maze[x][y] = 1;
maze[x + 1][y] = 1;
found = 1;
}
else if (direction == 2 && (y > 1 && maze[x][y - 2] == 0))
{
x2 = x;
y2 = y;
y -= 2;
maze[x][y] = 1;
maze[x][y + 1] = 1;
found = 1;
}
else if (direction == 3 && (x != height - 2 && maze[x + 2][y] == 0))
{
x2 = x;
y2 = y;
x += 2;
maze[x][y] = 1;
maze[x - 1][y] = 1;
found = 1;
}
} while (found == 0);
noLoop();
}
</script>
</body>
</html>

这段代码有几个问题。

让我们从为什么会出现这个错误开始。问题是,您在for循环中重用全局xy变量,当循环完成时,它将这些变量设置为大于您的maze数组。

这给我们带来了第二个问题:maze数组小于画布的宽度/高度。

代码不是100%工作,所以我不完全理解它应该做什么,但似乎xy不应该超过宽度/高度,但是你有一个条件y != width - 2,这将是真的,即使y大于width(顺便说一句,不应该是height吗??)

最后,在整个代码中,您有多个地方使用720400,而不是使用widthheight变量。这是不好的做法。

const width = 720;
const height = 400;
var x, y;
var maze = Array(width+1).fill(Array(height+1).fill(0));
function setup()
{
createCanvas(width, height);
}
function draw()
{
//inicial position
x = 1;
y = 1;
maze[x][y] = 1;
//grid
strokeWeight(1);
stroke('BLACK');
for (let x = 0; x <= width; x += 10) line(x, 0, x, height);
for (let y = 0; y <= height; y += 10) line(0, y, width, y);
found = 0;
do
{
direction = Math.floor(Math.random() * 4);
if (direction == 0 && (y <= height - 2 && maze[x][y + 2] == 0))
{
x2 = x;
y2 = y;
y += 2;
maze[x][y] = 1;
maze[x][y-1] = 1;
found = 1;
}
else if (direction == 1 && (x > 1 && maze[x - 2][y] == 0))
{
x2 = x;
y2 = y;
x -= 2;
maze[x][y] = 1;
maze[x + 1][y] = 1;
found = 1;
}
else if (direction == 2 && (y > 1 && maze[x][y - 2] == 0))
{
x2 = x;
y2 = y;
y -= 2;
maze[x][y] = 1;
maze[x][y + 1] = 1;
found = 1;
}
else if (direction == 3 && (x <= width - 2 && maze[x + 2][y] == 0))
{
x2 = x;
y2 = y;
x += 2;
maze[x][y] = 1;
maze[x - 1][y] = 1;
found = 1;
}
} while (found == 0);
noLoop();
}
<script src = "https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.js"></script>

最新更新