Maze generation: Difference between revisions

Content added Content deleted
(Fixed bug in first D version)
(Added second Python version)
Line 1,353: Line 1,353:
| | | |
| | | |
+--+--+--+--+--+--+--+--+--+--+--+</lang>
+--+--+--+--+--+--+--+--+--+--+--+</lang>
===Alternative version===
{{trans|D}}
<lang python>from random import randrange, choice
from collections import namedtuple

W, H = 11, 8
hWalls = [[True] * H for _ in xrange(W)]
vWalls = [[True] * H for _ in xrange(W)]
seen = [[False] * H for _ in xrange(W)]
P = namedtuple("P", "x y")

def visit(x, y):
seen[x][y] = True
D = [P(x-1,y), P(x+1,y), P(x,y-1), P(x,y+1)]
ns = [p for p in D if p.x>=0 and p.x<W and p.y>=0 and p.y<H]
while ns:
n = choice(ns)
if not seen[n.x][n.y]:
if x != n.x: hWalls[min(x, n.x)][y] = False
else: vWalls[x][min(y, n.y)] = False
visit(*n)
ns = [x for x in ns if x != n]

visit(randrange(W), randrange(H))

print "+" + ("--+" * W)
for y in xrange(H):
s = "|"
for x in xrange(W):
s += " |" if hWalls[x][y] else " "
s += "\n+"
for x in xrange(W):
s += "--+" if vWalls[x][y] else " +"
print s</lang>


=={{header|Tcl}}==
=={{header|Tcl}}==