tree.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #!/usr/bin/env python3
  2. """ turtle-example-suite:
  3. tdemo_tree.py
  4. Displays a 'breadth-first-tree' - in contrast
  5. to the classical Logo tree drawing programs,
  6. which use a depth-first-algorithm.
  7. Uses:
  8. (1) a tree-generator, where the drawing is
  9. quasi the side-effect, whereas the generator
  10. always yields None.
  11. (2) Turtle-cloning: At each branching point
  12. the current pen is cloned. So in the end
  13. there are 1024 turtles.
  14. """
  15. from turtle import Turtle, mainloop
  16. from time import perf_counter as clock
  17. def tree(plist, l, a, f):
  18. """ plist is list of pens
  19. l is length of branch
  20. a is half of the angle between 2 branches
  21. f is factor by which branch is shortened
  22. from level to level."""
  23. if l > 3:
  24. lst = []
  25. for p in plist:
  26. p.forward(l)
  27. q = p.clone()
  28. p.left(a)
  29. q.right(a)
  30. lst.append(p)
  31. lst.append(q)
  32. for x in tree(lst, l*f, a, f):
  33. yield None
  34. def maketree():
  35. p = Turtle()
  36. p.setundobuffer(None)
  37. p.hideturtle()
  38. p.speed(0)
  39. p.getscreen().tracer(30,0)
  40. p.left(90)
  41. p.penup()
  42. p.forward(-210)
  43. p.pendown()
  44. t = tree([p], 200, 65, 0.6375)
  45. for x in t:
  46. pass
  47. def main():
  48. a=clock()
  49. maketree()
  50. b=clock()
  51. return "done: %.2f sec." % (b-a)
  52. if __name__ == "__main__":
  53. msg = main()
  54. print(msg)
  55. mainloop()