A* Pathfinding Algorithm

0.4.1 · maintenance · verified Sun Apr 19

The `javascript-astar` package provides an efficient implementation of the A* search algorithm in JavaScript for finding the shortest path on a grid. Currently at version 0.4.1, it has been optimized to use a Binary Heap, resulting in significant performance improvements over its original list-based approach. The library supports various graph configurations, including weighted nodes and diagonal movement. A weight of 0 for a node designates it as an impassable obstacle, and specific constraints apply to other weight values. It is primarily designed for browser environments via script tags, exposing global variables, and likely supports CommonJS environments for server-side usage, given its version and use of Grunt for tooling.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates initializing a graph, performing basic A* search, and utilizing options for diagonal movement and custom node weights.

const { astar, Graph } = require('javascript-astar'); // For Node.js or bundlers; for browsers, `astar` and `Graph` are globals.

// Basic usage: Find path on a grid without diagonal movement or custom weights.
var graph = new Graph([
	[1,1,1,1],
	[0,1,1,0],
	[0,0,1,1]
]);
var start = graph.grid[0][0];
var end = graph.grid[1][2];
var result = astar.search(graph, start, end);
console.log('Path (no diagonals, no weight):', result.map(node => `(${node.x},${node.y})`).join(' -> '));

// With diagonals: Enable diagonal moves and use the diagonal heuristic.
var graphDiagonal = new Graph([
	[1,1,1,1],
	[0,1,1,0],
	[0,0,1,1]
], { diagonal: true });
var startDiagonal = graphDiagonal.grid[0][0];
var endDiagonal = graphDiagonal.grid[1][2];
var resultWithDiagonals = astar.search(graphDiagonal, startDiagonal, endDiagonal, { heuristic: astar.heuristics.diagonal });
console.log('Path (with diagonals):', resultWithDiagonals.map(node => `(${node.x},${node.y})`).join(' -> '));

// With weights: Define custom movement costs for nodes (0 for walls).
var graphWithWeight = new Graph([
	[1,1,2,30],
	[0,4,1.3,0],
	[0,0,5,1]
]);
var startWithWeight = graphWithWeight.grid[0][0];
var endWithWeight = graphWithWeight.grid[1][2];
var resultWithWeight = astar.search(graphWithWeight, startWithWeight, endWithWeight);
console.log('Path (with weights):', resultWithWeight.map(node => `(${node.x},${node.y})`).join(' -> '));

view raw JSON →