Anonymous user
Maze generation: Difference between revisions
→{{header|Python}}: correct solution, also python 2/3 compatible
(→{{header|C}}: cleanup) |
(→{{header|Python}}: correct solution, also python 2/3 compatible) |
||
Line 1,358:
=={{header|Python}}==
<lang python>from random import choice
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
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
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>+--+--+--+--+--+--+--+--+--+--+--+
| | | | |
+--+ +
| | | | | | | |
+ + + +--+--+
| | | |
+ +--+ + + +--+ +--+--+
| | |
+--+ +--+ +--+ +--+ +
| | |
+ + + +--+ +--+--+ +--+--+ +
| | | | | | |
+ + +--+ +--+--+--+--+ + + +
| | | | | | |
+ +--+--+--+ +--+--+ + + + +
| | | |
+--+--+--+--+--+--+--+--+--+--+--+</lang>
=={{header|Tcl}}==
|