[Pathfinding] inline getNeighbor() method
This commit is contained in:
parent
da7a6cfdd4
commit
2031291d00
@ -48,38 +48,35 @@ class AStarSearch {
|
|||||||
}
|
}
|
||||||
|
|
||||||
List<Node> shortestPath() {
|
List<Node> shortestPath() {
|
||||||
|
final LinkedList<Node> path = new LinkedList<>();
|
||||||
Node currentNode = search();
|
Node currentNode = search();
|
||||||
LinkedList<Node> path = new LinkedList<>();
|
|
||||||
|
if (currentNode != null) {
|
||||||
while (currentNode.getParent() != null) {
|
while (currentNode.getParent() != null) {
|
||||||
path.addFirst(currentNode);
|
path.addFirst(currentNode);
|
||||||
currentNode = currentNode.getParent();
|
currentNode = currentNode.getParent();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
return path;
|
return path;
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<Node> getNeighbors(Node current) {
|
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()) {
|
for (Direction direction : Direction.values()) {
|
||||||
final Node neighbor = getNeighbor(current, direction);
|
final Node node = new Node(current);
|
||||||
// If neighbor is a wall or off the grid (null), don't add it to the list
|
final Point loc = new Point(current.loc.x + direction.x, current.loc.y + direction.y);
|
||||||
if (neighbor != null) neighbors.add(neighbor);
|
// 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;
|
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 {
|
private enum Direction {
|
||||||
UP(0, 1),
|
UP(0, 1),
|
||||||
DOWN(0, -1),
|
DOWN(0, -1),
|
||||||
|
Loading…
Reference in New Issue
Block a user