Skip to content

Instantly share code, notes, and snippets.

@huckfinnaafb
Created January 1, 2012 22:19
Show Gist options
  • Save huckfinnaafb/1548499 to your computer and use it in GitHub Desktop.
Save huckfinnaafb/1548499 to your computer and use it in GitHub Desktop.
/*
A* Pathfinding
*/
function Path(map, start, end) {
// Sets
var open = [],
closed = [];
// Create node for start
var begin;
begin = new Path.Node(start);
begin.gscore = 0;
begin.hscore = Path.heuristic(start, end);
begin.fscore = begin.gscore + begin.hscore;
// Open set begins with start node
Path.append(open, begin);
var i;
// Avoiding infinite loops for testing
for (i = 0; i < 10; i += 1) {
if (open.length) {
// Node with lowest fscore
var current = Path.best(open);
// Current node not at the end of path
if (!Vector.isEqual(current.vector, end)) {
// Swap sets
Path.remove(open, current);
Path.append(closed, current);
// Loop through immediate neighbors
var j, neighbors = Path.neighbors(current);
for (j = 0; j < neighbors.length; j += 1) {
// Shorthand
var neighbor = neighbors[i];
// Tentative move cost
var cost = current.gscore + Vector.distance(current.vector, neighbor.vector);
if (Path.belongs(open, neighbor) && cost < neighbor.gscore) {
Path.remove(open, neighbor);
}
if (Path.belongs(closed, neighbor) && cost < neighbor.gscore) {
Path.remove(closed, neighbor);
}
if (!Path.belongs(closed, neighbor) && !Path.belongs(open, neighbor)) {
Path.append(open, neighbor);
neighbor.hscore = Path.heuristic(neighbor.vector, end);
neighbor.gscore = cost;
neighbor.fscore = neighbor.gscore + neighbor.hscore;
neighbor.parent = current;
}
}
}
}
}
console.log(closed);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment