Due: 9:00am, Monday, February 22. Value: 30 pts. Submit to Sauron.
In class we saw a simple program that displays a red ball
using the graphics package.
from graphics import *
center = Point(100, 100) # create a red ball at (100, 100)
ball = Circle(center, 20)
ball.setFill('red')
win = GraphWin('Ball') # create a window
ball.draw(win) # and put the ball inside it
loc = win.getMouse() # wait for click, get location of mouse
You will need to install the graphics package in
order to complete this assignment. To do this, right-click
graphics.py
,
select Save Link As…
or Save Target As…
from the pop-up menu, and save the file on your computer. Then start
a new file in the Wing IDE, copy the above code, and save it in the
same directory where you placed the graphics.py file.
If the above code doesn't work, contact the instructor.
Your assignment is to modify the above program so that when the user clicks the mouse, the ball moves toward the location of the click, at a rate of one pixel for every 0.05 seconds. It should do this for 5 mouse clicks.
To move toward the click, you'll want to compute the distance between the ball's center and the click's location using the distance formula:
You will want the animation to last dist frames.
(Of course, dist isn't an integer, but you can use
the int function to round it down to the correct
number of frames.)
With each step of the animation, you will want to move
the ball
(x1 − x0) / dist
pixels in the x-direction and
(y1 − y0) / dist
pixels in the
y-direction.
First write and test your program to handle just one click, and then
modify it so that after reaching the destination on one click, your program
waits for another click and then moves the ball toward it. Overall,
your program should handle 5 mouse clicks.
(Of course, you should implement this using a
for loop rather than copying the code five
times!)
You'll likely find that a click is not effective
until the ball completes moving to the last click's location;
that's fine.
Recall that you can retrieve the x-coordinate of a
point (such as loc) using its getX
method: loc.getX(). Similarly, getY
gives a point's y-coordinate. Recall also that you can
get a point object representing the circle's center using its
getCenter method: ball.getCenter().
This gives you a point, which you can then ask for an
x- and y-coordinate using that point's
getX and getY methods.