1. Exercise 1: polygon

Loops can be used in conjunction with turtles to make interesting designs.
Write the function polygon, which will produce different shapes as shown in the slides.

In [3]:
from turtle import *
In [ ]:
def polygon(numSides, sideLength):
    '''Draws a polygon with the specified number 
     of sides, each with the specified length.
     '''
    # Your code here
    for _ in range(numSides):
        fd(sideLength)
        rt(360.0/numSides)
In [ ]:
# Draw a triangle

polygon(3, 100)
In [ ]:
# Draw a square, reset canvas first

reset()
polygon(4, 100)
In [ ]:
# Draw a pentagon, reset canvas first
reset()
polygon(5, 75)
In [ ]:
# Draw an approximate circle, reset canvas first
reset()
polygon(100, 3)

2. Exercise 2: polyflow

In addition to the simple shapes we saw above, with loops we can create more interesting shapes too,
such as geometric flowers. Examples are shown in the slides.
Use the helper function polygon that you defined in Exercise 1 to write poloyflow.

In [ ]:
def polyFlow(numPetals, petalSides, petalLen):
    '''Draws "flowers" with numPetals arranged around
    a center point. Each petal is a polygon with
    petalSides sides of length petalLen.
    '''
    # Your code here
    for petal in range(numPetals):
        polygon(petalSides, petalLen)
        rt(360.0/numPetals)
In [ ]:
# Example 1: square petals
reset()
speed(10)
polyFlow(7, 4, 80)
In [ ]:
# Example 2: pentagon petals
reset()
speed(10)
polyFlow(10, 5, 75)
In [ ]:
# Example 3: hexagon petals
reset()
speed(10)
polyFlow(11, 6, 60)

3. Spiraling Turtles: A recursion example

Let's try to write together the recursive function spiral, which creates the images shown in the slides.

In [ ]:
def spiral(sideLen, angle, scaleFactor, minLength):
    '''
    Recursively creates a spiral, takes these parameters:
    1. sideLen is the length of the current side;
    2. angle is the amount the turtle turns left to draw the next side;
    3. scaleFactor is the multiplicative factor by which to scale the next side 
    (it is between 0.0 and 1.0);
    4. minLength is the smallest side length that the turtle will draw.
    '''
    if sideLen >= minLength:
        fd(sideLen)
        lt(angle)
        spiral(sideLen*scaleFactor, angle, scaleFactor, minLength)

To test the function with large values, we need to move the turtle from (0,0) in the center
of the canvas to some other point. However, whenever the turtle moves, it leaves a trail behind.
This is why we used the methods pu and pd (pen up and pen down).

To keep everything clean, we'll wrap it all in the function.

In [ ]:
def drawSpiral(sideLen, angle, scaleFactor, minLength):
    """Helper function to prepare the window for drawing and 
    then calling the spiral function.
    """
    reset()
    padding = 200
    width = sideLen + padding
    height = sideLen + padding
    setup(width, height, 0, 0)
    pu()
    goto(-height/2+padding/2, -width/2+padding/2)
    pd()
    spiral(sideLen, angle, scaleFactor, minLength)
    #exitonclick()
    
drawSpiral(625, 90, 0.7, 100)

Let's see the examples shown in slides:

In [ ]:
drawSpiral(200, 90, 0.9, 10)
In [ ]:
drawSpiral(200, 72, 0.97, 10)
In [ ]:
drawSpiral(200, 121, 0.95, 15)

4. Exercise 3: spiralBack (Invariance)

A function is invariant relative to an object’s state if the state of the object is the same
before and after the function is invoked.

Let's write the following function together. It's very similar to spiral, we just need to
undo the operations we did before the recursion.

In [ ]:
def spiralBack(sideLen, angle, scaleFactor, minLength):
    '''Draws a spiral. The state of the turtle (position,
    direction) after drawing the spiral should be the 
    same as before drawing the spiral. 
    '''
    # Your code here
    if sideLen >= minLength:
        fd(sideLen)
        lt(angle)
        spiralBack(sideLen*scaleFactor, angle, scaleFactor, minLength)
        rt(angle)
        bk(sideLen)
In [ ]:
reset()
spiralBack(200, 95, 0.93, 10)

5. Trees

The previous exercises showed invariance in the context of turtle spirals. Now we will use the idea of invariant functions to create more sophisticated turtle designs, again using recursion. The lecture slides show some designs created with the trees recursive function.

