Skip to content

Commit

Permalink
Support generating maze maps
Browse files Browse the repository at this point in the history
  • Loading branch information
weilycoder committed Nov 20, 2024
1 parent 669b09f commit 82c9f5f
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
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
35 changes: 35 additions & 0 deletions cyaron/maze.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
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(cx, cy):
d = [(0, -1), (0, 1), (-1, 0), (1, 0)]
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
carve_passages_from(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

0 comments on commit 82c9f5f

Please sign in to comment.