Implemented Aldous-Broder algorithm

This commit is contained in:
Kyler Olsen 2025-01-31 12:06:35 -07:00
parent e3eb9119ad
commit f704fb0343
2 changed files with 73 additions and 1 deletions

71
maze.py
View File

@ -947,3 +947,74 @@ class Wilson(VectorMaze):
elif direction == VectorEnum.Left: return index[0]-1, index[1]
elif direction == VectorEnum.Right: return index[0]+1, index[1]
else: return index[0], index[1]
class AldousBroder(VectorMaze):
__cells: list[list[VectorEnum]]
__width: int
__height: int
__current: tuple[int,int]
__remaining: int
def __init__(self, width: int, height: int | None = None):
self.__width = width
self.__height = height or width
self.__cells = [
list([VectorEnum.Null for _ in range(self.width)])
for _ in range(self.height)]
x, y = random.randint(0,self.width-1), random.randint(0,self.height-1)
self.__cells[y][x] = VectorEnum.Zero
self.__current = (x,y)
self.__remaining = self.width * self.height - 1
@property
def width(self) -> int:
return self.__width
@property
def height(self) -> int:
return self.__height
@property
def highlighted(self) -> tuple[int,int] | None:
# for y in range(self.height):
# for x in range(self.width):
# if self.__cells[y][x] == VectorEnum.Null:
# return self.__current
# return None
if self.__remaining > 0: return self.__current
else: return None
def __getitem__(self, index: tuple[int, int]) -> VectorEnum:
x, y = index
return self.__cells[y][x]
def step(self) -> bool:
if self.highlighted is not None:
neighbors = self._neighbors(self.highlighted)
cell = neighbors[random.randint(0,len(neighbors)-1)]
if self.__cells[cell[1]][cell[0]] == VectorEnum.Null:
self.__cells[cell[1]][cell[0]] = self.__direction(
self.highlighted, cell)
self.__remaining -= 1
self.__current = cell
return True
else: return False
def __direction(
self,
start: tuple[int,int],
end: tuple[int,int],
) -> VectorEnum:
if start[0] > end[0]: return VectorEnum.Right
if start[0] < end[0]: return VectorEnum.Left
if start[1] > end[1]: return VectorEnum.Down
if start[1] < end[1]: return VectorEnum.Up
return VectorEnum.Zero

View File

@ -121,7 +121,8 @@ VEC_MAZE_SIZE = (MAZE_SIZE + 1) // 2
# my_maze = maze.RecursiveDivision(MAZE_SIZE, depth_first=False)
# my_maze = maze.RecursiveDivision(MAZE_SIZE, binary=True)
# my_maze = maze.VectorWrapper(maze.Prim(VEC_MAZE_SIZE))
my_maze = maze.VectorWrapper(maze.Wilson(VEC_MAZE_SIZE))
# my_maze = maze.VectorWrapper(maze.Wilson(VEC_MAZE_SIZE))
my_maze = maze.VectorWrapper(maze.AldousBroder(VEC_MAZE_SIZE))
# for _ in range(512): my_maze.step()
# for _ in range(2048): my_maze.step()