Sierpinski, my first fractal

Posted on Aug 4, 2008


The Sierpinski triangle in Python, inspired by HTDP, and using Pygame




import sys
import pygame
from pygame.locals import *

class Point(object):
def __init__(self, x, y):
self.x, self.y = x, y

def distance_sq(self, other):
return (self.x-other.x)**2 + (self.y-other.y)**2

def distance(self, other):
return sqrt(self.distance_sq(other))

def tupl(self):
return (self.x, self.y)

def midpt(p1, p2):
return Point( (p1.x+p2.x)/2, (p1.y+p2.y)/2 )

def too_small(p1, p2, p3):
return max([ p1.distance_sq(p2), p2.distance_sq(p3), p3.distance_sq(p1) ]) < 5

def draw_line(p1, p2, surf, col):
pygame.draw.line(surf, col, p1.tupl(), p2.tupl())


def draw_triangle(a, b, c, screen, col):
if too_small(a, b, c):
return
else:
a_b = midpt(a, b)
a_c = midpt(a, c)
b_c = midpt(b, c)

draw_line(a, b, screen, col)
draw_line(b, c, screen, col)
draw_line(a, c, screen, col)

draw_triangle(a, a_b, a_c, screen, col)
draw_triangle(b, a_b, b_c, screen, col)
draw_triangle(c, b_c, a_c, screen, col)

pygame.init()
pygame.display.set_caption('Sierpinski')
screen = pygame.display.set_mode((640,480))
screen.fill((0, 0, 0))

draw_triangle(Point(10, 10), Point(630, 10), Point(310, 450), screen, (255, 0, 0))
draw_triangle(Point(50, 10), Point(630, 240), Point(310, 0), screen, (0, 255, 0))

while True:
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
pygame.display.update()

pygame.quit()