Build A Perfect Maze Recursively In Python
I have this project to build a perfect maze recursively by using python. I have a MyStack class which creates a stack to track the path that I go through. And a Cell class which re
Solution 1:
The problem is that you're not ensuring that the steps in your walk are valid.
The way you have it currently, walk
could pick a neighboor
that is out of the bounds of the maze. For example, if a maze is 5x5, attempting to access maze[5][?]
or maze[?][5]
will result in an IndexError
like you get.
To fix this, you could define an is_valid
method for your maze class, e.g.:
defis_valid(self, x, y):
return (0 <= x < self.size) and (0 <= y < self.size)
Then, you when you pick a neighboor
, you ensure it's valid:
#...else:
new = choice(neighboor)
whileself.is_valid(new[0], new[1]) == False:
new = choice(neighboor)
whileself.maze[new[0]][new[1]].getVisit():
#...
This snippet picks a neighboor
, then, if it's not valid, regenerates new
until it finds a valid one.
But this loop would be better written as:
#...else:
whileTrue:
new = choice(neighboor)
ifself.is_valid(new[0], new[1]): breakwhileself.maze[new[0]][new[1]].getVisit():
#...
There are more problems with your code, however, as you'll eventually see, but this will get you past this specific one.
Post a Comment for "Build A Perfect Maze Recursively In Python"