-
Notifications
You must be signed in to change notification settings - Fork 0
/
PathFinding.js
46 lines (41 loc) · 1.58 KB
/
PathFinding.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
var PF = require('pathfinding');
var finder = new PF.AStarFinder();
/**
* Finds the shortest path, from start -> target
* @param {Object} start Position object with x and y key-value pairs
* @param {Object} target Position object with x and y key-value pairs
* @param {Array} matrix Matrix with rows and columns.
* Values of 1 represents blocked tile
* Values of 0 represents walkable tile
* @return {Array} A list of array coordinates [x, y] to get to target
*/
var findPath = function findPath(start, target, matrix) {
var grid = new PF.Grid(matrix.length, matrix[0].length, matrix);
var path = finder.findPath(start.x, start.y, target.x, target.y, grid);
if (path.length > 0) {
return path;
} else {
console.warn('Unreachable target', target);
return null;
}
};
/**
* @param {Object} start Position object with x and y key-value pairs
* @param {Object} target Position object with x and y key-value pairs
* @param {Array} matrix Matrix with rows and columns.
* Values of 1 represents blocked tile
* Values of 0 represents walkable tile
* @return {Object} Position object with x and y key-value pairs
*/
exports.takeStep = function takeStep(start, target, matrix) {
var path = findPath(start, target, matrix);
// Return same nullvalue as findPath does
if (!path) return path;
// PathFinding returns the current position as the 0th step
var step = path[1];
return {
nextStep: { x: step[0], y: step[1] },
position: target,
distance: path.length
};
};