CSC111 movingBall3.py

From dftwiki3
Revision as of 14:38, 24 March 2010 by Thiebaut (talk | contribs) (Created page with '--~~~~ ---- <source lang="python"> from graphics import * import random W = 300 H = 300 #---------------------------------------------------------------- def simul( ballList )…')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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


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 = []

    #--- define a ball position and velocity ---
    c = Circle( Point( W/3, H/3 ), 15 )
    c.setFill( "red" )
    c.draw( win )
    ballList.append( [ c, 3-random.randrange( 6 ), 3-random.randrange( 6 )  ] )

    c = Circle( Point( 2*W/3, 2*H/3 ), 15 )
    c.setFill( "blue" )
    c.draw( win )
    ballList.append( [ c, 3-random.randrange( 6 ), 3-random.randrange( 6 )  ] )
    waitForClick( win, "Click to Start" )

    simul( ballList )

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

main()