Bouncing
By drawing inside of loops we can create animations. With the addition of conditional statements we can create less prescribed and more dynamic animations. For example, the direction an image is moving can change in different locations.
Details
Create a Python program that animates an image bouncing back and forth in the window. The image should begin by moving to the right edge of the screen. Once it reaches the right edge of the screen, the image should "bounce" and move to the left edge of the screen. Note: the program should have only one loop, but the image should bounce multiple times.
Example
-
The program should have a for loop where each
iteration the image is drawn at a different location. Do not
forget the
graphics.clear
andgraphics.wait
functions. - Create variables to represent the image's x and y coordinates. The variables should be defined before the animation loop.
- In addition to position, you need to store a variable for the images's speed.
- Use the accumulator pattern to update the x location of the image by the image's speed.
- If the image 'hits' the edge of the graphics window, change the direction of the image by changining its speed.
- Use a conditional statement comparing the image's x coordinate to the width of the window to determine if the image has 'hit' the edge of the screen.
Paint
One of the more interesting things that conditionals give us is the ability to interact with a graphical program in different ways. We can tell the difference between a mouse button being down vs. up, we can tell when a keyboard key is pressed, etc. This can also allow us to create programs which allows a user to express their...creativity!
Details
Create a Python program that uses the graphics module to allow the user to draw in a window with the mouse. When the user clicks and drags the mouse, the program should use the mouse position to repeatedly draw lines.
Example
-
The graphics module has a function
called
button_down
that returns whether a mouse button is pressed. Use 1 as the parameter to this function, to check for the left mouse button. Put this function inside of a for loop to repeatedly check whether the mouse button is down. The for loop can run any number of times, but it should have a call to thewait
function so that the loop doesn't run too fast. -
The program should keep track of two
values,
previous_x
andprevious_y
. The variables should be updated at the end of every iteration of the loop using the values ofmouse_x
andmouse_y
respectively. - When the mouse button is down, the program should use the current position of the mouse to draw a line from the previous location to the current location.
Challenge
Modify the program so that the user can chose between different line colors by clicking on a rectangle defining that color.