diff --git a/jumper/core/path.lua b/jumper/core/path.lua index 826c5e4..2819af3 100644 --- a/jumper/core/path.lua +++ b/jumper/core/path.lua @@ -67,12 +67,15 @@ if (...) then --- Evaluates the `path` length -- @class function + -- @tparam function heuristic Optional heuristic function for determining. + -- distance between nodes. Default: @{Heuristic.EUCLIDIAN}. -- @treturn number the `path` length -- @usage local len = p:getLength() - function Path:getLength() + function Path:getLength(heuristic) + local heuristic = heuristic or Heuristic.EUCLIDIAN local len = 0 for i = 2,#self._nodes do - len = len + Heuristic.EUCLIDIAN(self._nodes[i], self._nodes[i-1]) + len = len + heuristic(self._nodes[i], self._nodes[i-1]) end return len end @@ -193,6 +196,18 @@ if (...) then return self end + + --- Return a simplified form of the path. + -- @treturn table Array of `{x, y}` values in the path. + -- @usage x1, y1 = unpack(path:simplify()[1]) + function Path:simplify() + local simple = {} + for node in self:iter() do + simple[#simple + 1] = {node._x, node._y} + end + return simple + end + return setmetatable(Path, {__call = function(self,...) return Path:new(...) diff --git a/specs/path_specs.lua b/specs/path_specs.lua index cb880fe..51f7925 100644 --- a/specs/path_specs.lua +++ b/specs/path_specs.lua @@ -43,6 +43,12 @@ context('Module Path', function() p = Path() for i = 1,10 do p._nodes[#p._nodes+1] = Node(i,i) end assert_less_than(p:getLength()-9*math.sqrt(2),1e-6) + + --Test with diagonal distance + local Heuristics = require ('jumper.core.heuristics') + p = Path() + for i = 1,10 do p._nodes[#p._nodes+1] = Node(i,i) end + assert_equal(p:getLength(Heuristics.DIAGONAL), 9) end) test('Path:fill() interpolates a path', function() diff --git a/specs/pathfinder_specs.lua b/specs/pathfinder_specs.lua index bbba5b3..954dd14 100644 --- a/specs/pathfinder_specs.lua +++ b/specs/pathfinder_specs.lua @@ -140,7 +140,7 @@ context('Module Pathfinder', function() assert_equal(pf:getFinder(), 'ASTAR') end) - test('Passing nil sets \'ASTAR\` as the finder if no previous finder was set, is \'ASTAR\'', function() + test('Passing nil sets \'ASTAR\' as the finder if no previous finder was set, is \'ASTAR\'', function() local pf = PF(grid) pf:setFinder() assert_equal(pf:getFinder(), 'ASTAR')