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 motionscript.com):

#Idea from:  http://www.motionscript.com/mastering-expressions/simulation-basics-1.html

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()
    ball.speed(10)
    win.setworldcoordinates(0.0, -100.0, 500.0, 100.0)

    #Draw a line for the x-axis:
    ball.up()
    goto(0,0)
    ball.down()
    ball.forward(500)
    ball.up()
    ball.backward(500)
    ball.down()

    #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)
        ball.goto(time,int(amp*sin(freq*time*2*pi)))        

    win.exitonclick()         #Close the window when clicked
    
main()
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:

        abs(amp*sin(freq*time*2*pi))
Try adding this to your goto() statement, that is:
        ball.goto(time,abs(int(amp*sin(freq*time*2*pi))))        

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.