Skip to content

Instantly share code, notes, and snippets.

@enj enj/maze.py
Created Jan 9, 2017

Embed
What would you like to do?
maze
import random
def make_maze(columns=20, rows=20):
columns = columns / 2
rows = rows / 2
visited = [[0] * columns + [1] for _ in range(rows)] + [[1] * (columns + 1)]
ver = [["* "] * columns + ['*'] for _ in range(rows)] + [[]]
hor = [["**"] * columns + ['*'] for _ in range(rows + 1)]
def walk(x, y):
d = [
(x - 1, y),
(x, y + 1),
(x + 1, y),
(x, y - 1)
]
random.shuffle(d)
for (xx, yy) in d:
if visited[yy][xx]:
continue
if xx == x:
hor[max(y, yy)][x] = "* "
if yy == y:
ver[y][max(x, xx)] = " "
stack.append((xx, yy))
visited[yy][xx] = 1
sx = random.randrange(columns)
sy = random.randrange(rows)
visited[sy][sx] = 1
stack = [(sx,sy)]
while stack:
walk(*stack.pop())
s = ""
for (a, b) in zip(hor, ver):
s += ''.join(a + ['\n'] + b + ['\n'])
return s
if __name__ == '__main__':
print(make_maze(columns=40, rows=40))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.