-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcase.lua
More file actions
86 lines (73 loc) · 2.49 KB
/
case.lua
File metadata and controls
86 lines (73 loc) · 2.49 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
-- Module implementing pathfinding abilities for the cases on the grid
new = function(walkable)
local case = {}
case.g = 0 -- Distance from source
case.h = 0 -- Heuristic function result(usually pythagorian distance between current and goal)
case.f = 0 -- will be set to g + h
case.previous = nil
-- position of the grid which will be set after creation
case.x = nil
case.y = nil
case.walkable = walkable
function case:neighbours(grid)
-- Returns table of neighbors
local n = {}
if self.y > 1 and grid[self.y-1][self.x].walkable then -- upper neighbour
table.insert(n, grid[self.y-1][self.x])
end
if self.y < #grid and grid[self.y+1][self.x].walkable then -- lower neighbour
table.insert(n, grid[self.y+1][self.x])
end
if self.x > 1 and grid[self.y][self.x-1].walkable then -- left neighbour
table.insert(n, grid[self.y][self.x-1])
end
if self.x < #grid[1] and grid[self.y][self.x+1].walkable then -- right neighbour
table.insert(n, grid[self.y][self.x+1])
end
return n
end
function case:draw(cw, ch, c, debug)
local tx = (case.x-1) * (cw)
local ty = (case.y-1) * (ch)
love.graphics.setColor(c)
love.graphics.rectangle("fill", tx, ty, cw, ch)
if debug then
love.graphics.setColor(0, 0, 0)
love.graphics.draw(
love.graphics.newText(
g.font, self:debug_str()),
tx, ty)
end
end
function case:debug_str()
return "["..tostring(self.x)..";"..tostring(self.y).."] | f: "..tostring(round(self.f,3)).."\ng: "..tostring(round(self.g,3)).."\nh: "..tostring(round(self.f,3))
end
function case:dist_between(other)
return math.sqrt(
(self.x-other.x) * (self.x-other.x) +
(self.y-other.y) * (self.y-other.y)
)
end
function case:make_f()
case.f = case.g + case.h
return case.f
end
function case:build_path(source) -- Retraces the path using case.previous until it finds the source
local current = self
local path = {}
while true do
table.insert(path, current)
if current == source then
goto done
else
current = current.previous
end
end
::done::
return path
end
return case
end
return {
new = new
}