# RecursiveMaze
# Inspired by http:#weblog.jamisbuck.org/2011/1/12/maze-generation-recursive-division-algorithm
from Processing import *

N = 25          # Grid dimension (# cells)
gsize = 20      # Grid cell size (pixels)
vertical = 1    # Vertical direction constant
horizontal = 2  # Horizontal direction constant

window( N*gsize+1, N*gsize+1 )
noLoop()
background(255)
stroke(0)

# Divide the region given upper left and lower right 
# grid corner points
def divide(r1, c1, r2, c2):

    # Get divide direction (V, H or 0)
    direction = divDirection(r1, c1, r2, c2)

    # Divide in vertical direction
    if direction == vertical:

        # Calculate wall and opening locations
        cr = randomInt(c1+1, c2-1)
        rr = randomInt(r1, r2-1)

        # Draw wall
        gridLine(cr,r1,cr,rr)
        gridLine(cr,rr+1,cr,r2)

        # Recursively divide two subregions
        #delay(500)
        divide(r1,c1,r2,cr)
        divide(r1,cr,r2,c2)

    # Divide in horizontal direction
    elif direction == horizontal:

        # Calculate wall and opening locations
        cr = randomInt(c1, c2-1)
        rr = randomInt(r1+1, r2-1)

        # Draw wall
        gridLine(c1,rr,cr,rr)
        gridLine(cr+1,rr,c2,rr)

        # Recursively divide two subregions
        #delay(500)
        divide(r1,c1,rr,c2)
        divide(rr,c1,r2,c2)

    # No division. We're done.
    else:
        return

# Determine the direction for dividing the region
# based on which dimension is smaller.
# Stop when too small.
def divDirection(r1, c1, r2, c2):
    dr = r2 - r1              # Calculate deltas
    dc = c2 - c1
    if dr <= 1 or dc <= 1:    # Too small
        return 0                # No division
    elif dr < dc:             # Flat and wide
        return vertical         # Vertical division
    else:                     # Tall and narrow
        return horizontal       # Horizontal division

# Return a random integer in the range [min, max]
def randomInt(min, max):
    return round(random(min-0.5, max+0.5))

# Draw a line on a grid segment given grid points
def gridLine(r1, c1, r2, c2):
    line(r1*gsize, c1*gsize, r2*gsize, c2*gsize)

# Kick off the recursive divide on the whole sketch
divide(0,0,N,N)
