Today's lab will focus on the python's mathematics library and the turtle graphics library. An excellent overview of turtle graphics can be found at the How to think like a Computer Scientist.

Bouncing Ball

We will use the turtle graphics (built-in to python) to write a simulation of a bouncing ball.

Here is the first program (inspired from

#Idea from:

from turtle import *
from math import *

def main():
    veloc = .5  #horizontal velocity (pixels per second)
    amp = 75    #sine wave amplitude (pixels)
    freq = .01  #oscillations per second

    #Set up a graphics window and turtle:
    win = Screen()
    ball = Turtle()
    win.setworldcoordinates(0.0, -100.0, 500.0, 100.0)

    #Draw a line for the x-axis:

    #Draw a ball that follows a sine wave
    for time in range(500):
        #For each time step, move the turtle to (time, sin(time))
        #       (with some scaling to make it fill screen)

    win.exitonclick()         #Close the window when clicked
Save this file to your USB or MyDocuments folder and run the program. Let's go through what each part does:

To make the ball appear to bounce, we need for it to stay above the line representing the x-axis. Another way of saying that is its y-coordinate should always be positive. A simple way to do that is to take the absolute value of the expression for the y-coordinate:

Try adding this to your goto() statement, that is:

Try running your program to see the bouncing ball! Two more challenges to think about (ask your instructor for hints if you do not see how to do these, since questions about them will appear on quizzes and exams):

If you finish early, you may work on the programming problems.