I am trying to implement this method recursively. However, after a few seconds I get an Index Error sayings "Can't pop from empty stack." How can I correct this? Essentially, the point of the entire code (which I have not included) is to create a maze and guide a robot through it.
empty (unexplored) cell
EMPTY = 0
cell with an obstacle
OBSTACLE = 1
cell that is on the path
ON_PATH = 2
cell that has been explored, but is not on the path
EXPLORED = 3
cell the robot is in
ROBOT = 4
def solve(self, location):
eventType, done = None, False
self.maze[location[0]][location[1]] = ROBOT
if self.mode == GRAPHICAL_FULL:
self.display_init()
self.draw_maze()
elif self.mode == GRAPHICAL_LIMITED:
self.display_init()
self.update_maze()
while eventType != QUIT and not done:
if self.mode == GRAPHICAL_FULL or self.mode == GRAPHICAL_LIMITED:
for event in pygame.event.get():
eventType = event.type
new_location = self.find_next_step()
if new_location is None:
# Mark the current location as a dead end
self.maze[location[0]][location[1]] = EXPLORED
# pop the next cell off the path stack (go back one space)
location = self.path.pop()
self.maze[location[0]][location[1]] = ROBOT
self.solve(location)
else:
self.maze[location[0]][location[1]] = ON_PATH
self.path.push(location)
location = new_location
self.solve(location)
if self.mode == GRAPHICAL_FULL or self.mode == GRAPHICAL_LIMITED:
self.clock.tick(self.framerate)
self.update_maze()
self.screen.blit(self.background, (0,0))
pygame.display.flip()
if (self.maze[0][0] == EXPLORED or
location == (self.dimension['x']-1, self.dimension['y']-1)):
self.path.push(location)
done = True
return self.path
def find_next_step(self):
# Search for a place to go
for direction in SEARCH_ORDER:
new_location = (self.location[0] + direction['x'],
self.location[1] + direction['y'])
if (0 <= new_location[0] < self.dimension['x'] and
0 <= new_location[1] < self.dimension['y'] and
self.maze[new_location[0]][new_location[1]] == EMPTY):
self.maze[new_location[0]][new_location[1]] = ROBOT
return new_location
return None
eventTypetoQUITinside theforloop and then proceed with the recursive call anyway. Is this what you really want?