a simple shortest-path solver

I'm trying to remove some drudgery:
  https://merveilles.town/@akkartik/112086504775924524
This commit is contained in:
Kartik K. Agaram 2024-03-12 23:01:58 -07:00
parent b94cb009b0
commit 3c4ed9f0f8
2 changed files with 49 additions and 0 deletions

View File

@ -15,6 +15,7 @@ function car.load()
car.resize()
level_state = load_level(levels[curr_level])
player = player_state(level_state)
path = unwind_path(find_path(level_state, {x=15,y=12}, {x=12, y=9}))
end
function car.draw()
@ -25,6 +26,7 @@ function car.draw()
draw_buttons()
draw_level_number()
draw_win_state()
draw_path(path)
draw_hud()
end

47
screens/solve Normal file
View File

@ -0,0 +1,47 @@
function find_path(level, src, dst)
local done = initialize_array(false, lh, lw)
local cands = {}
table.insert(cands, {x=src.x, y=src.y})
while #cands > 0 do
local cand = table.remove(cands, 1)
local x,y = cand.x, cand.y
if x == dst.x and y == dst.y then return cand end
if y >= 1 and y <= lh and x >= 1 and x <= lw and not done[y][x] then
done[y][x] = true
local curr = level[y][x]
if curr ~= CELL_WALL and curr ~= CELL_CRATE and curr ~= CELL_CRATE_ON_TARGET then
table.insert(cands, {x=x-1, y=y, prev=cand})
table.insert(cands, {x=x+1, y=y, prev=cand})
table.insert(cands, {x=x, y=y-1, prev=cand})
table.insert(cands, {x=x, y=y+1, prev=cand})
end end end end
function unwind_path(c)
local result = {}
while c do
table.insert(result, {x=c.x, y=c.y})
c = c.prev
end
return result
end
function draw_path(path)
color(1,0,0)
for _,cell in ipairs(path) do
rect('line', left+(cell.x-1)*side, top+(cell.y-1)*side, side, side)
end end
function initialize_array(val, dim, ...)
local result = {}
local other_dims = {...}
if #other_dims == 0 then
for i=1,dim do
table.insert(result, val)
end
else
for i=1,dim do
table.insert(result, initialize_array(val, ...))
end
end
return result
end