UNPKG

@mousepox/math

Version:

Math-related objects and utilities

60 lines (59 loc) 1.7 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.astar = void 0; const core_1 = require("./core"); function makeNode(x, y, parent) { return { f: 0, g: 0, parent, x, y }; } function addNode(nodes, node) { const len = nodes.length; for (let i = 0; i < len; i++) { if (nodes[i].f > node.f) { nodes.splice(i, 0, node); return; } } nodes.push(node); } function createPathFromNode(node) { let n = node; const path = []; while (n !== undefined) { path.push({ x: n.x, y: n.y }); n = n.parent; } path.reverse(); return path; } function astar(grid, x1, y1, x2, y2) { const start = makeNode(x1, y1); const goal = makeNode(x2, y2); const open = [start]; const closed = []; while (open.length > 0) { const node = open.shift(); if (node === undefined) { break; } if (node.x === goal.x && node.y === goal.y) { return createPathFromNode(node); } else { grid.forEachAdjacent(node.x, node.y, (value, x, y) => { if (value !== 0) { return; } const index = grid.xyToIndex(x, y); if (closed.indexOf(index) === -1) { const n = makeNode(x, y, node); n.g = node.g + (0, core_1.distance)(n.x, n.y, node.x, node.y); n.f = n.g + (0, core_1.distance)(n.x, n.y, goal.x, goal.y); addNode(open, n); closed.push(index); } }); } } return; } exports.astar = astar;