diff --git a/screens/main b/screens/main index 870db64..c9c74a3 100644 --- a/screens/main +++ b/screens/main @@ -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 diff --git a/screens/solve b/screens/solve new file mode 100644 index 0000000..a7c0700 --- /dev/null +++ b/screens/solve @@ -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