/Demo/turtle/tdemo_tree.py

http://unladen-swallow.googlecode.com/ · Python · 63 lines · 58 code · 0 blank · 5 comment · 0 complexity · 00466d412667e8b4c7f2a15bd08041f6 MD5 · raw file

  1. #!/usr/bin/python
  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 the
  12. current pen is cloned. So in the end there
  13. are 1024 turtles.
  14. """
  15. from turtle import Turtle, mainloop
  16. from time import 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.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. print len(p.getscreen().turtles())
  48. def main():
  49. a=clock()
  50. maketree()
  51. b=clock()
  52. return "done: %.2f sec." % (b-a)
  53. if __name__ == "__main__":
  54. msg = main()
  55. print msg
  56. mainloop()