Maze generation: Difference between revisions
Content added Content deleted
(→{{header|Python}}: correct solution, also python 2/3 compatible) |
(→{{header|Python}}: right, 4 space tab) |
||
Line 1,361: | Line 1,361: | ||
def make_maze(height, width): |
def make_maze(height, width): |
||
conn = [ [[] for j in range(width)] for i in range(height) ] |
|||
visited = [ [ False for j in range(width) ] for i in range(height) ] |
|||
def neighbors(x, y): |
|||
return [ (i, j) for (i, j) in ((y+1, x), (y-1, x), (y, x+1), (y, x-1)) |
|||
if j >= 0 and j < width and i >= 0 and i < height |
|||
if not visited[i][j] ] |
|||
def walk(y, x, avail=width*height): |
|||
visited[y][x] = True |
|||
avail -= 1 |
|||
while avail: |
|||
n = neighbors(x, y) |
|||
if not len(n): return avail |
|||
(i,j) = choice(n) |
|||
conn[y][x].append((i,j)) |
|||
conn[i][j].append((y,x)) |
|||
avail = walk(i, j, avail) |
|||
walk(0, 0) |
|||
return conn |
|||
def show_maze(cells): |
def show_maze(cells): |
||
w, h = len(cells[0]), len(cells) |
|||
for row in range(2 * h + 1): |
|||
i, s = row//2, "" |
|||
for j in range(w): |
|||
if row == 2*h: |
|||
s = "+--" * w |
|||
elif row & 1: |
|||
s += " " if (i, j-1) in cells[i][j] else "| " |
|||
else: |
|||
s += "+ " if (i-1, j) in cells[i][j] else "+--" |
|||
s += "|" if row & 1 else "+" |
|||
print(s) |
|||
show_maze(make_maze(8, 11))</lang>output<lang>+--+--+--+--+--+--+--+--+--+--+--+ |
show_maze(make_maze(8, 11))</lang>output<lang>+--+--+--+--+--+--+--+--+--+--+--+ |