shinemic

turtle 正方形分形作图

Oct 26th, 2023
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.23 KB | None | 0 0
  1. """正方形分形作图 - turtle"""
  2.  
  3. import turtle
  4.  
  5. tur = turtle.Turtle()
  6. tur.shape('blank')
  7. tur.turtlesize(*(0.3,) * 3)
  8. tur._delay(0)
  9. tur.speed(0)
  10.  
  11.  
  12. def draw(depth, width, start_pos):
  13.  
  14.     # 回到左上角
  15.     tur.penup()
  16.     tur.goto(*start_pos)
  17.  
  18.     # 横向四条线
  19.     for i in range(4):
  20.         tur.goto(start_pos[0], start_pos[1] - width / 3 * i)
  21.         tur.pendown()
  22.         tur.seth(0)
  23.         tur.forward(width)
  24.         tur.penup()
  25.  
  26.     # 归位
  27.     tur.setpos(*start_pos)
  28.  
  29.     # 纵向四条线
  30.     for i in range(4):
  31.         tur.goto(start_pos[0] + width / 3 * i, start_pos[1])
  32.         tur.pendown()
  33.         tur.seth(270)
  34.         tur.forward(width)
  35.         tur.penup()
  36.  
  37.     # 归位
  38.     tur.setpos(*start_pos)
  39.  
  40.     # 如果需要画更深层次图形
  41.     if depth > 1:
  42.         depth -= 1
  43.         width /= 3
  44.         for v in range(3):
  45.             for h in range(3):
  46.                 if (h, v) != (1, 1):
  47.                     draw(depth, width, (start_pos[0] + h * width, start_pos[1] - v * width))
  48.  
  49.  
  50. # 当递归数较多时会影响显示性能,取消注释 tracer 及 update 的两行不显示绘图过程
  51.  
  52. turtle.tracer(1000, 0)
  53. draw(5, 750, (-375, 375))
  54. # turtle.update()
  55. turtle.mainloop()
  56.  
Add Comment
Please, Sign In to add comment