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