Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support generating maze maps #148

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cyaron/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from .graph import Edge, Graph
from .io import IO
from .math import *
from .maze import *
from .merger import Merger
from .polygon import Polygon
from .sequence import Sequence
Expand Down
38 changes: 38 additions & 0 deletions cyaron/maze.py
Original file line number Diff line number Diff line change
@@ -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
Loading