【发布时间】:2016-05-08 15:44:14
【问题描述】:
上下文
我正在尝试开发一个简单的 2D 游戏,其中一些“僵尸”将追赶我。
我计算路径的想法如下(X = 路径不可用):
[4] [4] [X] [1] [1] [2] [3] [4] [5]
[3] [X] [X] [0] [1] [X] [X] [X] [5]
[3] [2] [1] [1] [1] [X] [3] [4] [5]
[3] [2] [2] [2] [2] [2] [3] [4] [5]
从 0 开始,给它周围的位置 1 值,到接近 1 的位置,给 2 值,等等。这样我只需要搜索一个较低的索引就知道到达 0 的最快方法。
问题
(1) 我不知道这个算法是否有名字,所以我找不到关于它的信息。
(2) 计算这个的最优解/算法/流程
(3) 在我的手机中,游戏屏幕的分辨率为 1700 x 1440,因此我的代码需要 15 秒。我创建了一个最终值来缩小所有内容并降低矩阵大小,但是,仍然需要很多,实际上无法播放。
(4) 还有其他需求吗?也许添加线程?我不知道这是否可行...
我的代码(调试代码已删除)
代码
private void expandAllFrom(int x, int y){ // x and y already scalled down
nodes = new ArrayList<Point>(); // "nodes" is a global variable //
nodes.add(new Point(x, y));
while ( nodes.size() > 0 ){
Point p = nodes.remove(0);
expand(p.x, p.y);
}
}
private void expand(int x, int y){
int limXMin = x - 1, limXMax = x + 1, limYMin = y - 1, limYMax = y + 1;
int value = map[x][y];
// Check limits of screen
if ( limXMin < 0 ) limXMin = 0;
if ( limXMax > SCREEN_X_DIV - 1) limXMax = SCREEN_X_DIV - 1;
if ( limYMin < 0 ) limYMin = 0;
if ( limYMax > SCREEN_Y_DIV - 1) limYMax = SCREEN_Y_DIV - 1;
for (int i = limXMin; i <= limXMax; i++){
for (int j = limYMin; j <= limYMax; j++){
if ( map[i][j] == 0 ) {
if ( i != x || j != y ){
nodes.add(new Point(i, j));
map[i][j] = value + 1;
}
}
}
}
}
说明
我使用 FIFO 列表。我在其中添加节点,例如,流程将类似于:
(1) Add 0 position to expand node list.
(2) Expand 0 by setting 1 values arround it. Then add them to expand node list.
(2) Expand 1 by setting 2 values arround it. Then add them to expand node list.
(...)
(X) Expand 2 by setting 3 values arround it. Then add them to expand node list.
(Y) Expand 3 by setting 4 values arround it. Then add them to expand node list.
(...)
【问题讨论】:
-
听起来像 A*(A-start)
-
你的地图是随机的吗?
-
顺便说一句,
Queue通常更适合 FIFO 列表。例如,LinkedList -
是的,但是它的实现方式,当你删除第一个元素时,所有元素都必须移动,
LinkedList没有这个问题。 -
您不是在做 A*,从技术上讲,您正在对地图上的每个点进行 Dijkstra 算法(也称为 BFS,广度优先搜索)。你有多少僵尸?如果不是太多,您最好使用一种算法,该算法使用一些启发式 A* 类型搜索来搜索每个僵尸。看看qiao.github.io/PathFinding.js/visual 看看这些是如何工作的。
标签: java android algorithm artificial-intelligence