summaryrefslogtreecommitdiffstats
path: root/maze.py
diff options
context:
space:
mode:
Diffstat (limited to 'maze.py')
-rw-r--r--maze.py50
1 files changed, 50 insertions, 0 deletions
diff --git a/maze.py b/maze.py
new file mode 100644
index 0000000..bea4808
--- /dev/null
+++ b/maze.py
@@ -0,0 +1,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)