jpayne@68: #!/usr/bin/env python3 jpayne@68: """ turtle-example-suite: jpayne@68: jpayne@68: tdemo_tree.py jpayne@68: jpayne@68: Displays a 'breadth-first-tree' - in contrast jpayne@68: to the classical Logo tree drawing programs, jpayne@68: which use a depth-first-algorithm. jpayne@68: jpayne@68: Uses: jpayne@68: (1) a tree-generator, where the drawing is jpayne@68: quasi the side-effect, whereas the generator jpayne@68: always yields None. jpayne@68: (2) Turtle-cloning: At each branching point jpayne@68: the current pen is cloned. So in the end jpayne@68: there are 1024 turtles. jpayne@68: """ jpayne@68: from turtle import Turtle, mainloop jpayne@68: from time import perf_counter as clock jpayne@68: jpayne@68: def tree(plist, l, a, f): jpayne@68: """ plist is list of pens jpayne@68: l is length of branch jpayne@68: a is half of the angle between 2 branches jpayne@68: f is factor by which branch is shortened jpayne@68: from level to level.""" jpayne@68: if l > 3: jpayne@68: lst = [] jpayne@68: for p in plist: jpayne@68: p.forward(l) jpayne@68: q = p.clone() jpayne@68: p.left(a) jpayne@68: q.right(a) jpayne@68: lst.append(p) jpayne@68: lst.append(q) jpayne@68: for x in tree(lst, l*f, a, f): jpayne@68: yield None jpayne@68: jpayne@68: def maketree(): jpayne@68: p = Turtle() jpayne@68: p.setundobuffer(None) jpayne@68: p.hideturtle() jpayne@68: p.speed(0) jpayne@68: p.getscreen().tracer(30,0) jpayne@68: p.left(90) jpayne@68: p.penup() jpayne@68: p.forward(-210) jpayne@68: p.pendown() jpayne@68: t = tree([p], 200, 65, 0.6375) jpayne@68: for x in t: jpayne@68: pass jpayne@68: jpayne@68: def main(): jpayne@68: a=clock() jpayne@68: maketree() jpayne@68: b=clock() jpayne@68: return "done: %.2f sec." % (b-a) jpayne@68: jpayne@68: if __name__ == "__main__": jpayne@68: msg = main() jpayne@68: print(msg) jpayne@68: mainloop()