| import argparse |
| import random |
| import string |
| from collections import deque |
| from PIL import Image, ImageDraw, ImageFont |
|
|
|
|
| def generate_maze(rows, cols): |
| """ |
| Generate a perfect maze using DFS / recursive backtracking. |
| Returns: |
| vertical_walls[r][c]: whether there is a wall on the right of cell (r, c) |
| horizontal_walls[r][c]: whether there is a wall below cell (r, c) |
| |
| In a perfect maze, there is exactly one simple path between any two cells, |
| so any chosen entrance and exit will have a unique solution path. |
| """ |
| visited = [[False] * cols for _ in range(rows)] |
|
|
| |
| vertical_walls = [[True] * cols for _ in range(rows)] |
| horizontal_walls = [[True] * cols for _ in range(rows)] |
|
|
| def dfs(r, c): |
| visited[r][c] = True |
|
|
| directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] |
| random.shuffle(directions) |
|
|
| for dr, dc in directions: |
| nr, nc = r + dr, c + dc |
|
|
| if 0 <= nr < rows and 0 <= nc < cols and not visited[nr][nc]: |
| |
| if dr == -1: |
| horizontal_walls[nr][nc] = False |
| elif dr == 1: |
| horizontal_walls[r][c] = False |
| elif dc == -1: |
| vertical_walls[nr][nc] = False |
| elif dc == 1: |
| vertical_walls[r][c] = False |
|
|
| dfs(nr, nc) |
|
|
| dfs(0, 0) |
| return vertical_walls, horizontal_walls |
|
|
|
|
| def _carve_openings(draw, rows, cols, cell_size, wall_width, margin, openings): |
| """ |
| Draw the outer border of the maze while leaving openings. |
| |
| openings is a list of (side, index) tuples where: |
| - side in {"top", "bottom", "left", "right"} |
| - index is the row (for left/right) or column (for top/bottom), 0-based |
| """ |
| x0, y0 = margin, margin |
| x1, y1 = margin + cols * cell_size, margin + rows * cell_size |
| openings_set = set(openings) |
|
|
| |
| |
| |
| for c in range(cols): |
| if ("top", c) in openings_set: |
| continue |
| x_start = margin + c * cell_size |
| x_end = x_start + cell_size |
| y = y0 |
| draw.rectangle( |
| [ |
| x_start - wall_width // 2, |
| y - wall_width // 2, |
| x_end + (wall_width - 1) // 2, |
| y + (wall_width - 1) // 2, |
| ], |
| fill="black", |
| ) |
|
|
| |
| for c in range(cols): |
| if ("bottom", c) in openings_set: |
| continue |
| x_start = margin + c * cell_size |
| x_end = x_start + cell_size |
| y = y1 |
| draw.rectangle( |
| [ |
| x_start - wall_width // 2, |
| y - wall_width // 2, |
| x_end + (wall_width - 1) // 2, |
| y + (wall_width - 1) // 2, |
| ], |
| fill="black", |
| ) |
|
|
| |
| for r in range(rows): |
| if ("left", r) in openings_set: |
| continue |
| y_start = margin + r * cell_size |
| y_end = y_start + cell_size |
| x = x0 |
| draw.rectangle( |
| [ |
| x - wall_width // 2, |
| y_start - wall_width // 2, |
| x + (wall_width - 1) // 2, |
| y_end + (wall_width - 1) // 2, |
| ], |
| fill="black", |
| ) |
|
|
| |
| for r in range(rows): |
| if ("right", r) in openings_set: |
| continue |
| y_start = margin + r * cell_size |
| y_end = y_start + cell_size |
| x = x1 |
| draw.rectangle( |
| [ |
| x - wall_width // 2, |
| y_start - wall_width // 2, |
| x + (wall_width - 1) // 2, |
| y_end + (wall_width - 1) // 2, |
| ], |
| fill="black", |
| ) |
|
|
|
|
| def _label_openings(draw, rows, cols, cell_size, wall_width, margin, openings): |
| """ |
| Draw letter labels (A, B, C, ...) just outside each opening on the border. |
| Labels are placed on the outside of the maze, on the side where the wall |
| was opened. |
| """ |
| if not openings: |
| return |
|
|
| x0, y0 = margin, margin |
| x1, y1 = margin + cols * cell_size, margin + rows * cell_size |
| width = cols * cell_size + 2 * margin |
| height = rows * cell_size + 2 * margin |
|
|
| |
| try: |
| font = ImageFont.truetype("Arial.ttf", size=16) |
| except Exception: |
| try: |
| font = ImageFont.truetype("DejaVuSans.ttf", size=16) |
| except Exception: |
| font = ImageFont.load_default() |
|
|
| def _measure(text: str): |
| """ |
| Measure text width and height in pixels in a Pillow-version-tolerant way. |
| """ |
| |
| if hasattr(draw, "textbbox"): |
| left, top, right, bottom = draw.textbbox((0, 0), text, font=font) |
| return right - left, bottom - top |
|
|
| |
| if hasattr(font, "getbbox"): |
| left, top, right, bottom = font.getbbox(text) |
| return right - left, bottom - top |
|
|
| |
| return font.getsize(text) |
| offset = wall_width + 4 |
|
|
| |
| |
| opening_positions = [] |
| for side, index in openings: |
| if side == "left": |
| row = max(0, min(rows - 1, index)) |
| cx = x0 |
| cy = margin + row * cell_size + cell_size / 2 |
| elif side == "right": |
| row = max(0, min(rows - 1, index)) |
| cx = x1 |
| cy = margin + row * cell_size + cell_size / 2 |
| elif side == "top": |
| col = max(0, min(cols - 1, index)) |
| cx = margin + col * cell_size + cell_size / 2 |
| cy = y0 |
| elif side == "bottom": |
| col = max(0, min(cols - 1, index)) |
| cx = margin + col * cell_size + cell_size / 2 |
| cy = y1 |
| else: |
| continue |
|
|
| opening_positions.append((cx, cy, side, index)) |
|
|
| |
| |
| for i, (_cx, _cy, side, index) in enumerate(opening_positions): |
| label = string.ascii_uppercase[i % len(string.ascii_uppercase)] |
|
|
| if side == "left": |
| row = max(0, min(rows - 1, index)) |
| cy = margin + row * cell_size + cell_size / 2 |
| w, h = _measure(label) |
| x = x0 - offset - w |
| y = cy - h / 2 |
| elif side == "right": |
| row = max(0, min(rows - 1, index)) |
| cy = margin + row * cell_size + cell_size / 2 |
| w, h = _measure(label) |
| x = x1 + offset |
| y = cy - h / 2 |
| elif side == "top": |
| col = max(0, min(cols - 1, index)) |
| cx = margin + col * cell_size + cell_size / 2 |
| w, h = _measure(label) |
| x = cx - w / 2 |
| y = y0 - offset - h |
| elif side == "bottom": |
| col = max(0, min(cols - 1, index)) |
| cx = margin + col * cell_size + cell_size / 2 |
| w, h = _measure(label) |
| x = cx - w / 2 |
| y = y1 + offset |
| else: |
| continue |
|
|
| |
| |
| x = max(0, min(width - w, x)) |
| y = max(0, min(height - h, y)) |
|
|
| draw.text((x, y), label, fill="black", font=font) |
|
|
|
|
| def _find_path_cells(vertical_walls, horizontal_walls, rows, cols, start, goal): |
| """ |
| Return the set of (r, c) cells on the unique path between start and goal |
| in the maze defined by vertical_walls and horizontal_walls. |
| """ |
| (sr, sc) = start |
| (gr, gc) = goal |
|
|
| queue = deque([(sr, sc)]) |
| prev = {(sr, sc): None} |
|
|
| while queue: |
| r, c = queue.popleft() |
| if (r, c) == (gr, gc): |
| break |
|
|
| |
| |
| if r > 0 and not horizontal_walls[r - 1][c]: |
| nr, nc = r - 1, c |
| if (nr, nc) not in prev: |
| prev[(nr, nc)] = (r, c) |
| queue.append((nr, nc)) |
| |
| if r < rows - 1 and not horizontal_walls[r][c]: |
| nr, nc = r + 1, c |
| if (nr, nc) not in prev: |
| prev[(nr, nc)] = (r, c) |
| queue.append((nr, nc)) |
| |
| if c > 0 and not vertical_walls[r][c - 1]: |
| nr, nc = r, c - 1 |
| if (nr, nc) not in prev: |
| prev[(nr, nc)] = (r, c) |
| queue.append((nr, nc)) |
| |
| if c < cols - 1 and not vertical_walls[r][c]: |
| nr, nc = r, c + 1 |
| if (nr, nc) not in prev: |
| prev[(nr, nc)] = (r, c) |
| queue.append((nr, nc)) |
|
|
| |
| if (gr, gc) not in prev: |
| |
| return set() |
|
|
| path_cells = set() |
| cur = (gr, gc) |
| while cur is not None: |
| path_cells.add(cur) |
| cur = prev[cur] |
|
|
| return path_cells |
|
|
|
|
| def _build_opening_candidates(rows, cols, corner_buffer: int = 1): |
| """ |
| Build a list of candidate border cells to use as openings. |
| corner_buffer controls how many cells near each corner are excluded so |
| that openings do not sit directly on the corners. |
| """ |
| candidates = [] |
|
|
| |
| for c in range(corner_buffer, cols - corner_buffer): |
| candidates.append(("top", c, 0, c)) |
| candidates.append(("bottom", c, rows - 1, c)) |
|
|
| |
| for r in range(corner_buffer, rows - corner_buffer): |
| candidates.append(("left", r, r, 0)) |
| candidates.append(("right", r, r, cols - 1)) |
|
|
| return candidates |
|
|
|
|
| def _get_open_neighbors(vertical_walls, horizontal_walls, rows, cols, r, c): |
| """ |
| Return a list of neighbor cells (nr, nc) that are reachable from (r, c) |
| given the current wall configuration. |
| """ |
| neighbors = [] |
|
|
| |
| if r > 0 and not horizontal_walls[r - 1][c]: |
| neighbors.append((r - 1, c)) |
|
|
| |
| if r < rows - 1 and not horizontal_walls[r][c]: |
| neighbors.append((r + 1, c)) |
|
|
| |
| if c > 0 and not vertical_walls[r][c - 1]: |
| neighbors.append((r, c - 1)) |
|
|
| |
| if c < cols - 1 and not vertical_walls[r][c]: |
| neighbors.append((r, c + 1)) |
|
|
| return neighbors |
|
|
|
|
| def _reachable_cells(vertical_walls, horizontal_walls, rows, cols, start): |
| """ |
| Return the set of all cells reachable from start under the current wall |
| configuration. |
| """ |
| queue = deque([start]) |
| seen = {start} |
|
|
| while queue: |
| r, c = queue.popleft() |
| for nr, nc in _get_open_neighbors(vertical_walls, horizontal_walls, rows, cols, r, c): |
| if (nr, nc) not in seen: |
| seen.add((nr, nc)) |
| queue.append((nr, nc)) |
|
|
| return seen |
|
|
|
|
| def _opening_looks_natural(vertical_walls, horizontal_walls, rows, cols, r, c): |
| """ |
| Heuristic check: an opening is considered natural if its interior cell |
| has at least one open neighbor (and optionally could be extended). |
| """ |
| neighbors = _get_open_neighbors(vertical_walls, horizontal_walls, rows, cols, r, c) |
| return len(neighbors) >= 1 |
|
|
|
|
| def _isolate_decoy_region( |
| vertical_walls, |
| horizontal_walls, |
| rows, |
| cols, |
| root_cell, |
| forbidden_cells, |
| min_size: int = 3, |
| max_size: int = 12, |
| max_depth: int = 10, |
| ): |
| """ |
| Starting from the given root_cell, perform a BFS in the current maze |
| topology to get a connected subtree that does not contain any cells in |
| forbidden_cells. Then, by adding walls around this subtree, cut it off |
| from the main maze as an isolated "fake entrance" region. |
| |
| The resulting decoy region is still a valid maze-like structure composed |
| of cell edges/walls, but there is no path between it and the main maze. |
| """ |
| (sr, sc) = root_cell |
| if (sr, sc) in forbidden_cells: |
| return set() |
|
|
| |
| queue = deque([(sr, sc, 0)]) |
| subtree = {(sr, sc)} |
|
|
| |
| |
| |
| while queue and len(subtree) < max_size: |
| r, c, depth = queue.popleft() |
|
|
| |
| if depth >= max_depth: |
| continue |
|
|
| neighbors = _get_open_neighbors(vertical_walls, horizontal_walls, rows, cols, r, c) |
| random.shuffle(neighbors) |
|
|
| for nr, nc in neighbors: |
| if (nr, nc) in subtree or (nr, nc) in forbidden_cells: |
| continue |
|
|
| subtree.add((nr, nc)) |
| queue.append((nr, nc, depth + 1)) |
|
|
| if len(subtree) >= max_size: |
| break |
|
|
| |
| if len(subtree) < min_size: |
| return set() |
|
|
| |
| |
| for r, c in list(subtree): |
| |
| if r > 0: |
| nr, nc = r - 1, c |
| if (nr, nc) not in subtree: |
| horizontal_walls[r - 1][c] = True |
|
|
| |
| if r < rows - 1: |
| nr, nc = r + 1, c |
| if (nr, nc) not in subtree: |
| horizontal_walls[r][c] = True |
|
|
| |
| if c > 0: |
| nr, nc = r, c - 1 |
| if (nr, nc) not in subtree: |
| vertical_walls[r][c - 1] = True |
|
|
| |
| if c < cols - 1: |
| nr, nc = r, c + 1 |
| if (nr, nc) not in subtree: |
| vertical_walls[r][c] = True |
|
|
| return subtree |
|
|
|
|
| def draw_maze( |
| rows, |
| cols, |
| cell_size=32, |
| wall_width=5, |
| margin=8, |
| filename="maze.png", |
| entrances=None, |
| num_openings=4, |
| ): |
| """ |
| Draw a maze image. |
| |
| Parameters: |
| rows, cols: maze grid size |
| cell_size: size (in pixels) of each cell |
| wall_width: wall thickness (in pixels). If an even value is provided, |
| it will be rounded up to the next odd value to keep walls |
| symmetric around grid lines. |
| margin: outer margin (in pixels) |
| filename: output image filename |
| entrances: optional list of (side, index) tuples that define openings |
| in the outer border. Examples: |
| [("left", 0), ("right", rows - 1)] |
| [("top", 0), ("bottom", cols - 1)] |
| [("left", 0), ("left", rows - 1), ("right", rows // 2)] |
| If provided, all of these openings are carved visually, |
| but only two of them are connected to the interior; all |
| others are dead ends. |
| num_openings: if entrances is None, this many random openings will be |
| carved on the outer border (clamped so it is at least 2 |
| and at most the number of border cells). Exactly one |
| entrance and one exit will connect to the maze interior; |
| all others are dead ends (no path to an exit). |
| |
| The underlying maze is perfect (DFS backtracking) before we cut any |
| additional dead-end openings, so between the unique entrance and exit |
| there is exactly one simple path. Any other opening leads only to an |
| isolated pocket with no exit. |
| """ |
| |
| if wall_width % 2 == 0: |
| wall_width += 1 |
|
|
| vertical_walls, horizontal_walls = generate_maze(rows, cols) |
|
|
| |
| |
| |
| label_pad = max(16, wall_width * 2) |
| draw_margin = margin + label_pad |
|
|
| width = cols * cell_size + 2 * draw_margin |
| height = rows * cell_size + 2 * draw_margin |
|
|
| img = Image.new("RGB", (width, height), "white") |
| draw = ImageDraw.Draw(img) |
|
|
| |
| if entrances is None: |
| |
| border_cells = _build_opening_candidates(rows, cols, corner_buffer=1) |
| max_openings = len(border_cells) |
| k = max(2, min(num_openings, max_openings)) |
|
|
| |
| min_path_len = (rows * cols) // 3 |
| candidate_pairs = [] |
|
|
| for i in range(len(border_cells)): |
| for j in range(i + 1, len(border_cells)): |
| a = border_cells[i] |
| b = border_cells[j] |
| path = _find_path_cells( |
| vertical_walls, |
| horizontal_walls, |
| rows, |
| cols, |
| (a[2], a[3]), |
| (b[2], b[3]), |
| ) |
| if len(path) >= min_path_len: |
| candidate_pairs.append((a, b, path)) |
|
|
| if candidate_pairs: |
| first, second, path_cells = random.choice(candidate_pairs) |
| else: |
| |
| first, second = random.sample(border_cells, 2) |
| path_cells = _find_path_cells( |
| vertical_walls, |
| horizontal_walls, |
| rows, |
| cols, |
| (first[2], first[3]), |
| (second[2], second[3]), |
| ) |
|
|
| main_border_cells = [first, second] |
| (side_a, idx_a, ra, ca) = first |
| (side_b, idx_b, rb, cb) = second |
|
|
| |
| forbidden_cells = set(path_cells) |
|
|
| |
| |
| remaining_border = [ |
| cell for cell in border_cells |
| if cell not in main_border_cells |
| and (cell[2], cell[3]) not in path_cells |
| and _opening_looks_natural( |
| vertical_walls, horizontal_walls, rows, cols, cell[2], cell[3] |
| ) |
| ] |
|
|
| extra_to_pick = max(0, min(k - 2, len(remaining_border))) |
| extra_border_cells = [] |
|
|
| random.shuffle(remaining_border) |
| for side, idx, r, c in remaining_border: |
| if len(extra_border_cells) >= extra_to_pick: |
| break |
|
|
| |
| |
| |
| total_cells = rows * cols |
| decoy_min_size = 3 |
| |
| decoy_max_size = max(12, (total_cells * 3) // 5) |
| |
| decoy_max_depth = total_cells |
|
|
| |
| |
| subtree = _isolate_decoy_region( |
| vertical_walls, |
| horizontal_walls, |
| rows, |
| cols, |
| (r, c), |
| forbidden_cells, |
| min_size=decoy_min_size, |
| max_size=decoy_max_size, |
| max_depth=decoy_max_depth, |
| ) |
|
|
| if not subtree: |
| continue |
|
|
| extra_border_cells.append((side, idx, r, c)) |
| |
| forbidden_cells.update(subtree) |
|
|
| |
| all_border_cells = main_border_cells + extra_border_cells |
| entrances_to_draw = [(side, idx) for (side, idx, _r, _c) in all_border_cells] |
|
|
| |
| |
| main_component = _reachable_cells( |
| vertical_walls, |
| horizontal_walls, |
| rows, |
| cols, |
| (ra, ca), |
| ) |
| if (rb, cb) not in main_component: |
| |
| first, second = random.sample(border_cells, 2) |
| main_border_cells = [first, second] |
| (side_a, idx_a, ra, ca) = first |
| (side_b, idx_b, rb, cb) = second |
| path_cells = _find_path_cells( |
| vertical_walls, |
| horizontal_walls, |
| rows, |
| cols, |
| (ra, ca), |
| (rb, cb), |
| ) |
| entrances_to_draw = [(first[0], first[1]), (second[0], second[1])] |
|
|
| else: |
| |
| valid = True |
| for side, idx, r, c in extra_border_cells: |
| decoy_component = _reachable_cells( |
| vertical_walls, |
| horizontal_walls, |
| rows, |
| cols, |
| (r, c), |
| ) |
| if (rb, cb) in decoy_component: |
| valid = False |
| break |
|
|
| if not valid: |
| |
| entrances_to_draw = [ |
| (first[0], first[1]), |
| (second[0], second[1]), |
| ] |
| else: |
| |
| entrances_to_draw = entrances |
|
|
| |
| _carve_openings(draw, rows, cols, cell_size, wall_width, draw_margin, entrances_to_draw) |
| _label_openings(draw, rows, cols, cell_size, wall_width, draw_margin, entrances_to_draw) |
|
|
| |
| for r in range(rows): |
| for c in range(cols): |
| cell_x = draw_margin + c * cell_size |
| cell_y = draw_margin + r * cell_size |
|
|
| |
| |
| if vertical_walls[r][c] and c != cols - 1: |
| x = cell_x + cell_size |
| draw.rectangle( |
| [ |
| x - wall_width // 2, |
| cell_y - wall_width // 2, |
| x + (wall_width - 1) // 2, |
| cell_y + cell_size + (wall_width - 1) // 2, |
| ], |
| fill="black", |
| ) |
|
|
| |
| |
| if horizontal_walls[r][c] and r != rows - 1: |
| y = cell_y + cell_size |
| draw.rectangle( |
| [ |
| cell_x - wall_width // 2, |
| y - wall_width // 2, |
| cell_x + cell_size + (wall_width - 1) // 2, |
| y + (wall_width - 1) // 2, |
| ], |
| fill="black", |
| ) |
|
|
| img.save(filename) |
| print(f"Maze has been saved to {filename}") |
|
|
|
|
| if __name__ == "__main__": |
| parser = argparse.ArgumentParser(description="Generate and save a random perfect maze image.") |
| parser.add_argument("--rows", type=int, default=10, help="Number of rows in the maze grid.") |
| parser.add_argument("--cols", type=int, default=10, help="Number of columns in the maze grid.") |
| parser.add_argument("--cell-size", type=int, default=32, help="Pixel size of each maze cell.") |
| parser.add_argument( |
| "--wall-width", |
| type=int, |
| default=5, |
| help="Wall thickness in pixels. Even values are rounded up to the next odd value.", |
| ) |
| parser.add_argument("--margin", type=int, default=8, help="Outer margin in pixels around the maze.") |
| parser.add_argument( |
| "--num-openings", |
| type=int, |
| default=4, |
| help=( |
| "Total number of border openings. Exactly two of them form the unique " |
| "solvable entrance/exit pair; the rest are dead-end decoys." |
| ), |
| ) |
| parser.add_argument( |
| "--output", |
| type=str, |
| default="random_maze.png", |
| help="Output image filename.", |
| ) |
|
|
| args = parser.parse_args() |
|
|
| draw_maze( |
| rows=args.rows, |
| cols=args.cols, |
| cell_size=args.cell_size, |
| wall_width=args.wall_width, |
| margin=args.margin, |
| filename=args.output, |
| num_openings=args.num_openings, |
| ) |