Skip to content

Instantly share code, notes, and snippets.

@Mulperi
Created April 18, 2023 12:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mulperi/fdb45fc600d1233914e5e3a1b932389b to your computer and use it in GitHub Desktop.
Save Mulperi/fdb45fc600d1233914e5e3a1b932389b to your computer and use it in GitHub Desktop.
PICO-8 Lua breadth first search pathfinding
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