In [ ]:
def tree(levels, trunkLen, angle, shrinkFactor):
    '''Draws recursively a tree design with the following parameters:
    1. levels is the number of branches on any path from the root to a leaf
    2. trunkLen is the length of the base trunk of the tree
    3. angle is the angle from the trunk for each subtree
    4. shrinkFactor is the shrinking factor for each subtree.
    '''
    if levels > 0:
        # Draw the trunk.
        fd(trunkLen)
        # Turn and draw the right subtree.
        rt(angle)
        tree(levels-1, trunkLen*shrinkFactor, angle, shrinkFactor)
        # Turn and draw the left subtree.
        lt(angle * 2)
        tree(levels-1, trunkLen*shrinkFactor, angle, shrinkFactor)
        # Turn back and back up to root without drawing.
        rt(angle)
        pu()
        bk(trunkLen)
        pd()

Let's try the tree from the slides:

In [ ]:
reset()
lt(90) # Face north first to grow the tree upwards
tree(3, 60, 45, 0.6)

Let's create a more sophisticated tree:

In [ ]:
reset()
lt(90) # Face north first to grow the tree upwards
speed(20)
tree(7, 75, 30, 0.8)

Yet another sophisticated tree:

In [ ]:
reset()
lt(90) # Face north first to grow the tree upwards
speed(20)
tree(10, 80, 45, 0.7)

6. Random Trees

The function tree creates symmetric, perfect trees that don't resemble natural trees. Can we do better? Yes, by introducing randomness.

Run the code below and then study how it works.

In [4]:
import random

def treeRandom(trunkLen, minLength, thickness, minThickness, 
               minAngle, maxAngle, minShrink, maxShrink):
    
    if (trunkLen < minLength) or (thickness < minThickness): # Base case
        pass # Do nothing
    else:
        angle1 = random.uniform(minAngle, maxAngle)
        angle2 = random.uniform(minAngle, maxAngle)
        shrink1 = random.uniform(minShrink, maxShrink)
        shrink2 = random.uniform(minShrink, maxShrink)
        pensize(thickness)
        fd(trunkLen)
        rt(angle1)
        treeRandom(trunkLen*shrink1, minLength, thickness*shrink1,
                   minThickness, minAngle, maxAngle, minShrink, maxShrink)
        lt(angle1 + angle2)
        treeRandom(trunkLen*shrink2, minLength, thickness*shrink2, 
                   minThickness, minAngle, maxAngle, minShrink, maxShrink)
        rt(angle2)
        pensize(thickness)
        bk(trunkLen)
In [5]:
reset()
speed(10)
lt(90) # Face north first to grow the tree upwards
treeRandom(120, 3, 20, 1, 15, 55, 0.5, 0.8)

7. Fruitful spiraling: spiralLength

First some housekeeping function to setup the turtle drawing:

In [ ]:
from turtle import *

setup(600, 600, 0, 0)

def resetTurtle():
    reset()
    pu()
    goto(-250, -250)
    pd()

The function spiralLength below modifies the function spiralBack that we covered in the previous lecture so that it returns the total length of lines in the spiral.

In [ ]:
def spiralLength(sideLen, angle, scaleFactor, minLength):
    """Draws a spiral based on the given parameters and leaves the turtle's location
    and orientation invariant. Also returns the total length of lines in the spiral.
    """
    if sideLen < minLength:
        return 0
    else:
        fd(sideLen); lt(angle)        # Put two statements on one line with semi-colon
        subLen = spiralLength(sideLen*scaleFactor, 
                              angle, 
                              scaleFactor, 
                              minLength) 
        rt(angle); bk(sideLen)
        return sideLen + subLen

Invoke the function:

In [ ]:
resetTurtle()
totalLen = spiralLength(100, 90, 0.5, 5)
print("The total length of the spiral is", totalLen)

8. Exercise 4: spiralCount

Below we have copied spiralLength and modified it to be named spiralCount. The goal is to specify what should go in the return statements, so that the function returns the number of lines in the spiral.

In [ ]:
def spiralCount(sideLen, angle, scaleFactor, minLength):
    """Draws a spiral based on the given parameters and leaves the turtle's location
    and orientation invariant. Also returns the number lines in the spiral.
    """
    if sideLen < minLength:
        # Add the return statement
        # Your code here
        return 0
    else:
        fd(sideLen); lt(angle) # Put two statements on one line with semi-colon
        subCount = spiralCount(sideLen*scaleFactor, 
                               angle, 
                               scaleFactor, 
                               minLength) 
        rt(angle); bk(sideLen)
        # Add the return statement
        # Your code here
        return 1 + subCount

Invoke the function:

In [ ]:
resetTurtle()
totalCount = spiralCount(100, 90, 0.5, 5)
print("The number of lines in the spiral is", totalCount)

9 Exercise 5: spiralTuple

Now, copy below your working version of spiralLength and modify it to be a function spiralTuple that returns a pair (i.e., a 2-tuple) of:

  • the length of lines in the spiral and
  • the number of lines in the spiral.
