user3517740
user3517740

Reputation: 47

right side of fractal tree using turtle in python

I am just a beginner and am trying to make a fractal tree using python's turtle by making a recursive function. I think I've got the function so far that it makes the entire left side of my fractal but it doesn't make the right side. How do I fix that? Any and all advice would be appreciated!

def svTree( trunkLength, levels ):
    """ uses the turtle drawing functions to return a tree with a specified number of levels
    input: two integers, trunkLength and levels
    """

    newtrunkLength = trunkLength *.5


    forward(trunkLength)

    if levels ==1:
           penup()


    else:
        left(45)         
        forward(trunkLength * 0.5)
        backward(trunkLength * 0.5)
        right(90)
        forward(trunkLength * 0.5)
        backward(trunkLength * 0.5)
        left(90)
        return svTree(newtrunkLength,levels-1)

Upvotes: 0

Views: 3384

Answers (1)

mtadd
mtadd

Reputation: 2555

Save the position of the turtle prior to recursing down the left branch, then reset the turtle and draw the right branch:

def svTree(length, level):
   if level == 1:
      return

   #draw level's trunk
   down()
   forward(length)
   up()

   #save turtle position and heading
   pos = position()
   hdg = heading()

   #draw left branch
   left(45)
   svTree(length / 2, level - 1)

   #restore turtle position and heading
   setposition(pos)
   setheading(hdg)

   #draw right branch
   right(45)
   svTree(length / 2, level - 1)

If you don't want to save position and heading at each method call, you can also make sure the turtle cursor ends at the same position and heading as it begins at each method call.

def svTree(length, level):
    if level == 1:
        return

    #draw level's trunk
    down()
    forward(length)
    up()

    #draw left branch
    left(45)
    svTree(length/2, level-1)

    #draw right branch
    right(90)
    svTree(length/2, level-1)

    #return cursor to state when function called
    left(45)
    backward(length)

Upvotes: 1

Related Questions