'''
Created on Apr 3, 2011

create Sierpinski Triangle using PIL

@author: ola, modified by rcd
'''
import Image       # PIL
import ImageDraw   # PIL


def midpoint(p, q, factor=0.5):
    '''
    returns point, an (x,y)-tuple, between the given points
    '''
    return ((p[0]+q[0])*factor,(p[1]+q[1])*factor)


def draw_shape(image, points):
    '''
    draws shape enclosed by the given points
    '''
    for i,p in enumerate(points):
        image.line([p, points[(i+1)%len(points)]])


def sierpinski(image, level, points):
    '''
    calculates points for sub triangles, uses recursion for steps
    '''
    # base case: nothing to do
    if level <= 0 or len(points) == 0:
        return
    # general case: draw big triangle
    draw_shape(image, points)
    # make smaller triangles from each point and adjacent midpoints
    mid01 = midpoint(points[0], points[1])
    mid02 = midpoint(points[0], points[2])
    mid12 = midpoint(points[1], points[2])
    # TODO: complete the parameters to these recursive calls
    sierpinski(image, 0, [])
    sierpinski(image, 0, [])
    sierpinski(image, 0, [])



picture = Image.new('RGB', (700, 700))
drawnimage = ImageDraw.Draw(picture)

triangle = ((0, 700), (700, 700), (350, 0))
# draw the triangle and calculate next triangle corner coordinates
sierpinski(drawnimage, 7, triangle)
picture.show()
