The Sierpinsky triangle is a simple fractal pattern that can be drawn using the chaos game method. While it seems that the triangle should be drawn using lines, it is actually created by just plotting point according to the chaos game algorithm. This code was generated at a one day Python workshop in Vancouver largely due to the curiosity of one student, June Yakavonis, in her first day using Python. A fun future goal would be to randomly animate the triangle using BlockGrid.animate
method.
import random as rn
from ipythonblocks import BlockGrid
def draw_srpk_tri(dim = 100, iterations = 1000, background_color = (255,255,255), triangle_color = (0,0,0) ,block_size = 3):
'''
Draws a Sierpinski triangle using the chaos game approach (http://en.wikipedia.org/wiki/Chaos_game)
Parameters:
dim -- integer, the dimensions of the square to draw the triangle in, default is 100
iterations -- integer, the number of points to create the triangle with, the higher the value, the more resolution, default is 1000
background_color -- tuple of integers, the RGB values of the background color of the square, default is black
triangle_color -- tuple of integers, the RGB values of the triangle color of the square, default is white
block_size -- integer, the number of pixels that make up a block, bigger is easier to see, but more coarse, default is 3
Authors:
June Yakavonis <jwyframed@gmail.com>
Ted Hart <edmund.m.hart@gmail.com>
'''
srpnskgrid = BlockGrid(dim, dim, background_color, block_size = block_size, lines_on = 0)
vertices = [[(dim - 1),0],[0,int(dim / 2)],[(dim - 1),(dim - 1)]]
for i in vertices:
srpnskgrid[i[0],i[1]].rgb = triangle_color
point_x = rn.randint(0,dim)
point_y = rn.randint(0,int(point_x * .5))
i = 0
points = []
while i < iterations:
r_vert = rn.randint(0,2)
point_x = int((vertices[r_vert][0] + point_x) * 0.5)
point_y = int((vertices[r_vert][1] + point_y) * 0.5)
points.append([point_x,point_y])
i += 1
#stored as a list for the possibility of animating later.
for x in points:
srpnskgrid[x[0],x[1]].rgb = triangle_color
return srpnskgrid
Here we can just draw a triangle with the function defaults.
draw_srpk_tri()
We can up the iterations and downsize the pixel/block ratio for a classic triangle and change the colors.
draw_srpk_tri(dim = 200, iterations = 10000, background_color=(0,0,255), triangle_color = (255,0,0), block_size=1)