A* Pathfinding java not working properly [closed]

不羁岁月 提交于 2019-12-14 03:14:05

问题


I am creating a Maze game in java and wants to add a smarty ghost (like Pacman) that move towards user location to catch him. For smarty ghost I chose A* PathFinding Algorithm and found below links for implementing this algorithm :

https://code.google.com/p/a-star/source/browse/trunk/java/PathFinder.java?r=8

https://code.google.com/p/a-star/source/browse/trunk/java/AStar.java?r=8

But the code is not completely working properly , I mean the code only seems to find paths going from top left to bottom right, not for example left - right - left - left down .

for e.g :

if

 source = (0,0)
 Destination = (8,8)     // works perfectly..

if

  source = (8,8)
  Destination = (0,0)     // doesn't  work :(

Please help me to correct this code or give useful link for implementing this.


回答1:


I think the issue is in this part of the code:

protected List<Node> generateSuccessors(Node node){
                List<Node> ret = new LinkedList<Node>();
                int x = node.x;
                int y = node.y;
                if(y < map.length - 1 && map[y+1][x] == 1)
                                ret.add(new Node(x, y+1));

                if(x < map[0].length - 1 && map[y][x+1] == 1)
                                ret.add(new Node(x+1, y));

                return ret;
}

This code is returning a list of neighbours for the current node, however it only tries down and right directions. Try adding corresponding code for any other directions you wish to follow, e.g.

if(y > 0 && map[y-1][x] == 1)
                ret.add(new Node(x, y-1));
if(x > 0 && map[y][x-1] == 1)
                ret.add(new Node(x-1, y));


来源:https://stackoverflow.com/questions/25804431/a-pathfinding-java-not-working-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!