import random from itertools import product from typing import Tuple, Set, Union, Any, List, NamedTuple from pprint import pprint class Cell(NamedTuple): x: int y: int class Wall(NamedTuple): first_cell: Cell second_cell: Cell class Maze: def __init__(self, width: int, height: int): self.cells = set(Cell(*c) for c in product(range(width), range(height))) self.maze = dict() for cell in self.cells: self.maze[cell] = self.get_neighbours(cell) self.walls = self.get_walls() self.generate_maze() def get_neighbours(self, cell: Cell) -> Set[Cell]: diffs = ((0, 1), (0, -1), (1, 0), (-1, 0)) return set(Cell(cell.x + x, cell.y + y) for x, y in diffs if Cell(cell.x + x, cell.y + y) in self.cells) def get_walls(self) -> Set[Wall]: walls = set() for cell in self.cells: walls.update(set(Wall(*sorted([cell, c])) for c in self.maze[cell])) return walls def generate_maze(self) -> None: visited = set() unvisited = list(self.cells) node = random.choice(unvisited) visited.add(node) unvisited.remove(node) while unvisited: random_neighbour = random.choice(list(self.maze[node])) if random_neighbour not in visited: self.walls.remove(Wall(*sorted([node, random_neighbour]))) visited.add(random_neighbour) try: unvisited.remove(random_neighbour) except ValueError: pass node = random_neighbour def generate_prim_maze(self) -> None: visited = set() node = random.choice(list(self.cells)) visited.add(node) removed_walls = set() wall_list = [w for w in self.walls if node in w] while wall_list: random_wall = random.choice(wall_list) wall_list.remove(random_wall) cell1, cell2 = random_wall if (cell1 in visited) != (cell2 in visited): removed_walls.add(random_wall) self.walls.remove(random_wall) visited.add(cell1) visited.add(cell2) wall_list.extend( set(w for w in self.walls if (cell1 in w) or (cell2 in w)).difference(removed_walls) ) if __name__ == "__main__": maze = Maze(3, 3) pprint(maze.walls)