[Pathfinding] inline getNeighbor() method

This commit is contained in:
Thibaud Gasser 2018-10-01 15:56:53 +02:00
parent da7a6cfdd4
commit 2031291d00

View File

@ -48,38 +48,35 @@ class AStarSearch {
}
List<Node> shortestPath() {
final LinkedList<Node> path = new LinkedList<>();
Node currentNode = search();
LinkedList<Node> path = new LinkedList<>();
while (currentNode.getParent() != null) {
path.addFirst(currentNode);
currentNode = currentNode.getParent();
}
if (currentNode != null) {
while (currentNode.getParent() != null) {
path.addFirst(currentNode);
currentNode = currentNode.getParent();
}
}
return path;
}
private List<Node> getNeighbors(Node current) {
LinkedList<Node> neighbors = new LinkedList<>();
final Dimension gridSize = grid.getSize();
final LinkedList<Node> neighbors = new LinkedList<>();
for (Direction direction : Direction.values()) {
final Node neighbor = getNeighbor(current, direction);
// If neighbor is a wall or off the grid (null), don't add it to the list
if (neighbor != null) neighbors.add(neighbor);
final Node node = new Node(current);
final Point loc = new Point(current.loc.x + direction.x, current.loc.y + direction.y);
// If the node is a wall, don't add it to the list
if (grid.get(loc).isWall()) continue;
// Don't overflow off the grid
if (loc.x > gridSize.width || loc.y > gridSize.height) continue;
node.setLoc(loc);
neighbors.add(node);
}
return neighbors;
}
private Node getNeighbor(Node current, Direction direction) {
final Dimension gridSize = grid.getSize();
final Node node = new Node(current);
final Point loc = new Point(current.loc.x + direction.x, current.loc.y + direction.y);
if (grid.get(loc).isWall()) return null;
// Don't overflow off the grid
if (loc.x > gridSize.width || loc.y > gridSize.height) return null;
node.setLoc(loc);
return node;
}
private enum Direction {
UP(0, 1),
DOWN(0, -1),