Hello, trying to make use of a maze creation algorithm called the recursive backtracker.
PS: The original code was made in python (so not by me.) and i need help fixing it so it works.
local function valid(i,j)
return (i >= 0 and i <=2) and (j >= 0 and j <= 2)
end
local matrix = {[0] = {'.', '.', '.'}, [1] = {'.', 'X', '.'}, [2] = {'.', 'G', 'X'}}
-- an array that marks indices as visited or not
local visit = {[0] = {0,0,0},[1] = {0,0,0},[2] = {0,0,0}}
-- the path that is used in the back tracking
local path = {}
-- this will be a list of lists containing ALL the paths that can reach the GOAL
local ans = {}
-- these are the neighbors indices
local row = {-1, 1, 0, 0}
local col = {0, 0, 1, -1}
-- just a dummy matrix to start with
local function backtrack(i,j)
-- if matrix[i][j] is visited, then do nothing
-- if it is a wall, then do not insert it in the path from the first place
print(i,j)
print(visit[i])
if visit[i][j] ~= 0 or matrix[i][j] == 'X' then
return
end
-- mark the index as visited as to not visit it again
visit[i][j] = 1
-- add the index to the path
table.insert(path,table.unpack({i,j}))
-- if it is the GOAL, then store this path somewhere,
-- and pop the last index to traverse other paths that reaches the GOAL
if matrix[i][j] == 'G' then
-- any paths that reach the GOAL are appended here
table.insert(ans,table.pack(path))
return
end
-- loop on the neighbors. if they are valid indices, do the same work again
for k = 1,3,1 do
local nwi = i + row[k]
local nwj = j + col[k]
if valid(nwi, nwj) then
backtrack(nwi, nwj)
-- after finishing this index, just pop because we do not need it any more
end
end
return
end
backtrack(0,0)
if #ans == 0 then
print("no path found!")
else
print(ans)
end
Orginal code ^^
So, basically it errors at the fifth line in the function, attempt to index nil with number. Any help is appreciated :))))