Advertisement
Guest User

Untitled

a guest
Jul 5th, 2015
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. import turtle
  2. import numpy as np
  3.  
  4. '''
  5. Function that creates a Sierpinski Triangle
  6. Takes in side and number of times to repeat this pattern
  7. as an argument.
  8. '''
  9. def draw_triangle_up(tobi, angle, side):
  10. for i in range(0, 3):
  11. tobi.forward(side)
  12. tobi.left(angle)
  13.  
  14. def draw_triangle_down(tobi, angle, side):
  15. for i in range(0, 3):
  16. tobi.forward(side)
  17. tobi.right(angle)
  18.  
  19.  
  20. def draw_equilateral_triangle(tobi, side, upside_down):
  21. if upside_down:
  22. draw_triangle_down(tobi, 120, side)
  23. else:
  24. draw_triangle_up(tobi, 120, side)
  25.  
  26. def draw_sub_triangles(tobi, start_x, start_y, side, cur_count, num_times):
  27. if cur_count > num_times:
  28. return
  29. else:
  30.  
  31. # no drawing while setting the current index
  32. tobi.penup()
  33. tobi.setx(start_x)
  34. tobi.sety(start_y)
  35.  
  36. # now put the pen down so we can see what we are drawing
  37. tobi.pendown()
  38.  
  39. draw_equilateral_triangle(tobi, side, True)
  40.  
  41. cur_count += 1
  42. draw_sub_triangles(tobi, (start_x - side/4.0), (start_y - ((np.sqrt(3) * side)) / 4.0), side/2.0, cur_count, num_times)
  43. draw_sub_triangles(tobi, (start_x + side/4.0), (start_y + ((np.sqrt(3) * side)) / 4.0), side/2.0, cur_count, num_times)
  44. 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)
  45.  
  46.  
  47. def sierpinski_triangle(side, num_times=1):
  48. # get turtle screen singleton object
  49. window = turtle.Screen()
  50. window.delay(50)
  51.  
  52. # instantiate turtle object
  53. tobi = turtle.Turtle()
  54.  
  55. # maintain a list of start points
  56. start_points = [(tobi.xcor(), tobi.ycor(), side)]
  57.  
  58. # maintain current count
  59. cur_count = 0
  60.  
  61. # draw main triangle
  62. draw_equilateral_triangle(tobi, side, False)
  63.  
  64.  
  65. draw_sub_triangles(tobi, (tobi.xcor() + side/4.0), (tobi.ycor()+ ((np.sqrt(3) * side) / 4.0)), side/2.0, cur_count, num_times)
  66.  
  67. window.exitonclick()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement