Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions jumper/core/path.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(...)
Expand Down
6 changes: 6 additions & 0 deletions specs/path_specs.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
2 changes: 1 addition & 1 deletion specs/pathfinder_specs.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down