diff --git a/cyaron/__init__.py b/cyaron/__init__.py index ec5f271..c6d3fc5 100644 --- a/cyaron/__init__.py +++ b/cyaron/__init__.py @@ -15,6 +15,7 @@ from .graph import Edge, Graph from .io import IO from .math import * +from .misc import * from .merger import Merger from .polygon import Polygon from .sequence import Sequence diff --git a/cyaron/misc.py b/cyaron/misc.py new file mode 100644 index 0000000..8212027 --- /dev/null +++ b/cyaron/misc.py @@ -0,0 +1,38 @@ +import random + +__all__ = ["generate_maze"] + + +def generate_maze( + width: int, + height: int, + *, + wall: str = "#", + way: str = ".", + start: str = "S", + end: str = "T", +): + maze = [[wall for _ in range(width)] for _ in range(height)] + + def carve_passages_from(x, y): + stack = [(x, y)] + d = [(0, -1), (0, 1), (-1, 0), (1, 0)] + while len(stack) >= 1: + cx, cy = stack.pop() + random.shuffle(d) + for dx, dy in d: + nx, ny = cx + dx * 2, cy + dy * 2 + if 0 <= nx < width and 0 <= ny < height and maze[ny][nx] == wall: + maze[ny][nx] = maze[cy + dy][cx + dx] = way + stack.append((nx, ny)) + + start_x = random.randrange(0, width) + start_y = random.randrange(0, height) + maze[start_y][start_x] = start + carve_passages_from(start_x, start_y) + + end_x, end_y = random.choice([(x, y) for x in range(width) + for y in range(height) if maze[y][x] == way]) + maze[end_y][end_x] = end + + return maze