'''lecture_35_recursion_turtle_tree.py Uses recursion and turtle to draw trees Oliver W. Layton CS 151: Computational Thinking: Visual Media Spring 2021 ''' import turtle class Tree: def __init__(self, start_x, start_y): ''' Get turtle ready and in-position to draw an upright tree. Show animations (but fast ones) with speed of 7 ''' self.screen = turtle.Screen() self.turt = turtle.Turtle() # So we can see the tree being drawn, but not too slowly self.turt.speed(0) # Draw trees upward self.turt.setheading(90) self.turt.color('blue') def goto(self, x, y): self.turt.penup() self.turt.goto(x, y) self.turt.pendown() def hold(self): self.screen.exitonclick() def drawTree(self, distance): '''Draw a tree recursively with initial trunk/branch length `distance`. - Draw branches that look like "forks": straight part then left and right offshots +/-20 deg offset from straight. - Stop drawing branches when the branch distance is <= 5 - After drawing left, right, and straight portions, always restore the turtle position to what it was before drawing the "fork". ''' # What is the base case? # Stop drawing branches when the branch distance is <= 5 if distance < 5: return # If we made it this far, the distance is > 5. # Draw the trunk of the tree self.turt.forward(distance) # Before we draw any branches, save turtle current position (x, y) # so we know where to get back to when we want to draw the right # branch x, y = self.turt.position() # Draw left branch (subtree). Branch angle = 20 from current heading self.turt.left(20) self.drawTree(distance/2) self.goto(x, y) # Draw right branch (subtree). Branch angle = 20 from current heading self.turt.right(40) self.drawTree(distance/2) self.turt.left(20) self.goto(x, y) if __name__ == '__main__': tree = Tree(0, -700) # Draw the tree using recursion tree.drawTree(200) # Keep the screen up until we click tree.hold()