'''
Show a ball bouncing off the sides of the window.
'''
from graphics import *
import time, random, math
RADIUS = 10
def bounceInBox(ball1, dx1, dy1, xLow, xHigh, yLow, yHigh):
''' Animate a shape moving in jumps (dx, dy), bouncing when
its center reaches the low and high x and y coordinates.
'''
delay = .03
for i in range(6000):
ball1.move(dx1, dy1)
center1 = ball1.getCenter()
x1 = center1.getX()
y1 = center1.getY()
if x1 < xLow:
dx1 = -dx1
elif x1 > xHigh:
dx1 = -dx1
if y1 < yLow:
dy1 = -dy1
elif y1 > yHigh:
dy1 = -dy1
time.sleep(delay)
def getRandomPoint(xLow, xHigh, yLow, yHigh):
'''Return a random Point with coordinates in the range specified.'''
x = random.randrange(xLow, xHigh+1)
y = random.randrange(yLow, yHigh+1)
return Point(x, y)
def makeDisk(center, radius, win, color):
'''return a red disk that is drawn in win with given center and radius.'''
disk = Circle(center, radius)
disk.setOutline(color)
disk.setFill(color)
disk.draw(win)
return disk
# bounceBall() is set up for two balls, but just one is used initially
def bounceBall(dx1, dy1, dx2, dy2):
'''Make a ball bounce around the screen, initially moving by (dx, dy)
at each jump.'''
win = GraphWin('Ball Bounce', 290, 290)
#pld win.yUp()
xLow = RADIUS # center is separated from the wall by the radius at a bounce
xHigh = win.getWidth() - RADIUS
yLow = RADIUS
yHigh = win.getHeight() - RADIUS
center1 = getRandomPoint(xLow, xHigh, yLow, yHigh)
ball1 = makeDisk(center1, RADIUS, win, "red")
bounceInBox(ball1, dx1, dy1, xLow, xHigh, yLow, yHigh)
#pld win.close()
bounceBall(3, 5, 6, 2) # set up for two balls