Search code examples
pythonturtle-graphicsfractals

Right side of Fractal Tree Missing using turtle in python 3


I tried to make a fractal tree in python using the turtle module. This is what I have so far:

    import turtle
    t1 = turtle.Turtle()
    t1.speed(0)
    t1.left(90)
    t1.hideturtle()
    def branch(len):
      t1.forward(len)
      if(len>20):
        angle = 45
        xCor = t1.xcor()
        yCor = t1.ycor()
        t1.left(angle)
        branch(len*0.67)
        t1.goto(xCor, yCor)
        xCor = t1.xcor()
        yCor = t1.ycor()
        t1.left(-angle)
        branch(len*0.67)
        t1.goto(xCor, yCor)
    branch(100)

However, this results in the right part of the fractal tree missing, and same with half of the left part of the tree.

Here is a picture: Result of Code

Here is the other picture where I multiplied the angle by 0.1

Result of Code

Here are the changes i made to my code:

Code


Solution

  • To get the tree you want you need to save the turtle's heading before you do a branch so that you can restore it after you do a branch. The easy way to do that is to use the .heading and .setheading methods.

    I've also made another minor change. I use the .position method to get the turtle's current position in a tuple, rather than making two separate calls.

    BTW, it's not a good idea to use len as a variable name because that shadows the built-in len function.

    import turtle
    
    t1 = turtle.Turtle()
    
    t1.speed(0)
    t1.left(90)
    t1.hideturtle()
    # Move the turtle down the screen to make room for the tree
    t1.up()
    t1.forward(-200)
    t1.down()
    
    angle = 45
    
    def branch(length):
        t1.forward(length)
        if length > 20:
            xy = t1.position()
            head = t1.heading()
            length *= 0.67
    
            t1.left(angle)
            branch(length)
    
            t1.setheading(head)
            t1.goto(xy)
            t1.right(angle)
            branch(length)
    
            t1.goto(xy)
    
    branch(100)
    turtle.done()