As usual, create a directory to hold today's files. All programs that you write today should be stored in this directory.
$ cd ~/cs120/labs $ mkdir lab12 $ cd lab12
Last lab we were able to use conditionals to create a simple text based game. Today we will use conditionals and the graphics module to create a simple graphical game. But first we are going to create an interactive animation.
Download the bouncing_ball.py Python program that we created in class and the graphics.py module that it uses. Modify the program so that it also draws a keyboard controlled rectangle at the bottom of the screen. When the user holds down the left arrow key, the rectangle should move left. When the user holds down the right arrow key, the rectangle should move right. It should not be possible to move the rectangle any other direction. If the ball and the rectangle intersect, nothing should happen. You can either search for your own images onlin, or you can use the following images:
Test your program thoroughly and make sure your code follows the course's code conventions.
$ python3 bouncing_ball.py
key_pressed
function returns a bool depending on whether a key is
currently being pressed.
key_pressed
function has one parameter, a
string, that represents a keyboard key. The strings for the
left and right arrow keys are 'Left' and 'Right'.
graphics.clear
function, that change the
rectangle's x coordinate variable if an arrow key is being
pressed.
The game isn't very fun if you can lose track of what you are controlling on the screen. Modify the program so that the rectangle can not move off of the screen.
One of the first successful video games was Pong. Back in the 1970's a game of Pong was so complicated that devices were sold that played only Pong. Today, Pong is the "Hello World" version of a video game; It's typically the first one you write. Today you are going to create a 1-player version of Pong.
Modify the bouncing_ball.py program from the last activity to make the ball interact with the rectangle. When the bottom of the ball hits the top of the rectangle the ball should bounce like it hit the bottom of the window. The ball should no longer bounce if it hits the bottom of the window.
Test your program thoroughly and make sure your code follows the course's code conventions.
$ python3 bouncing_ball.py
Testing if the bottom of the ball hits the top of the paddle requires testing for three different conditions:
To test if all three of these conditions are true, the if statements must be nested.
Modify the program so that it keeps score. Every time the ball hits the rectangle the score should go up by one. If the ball goes off the bottom of the screen the score should be set to 0 and the ball's location and velocity should be reset to their initial values. Use the graphics module to display the score in the window.