我正在尝试将我的一个C#路径查找程序转换为JavaScript,以便在HTML画布上以图形方式显示。我已经被困了几天,因为它一直在抛出错误。
该程序基本上是一个网格,它有一个起始图块,结束图块,可行走的图块和障碍图块。该计划旨在使用可行走的瓷砖绘制从开始到结束瓷砖的路径,并避开障碍物瓷砖。
当我尝试计算路径时会触发它引发的错误,错误是:
未捕获的TypeError:无法读取未定义的属性“0”
它触发的代码行是一个检查,它会查看活动磁贴下方的磁贴,看看它是否可行而不是障碍:
if (pathGrid[r + 1][c] >= walkableID && pathGrid[r + 1][c] != obstacleID)
这是其中的一部分:
for (var r = 0; r < gridHeight; r++)
{
for (var c = 0; c < gridWidth; c++)
{
if (pathGrid[r][c] == walkableID || pathGrid[r][c] == targetID)
{
// check that it is not last row
if (r < gridHeight)
{
// check that below is walkable and not an obstacle
/*error*/if (pathGrid[r + 1][c] >= walkableID && pathGrid[r + 1][c] != obstacleID)
{
pathGrid2[r][c] = (pathGrid[r + 1][c] += 1);
changeMade = true;
}
}
// check that it is not first row
if (r > 0)
{
// check that above is walkable and not an obstacle
if (pathGrid[r - 1][c] >= walkableID && pathGrid[r - 1][c] != obstacleID)
{
pathGrid2[r][c] = (pathGrid[r - 1][c] += 1);
changeMade = true;
}
}
}
}
}
如果我注释掉发生此错误的语句,则活动磁贴上方,左侧和右侧的检查运行正常,没有错误。我无法理解为什么这会引起错误。
我确保所有使用的网格都是事先初始化的并包含空元素:
var playerID = 0
var targetID = -2
var walkableID = -1
var obstacleID = -3
var pathGrid = [[]];
var pathGrid2 = [[]];
var tempGrid = [[]];
for (var r = 0; r < gridHeight; r++)
{
pathGrid[r] = [];
pathGrid2[r] = [];
tempGrid[r] = [];
for (var c = 0; c < gridWidth; c++)
{
pathGrid[r][c] = 0;
pathGrid2[r][c] = 0;
tempGrid[r][c] = 0;
}
}