I am trying to write a code that solves a basic maze made up of a list of lists with '#' symbolizing walls, '.' are free spaces, S is the start and E is the end. My algorithm consists of first checking to see if the space to the right is free, if not it then checks the space up, then down, and finally to the left. I also realize that this creates a problem if there is a dead end but I'll worry about that later. So far I have code that prints the list and finds the index value of the start point which is (2,0). Basically what I am trying to do is take that starting value as the argument for my def solve function and then iterate over my algorithm while marking visited positions as 'x'... if that makes any sense. When I run the code I keep getting
if maze[r+1][c] == '.':
NameError: name 'r' is not defined
Also I can't seem to print my maze correctly on this website so here is my maze.
def main():
print_maze()
start()
solve(start())
print_maze()
def print_maze():
for r in range(0,len(maze)):
for c in range(0,len(maze)):
print(maze[r][c], end='')
print('')
def start():
find_value = 'S'
for r in range(0,len(maze)):
for c in range (0,len(maze)):
if find_value in maze[r][c]:
return(r,c)
break
def solve(position):
if maze[r+1][c] == '.':
maze[r][c] = 'x'
return (r,c)
elif maze[r][c+1] == '.':
maze[r][c] = 'x'
return (r,c)
elif maze[r][c-1] == '.':
maze[r][c] = 'x'
return (r,c)
elif maze[r-1][c] == '.':
maze[r][c] = 'x'
return (r,c)
else:
print('Route Error')
main()
The error you are encountering occurs because main
calls solve
without a required argument.
def main():
print_maze()
start()
solve() # Error! Missing required arg
print_maze()
Since solve
redefines start_point
right away you can just remove that required argument:
def solve():
start_point = start()
Finally, you didn't provide maze
so anybody trying to help you beyond this problem won't be able to
You need to pass the value returned from start()
into the solve()
function because you listed it as an argument. You can then remove the start_point=
portion from the solve()
function.
def main():
print_maze()
start = start()
solve(start)
print_maze()
Try to change the def slove format eg; == "X" = "x²"
来源:https://stackoverflow.com/questions/56009216/how-to-solve-a-basic-maze-using-functions-in-python