Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import turtle
- import numpy as np
- '''
- Function that creates a Sierpinski Triangle
- Takes in side and number of times to repeat this pattern
- as an argument.
- '''
- def draw_triangle_up(tobi, angle, side):
- for i in range(0, 3):
- tobi.forward(side)
- tobi.left(angle)
- def draw_triangle_down(tobi, angle, side):
- for i in range(0, 3):
- tobi.forward(side)
- tobi.right(angle)
- def draw_equilateral_triangle(tobi, side, upside_down):
- if upside_down:
- draw_triangle_down(tobi, 120, side)
- else:
- draw_triangle_up(tobi, 120, side)
- def draw_sub_triangles(tobi, start_x, start_y, side, cur_count, num_times):
- if cur_count > num_times:
- return
- else:
- # no drawing while setting the current index
- tobi.penup()
- tobi.setx(start_x)
- tobi.sety(start_y)
- # now put the pen down so we can see what we are drawing
- tobi.pendown()
- draw_equilateral_triangle(tobi, side, True)
- cur_count += 1
- draw_sub_triangles(tobi, (start_x - side/4.0), (start_y - ((np.sqrt(3) * side)) / 4.0), side/2.0, cur_count, num_times)
- draw_sub_triangles(tobi, (start_x + side/4.0), (start_y + ((np.sqrt(3) * side)) / 4.0), side/2.0, cur_count, num_times)
- draw_sub_triangles(tobi, (start_x + 3 * side/4.0), (start_y - ((np.sqrt(3) * side)) / 4.0), side/2.0, cur_count, num_times)
- def sierpinski_triangle(side, num_times=1):
- # get turtle screen singleton object
- window = turtle.Screen()
- window.delay(50)
- # instantiate turtle object
- tobi = turtle.Turtle()
- # maintain a list of start points
- start_points = [(tobi.xcor(), tobi.ycor(), side)]
- # maintain current count
- cur_count = 0
- # draw main triangle
- draw_equilateral_triangle(tobi, side, False)
- draw_sub_triangles(tobi, (tobi.xcor() + side/4.0), (tobi.ycor()+ ((np.sqrt(3) * side) / 4.0)), side/2.0, cur_count, num_times)
- window.exitonclick()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement