Advertisement
Mangus875

Turtle Graphics Hilbert Curve

Jan 5th, 2024
924
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.94 KB | None | 0 0
  1. import turtle
  2. t = turtle.Turtle()
  3. t.speed(5)
  4. t.width(3)
  5. t.ht()
  6. t.tracer(50)
  7.  
  8. def hilbertSize(i):
  9.     return 2**i - 1
  10.  
  11. hilbIters = 5
  12. lineSeg = (t.window_width()-50) / hilbertSize(hilbIters)
  13. offset = hilbertSize(hilbIters)*lineSeg/2
  14. t.pu()
  15. t.goto(-offset, offset)
  16. t.pd()
  17.  
  18. def hilbert(iteration):
  19.     path = "A"
  20.     newPath = ""
  21.     while iteration > 0:
  22.         for c in path:
  23.             if c == 'A':
  24.                 newPath += "+BF-AFA-FB+"
  25.             elif c == 'B':
  26.                 newPath += "-AF+BFB+FA-"
  27.             else:
  28.                 newPath += c
  29.         path = newPath
  30.         newPath = ""
  31.         iteration -= 1
  32.     return path
  33.  
  34. def cleanPath(path):
  35.     newPath = ""
  36.     for c in path:
  37.         if c == 'F' or c == '+' or c == '-':
  38.             newPath += c
  39.     return newPath
  40.  
  41. def turn(ang):
  42.     t.seth(t.heading()+ang)
  43.  
  44. def drawPath(path):
  45.     for c in path:
  46.         #c = c.upper()
  47.         if c == 'F':
  48.             t.fd(lineSeg)
  49.         elif c == '+':
  50.             turn(-90)
  51.         elif c == '-':
  52.             turn(90)
  53.     t.tracer(1)
  54.  
  55.  
  56. path = cleanPath(hilbert(hilbIters))
  57. drawPath(path)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement