Advertisement
asweigart

drunkSierpinskiTriangle.py

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