How can we animate the ball to make it look like it is bouncing off the walls of the window?
Here is a simple animation, by moving the circle just a little bit, many times:
c = Circle(...)
for i in range(100):
c.move(1,0)
This will move the circle by one pixel to the right, 100 times.
If you try that and it moves too fast, you can slow down the computer
using the sleep()
function. Try this:
from time import sleep
c = Circle(...)
for i in range(100):
c.move(1,0)
sleep(0.01)
That will move the circle, then pause for 0.01 seconds, then move again, pause, etc. Adjust the sleep amount until you get the animation you want.
How do we keep moving the ball until the user clicks the mouse
or hits a key? If we use gw.getMouse()
, the whole program will
pause until the user clicks the mouse. We want to check if the user
clicked, but not stop the program and wait for a click. A different
method, checkMouse()
, just checks to see if a click occurred.
Give this a try:
while True:
c.move(1,0)
sleep(0.01)
click = gw.checkMouse()
if click != None:
break
This will check to see if the mouse was clicked. If it was, then
gw.checkMouse()
returns the Point
where it was clicked. If it was
not clicked, gw.checkMouse()
returns None
. So if click
is not None
(i.e., there was a mouse click), we should break
out of the while
loop.
You can also use the getKey()
and checkKey()
methods to get key presses
from the user. Try something like this to see what getKey()
returns for
different key presses (hit q to quit):
while True:
key = gw.getKey()
if key == 'q':
break
else:
print(key)
If the ball goes too far to the right, we want to make it appear to bounce off the wall and move back to the left. Using a variable for the amount to move, we want something like this:
c = Circle(...)
dx = 1 # how far to move in the x direction
while loop:
c.move(dx,0)
if c is too far to the right or left:
dx = -1.0*dx # turn it around
Using c.getCenter()
and c.getRadius()
, we can figure out where the ball
is and where the sides of the ball are. If the center+radius is at the right
edge of the window, or the center-radius is at the left edge of the window,
we want to turn it around and go the other way. See the getX()
point method
for how to get the x-coordinate of the center point.
See if you can animate a circle object, bouncing back and forth in the x direction, until the user hits the q key.