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)