Created
April 18, 2023 12:59
-
-
Save Mulperi/fdb45fc600d1233914e5e3a1b932389b to your computer and use it in GitHub Desktop.
PICO-8 Lua breadth first search pathfinding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function inlist(list, item) | |
for i=1, #list do | |
if list[i].x == item.x and | |
list[i].y == item.y then | |
return true | |
end | |
end | |
return false | |
end | |
function bfs(start, target) | |
local queue = {} | |
local path = {} | |
local visited = {} | |
add(visited, start) | |
add(queue, start) | |
while #queue > 0 do | |
local cell = queue[1] | |
del(queue, queue[1]) | |
if cell.x == target.x and cell.y == target.y then | |
add(path, cell) | |
while cell.parent do | |
cell = cell.parent | |
add(path, cell) | |
end | |
break | |
end | |
-- add neighbors to queue if they are not blocked. | |
for i = 1, 4 do | |
if cell.n[i] | |
and not cell.n[i].blocked | |
and not inlist(visited, cell.n[i]) | |
then | |
add(queue, cell.n[i]) | |
add(visited, cell.n[i]) | |
cell.n[i].parent = cell | |
end | |
end | |
end | |
return path | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment