【发布时间】:2012-05-05 03:18:33
【问题描述】:
我在一个简单的 JavaScript 中使用 A* 寻路脚本。我将我的游戏分解为 SSCCE。无论如何,我的游戏有 15 列和 10 行。
在您单击最右侧 5 列上的任意位置之前,寻路一直有效。所以如果X 是11 或更大。你会得到这个错误。 Uncaught TypeError: Cannot read property '7' of undefined 其中7 是您单击位置的Y 轴。
这是我的SSCCE。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type='text/javascript' src='graphstar.js'></script>
<script type="text/javascript">
var board;
</script>
<script type='text/javascript' src='astar.js'></script>
<script type="text/javascript">
$(document).ready(function()
{
// UP to DOWN - 10 Tiles (Y)
// LEFT to RIGHT - 15 Tiles (X)
graph = new Graph([
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1],
[1, 13, 1, 13, 13, 13, 13, 13, 1, 1, 1, 1, 1, 13, 13, 1],
[1, 13, 1, 1, 13, 1, 1, 13, 1, 13, 13, 1, 13, 13, 13, 1],
[1, 13, 13, 1, 1, 1, 13, 13, 1, 13, 13, 1, 1, 1, 13, 1],
[1, 13, 13, 1, 13, 1, 13, 13, 13, 13, 13, 1, 13, 13, 13, 1],
[1, 13, 13, 13, 13, 1, 13, 13, 13, 13, 13, 1, 13, 13, 13, 1],
[1, 13, 1, 13, 13, 13, 13, 13, 1, 1, 1, 1, 13, 13, 13, 1],
[1, 13, 1, 1, 1, 1, 13, 13, 13, 13, 1, 13, 13, 13, 13, 1],
[1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
]);
//Let's do an example test.
start = graph.nodes[1][2]; // x - y (15 columns across, 10 rows down)
end = graph.nodes[12][7]; // x - y (15 columns across, 10 rows down)
result = astar.search(graph.nodes, start, end);
});
</script>
</head>
<body>
Loading... pathfinding. Look in Chrome Console/Firefox Firebug for more information.
</body>
</html>
如您所见,我的游戏是jQuery。还有graphstar.js 和astar.js。不要担心astar.js,因为它工作正常。 graphstar.js 是我的问题所在。 astar.js 是布置 nodes 等的地方。 graphstar.js 是绘制地图的位置。
在这里查看整个graphstar.js:http://pastebin.com/kx4mw86z(这里是astar.js:http://pastebin.com/wtN2iF15)
这是它在graphstar.js 中的布局:
// Creates a Graph class used in the astar search algorithm.
function Graph(grid) {
var nodes = [];
var row, rowLength, len = grid.length;
for (x = 0; x <= 10; x++) {
row = grid[x];
nodes[x] = new Array(15);
for (y = 0; y <= 15; y++) {
nodes[x][y] = new GraphNode(x, y, row[y]);
}
}
this.input = grid;
this.nodes = nodes;
}
我知道我的X 的最高值是15,而我的Y 的最高值是 10。但我试着弄乱它.. 我会出错。有时没有错误,页面会卡住。
帮助?
新的图形格式:
for (y = 0; y <= 10; y++) {
row = grid[y];
nodes[y] = new Array(15);
for (x = 0; x <= 15; x++) {
console.log("X: " + x + " Y: " + y);
//console.log("Row: " + row[x]);
nodes[x][y] = new GraphNode(x, y, row[x]);
}
}
【问题讨论】:
-
graph.nodes[12][7]表示向下 12,跨 7,具体取决于您布置阵列的方式。但是没有第 12 行。也许你的意思是[7][12]? -
不,因为那样会混淆我的 Y 和 X。
-
...这是我的意思,你把它们弄混了。
-
我明白了。我试图改变它们,但我仍然得到同样的错误。只有这一次..那个数字是0。
标签: javascript jquery html a-star