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 5×5, 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.:
def is_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)
while self.is_valid(new[0], new[1]) == False:
new = choice(neighboor)
while self.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:
while True:
new = choice(neighboor)
if self.is_valid(new[0], new[1]): break
while self.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.
2
solved build a perfect maze recursively in python