CSE 1710.03A Programming for Digital Media
Lab 12
Due date: Dec 7, 2009 at 20:00
An animation of a bouncing rectangle
A simple way to create the animation of an object bouncing around on
the screen is to advance the rectangle one step at a time and then
refresh the screen. For this you need to do the following:
First, create an empty image. Then select a random position (x,y), and
draw a filled rectangle at that position. Select a random diagonal
direction (dx,dy) and then show the image.
Then loop over the following steps: First, erase the (old) rectangle
by drawing a white rectangle over it. Then add the (dx,dy) direction to the
current position and draw the (new) rectangle there. Then redraw the
image in the current window.
The size of the image must be 400 x 300 pixels. The rectangle must
be filled in red and must be 20 x 20 pixels. The function
to generate the animation must be called bounce() and
must execute two thousand iterations/steps and stop after that.
Here are a couple of hints:
- show(picture) generates a new window every time. To avoid
this, call show() only once, e.g. after the initial
rectangle has been drawn. For all further updates, call
repaint(picture) instead!
- Use random.randint(min,max) to generate a random integer
between min and max (inclusive).
- To generate a random diagonal direction,
first generate a random integer between
0 and 1 (inclusive), multiply it by 2 and subtract one to generate
a value that is either -1 or +1.
The repeat the same computation for the dy coordinate.
- After having added the direction, you have to check that you
are not out of bounds, i.e. that the new position is inside the
window. This concerns both the x and y coordinates, for both
the minimum and maximum (i.e. left & right for the x coordinate, and correspondingly for y).
If you hit any boundary, set the coordinate to the boundary and
reverse the respective coordinate of the direction by simply
negating that value of the direction. In other words,
if you hit the right boundary, reverse (only) the x direction, etc.
This will ensure that the rectangle bounces off the borders.
What to Turn in
The file containing both functions defined above must be named
lab12.py.
As mentioned previously, you have to add comments with
your own identification (name, student ID, date).
Remember to save the file after you modify it!
How to submit
As in the labs, you hand in this lab the submit command on the Linux systems that are behind the PRISM lab infrastructure. For details on how to submit, please refer to lab02. However, this time please
submit to lab12, i.e. issue the command
submit 1710 lab12 lab12.py
Note: You must do all the above steps correctly for receiving
full credit for this labtest.