File size: 25,825 Bytes
f69e256 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 | 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,
) |