How to solve a basic maze using functions in python?

我怕爱的太早我们不能终老 提交于 2019-12-02 19:49:20

问题


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()

回答1:


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




回答2:


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()



回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!