I tried the object approach on my Pythagoras Tree. When a Tree object is created it initially shows nothing on the screen but a blank canvas. Each time the method grow() is called on the Tree object it grows a ‘generation’. Much like a real tree would grow a bit each year.
The program actually looks a lot like my earlier version. You might notice these differences:
- Each recursive call to create a ‘tree’ gets its own turtle (1024+1 turtles for n=10)
- I need the position of the current turtle and give them as arguments to a new Tree object I create. I use the Turtle’s xcor() and ycor() methods to retrieve the x and y coordinates and pass them to the constructor.
- I use a helper method set_start_rightbranch() to offset the starting point to right place for the drawing of the right branch.
- To help decide a branch if it has yet to grow I introduced the property ‘grown’ to the Tree object. At creation it is set to False and after growing the grow method sets it to True.
- I set the turtle speed to fastest (and that’s still pretty slow)
- I have chosen to hide the turtles (it was unsetteling to see that many turtles on the screen)
import math import turtle class Tree: def __init__(self, x, y, size, angle): self.grown = False self.x = x self.y = y self.size = size self.angle = angle self.t = turtle.Pen() self.t.speed(0) self.t.hideturtle() self.t.penup() self.t.goto(x, y) self.t.left(90) self.t.right(self.angle) self.t.pendown() def grow(self): if not self.grown: self.t.forward(self.size) self.leftbranch = Tree(self.t.xcor(), self.t.ycor(), \ math.sqrt((self.size*self.size)/2), self.angle-45) self.t.right(90) self.t.forward(self.size) self.rightbranch = Tree(self.t.xcor(), self.t.ycor(), \ math.sqrt((self.size*self.size)/2), self.angle+45) self.t.right(90) self.t.forward(self.size) self.t.right(90) self.t.forward(self.size) self.t.right(90) self.grown = True return else: self.leftbranch.grow() self.rightbranch.set_start_rightbranch() self.rightbranch.grow() return def set_start_rightbranch(self): self.t.penup() self.t.left(90) self.t.forward(self.size) self.t.right(90) self.t.pendown() return tree = Tree(-50, -200, 100, 0) for i in range(0, 10): tree.grow()