1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
import random
import sys
grid = [ [0] * 10 for x in range(10) ]
N, S, E, W = 1, 2, 4, 8
DX = { E: 1, W: -1, N: 0, S: 0 }
DY = { E: 0, W: 0, N: -1, S: 1 }
OPPOSITE = { E: W, W: E, N: S, S: N }
def carve_passages_from(cx, cy, grid):
directions = [N, S, E, W]
random.shuffle(directions)
for direction in directions:
nx, ny = cx + DX[direction], cy + DY[direction]
if 0 <= ny <= len(grid) - 1 and 0 <= nx <= len(grid[ny]) - 1 and grid[ny][nx] == 0:
grid[cy][cx] |= direction
grid[ny][nx] |= OPPOSITE[direction]
carve_passages_from(nx, ny, grid)
carve_passages_from(0, 0, grid)
def print_maze(grid):
height = len(grid)
width = len(grid[0])
for y in range(0, height):
sys.stdout.write("|")
for x in range(0, width):
if grid[y][x] & S != 0:
sys.stdout.write(" ")
else:
sys.stdout.write("_")
if grid[y][x] & E != 0:
if grid[y][x] | grid[y][x+1] & S != 0:
sys.stdout.write(" ")
else:
sys.stdout.write("_")
else:
sys.stdout.write("|")
print()
print_maze(grid)
|