A* Pathfinding java not working properly [closed]

2019-09-01 07:34发布

问题:

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));