Difference between revisions of "CSC111 movingBall3.py"
(Created page with '--~~~~ ---- <source lang="python"> from graphics import * import random W = 300 H = 300 #---------------------------------------------------------------- def simul( ballList )…') |
|||
Line 3: | Line 3: | ||
<source lang="python"> | <source lang="python"> | ||
+ | # movingBall3.py | ||
+ | # D Thiebaut | ||
+ | # solution program for parts of Lab 8. | ||
+ | # The program | ||
from graphics import * | from graphics import * | ||
import random | import random | ||
Line 40: | Line 44: | ||
ballList = [] | 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" ) | waitForClick( win, "Click to Start" ) | ||
+ | #--- run the simulation --- | ||
simul( ballList ) | simul( ballList ) | ||
Latest revision as of 14:42, 24 March 2010
--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()