Python beginners challenge #6: Understanding and modifying existing code
In this challenge, you will do some simple graphics using Pygame. Later challenges will allow you to actually build full games using Pygame.
For this challenge, you need to show a ball moving across the screen, and when it hits a wall it bounces and continues moving in the new direction.
-
Download PyGame and install it. To check if it has installed properly, open a python command line (or the IDLE interface) and type
import pygame
If this gives you an error, your installation has not worked. If you don't see any error on screen, then the installation has been successful.
-
Read and understand the Pygame Introduction. Make sure you understand what is going on. Otherwise you will not be able to complete this challenge.
-
Try to create and run the 'bouncing ball animation' given in the Pygame introduction. You will need to do the following:
- Create a file called bounce.py. Copy-n-paste the code from the Pygame introduction into bounce.py and save it
- Download the image of the ball and save it in the same directory as 'bounce.py'.
-
Now when you try to run the program, it will probably give you an error like this:
pygame.error: Couldn't open ball.bmp
-
Change the name of the image file in bounce.py to make this error go away
-
Now, the program will probably run, but the ball whizzes past the screen too fast. To slow down the game you'll need to use the 'tick' method of pygame.time.Clock. Basically, you'll need to insert this line at the beginning of your program:
clock = pygame.time.Clock()
and then you'll need to insert this line as the first line of code inside the while loop:
clock.tick(60)
this ensures that the game does not go faster than 60 frames per second.
Bonus challenge #1: Replace the 'ball' in this animation with the head of someone you dislike, taken from a photo. So, when this program is run, instead of a ball bouncing, you see someone's head bouncing
Bonus challenge #2: Modify this animation so that when the mouse is clicked on the ball (or photo from challenge #1), the animation ends (and the program exits). Check the documentation for pygame.event to see how you can do this. (Hint: you'll need to use the MOUSEDOWN event).