Mini-Lab: Recursion



In this mini-lab we will experiment with using recursive functions to draw pictures with fractal structure.

Recursive Trees

  1. The following function draws a very simple tree with a trunk and two branches:
    def drawTree(pic, startX, startY, height, width):
      #Add a check so that the new tree is only drawn if the height and 
      #width are greater than 0
      endBranch1X = startX - width/2
      endBranch2X = startX + width/2
      endTrunkY = startY - height / 2
      endBranchY = startY - height 
      addLine(pic, startX, startY, startX, endTrunkY)
      addLine(pic, startX, endTrunkY, endBranch1X, endBranchY) 
      addLine(pic, startX, endTrunkY, endBranch2X, endBranchY)
      #Make recursive calls to drawTree, so that smaller trees will
      #be drawn at the end of the two branches. 
    Copy this function into your .py file and try it out.

  2. Now follow the comments in this function to create a recursive version that draws additional "trees" at the endpoints of the branches. Try calling your function with different values for the height and width parameters.

  3. (IF YOU HAVE TIME) The tree we generated above doesn't look very realistic. One problem is that the trunk is no thicker than any of the branches. In a more realistic tree, the trunk would be the thickest part, and the branches would get progressively skinnier as we moved outward. The following function can be used to draw lines of a specified width:
    def addThickLine(pic,startX, startY, endX, endY, thick, color = black):
      hThick = thick/2
      for xOffset in range(-hThick, thick - hThick):
        for yOffset in range(-hThick, thick - hThick):
          addLine(pic, startX + xOffset, startY + yOffset, endX + xOffset, endY+yOffset, color)
    This function works exactly like the built in addLine function, except that it takes one additional parameter to specify the thickness of the line.

    Create a new version of your drawTree function that makes each successive branch thinner than the one before. This can be accomplished by adding an additional parameter to your function to indicate the current thickness, and by reducing that value in each recursive call.

Submit your results

  1. Submit the file you created in this mini-lab via .