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) ]
conn = [ [[] for j in range(width)] for i in range(height) ]
visited = [ [ False 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):
def neighbors(x, y):
return [ (i, j) for (i, j) in ((y+1, x), (y-1, x), (y, x+1), (y, x-1))
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 j >= 0 and j < width and i >= 0 and i < height
if not visited[i][j] ]
if not visited[i][j] ]


def walk(y, x, avail=width*height):
def walk(y, x, avail=width*height):
visited[y][x] = True
visited[y][x] = True
avail -= 1
avail -= 1


while avail:
while avail:
n = neighbors(x, y)
n = neighbors(x, y)
if not len(n): return avail
if not len(n): return avail


(i,j) = choice(n)
(i,j) = choice(n)
conn[y][x].append((i,j))
conn[y][x].append((i,j))
conn[i][j].append((y,x))
conn[i][j].append((y,x))


avail = walk(i, j, avail)
avail = walk(i, j, avail)


walk(0, 0)
walk(0, 0)
return conn
return conn


def show_maze(cells):
def show_maze(cells):
w, h = len(cells[0]), len(cells)
w, h = len(cells[0]), len(cells)
for row in range(2 * h + 1):
for row in range(2 * h + 1):
i, s = row//2, ""
i, s = row//2, ""
for j in range(w):
for j in range(w):
if row == 2*h:
if row == 2*h:
s = "+--" * w
s = "+--" * w
elif row & 1:
elif row & 1:
s += " " if (i, j-1) in cells[i][j] else "| "
s += " " if (i, j-1) in cells[i][j] else "| "
else:
else:
s += "+ " if (i-1, j) in cells[i][j] else "+--"
s += "+ " if (i-1, j) in cells[i][j] else "+--"
s += "|" if row & 1 else "+"
s += "|" if row & 1 else "+"
print(s)
print(s)


show_maze(make_maze(8, 11))</lang>output<lang>+--+--+--+--+--+--+--+--+--+--+--+
show_maze(make_maze(8, 11))</lang>output<lang>+--+--+--+--+--+--+--+--+--+--+--+