99 lines
3.4 KiB
Python
Executable File
99 lines
3.4 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
# maze - generate a random ASCII maze
|
|
# Usage: maze [-w WIDTH] [-h HEIGHT] [--seed N] [--solve]
|
|
import argparse, random, sys
|
|
|
|
def generate(w, h, seed=None):
|
|
rng = random.Random(seed)
|
|
# cells: walls grid (2h+1) x (2w+1); True = wall
|
|
gw, gh = 2 * w + 1, 2 * h + 1
|
|
grid = [[True] * gw for _ in range(gh)]
|
|
stack = [(0, 0)]
|
|
grid[1][1] = False
|
|
seen = {(0, 0)}
|
|
while stack:
|
|
cx, cy = stack[-1]
|
|
nbrs = []
|
|
for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
|
|
nx, ny = cx + dx, cy + dy
|
|
if 0 <= nx < w and 0 <= ny < h and (nx, ny) not in seen:
|
|
nbrs.append((nx, ny, dx, dy))
|
|
if not nbrs:
|
|
stack.pop(); continue
|
|
nx, ny, dx, dy = rng.choice(nbrs)
|
|
grid[2 * cy + 1 + dy][2 * cx + 1 + dx] = False
|
|
grid[2 * ny + 1][2 * nx + 1] = False
|
|
seen.add((nx, ny))
|
|
stack.append((nx, ny))
|
|
grid[1][0] = False # entrance
|
|
grid[2 * h - 1][2 * w] = False # exit
|
|
return grid
|
|
|
|
def solve(grid, w, h):
|
|
# BFS from entrance (0,1) to exit (2w, 2h-1) on the wall grid
|
|
from collections import deque
|
|
start, goal = (0, 1), (2 * w, 2 * h - 1)
|
|
q = deque([start]); prev = {start: None}
|
|
while q:
|
|
x, y = q.popleft()
|
|
if (x, y) == goal:
|
|
break
|
|
for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
|
|
nx, ny = x + dx, y + dy
|
|
if (0 <= ny < len(grid) and 0 <= nx < len(grid[0])
|
|
and not grid[ny][nx] and (nx, ny) not in prev):
|
|
prev[(nx, ny)] = (x, y); q.append((nx, ny))
|
|
if goal not in prev:
|
|
return []
|
|
path, cur = [], goal
|
|
while cur is not None:
|
|
path.append(cur); cur = prev[cur]
|
|
return path[::-1]
|
|
|
|
def render(grid, path=None):
|
|
pathset = set(path or [])
|
|
out = []
|
|
for y, row in enumerate(grid):
|
|
line = ""
|
|
for x, wall in enumerate(row):
|
|
if (x, y) in pathset:
|
|
line += "."
|
|
elif wall:
|
|
line += "#"
|
|
else:
|
|
line += " "
|
|
out.append(line)
|
|
return "\n".join(out)
|
|
|
|
def selftest():
|
|
for seed in (1, 2, 3):
|
|
g = generate(10, 10, seed=seed)
|
|
path = solve(g, 10, 10)
|
|
assert path, f"no solution seed {seed}"
|
|
assert path[0] == (0, 1) and path[-1] == (20, 19)
|
|
assert render(g)
|
|
g = generate(5, 5, seed=0)
|
|
assert len(g) == 11 and len(g[0]) == 11
|
|
print(render(g, solve(g, 5, 5)))
|
|
print("maze selftest OK")
|
|
|
|
def main():
|
|
p = argparse.ArgumentParser(description="Generate a random ASCII maze.")
|
|
p.add_argument("-w", "--width", type=int, default=20, help="maze width in cells (default 20)")
|
|
p.add_argument("-H", "--height", type=int, default=10, help="maze height in cells (default 10)")
|
|
p.add_argument("--seed", type=int, default=None, help="seed for deterministic output")
|
|
p.add_argument("--solve", action="store_true", help="show the solution path as dots")
|
|
p.add_argument("--selftest", action="store_true", help="run a built-in self-test and exit")
|
|
a = p.parse_args()
|
|
if a.selftest:
|
|
selftest(); return 0
|
|
if a.width < 2 or a.height < 2:
|
|
p.error("width and height must be >= 2")
|
|
grid = generate(a.width, a.height, a.seed)
|
|
path = solve(grid, a.width, a.height) if a.solve else None
|
|
print(render(grid, path))
|
|
return 0
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|