Created
July 23, 2018 14:56
-
-
Save mpawliuk/3eb4ef6c810fcdaddb36f8ec06ff3a9f to your computer and use it in GitHub Desktop.
Adapted code for Math Circle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
from PIL import Image | |
imgx = 500; imgy = 500 | |
image = Image.new("RGB", (imgx, imgy)) | |
pixels = image.load() | |
mx = 10; my = 10 # width and height of the maze | |
maze = [[0 for x in range(mx)] for y in range(my)] | |
dx = [0, 1, 0, -1]; dy = [-1, 0, 1, 0] # 4 directions to move in the maze | |
color = [(0,0, 0), (255, 255, 255)] # RGB colors of the maze | |
# start the maze from a random cell | |
stack = [(random.randint(0, mx - 1), random.randint(0, my - 1))] | |
while len(stack) > 0: | |
(cx, cy) = stack[-1] | |
maze[cy][cx] = 1 | |
# find a new cell to add | |
nlst = [] # list of available neighbors | |
for i in range(4): | |
nx = cx + dx[i]; ny = cy + dy[i] | |
if nx >= 0 and nx < mx and ny >= 0 and ny < my: | |
if maze[ny][nx] == 0: | |
# of occupied neighbors must be 1 | |
ctr = 0 | |
for j in range(4): | |
ex = nx + dx[j]; ey = ny + dy[j] | |
if ex >= 0 and ex < mx and ey >= 0 and ey < my: | |
if maze[ey][ex] == 1: ctr += 1 | |
if ctr == 1: nlst.append(i) | |
# if 1 or more neighbors available then randomly select one and move | |
if len(nlst) > 0: | |
ir = nlst[random.randint(0, len(nlst) - 1)] | |
cx += dx[ir]; cy += dy[ir] | |
stack.append((cx, cy)) | |
else: stack.pop() | |
# Print maze | |
for row in maze: | |
print(row) | |
def moves(row,col,maze): | |
"""replace Maze entry with possible moves.""" | |
pos_moves = ["N","E","S","W"] | |
print(row,col, maze[row][col]) | |
if maze[row][col] == 0: | |
return [] | |
if row == 0: | |
pos_moves.remove("N") | |
elif maze[row-1][col] == 0: | |
pos_moves.remove("N") | |
if row == len(maze)-1: | |
pos_moves.remove("S") | |
elif maze[row+1][col] == 0: | |
pos_moves.remove("S") | |
if col == 0: | |
pos_moves.remove("W") | |
elif maze[row][col-1] == 0: | |
pos_moves.remove("W") | |
if col == len(maze[row])-1: | |
pos_moves.remove("E") | |
elif maze[row][col+1] == 0: | |
pos_moves.remove("E") | |
return pos_moves | |
new_maze = [[moves(i,j,maze) for j in range(len(maze[i]))] for i in range(len(maze))] | |
for row in new_maze: | |
print(row) | |
# paint the maze | |
for ky in range(imgy): | |
for kx in range(imgx): | |
pixels[kx, ky] = color[maze[my * ky // imgy][mx * kx // imgx]] | |
image.save("Maze_" + str(mx) + "x" + str(my) + ".png", "PNG") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment