我正在尝试用python编写BFS迷宫求解器,以便代理可以通过Maze类中的moves()
和neighbor()
函数引导显示的网格。但是,我正在编写代理并在实现它时遇到一些问题。有谁知道我应该在agent.bfs()
函数中输入什么变量而不是路径,到目前为止,我已经做了一些循环逻辑。
import time
import queue
class Maze(object):
"""A pathfinding problem."""
def __init__(self, grid, location):
"""Instances differ by their current agent locations."""
self.grid = grid
self.location = location
def display(self):
"""Print the maze, marking the current agent location."""
for r, row in enumerate(self.grid):
for c, col in enumerate(self.grid):
if (r, c) == self.location:
print("*", end="")
elif (r,c)==(19,18):
print("o", end="")
else:
print(self.grid[r][c],end="")
print()
print()
def moves(self,way):
"""Return a list of possible moves given the current agent location."""
if way=="L" :
self.location=self.location(-1,0)
print("Left")
self.display()
elif way=="R" :
self.location=self.location(1,0)
print("Right")
self.display()
elif way=="U" :
self.location=self.location(0,1)
print("Up")
self.display()
elif way=="D" :
self.location=self.location(0,-1)
print("Down")
self.display()
return self.location
def neighbor(self, move):
"""Return another Maze instance with a move made."""
way="NULL"
if self.location(-1,0)==" ":
way="L"
elif self.location(1,0)==" ":
way="R"
elif self.location(0,1)==" ":
way="U"
elif self.location(0,-1)==" ":
way="D"
return way
class Agent(object):
"""Knows how to find the exit to a maze with BFS."""
def bfs(self, maze, goal,path):
"""Return an ordered list of moves to get the maze to match the goal."""
#line= queue.Queue()
#line.put("+")
#add=""
visited=[]
frontier=[maze.location]
if maze.location==goal:
maze.display()
# time.sleep(20)
return
else:
if path not in visited:
visited.append(path)
neighbors=maze.moves [path]
for neighbor in neighbors:
queue.append(neighbor)
return visited
#put = add + x
#if Maze(grid,(1,1)):
#line.put(put)
def main():
"""Create a maze, solve it with BFS, and console-animate."""
grid = ["XXXXXXXXXXXXXXXXXXXX",
"X X X X",
"X XXXXX XXXX XXX XXX",
"X X X X X",
"X X XXX XXXXXX X X X",
"X X X X X X",
"X XXX XXXXXX XXXXX X",
"X XXX X X X X",
"X XXX XXXXX",
"XXXXX XXXXXX X",
"X XXX X X X X X",
"XXX XXX X X XXXX X X",
"X X X XX X X X",
"XXXXX XXXX X XXX",
"X X XXX X X",
"X XXXXX X XXXX XXX X",
"X X X X X X",
"X X XXXXXX X XXXXX X",
"X X X",
"XXXXXXXXXXXXXXXXXX X"]
maze = Maze(grid, (1, 1))
maze.display()
agent = Agent()
goal = Maze(grid, (19, 18))
path = agent.bfs(maze, goal)
while path:
move = path.pop(0)
maze = maze.neighbor(move)
time.sleep(0.25)
maze.display()
if __name__ == '__main__':
main()