CSC111 movingBall3.py

From dftwiki3
Revision as of 14:42, 24 March 2010 by Thiebaut (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

--D. Thiebaut 18:38, 24 March 2010 (UTC)


# movingBall3.py
# D Thiebaut
# solution program for parts of Lab 8.
# The program 
from graphics import *
import random

W = 300
H = 300

#----------------------------------------------------------------
def simul( ballList ):
    for step in range( 300 ):
        for i in range( len( ballList ) ):
            c, dx, dy = ballList[ i ]
            radius = c.getRadius()
            x = c.getCenter().getX()
            y = c.getCenter().getY()
            if not ( radius <= x <= W-radius ):
                dx = -dx
            if not ( radius <= y <= H-radius ):
                dy = -dy
            c.move( dx, dy )
            ballList[ i ] = [ c, 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 )
    ballList = []

    #--- create a list of two balls --- 
    for i in range( 2 ):
        #--- generate a ball with random x and y ---
        c = Circle( Point( random.randrange( W/3, 2*W/3 ), 
                            random.randrange( H/3, 2*H/3 ) ), 15 )
        c.setFill( "red" )
        c.draw( win )
        #--- add it to the list --- 
        ballList.append( [ c, 3-random.randrange( 6 ), 3-random.randrange( 6 )  ] )

    waitForClick( win, "Click to Start" )

    #--- run the simulation ---
    simul( ballList )

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

main()