diff options
| author | yctct <yctct@yctct.com> | 2026-11-25 18:12:50 +0100 |
|---|---|---|
| committer | yctct <yctct@yctct.com> | 2026-11-25 18:12:50 +0100 |
| commit | 6bd4eedc6a41fba60d7e0bc8776272541657c284 (patch) | |
| tree | 90b36731e7c6e0dd631d230d2bf777b002238594 | |
| -rw-r--r-- | .gitignore | 4 | ||||
| -rw-r--r-- | LICENSE | 19 | ||||
| -rw-r--r-- | README | 136 | ||||
| -rw-r--r-- | dist/mazegen-0.0.1-py3-none-any.whl | bin | 0 -> 10840 bytes | |||
| -rw-r--r-- | dist/mazegen-0.0.1.tar.gz | bin | 0 -> 11394 bytes | |||
| -rw-r--r-- | pyproject.toml | 24 | ||||
| -rw-r--r-- | src/mazegen/__init__.py | 6 | ||||
| -rw-r--r-- | src/mazegen/__main__.py | 16 | ||||
| -rw-r--r-- | src/mazegen/cell.py | 19 | ||||
| -rw-r--r-- | src/mazegen/find_shortest_path.py | 129 | ||||
| -rw-r--r-- | src/mazegen/flush.py | 22 | ||||
| -rw-r--r-- | src/mazegen/maze.py | 347 |
12 files changed, 722 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5d6bca0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +__pycache__ +*swp +*txt +mazegen.egg-info/ @@ -0,0 +1,19 @@ +Copyright (c) 2026 amazing contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. @@ -0,0 +1,136 @@ +## Description + +This directory carries a package to generate a maze. + +## Usage + +The maze generator will return a list of list of Cell objects. + +Example taken from __main__.py: + + + from .maze import Maze + + def main() -> None: + # pass parameters to Maze + # width, height, entry, exit, perfect + maze: Maze = Maze(20, 15, (1, 1), (20, 15), True) + maze.initiate_grid() + maze.draw_pattern() + maze.dfs_carve() + + print(maze) # will print a maze object + print(maze.grid) # will print the maze grid + print(maze.grid[1][1]) # will print a cell object (1, 1) + + if __name__ == "__main__": + main() + +## Instructions + +Create a virtual environment: + + $ Python3 -m venv .venv + +Activate a virtual environment + + $ source .venv/bin/activate + +Uncompress package: + + $ tar xvf mazegen-\*.tar.gz + $ mazegen-*/src + +Run the package: + + $ python -m mazegen + +Deactivate a virtual environment + + $ deactivate + +## Algorithm for maze generation + +### Carving the maze with Deep-First Search (DFS) + +This program uses DFS to carve the maze. Depth-first search is a graph traversal algorithm that starts at a given root node and traverses the graph as long as it has unvisited reachable nodes. As soon as it hits a 'dead end', it backtracks to the latest visited nodes, that still has reachable unvisited nodes and continues from there. +It needs a stack data structure to be implemented, which can also be the internal function call stack of a recursive implementation. + +How our implementation works: + +The recursive helper function *dfs_recursion(self, curr_pos: tuple)* takes the position of any given cell in the grid (in our case the entry cell) and starts recursion from there. +In each recursion, it performs the following steps: + +- set the current cell to 'visited' +- compute the coordinates of the surrounding (= reachable) cells in the grid (called up, down, left, right) and store them in the list 'reachable' +- It goes into a while-true loop to go into recursion for every reachable cell (true loop is exited if reachable list is empty) +- Inside the loop: + - filter out all visited cells from reachable list + - check break condition + - choose random cell from reachable list + - depending on which surrounding cell was chosen (up, left, right or down) destroy the wall into that direction and also the adjacent wall from the surrounding cell + - we do that by subtracting the amount from the wall configuration number, that will set the bit to 0 that represents the chosen direction (4 bit number is code for NESW -> e.g. 1011) + - go into recursion with the position of the chosen surrounding cell +- algorithm will terminate, as soon as all recursive calls have been eliminated from the call stack (which happens, once all cells have been visited) + +Side note: The maze has a padding of invisible visited cells surrounding its borders, which makes sure the DFS can't break out of the maze + +### Finding the shortest path with Breadth First Search (BFS) + +This program uses BFS to find the shortest path from ENTRY to EXIT. + +First we create a list 'queue' where cells will be added. + +The algorithm start traversing the maze starting from ENTRY. + +For each cell i.e. 'current', the function: + +- mark the current cell as VISITED (VISITED is an attribute of a Cell object) +- add the current cell to the queue +- check whether there are walls blocking access to the adjacent cells of the current cell +- if there is no wall: + - check whether the adjacent cell is VISITED + - if the adjacent cell is not VISITED + - add the adjacent cell to the queue + - compute the shortest path to that cell +- repeat the above steps for all adjacent cells +- remove the current cell from the queue +- repeat the above steps as long as the queue exist + +**How do we check whether there is a wall?** + +Each function has an attribute WALLS which holds an hexadecimal digit. For example, when cell.WALLS is 15 it means that the cell has 4 walls. + +How can we tell that 15 means that there are 4 walls (North, East, South, West)? + +Walls are represented under their binary form, that is: 1 1 1 1. Each binary corresponds to a cardinal direction, respectively North, East, South, West. 1 1 1 1 means that a cell has four walls, 1 0 1 0 means that a cell has walls on both, its North and South sides. + +How does 15 relate to 1 1 1 1? + +15 = 8 + 4 + 2 + 1 + +each digit relates to a binary 1 1 1 1. + +For example the hexadecimal digit 11 is 8 + 0 + 2 + 1 so 1 0 1 1 meaning that a cell whose hexadecimal digit is 11 has walls on its North, South and West sides. + +So far we can tell if a cell has walls by *looking* at the binaries, but how can we, for example, compute whether a cell has a wall on the West side? + +We run modulus 2 on 15. If this is False, the least significant bit (the most right value under its binary form 1 1 1 1) is 1, so there is a wall. + +If the value is 14 (8 + 4 + 2 + 0 so 1 1 1 0), modulus 2 returns 0, which tells us that there is no walls. + +How do we check the subsequent walls moving to the left? + +We run a floor division on the hexadecimal digit . + +For example, if we run a floor division of 15 // 2 we get 7. + +7 is 4 + 2 + 1 so 0 1 1 1. We omit the most left zero so we have 1 1 1, that is N E S. + +We can now run modulus 2 on 7 (which return 1, so there is a wall on the South side). + +## License + +Expat license, see LICENSE + + diff --git a/dist/mazegen-0.0.1-py3-none-any.whl b/dist/mazegen-0.0.1-py3-none-any.whl Binary files differnew file mode 100644 index 0000000..2a18929 --- /dev/null +++ b/dist/mazegen-0.0.1-py3-none-any.whl diff --git a/dist/mazegen-0.0.1.tar.gz b/dist/mazegen-0.0.1.tar.gz Binary files differnew file mode 100644 index 0000000..bf664ab --- /dev/null +++ b/dist/mazegen-0.0.1.tar.gz diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..81d7d0e --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,24 @@ +[build-system] +requires = ["setuptools >= 77.0.3"] +build-backend = "setuptools.build_meta" + +[project] +name = "mazegen" +version = "0.0.1" +authors = [ + { name="yctct"}, + { name="amazing_esra"} +] +description = "A maze generator" +readme = "README" +requires-python = ">=3.1" +classifiers = [ + "Programming Language :: Python :: 3", + "Operating System :: OS Independent", +] +license = "Expat" +license-files = ["LICENSE"] + +[project.urls] +Homepage = "https://git.yctct.com/mazegen" + diff --git a/src/mazegen/__init__.py b/src/mazegen/__init__.py new file mode 100644 index 0000000..8bd6adc --- /dev/null +++ b/src/mazegen/__init__.py @@ -0,0 +1,6 @@ +from .cell import Cell +from .maze import MazeGenerator +from .flush import flush_cells +from .find_shortest_path import compute_shortest_path + +__all__ = ["Cell", "MazeGenerator", "flush", "flush_cells", "compute_shortest_path"] diff --git a/src/mazegen/__main__.py b/src/mazegen/__main__.py new file mode 100644 index 0000000..3e8dc34 --- /dev/null +++ b/src/mazegen/__main__.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python3 +from .maze import MazeGenerator + + +def main() -> None: + maze: MazeGenerator = MazeGenerator(20, 15, (1, 1), (20, 15), True) + maze.initiate_grid() + maze.draw_pattern() + maze.dfs_carve() + print(maze) + maze.make_imperfect() + maze.visualize() + + +if __name__ == "__main__": + main() diff --git a/src/mazegen/cell.py b/src/mazegen/cell.py new file mode 100644 index 0000000..124e7fb --- /dev/null +++ b/src/mazegen/cell.py @@ -0,0 +1,19 @@ +import typing + + +class Cell: + def __init__(self, position: tuple) -> None: + """Initialize a cell""" + self.IS_DEST = False + self.VISITED = False + # show if cell is part of 42 pattern + self.IS_PATTERN = False + self.POSITION = position + # Scheme: 15 in binary -> 1111; Directions: 1=W 1=S 1=E 1=N + self.WALLS = 15 + # show if cell is part of shortest path + self.IS_PATH = False + # to store cells that path to self + self.PATH: typing.List = [] + # to store cardinal directions to self from start + self.DIRECTIONS: typing.List = [] diff --git a/src/mazegen/find_shortest_path.py b/src/mazegen/find_shortest_path.py new file mode 100644 index 0000000..cba43f6 --- /dev/null +++ b/src/mazegen/find_shortest_path.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 + +from .maze import MazeGenerator +import typing +from .flush import flush_cells +from .cell import Cell + + +def record_directions(current: Cell, adjacent: Cell, direction: str) -> None: + """Update the shortest path to a given cell + as path of cardinal directions""" + adjacent.DIRECTIONS = current.DIRECTIONS.copy() + adjacent.DIRECTIONS.append(direction) + + +def update_path(current: Cell, adj: Cell) -> None: + """Update the shortest path to a given cell as a path of cell objects""" + adj.PATH = current.PATH.copy() + adj.PATH.append(adj) + + +def process_adjacent_cell(adj: Cell, + queue: typing.List, + current: Cell, + direction: str) -> None: + """check if the adjacent cell is visited; if not: + append it to the queue, mark it as VISITED, + update its PATH and record cardinal directions + from the start of the maze to the adjacent cell""" + if not adj.VISITED: + adj.VISITED = True + queue.append(adj) + update_path(current, adj) + record_directions(current, adj, direction) + + +def has_wall(walls: int, direction: str) -> bool: + """Check whether there is a wall in a given direction""" + # We don't need floor division for N + if direction == "E": + walls = walls // 2 + if direction == "S": + for _ in range(2): + walls = walls // 2 + if direction == "W": + for _ in range(3): + walls = walls // 2 + if walls % 2 == 0: + return False + return True + + +def is_outlet(current: Cell, maze: MazeGenerator) -> bool: + """Check whether the current cell is the outlet to the maze""" + # unpack tuple to make a cell object + x2, y2 = maze.outlet + # x col, y row + end: Cell = maze.grid[x2][y2] + if current == end: + for cell in current.PATH: + cell.IS_PATH = True + return True + return False + + +def compute_shortest_path(maze: MazeGenerator) -> None: + """Find the shortest path from the entry to the outlet""" + queue: typing.List = [] + x1, y1 = maze.entry + # x col, y row + start: Cell = maze.grid[x1][y1] + start.IS_PATH = True + current: Cell = start + queue.append(current) + while queue: + # Have the algorithm reached the end/outlet + if is_outlet(current, maze) is True: + return + # Initiate cell objects for each adjacenting cell + # of 'current' cell + adjacent_west = maze.grid[x1 - 1][y1] + adjacent_south = maze.grid[x1][y1 + 1] + adjacent_east = maze.grid[x1 + 1][y1] + adjacent_north = maze.grid[x1][y1 - 1] + # Initiate a list with cardinal direction and their + # respective adjacent cells + neighbours: typing.List = [("W", adjacent_west), + ("S", adjacent_south), + ("E", adjacent_east), + ("N", adjacent_north) + ] + # Loop through each adjacent cells + for adjacent in neighbours: + # adjacent[0] is the cardinal direction e.g. S for 'South' + # adjacent[1] is the corresponding adjacent cell object + if has_wall(current.WALLS, adjacent[0]) is False: + process_adjacent_cell(adjacent[1], + queue, + current, + adjacent[0]) + # We only enter the block below + # if there are cells left in the queue + if len(queue) > 1: + current = queue[1] + x1, y1 = current.POSITION + queue.pop(0) + + +if __name__ == "__main__": + # MazeGenerator(width, height, entry, outlet, perfect) + # self.rows: int = self.height + 2 + # self.cols: int = self.width + 2 + maze: MazeGenerator = MazeGenerator(10, 14, (1, 1), (10, 14), True) + # print("width, x:", maze.width) + # print("col, x:", maze.cols) + # print("height, y:", maze.height) + # print("rows, y:", maze.rows) + print(f"start: {maze.entry}") + print(f"outlet/end: {maze.outlet}") + maze.initiate_grid() + maze.draw_pattern() + maze.dfs_carve() + flush_cells(maze) + compute_shortest_path(maze) + maze.show_path = True + maze.visualize() + x, y = maze.outlet + outlet = maze.grid[x][y] + print(outlet.DIRECTIONS) diff --git a/src/mazegen/flush.py b/src/mazegen/flush.py new file mode 100644 index 0000000..c334388 --- /dev/null +++ b/src/mazegen/flush.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 + +from .maze import MazeGenerator + + +def flush_cells(maze: MazeGenerator) -> None: + for col in maze.grid: + for cell in col: + cell.VISITED = False + + +if __name__ == "__main__": + maze: MazeGenerator = MazeGenerator(16, 10, (1, 1), (9, 12), True) + maze.initiate_grid() + maze.draw_pattern() + maze.dfs_carve() + maze.visualize() + flush_cells(maze) + for col in maze.grid: + for cell in col: + print(cell.VISITED, " ", end='') + print() diff --git a/src/mazegen/maze.py b/src/mazegen/maze.py new file mode 100644 index 0000000..7d2a554 --- /dev/null +++ b/src/mazegen/maze.py @@ -0,0 +1,347 @@ +#!/usr/bin/env python3 + +from .cell import Cell +import random + +# ANSI colors for entry and outlet cell coloring and maze coloring +red: str = "\033[31m" +green: str = "\033[32m" +yellow: str = "\033[33m" +blue: str = "\033[34m" +white: str = "\033[0m" +cyan: str = "\033[96m" +magenta: str = "\033[95m" + + +class MazeGenerator: + # using the attibute 'outlet' instead of 'exit' + # because the string 'exit' is a Python keyword + def __init__(self, + width: int = 15, + height: int = 15, + entry: tuple = (1, 1), + outlet: tuple = (15, 15), + perfect: bool = True, + seed: int | None = None) -> None: + # ensure neither width nor height is smaller than 2 + if width >= 2: + self.width: int = width + else: + self.width = 2 + if height >= 2: + self.height: int = height + else: + self.height = 2 + # set entry to lower right corner + # if out of bounds to right/down direction + if entry[0] > self.width or entry[1] > self.height: + self.entry: tuple = (self.width, self.height) + # set entry to upper left corner + # if out of bounds to left/up direction + elif entry[0] < 1 or entry[1] < 1: + self.entry = (1, 1) + else: + self.entry = entry + # set outlet to lower right corner + # if out of bounds to right/down direction + if outlet[0] > self.width or outlet[1] > self.height: + self.outlet: tuple = (self.width, self.height) + # set outlet to upper left corner if out of bounds to left/up direction + elif outlet[0] < 1 or outlet[1] < 1: + self.outlet = (1, 1) + else: + self.outlet = outlet + self.perfect: bool = perfect + # we have 2 padding rows and cols each ("invisible border walls") + self.rows: int = self.height + 2 + self.cols: int = self.width + 2 + self.show_path: bool = False + self.color: str = white + self.seed: int | None = seed + + def initiate_grid(self) -> None: + """ Initialize a grid with all the cells""" + # the inner lists of the 2D list represent the columns (x dimension) + self.grid: list = [[] for i in range(self.cols)] + for col in range(self.cols): + for row in range(self.rows): + # a cell object with position (col = x, row = y) is initiated + unique_cell = Cell((col, row)) + # set border/padding cells of the maze to visited + if col == 0 or col == self.cols - 1 \ + or row == 0 or row == self.rows - 1: + unique_cell.VISITED = True + # place new cell object at correct position in grid structure + self.grid[col].append(unique_cell) + + def visualize(self) -> None: + """Visualize the maze with walls from arbitrary UTF-8 character""" + # set print-out color to self.color attribute + print(self.color) + # the UTF-8 character to build the walls from + utf_8: str = "█" + + # print top walls of top row + for k in range(1, self.cols - 1): + print(f"{utf_8}{utf_8}{utf_8}{utf_8}", end="") + # print last top wall and line break + print(f"{utf_8}") + + # iterate row by row + for i in range(1, self.rows - 1): + # print potential west walls of all cells in each row + for j in range(1, self.cols - 1): + # choose current cell object from grid + curr_cell: Cell = self.grid[j][i] + wall_status: int = curr_cell.WALLS + # access most significant bit of wall + # config number (= west wall) + west: int = (wall_status // 2 // 2 // 2) % 2 + # case: west wall stands + if (west == 1): + # case: cell is part of pattern -> display cell as filled + if curr_cell.IS_PATTERN: + print(f"{utf_8}" + f"{utf_8}{utf_8}{utf_8}", end="") + # case: cell is entry -> print cyan cell + # (and continue printing in previous color) + elif curr_cell.POSITION == self.entry: + print(f"{utf_8}", end="") + print(cyan + f"{utf_8}{utf_8}{utf_8}" + + self.color, end="") + # case: cell is outlet -> print magenta cell + # (and continue printing in previous color) + elif curr_cell.POSITION == self.outlet: + print(f"{utf_8}", end="") + print(magenta + f"{utf_8}{utf_8}{utf_8}" + + self.color, end="") + # case: cell is part of path + # and path display is toggled on + # -> display path symbol + elif curr_cell.IS_PATH and self.show_path: + print(f"{utf_8}" + " * ", end="") + # case: ordinary cell -> display as empty + else: + print(f"{utf_8}" + " ", end="") + # case: west wall does not stand + else: + # case: cell is entry -> print cyan cell + # (and continue printing in previous color) + if curr_cell.POSITION == self.entry: + print(" ", end="") + print(cyan + f"{utf_8}{utf_8}{utf_8}" + + self.color, end="") + # case: cell is outlet -> print magenta cell + # (and continue printing in previous color) + elif curr_cell.POSITION == self.outlet: + print(" ", end="") + print(magenta + f"{utf_8}{utf_8}{utf_8}" + + self.color, end="") + # case: cell is part of path + # and path display is toggled on -> display path symbol + elif curr_cell.IS_PATH and self.show_path: + print(" " + " * ", end="") + # case: ordinary cell -> display as empty + else: + print(" " + " ", end="") + print(f"{utf_8}") + + # print potential south walls + # and south-west corners of all cells in each row + for j in range(1, self.cols - 1): + wall_status = self.grid[j][i].WALLS + # accesss 2nd most significant bit of + # wall conf number (= south wall) + south: int = (wall_status // 2 // 2) % 2 + # case: south wall stands + if (south == 1): + print(f"{utf_8}{utf_8}{utf_8}{utf_8}", end="") + # case: south wall does not stand + else: + print(f"{utf_8}" + " ", end="") + print(f"{utf_8}") + + def set_color(self, color: str) -> None: + """ Set color attribute of maze according + to parameter color (string) """ + if color == "green": + self.color = green + elif color == "red": + self.color = red + elif color == "blue": + self.color = blue + elif color == "white": + self.color = white + elif color == "yellow": + self.color = yellow + elif color == "white": + self.color = white + else: + return + + def dfs_carve(self) -> None: + """Carve a perfect maze with DFS, starting at entry position""" + # set the given seed for the Rand Num Generator (None by default) + random.seed(self.seed) + + def dfs_recursion(self: MazeGenerator, curr_pos: tuple) -> None: + """Nested Recursive Helper Function""" + x: int = curr_pos[0] + y: int = curr_pos[1] + # set current cell to visited + self.grid[x][y].VISITED = True + # compute the coordinates of up, down, left + # and right cell relative to current + up: tuple = (x, y - 1) + down: tuple = (x, y + 1) + left: tuple = (x - 1, y) + right: tuple = (x + 1, y) + # list of reachable cells. + # Some will be filtered out later if they are visited already + reachable: list = [up, down, left, right] + + # carving into every possible direction + while True: + # filter out all cells/tuples that have already been visited + reachable = [ + pos for pos in reachable + if self.grid[pos[0]][pos[1]].VISITED + is False + ] + # recursion anchor + if len(reachable) <= 0: + break + # choose random direction from list of reachable cells + next_pos: tuple = random.choice(reachable) + x_next: int = next_pos[0] + y_next: int = next_pos[1] + + # Figure out which direction was chosen by the random call: + if x_next < x: + # left was chosen -> destroy west wall + self.grid[x][y].WALLS -= 8 + # destroy adjacent wall of next cell (east) + self.grid[x_next][y_next].WALLS -= 2 + elif y_next > y: + # down was chosen -> destroy south wall + self.grid[x][y].WALLS -= 4 + # destroy adjacent wall of next cell (north) + self.grid[x_next][y_next].WALLS -= 1 + elif x_next > x: + # right was chosen -> destroy east wall + self.grid[x][y].WALLS -= 2 + # destroy adjacent wall of next cell (west) + self.grid[x_next][y_next].WALLS -= 8 + else: + # up was chosen -> destroy north wall + self.grid[x][y].WALLS -= 1 + # destroy adjacent wall of next cell (south) + self.grid[x_next][y_next].WALLS -= 4 + + dfs_recursion(self, next_pos) + return + + # Call helper function + dfs_recursion(self, self.entry) + + def draw_pattern(self) -> None: + """Mark all 42 pattern cells as part of the pattern and as visited""" + # find middle of maze + row: int = self.height // 2 + col: int = self.width // 2 + # Initiate list where cells will be appended to + pattern: list = [] + # append list pattern_cells with cells + # that constitutes the 42 pattern + # draw a 4 + pattern.append(self.grid[col][row]) + pattern.append(self.grid[col][row + 1]) + pattern.append(self.grid[col][row + 2]) + pattern.append(self.grid[col - 1][row]) + pattern.append(self.grid[col - 2][row]) + pattern.append(self.grid[col - 2][row - 1]) + pattern.append(self.grid[col - 2][row - 2]) + # draw a 2 + pattern.append(self.grid[col + 2][row]) + pattern.append(self.grid[col + 3][row]) + pattern.append(self.grid[col + 4][row]) + pattern.append(self.grid[col + 4][row - 1]) + pattern.append(self.grid[col + 4][row - 2]) + pattern.append(self.grid[col + 3][row - 2]) + pattern.append(self.grid[col + 2][row - 2]) + pattern.append(self.grid[col + 2][row + 1]) + pattern.append(self.grid[col + 2][row + 2]) + pattern.append(self.grid[col + 3][row + 2]) + pattern.append(self.grid[col + 4][row + 2]) + # iterate the list of pattern cells and set is_pattern and visited + for cell in pattern: + cell.IS_PATTERN = True + cell.VISITED = True + + def make_imperfect(self) -> None: + """Change a perfect maze to imperfect (potentially multiple paths)""" + # choose 4 random cells that are not part of 42 pattern + # or adjacent to it or adjacent + # to a border wall + for i in range(4): + while True: + # choose random coordinates + # at least one row/col away from border wall + x: int = random.randint(2, self.width - 1) + y: int = random.randint(2, self.height - 1) + rand_cell: Cell = self.grid[x][y] + up: Cell = self.grid[x][y - 1] + down: Cell = self.grid[x][y + 1] + left: Cell = self.grid[x - 1][y] + right: Cell = self.grid[x + 1][y] + adjacent: list[Cell] = [up, down, left, right] + # choose new cell if the cell itself + # or an adjacent one is part of the + # 42 pattern + if ( + rand_cell.IS_PATTERN is True or + any(cell.IS_PATTERN for cell in adjacent) is True + ): + continue + else: + # check all walls of the cell + # and destroy the first solid wall + # that is detected + cell_walls: int = rand_cell.WALLS + # check north wall + if cell_walls % 2 == 1: + # destroy north wall of current cell + rand_cell.WALLS -= 1 + # destroy south wall of up cell + up.WALLS -= 4 + # check east wall + elif (cell_walls // 2) % 2 == 1: + # destroy east wall of current cell + rand_cell.WALLS -= 2 + # destroy west wall of right cell + right.WALLS -= 8 + # check south wall + elif (cell_walls // 2 // 2) % 2 == 1: + # destroy south wall of current cell + rand_cell.WALLS -= 4 + # destroy north wall of down cell + down.WALLS -= 1 + # check west wall + elif (cell_walls // 2 // 2 // 2) % 2 == 1: + # destroy west wall of current cell + rand_cell.WALLS -= 8 + # destroy east wall of left cell + left.WALLS -= 2 + else: + continue + break + + +# if __name__ == "__main__": +# maze: MazeGenerator = MazeGenerator(20, 15, (1, 1), (20, 15), True) +# maze.initiate_grid() +# maze.draw_pattern() +# maze.dfs_carve() +# maze.visualize() +# maze.make_imperfect() +# print("IMPERFECT: ") +# maze.visualize() |
