CSC111 moveBall.py

From dftwiki3
Jump to: navigation, search

--D. Thiebaut 13:17, 24 March 2010 (UTC)


A program moving a ball in a random direction at a random speed. The ball leaves the screen eventually...

# moveBall.py
# A program that uses the graphics library to display a ball
# (circle) starting in the middle of the screen and moving
# in a random direction, at a random speed.  The program
# moves the ball in 200 steps and stops afterward.
#

from graphics import *
import random

W = 300
H = 300

#----------------------------------------------------------------
def simul( c, dx, dy ):
    for step in range( 200 ):
        c.move( dx, dy )

#----------------------------------------------------------------
def waitForClick( win, message ):
    """ waitForClick: stops the GUI and displays a message.  
    Returns when the user clicks the window. The message is erased."""

    # wait for user to click mouse to start
    startMsg = Text( Point( win.getWidth()/2, win.getHeight()/2 ), message )
    startMsg.draw( win )    # display message
    win.getMouse()          # wait
    startMsg.undraw()       # erase

#----------------------------------------------------------------
def main():
    win = GraphWin( "moving ball", W, H )
    #--- define a ball position and velocity ---
    c = Circle( Point( W/2, H/2 ), 15 )
    c.setFill( "red" )
    c.draw( win )

    waitForClick( win, "Click to Start" )

    simul( c, 3-random.randrange( 6 ), 3-random.randrange( 6 ) )

    waitForClick( win, "Click to End" )
    win.close()

main()