maze-solver/maze.py

101 lines
3.1 KiB
Python
Raw Normal View History

from typing import List
from time import sleep
import random
from graphics import Window
from cell import Cell
class Maze:
"""
Maze represents a two-dimensional grid of Cells.
"""
def __init__(
self,
x_position: int,
y_position: int,
num_cell_rows: int,
num_cells_per_row: int,
cell_size_x: int,
cell_size_y: int,
window: Window = None,
seed=None,
) -> None:
self._x_position = x_position
self._y_position = y_position
self._num_cell_rows = num_cell_rows
self._num_cells_per_row = num_cells_per_row
self._cell_size_x = cell_size_x
self._cell_size_y = cell_size_y
self._window = window
self._seed = None
# Generate the seed if it does not exist
if seed:
self._seed = seed
else:
random.seed(self._seed)
# Create the Maze's cells
self._cells: List[List[Cell]] = [None for i in range(self._num_cell_rows)]
self._create_cells()
self._open_entrance_and_exit()
def _create_cells(self) -> None:
"""
creates all the cells and draws them.
"""
cursor_x = self._x_position
cursor_y = self._y_position
for i in range(self._num_cell_rows):
cells: List[Cell] = [None for j in range(self._num_cells_per_row)]
for j in range(self._num_cells_per_row):
cell = Cell(
cursor_x,
cursor_y,
(cursor_x + self._cell_size_x),
(cursor_y + self._cell_size_y),
self._window
)
cells[j] = cell
if j == self._num_cells_per_row - 1:
cursor_x = self._x_position
else:
cursor_x += self._cell_size_x
self._cells[i] = cells
cursor_y += self._cell_size_y
if self._window:
self._draw_cells()
def _open_entrance_and_exit(self) -> None:
"""
opens the maze's entrance and exit cells by breaking their respective
walls. The entrance is located at the top left and the exit is located
at the bottom right of the maze.
"""
self._cells[0][0].configure_walls(top=False)
self._cells[0][0].draw()
self._cells[self._num_cell_rows - 1][self._num_cells_per_row - 1].configure_walls(bottom=False)
self._cells[self._num_cell_rows - 1][self._num_cells_per_row - 1].draw()
def _draw_cells(self) -> None:
"""
draws all the cells on the maze with a short pause between each cell
for animation purposes.
"""
for i in range(self._num_cell_rows):
for j in range(self._num_cells_per_row):
self._cells[i][j].draw()
self._animate()
def _animate(self) -> None:
"""
redraws the application and pauses for a short period of time to
provide an animation effect.
"""
self._window.redraw()
sleep(0.05)