【发布时间】:2012-05-05 08:21:42
【问题描述】:
我在一个简单的 JavaScript 2D(画布)游戏中使用A* pathfinding script。我将我的游戏分解为SSCCE。无论如何,我的游戏有 15 列和 10 行。
问题是我得到的错误。下面我有一种方法来开始和结束节点之间的路径。这是line 15 上的错误消息Uncaught TypeError: Cannot set property '0' of undefined。第 15 行是第二个 for 循环之间的 nodes[x][y] = new GraphNode(x, y, row[x]);。
这是我的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: 1, Y: 2
end = graph.nodes[12][7]; // X: 12, Y: 7
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/5AYRreip(这里是astar.js:http://pastebin.com/ee6PMzc3)
这是它在graphstar.js 中的布局:
function Graph(grid) {
var nodes = [];
var row, rowLength, len = grid.length;
for (y = 0; y <= 15; y++) {
row = grid[y];
nodes[y] = new Array(15);
for (x = 0; x <= 10; x++) {
nodes[x][y] = new GraphNode(x, y, row[x]);
}
}
this.input = grid;
this.nodes = nodes;
}
所以,如您所见...Y 可以是10 或更低。 X 可以是 15 或更低。但是,我收到此错误。
我在哪里输入end = graph.nodes[12][7]; // X: 12, Y: 7
应该可以工作,因为它在 X 和 Y 范围内......但是我什至在首先设置它时遇到了麻烦。
为什么未定义?
更新新内容
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]);
}
}
【问题讨论】:
标签: javascript jquery html a-star