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)] # Initially, every cell has a right wall and a bottom wall 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]: # Remove the wall between the current cell and the neighboring cell if dr == -1: # up horizontal_walls[nr][nc] = False elif dr == 1: # down horizontal_walls[r][c] = False elif dc == -1: # left vertical_walls[nr][nc] = False elif dc == 1: # right 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) # Top border: one rectangle per cell-width segment, skipping openings. # Each segment extends half a wall-width beyond its nominal endpoints so # that neighboring segments overlap slightly and avoid pixel gaps. 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", ) # Bottom border 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", ) # Left border 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", ) # Right border 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 to use a more readable TrueType font; fall back to default bitmap font. 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. """ # Newer Pillow versions: prefer textbbox for accurate metrics if hasattr(draw, "textbbox"): left, top, right, bottom = draw.textbbox((0, 0), text, font=font) return right - left, bottom - top # Fallback to font methods if hasattr(font, "getbbox"): left, top, right, bottom = font.getbbox(text) return right - left, bottom - top # Oldest fallback return font.getsize(text) offset = wall_width + 4 # distance from the outer wall to the label # Compute a geometric position for each opening so that labels can be # ordered from left to right (and then top to bottom when x is equal). 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)) # Preserve the logical order of openings (e.g., main openings first, # followed by decoys) instead of reordering by geometry. 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 # Clamp to stay within the image so labels are always visible, # even when the margin is small. 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 # Explore neighbors based on wall configuration # Up 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)) # Down 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)) # Left 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)) # Right 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)) # Reconstruct path from goal back to start if (gr, gc) not in prev: # Should not happen in a perfect maze, but guard anyway 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 = [] # Top and bottom rows, skipping a few cells near the corners for c in range(corner_buffer, cols - corner_buffer): candidates.append(("top", c, 0, c)) candidates.append(("bottom", c, rows - 1, c)) # Left and right columns, skipping corners (and respecting the buffer) 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 = [] # Up if r > 0 and not horizontal_walls[r - 1][c]: neighbors.append((r - 1, c)) # Down if r < rows - 1 and not horizontal_walls[r][c]: neighbors.append((r + 1, c)) # Left if c > 0 and not vertical_walls[r][c - 1]: neighbors.append((r, c - 1)) # Right 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() # BFS queue stores (row, col, depth_from_root). queue = deque([(sr, sc, 0)]) subtree = {(sr, sc)} # Grow a limited-size, limited-depth subtree around root_cell that does not # intersect the forbidden_cells set. This keeps decoy regions compact and # shallow rather than cutting out huge, full-featured submazes. while queue and len(subtree) < max_size: r, c, depth = queue.popleft() # Do not extend beyond the maximum depth from the opening. 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 the subtree is too small, we simply skip using it as a decoy. if len(subtree) < min_size: return set() # Add walls on all edges between this subtree and the rest of the maze # so that it is completely disconnected from the main maze. for r, c in list(subtree): # Up neighbor if r > 0: nr, nc = r - 1, c if (nr, nc) not in subtree: horizontal_walls[r - 1][c] = True # Down neighbor if r < rows - 1: nr, nc = r + 1, c if (nr, nc) not in subtree: horizontal_walls[r][c] = True # Left neighbor if c > 0: nr, nc = r, c - 1 if (nr, nc) not in subtree: vertical_walls[r][c - 1] = True # Right neighbor 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. """ # Ensure wall width is an odd number so rectangles are symmetric if wall_width % 2 == 0: wall_width += 1 vertical_walls, horizontal_walls = generate_maze(rows, cols) # Give extra canvas space so border labels have room outside the maze. # This does not change the "inner" margin between maze and outer walls # seen visually by the user; it only affects total image size. 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) # Decide entrance / exit and (optionally) additional decoy openings if entrances is None: # Build filtered list of border candidates that are not too close to corners. border_cells = _build_opening_candidates(rows, cols, corner_buffer=1) max_openings = len(border_cells) k = max(2, min(num_openings, max_openings)) # Choose entrance/exit pair based on actual path length through the maze. 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: # Fallback: pick any two border cells and use their path 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 # Track cells already "used" (main path) so decoys never reuse them. forbidden_cells = set(path_cells) # Only place decoys on border cells that are not on the main path and # whose interior cell looks reasonably natural as an opening. 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 # Allow decoy regions to be fairly large and deep so they feel # comparable in scale to the main maze, while still being isolated # and reachable only from a single opening. total_cells = rows * cols decoy_min_size = 3 # Up to roughly 60% of the maze cells for a single decoy region. decoy_max_size = max(12, (total_cells * 3) // 5) # Depth bound effectively lets the region explore as far as area allows. decoy_max_depth = total_cells # From (r, c), grow a small decoy subtree that does not intersect # the main path, and cut it off to form a fake region. 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)) # Add these cells to forbidden so later decoys do not overlap. forbidden_cells.update(subtree) # All border cells where we actually create visual openings all_border_cells = main_border_cells + extra_border_cells entrances_to_draw = [(side, idx) for (side, idx, _r, _c) in all_border_cells] # Final validation: ensure main entrance/exit are connected, and decoys # cannot reach the exit. main_component = _reachable_cells( vertical_walls, horizontal_walls, rows, cols, (ra, ca), ) if (rb, cb) not in main_component: # In the unlikely event this fails, fall back to a simple, direct pair. 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: # Verify each decoy opening does not connect to the real exit. 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: # If validation fails, degrade gracefully by dropping decoys. entrances_to_draw = [ (first[0], first[1]), (second[0], second[1]), ] else: # If explicit entrances are provided, treat all of them as real openings entrances_to_draw = entrances # Finally, carve the visual openings in the outer border and label them _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) # Draw internal walls for r in range(rows): for c in range(cols): cell_x = draw_margin + c * cell_size cell_y = draw_margin + r * cell_size # Right wall (extend half a wall-width above and below so it # slightly overlaps neighboring horizontal walls) 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", ) # Bottom wall (extend half a wall-width left and right so it # slightly overlaps neighboring vertical walls) 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, )