How to Think Like a Computer Scientist: Learning with Python 2nd Edition/Case Study: Catch
Case Study: Catch
editGetting started
editIn our first case study we will build a small video game using the facilities in the GASP package. The game will shoot a ball across a window from left to right and you will manipulate a mitt at the right side of the window to catch it.
Using while to move a ball
editwhile statements can be used with gasp to add motion to a program. The following program moves a black ball across an 800 x 600 pixel graphics canvas. Add this to a file named pitch.py:
As the ball moves across the screen, you will see a graphics window that looks like this:
GASP ball on yellow background Trace the first few iterations of this program to be sure you see what is happening to the variables x and y.
Some new things to learn about GASP from this example:
- begin_graphics can take arguments for width, height, title, and background color of the graphics canvas.
- set_speed can takes a frame rate in frames per second.
- Adding filled=True to Circle(...) makes the resulting circle solid.
- ball = Circle stores the circle (we will talk later about what a circle actually is) in a variable named ball so that it can be referenced later.
- The move_to function in GASP allows a programmer to pass in a shape (the ball in this case) and a location, and moves the shape to that location.
- The update_when function is used to delay the action in a gasp program util a specified event occurs. The event 'next_tick' waits until the next frame, for an amount of time determined by the frame rate set with set_speed. Other valid arguments for update_when are 'key_pressed' and 'mouse_clicked'.
Varying the pitches
editTo make our game more interesting, we want to be able to vary the speed and direction of the ball. GASP has a function, random_between(low, high), that returns a random integer between low and high. To see how this works, run the following program:
Each time the function is called a more or less random integer is chosen between -5 and 5. When we ran this program we got:
-2 -1 -4 1 -2 3 -5 -3 4 -5
You will probably get a different sequence of numbers.
Let's use random_between to vary the direction of the ball. Replace the line in pitch.py that assigns 1 to y:
with an assignment to a random number between -4 and 4:
Making the ball bounce
editRunning this new version of the program, you will notice that ball frequently goes off either the top or bottom edges of the screen before it completes its journey. To prevent this, let's make the ball bounce off the edges by changing the sign of dy and sending the ball back in the opposite verticle direction.
Add the following as the first line of the body of the while loop in pitch.py:
Run the program several times to see how it behaves.
The break statement
editThe break statement is used to immediately leave the body of a loop. The following program impliments simple simple guessing game:
Using a break statement, we can rewrite this program to eliminate the duplication of the input statement:
This program makes use of the mathematical law of trichotomy (given real numbers a and b, a > b, a < b, or a = b). While both versions of the program are 15 lines long, it could be argued that the logic in the second version is clearer.
Put this program in a file named guess.py.
Responding to the keyboard
editThe following program creates a circle (or mitt ) which responds to keyboard input. Pressing the j or k keys moves the mitt up and down, respectively. Add this to a file named mitt.py:
Run mitt.py, pressing j and k to move up and down the screen.
Checking for collisions
editThe following program moves two balls toward each other from opposite sides of the screen. When they collide , both balls disappear and the program ends:
Put this program in a file named collide.py and run it.
Putting the pieces together
editIn order to combine the moving ball, moving mitt, and collision detection, we need a single while loop that does each of these things in turn:
Put this program in a file named catch.py and run it several times. Be sure to catch the ball on some runs and miss it on others.
Displaying text
editThis program displays scores for both a player and the computer on the graphics screen. It generates a random number of 0 or 1 (like flipping a coin) and adds a point to the player if the value is 1 and to the computer if it is not. It then updates the display on the screen.
Put this program in a file named scores.py and run it.
We can now modify catch.py to display the winner. Immediately after the if ball_x > 810: conditional, add the following:
It is left as an exercise to display when the player wins.
Abstraction
editOur program is getting a bit complex. To make matters worse, we are about to increase its complexity. The next stage of development requires a nested loop. The outer loop will handle repeating rounds of play until either the player or the computer reaches a winning score. The inner loop will be the one we already have, which plays a single round, moving the ball and mitt, and determining if a catch or a miss has occured.
Research suggests there is are clear limits to our ability to process cognitive tasks (see George A. Miller's The Magical Number Seven, Plus or Minus Two: Some Limits on our Capacity for Processing Information_). The more complex a program becomes, the more difficult it is for even an experienced programmer to develop and maintain.
To handle increasing complexity, we can wrap groups of related statements in functions, using abstraction to hide program details. This allows us to mentally treat a group of programming statements as a single concept, freeing up mental bandwidth for further tasks. The ability to use abstraction is one of the most powerful ideas in computer programming.
Here is a completed version of catch.py:
Some new things to learn from this example:
Following good organizational practices makes programs easier to read. Use the following organization in your programs:
- imports
- global constants
- function definitions
- main body of the program
- Symbolic constants like COMPUTER_WINS, PLAYER_WINS, and QUIT can be used to enhance readability of the program. It is customary to name constants with all capital letters. In Python it is up to the programmer to never assign a new value to a constant , since the language does not provide an easy way to enforce this (many other programming languages do).
- We took the version of the program developed in section 8.8 and wrapped it in a function named play_round(). play_round makes use of the constants defined at the top of the program. It is much easier to remember COMPUTER_WINS than it is the arbitrary numeric value assigned to it.
- A new function, play_game(), creates variables for player_score and comp_score. Using a while loop, it repeatedly calls play_round, checking the result of each call and updating the score appropriately. Finally, when either the player or computer reach 5 points, play_game returns the winner to the main body of the program, which then displays the winner and then quits.
There are two variables named result---one in the play_game function and one in the main body of the program. While they have the same name, they are in different namespaces, and bear no relation to each other. Each function creates its own namespace, and names defined within the body of the function are not visible to code outside the function body. Namespaces will be discussed in greater detail in the next chapter.
Glossary
editExercises
edit- What happens when you press the key while running mitt.py? List the two lines from the program that produce this behavior and explain how they work.
- What is the name of the counter variable in guess.py? With a proper strategy, the maximum number of guesses required to arrive at the correct number should be 11. What is this strategy?
- What happens when the mitt in mitt.py gets to the top or bottom of the graphics window? List the lines from the program that control this behavior and explain in detail how they work.
- Change the value of ball1_dx in collide.py to 2. How does the program behave differently? Now change ball1_dx back to 4 and set ball2_dx to -2. Explain in detail how these changes effect the behavior of the program.
- Comment out (put a # in front of the statement) the break statement in collide.py. Do you notice any change in the behavior of the program? Now also comment out the remove_from_screen(ball1) statement. What happens now? Experiment with commenting and uncommenting the two remove_from_screen statements and the break statement until you can describe specifically how these statement work together to produce the desired behavior in the program.
Where can you add the lines
to the version of catch.py in section 8.8 so that the program displays this message when the ball is caught?- Trace the flow of execution in the final version of catch.py when you press the escape key during the execution of play_round. What happens when you press this key? Why?
- List the main body of the final version of catch.py. Describe in detail what each line of code does. Which statement calls the function that starts the game?
- Identify the function responsible for displaying the ball and the mitt. What other operations are provided by this function?
Which function keeps track of the score? Is this also the function that displays the score? Justify your answer by discussing specific parts of the code which implement these operations.
Project: pong.py
editPong_ was one of the first commercial video games. With a capital P it is a registered trademark, but pong is used to refer any of the table tennis like paddle and ball video games.
catch.py already contains all the programming tools we need to develop our own version of pong. Incrementally changing catch.py into pong.py is the goal of this project, which you will accomplish by completing the following series of exercises:
- Copy catch.py to pong1.py and change the ball into a paddle by using Box instead of the Circle. You can look at Appendix A for more information on Box. Make the adjustments needed to keep the paddle on the screen.
Copy pong1.py to pong2.py. Replace the distance function with a boolean function hit(bx, by, r, px, py, h) that returns True when the vertical coordinate of the ball (by) is between the bottom and top of the paddle, and the horizontal location of the ball (bx) is less than or equal to the radius (r) away from the front of the paddle. Use hit to determine when the ball hits the paddle, and make the ball bounce back in the opposite horizontal direction when hit returns True. Your completed function should pass these doctests:
Finally, change the scoring logic to give the player a point when the ball goes off the screen on the left.Copy pong2.py to pong3.py. Add a new paddle on the left side of the screen which moves up when 'a' is pressed and down when 's' is pressed. Change the starting point for the ball to the center of the screen, (400, 300), and make it randomly move to the left or right at the start of each round.