In [ ]:
def spiralTuple(sideLen, angle, scaleFactor, minLength):
    """Draws a spiral based on the given parameters and leaves the turtle's 
    location and orientation invariant. Also returns a pair (2-tuple) of 
    (1) the length of lines in the spiral
    (2) the number of lines in the spiral.
    """
    # Your code here
    if sideLen < minLength:
        return (0, 0)
    else:
        fd(sideLen); lt(angle) # Put two statements on one line with semi-colon
        subLen, subCount = spiralTuple(sideLen*scaleFactor, 
                                       angle, 
                                       scaleFactor, 
                                       minLength) 
        rt(angle); bk(sideLen)
        return sideLen + subLen, 1 + subCount

Invoke the function:

In [ ]:
resetTurtle()
(totalLength, totalCount) = spiralTuple(512, 90, 0.5, 5)
print(f"The spiral has {totalCount} lines whose total length is {totalLength}")

10. Exercise 6: Fruitful trees - branchCount

Similarly to the modifications that we did to functions that draw spirals, we can modify the function that draws trees to become a fruitful function, to count the number of branches that are drawn.

Below is the original tree function for drawing a tree:

In [ ]:
def tree(levels, trunkLen, angle, shrinkFactor):
    '''Draws recursively a tree design with the following parameters:
    1. levels is the number of branches on any path from the root to a leaf
    2. trunkLen is the length of the base trunk of the tree
    3. angle is the angle from the trunk for each subtree
    4. shrinkFactor is the shrinking factor for each subtree.
    '''
    if levels <= 0:
        pass
    else:
        # Draw the trunk.
        fd(trunkLen)
        # Turn and draw the right subtree.
        rt(angle)
        tree(levels-1, trunkLen*shrinkFactor, angle, shrinkFactor)
        # Turn and draw the left subtree.
        lt(angle * 2)
        tree(levels-1, trunkLen*shrinkFactor, angle, shrinkFactor)
        # Turn back and back up to root without drawing.
        rt(angle)
        pu()
        bk(trunkLen)
        pd()

Copy and modify the solution of tree so that it becomes branchCount, which in addition to drawing the tree also returns the number of all branches in the tree.

Note: Don't forget to change the function name in the recursive calls from tree to branchCount when you paste the solution in the cell below.

In [ ]:
def branchCount(levels, trunkLen, angle, shrinkFactor):
    '''Draws recursively a tree design with the following parameters:
    1. levels is the number of branches on any path from the root to a leaf
    2. trunkLen is the length of the base trunk of the tree
    3. angle is the angle from the trunk for each subtree
    4. shrinkFactor is the shrinking factor for each subtree.
    '''
    # Your code here
    if levels <= 0:
        return 0
    else:
        # Draw the trunk.
        fd(trunkLen)
        # Turn and draw the right subtree.
        rt(angle)
        # Keep track of branches for the right subtree
        branchCount1 = branchCount(levels-1, trunkLen*shrinkFactor, angle, shrinkFactor)
        # Turn and draw the left subtree.
        lt(angle * 2)
        # Keep track of branches for the left subtree
        branchCount2 = branchCount(levels-1, trunkLen*shrinkFactor, angle, shrinkFactor)
        # Turn back and back up to root without drawing.
        rt(angle)
        pu()
        bk(trunkLen)
        pd()
        return 1 + branchCount1 + branchCount2

Let's draw a small tree with level 3:

In [ ]:
reset()
lt(90) # Face north first to grow the tree upwards
print(f"The number of branches drawn is {branchCount(3, 60, 45, 0.6)}")

Let's draw a bigger tree with level 7:

In [ ]:
reset()
lt(90) # Face north first to grow the tree upwards
speed(20)
print(f"The number of branches drawn is {branchCount(7, 75, 30, 0.8)}")

11. More fun with turtles: drawing fractals

Define the koch and snowflake functions as indicated on the slides.

HINT: The koch function does work in its base case. It also calls itself several times in the recursive case.

In [ ]:
def koch(levels, size):
    # Your code here
    if levels == 0:
        fd(size)
    else:
        koch(levels-1, size/3.0)
        lt(60)
        koch(levels-1, size/3.0)
        rt(120)
        koch(levels-1, size/3.0)
        lt(60)
        koch(levels-1, size/3.0)
In [ ]:
# Invoke the function
reset()
speed(20)
koch(3, 250)

Once you write the function koch, writing snowflake is really simple. This is because snowflake is not a recursive function. It simply calls the function koch that is recursive.

In [ ]:
def snowflake(levels, size):
    # Your code here
    for i in range(3):
        koch(levels, size)
        rt(120)
In [ ]:
# invoke the function
reset()
speed(20)
snowflake(3, 250)

This is all for today's lecture!