Advertisement
asweigart

sierpinskiTriangle.py

May 15th, 2018
307
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.76 KB | None | 0 0
  1. import turtle
  2. turtle.tracer(100, 0) # Increase the first argument to speed up the drawing.
  3. turtle.setworldcoordinates(0, 0, 700, 700)
  4. turtle.hideturtle()
  5.  
  6. MIN_SIZE = 4 # Try changing this to decrease/increase the amount of recursion.
  7.  
  8. def midpoint(startx, starty, endx, endy):
  9.     # Return the x, y coordinate in the middle of the four given parameters.
  10.     xDiff = abs(startx - endx)
  11.     yDiff = abs(starty - endy)
  12.     return (min(startx, endx) + (xDiff / 2.0), min(starty, endy) + (yDiff / 2.0))
  13.  
  14. def isTooSmall(ax, ay, bx, by, cx, cy):
  15.     # Determine if the triangle is too small to draw.
  16.     width = max(ax, bx, cx) - min(ax, bx, cx)
  17.     height = max(ay, by, cy) - min(ay, by, cy)
  18.     return width < MIN_SIZE or height < MIN_SIZE
  19.  
  20. def drawTriangle(ax, ay, bx, by, cx, cy):
  21.     if isTooSmall(ax, ay, bx, by, cx, cy):
  22.         # BASE CASE
  23.         return
  24.     else:
  25.         # RECURSIVE CASE
  26.         # Draw the triangle.
  27.         turtle.penup()
  28.         turtle.goto(ax, ay)
  29.         turtle.pendown()
  30.         turtle.goto(bx, by)
  31.         turtle.goto(cx, cy)
  32.         turtle.goto(ax, ay)
  33.         turtle.penup()
  34.  
  35.         # Calculate midpoints between points A, B, and C.
  36.         mid_ab = midpoint(ax, ay, bx, by)
  37.         mid_bc = midpoint(bx, by, cx, cy)
  38.         mid_ca = midpoint(cx, cy, ax, ay)
  39.  
  40.         # Draw the three inner triangles.
  41.         drawTriangle(ax, ay, mid_ab[0], mid_ab[1], mid_ca[0], mid_ca[1])
  42.         drawTriangle(mid_ab[0], mid_ab[1], bx, by, mid_bc[0], mid_bc[1])
  43.         drawTriangle(mid_ca[0], mid_ca[1], mid_bc[0], mid_bc[1], cx, cy)
  44.         return
  45.  
  46. # Draw an equilateral Sierpinski triangle.
  47. drawTriangle(50, 50, 350, 650, 650, 50)
  48.  
  49. # Draw a skewed Sierpinski triangle.
  50. #drawTriangle(30, 250, 680, 600, 500, 80)
  51.  
  52. turtle.exitonclick()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement