List of usage examples for com.badlogic.gdx.utils BinaryHeap BinaryHeap
public BinaryHeap()
From source file:com.vlaaad.dice.game.world.util.AStar.java
License:Open Source License
public static Array<Coordinate> search(World grid, WorldObject startObject, WorldObject endObject, boolean near) { Node start = Pools.obtain(Node.class).set(startObject.getX(), startObject.getY()); Node end = Pools.obtain(Node.class).set(endObject.getX(), endObject.getY()); nodes.put(start.x, start.y, start);/*from w ww . j a v a 2 s . c o m*/ nodes.put(end.x, end.y, end); BinaryHeap<Node> openHeap = new BinaryHeap<Node>(); openHeap.add(start); List<Node> neighbours = new LinkedList<Node>(); Node nearNode = null; boolean searchNear = true; while (openHeap.size > 0) { Node current = openHeap.pop(); int cx = current.x - end.x; int cy = current.y - end.y; if (cx == 0 && cy == 0) { Array<Coordinate> result = new Array<Coordinate>(); while (current.parent != null) { result.add(Coordinate.obtain(current.x, current.y)); current = current.parent; } result.reverse(); cleanUp(); return result; } if (near && searchNear && !isValid(grid, end.x, end.y)) { nearNode = current; if (Math.abs(cx) <= 1 && Math.abs(cy) <= 1) { searchNear = false; } } current.closed = true; neighbours.clear(); int gScore = current.g + 1; addNeighbours(grid, neighbours, current); for (Node neighbour : neighbours) { if (neighbour.closed) continue; if (!neighbour.visited || gScore < neighbour.g) { neighbour.parent = current; int dx = neighbour.x - end.x; int dy = neighbour.y - end.y; neighbour.h = (float) (Math.sqrt(dx * dx + dy * dy)); neighbour.g = gScore; neighbour.f = neighbour.g + neighbour.h; if (!neighbour.visited) { openHeap.add(neighbour); } openHeap.setValue(neighbour, neighbour.f); neighbour.visited = true; } } } if (nearNode != null && !searchNear) { Array<Coordinate> result = new Array<Coordinate>(); while (nearNode.parent != null) { result.add(Coordinate.obtain(nearNode.x, nearNode.y)); nearNode = nearNode.parent; } result.reverse(); cleanUp(); return result; } cleanUp(); return null; }