Java中的星形实现

时间:2014-06-16 04:38:27

标签: java a-star

所以我目前在A * Pathfinding的最后修改方面遇到了麻烦,我已经完成了所有必要的辅助功​​能,而且我实际上已经在Javascript和ActionScript中实现了这个算法,但是我在使用Java中的列表时绊倒了。

它没有出现任何错误,但我需要进行最后的修改,以便我可以测试以确保它正常运行。

我需要做的是对openList进行排序,以便我可以检索成本最低的节点,这是我需要帮助的地方。

这就是我所拥有的:

public class Pathfinding
{
    List<Node> closedList = new ArrayList<Node>();
    List<Node> openList = new ArrayList<Node>();

public Node calculateShortestDistance(List<Integer> tiles, Node start, Node goal, List<Integer> passableTiles)
{

    Node currentNode = new Node(start.row, start.col, start.gCost, start.fCost, null);

    while(!catchMeIfYouCan(currentNode, goal))
    {
        int row = currentNode.row;
        int col = currentNode.col + 1;

        addChild(row, col, tiles, passableTiles, currentNode, goal, openList, closedList);

        //left child
        col -= 2;
        addChild(row, col, tiles, passableTiles, currentNode, goal, openList, closedList);

        //top child
        col++;
        row--;
        addChild(row, col, tiles, passableTiles, currentNode, goal, openList, closedList);

        //bottom child
        row += 2;
        addChild(row, col, tiles, passableTiles, currentNode, goal, openList, closedList);

        //bottom right
        col++;
        addChild(row, col, tiles, passableTiles, currentNode, goal, openList, closedList);

        //bottom left
        col -= 2;
        addChild(row, col, tiles, passableTiles, currentNode, goal, openList, closedList);

        //top left
        row -= 2;
        addChild(row, col, tiles, passableTiles, currentNode, goal, openList, closedList);

        //top right
        col += 2;
        addChild(row, col, tiles, passableTiles, currentNode, goal, openList, closedList);

        //Put currentNode in the closedList
        closedList.add(currentNode);
        //Sort the openList

        //Assign currentNode to the last element in the List

    }
    return currentNode;
}

1 个答案:

答案 0 :(得分:1)

对列表进行排序非常简单。首先,您需要使Node Comparable:

class Node implements Comparable<Node>

然后你需要写:

public boolean compareTo(Node other)

那应该是一个平等的考验。

然后,您可以轻松使用Collections.sort()

Collections.sort(openList);