How to Think Like a Computer Scientist: Learning with Python 2nd Edition/Case Study: Catch

= Case Study: Catch =

Getting started
In 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
while 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:

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 <tt>filled=True</tt> to <tt>Circle(...)</tt> makes the resulting circle solid.
 * <tt>ball = Circle</tt> stores the circle (we will talk later about what a circle actually is) in a variable named <tt>ball</tt> so that it can be referenced later.
 * The <tt>move_to</tt> 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 <tt>update_when</tt> function is used to delay the action in a gasp program util a specified event occurs. The event <tt>'next_tick'</tt> waits until the next frame, for an amount of time determined by the frame rate set with <tt>set_speed</tt>. Other valid arguments for <tt>update_when</tt> are <tt>'key_pressed'</tt> and <tt>'mouse_clicked'</tt>.

Varying the pitches
To make our game more interesting, we want to be able to vary the speed and direction of the ball. GASP has a function, <tt>random_between(low, high)</tt>, that returns a random integer between <tt>low</tt> and <tt>high</tt>. 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 <tt>random_between</tt> to vary the direction of the ball. Replace the line in <tt>pitch.py</tt> that assigns <tt>1</tt> to <tt>y</tt>:

with an assignment to a random number between -4 and 4:

Making the ball bounce
Running 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 <tt>dy</tt> 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 <tt>pitch.py</tt>:

Run the program several times to see how it behaves.

The <tt>break</tt> statement
The break statement is used to immediately leave the body of a loop. The following program impliments simple simple guessing game:

Using a <tt>break</tt> statement, we can rewrite this program to eliminate the duplication of the <tt>input</tt> statement:

This program makes use of the mathematical law of trichotomy (given real numbers a and b, a &gt; b, a &lt; 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 <tt>guess.py</tt>.

Responding to the keyboard
The following program creates a circle (or mitt ) which responds to keyboard input. Pressing the <tt>j</tt> or <tt>k</tt> keys moves the mitt up and down, respectively. Add this to a file named <tt>mitt.py</tt>:

Run <tt>mitt.py</tt>, pressing <tt>j</tt> and <tt>k</tt> to move up and down the screen.

Checking for collisions
The 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 <tt>collide.py</tt> and run it.

Putting the pieces together
In order to combine the moving ball, moving mitt, and collision detection, we need a single <tt>while</tt> loop that does each of these things in turn:

Put this program in a file named <tt>catch.py</tt> and run it several times. Be sure to catch the ball on some runs and miss it on others.

Displaying text
This 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 <tt>scores.py</tt> and run it.

We can now modify <tt>catch.py</tt> to display the winner. Immediately after the <tt>if ball_x &gt; 810:</tt> conditional, add the following:

It is left as an exercise to display when the player wins.

Abstraction
Our 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 <tt>catch.py</tt>:

Some new things to learn from this example:

<ul> <li> Following good organizational practices makes programs easier to read. Use the following organization in your programs: <ul> <li>imports</li> <li>global constants</li> <li>function definitions</li> <li>main body of the program</li></ul> </li> <li>Symbolic constants like <tt>COMPUTER_WINS</tt>, <tt>PLAYER_WINS</tt>, and <tt>QUIT</tt> 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).</li> <li>We took the version of the program developed in section 8.8 and wrapped it in a function named <tt>play_round</tt>. <tt>play_round</tt> makes use of the constants defined at the top of the program. It is much easier to remember <tt>COMPUTER_WINS</tt> than it is the arbitrary numeric value assigned to it.</li> <li>A new function, <tt>play_game</tt>, creates variables for <tt>player_score</tt> and <tt>comp_score</tt>. Using a <tt>while</tt> loop, it repeatedly calls <tt>play_round</tt>, checking the result of each call and updating the score appropriately. Finally, when either the player or computer reach 5 points, <tt>play_game</tt> returns the winner to the main body of the program, which then displays the winner and then quits.</li> <li> There are two variables named <tt>result</tt>---one in the <tt>play_game</tt> 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. </li></ul>

Exercises
<ol> <li>What happens when you press the key while running <tt>mitt.py</tt>? List the two lines from the program that produce this behavior and explain how they work.</li> <li>What is the name of the counter variable in <tt>guess.py</tt>? With a proper strategy, the maximum number of guesses required to arrive at the correct number should be 11. What is this strategy?</li> <li>What happens when the mitt in <tt>mitt.py</tt> 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.</li> <li>Change the value of <tt>ball1_dx</tt> in <tt>collide.py</tt> to 2. How does the program behave differently? Now change <tt>ball1_dx</tt> back to 4 and set <tt>ball2_dx</tt> to -2. Explain in detail how these changes effect the behavior of the program.</li> <li>Comment out (put a <tt>#</tt> in front of the statement) the <tt>break</tt> statement in <tt>collide.py</tt>. Do you notice any change in the behavior of the program? Now also comment out the <tt>remove_from_screen(ball1)</tt> statement. What happens now? Experiment with commenting and uncommenting the two <tt>remove_from_screen</tt> statements and the <tt>break</tt> statement until you can describe specifically how these statement work together to produce the desired behavior in the program.</li> <li> Where can you add the lines

to the version of <tt>catch.py</tt> in section 8.8 so that the program displays this message when the ball is caught?</li> <li>Trace the flow of execution in the final version of <tt>catch.py</tt> when you press the <tt>escape</tt> key during the execution of <tt>play_round</tt>. What happens when you press this key? Why?</li> <li>List the main body of the final version of <tt>catch.py</tt>. Describe in detail what each line of code does. Which statement calls the function that starts the game?</li> <li>Identify the function responsible for displaying the ball and the mitt. What other operations are provided by this function?</li> <li> 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. </li></ol>

Project: <tt>pong.py</tt>
Pong_ 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.

<tt>catch.py</tt> already contains all the programming tools we need to develop our own version of pong. Incrementally changing <tt>catch.py</tt> into <tt>pong.py</tt> is the goal of this project, which you will accomplish by completing the following series of exercises:

<ol> <li>Copy <tt>catch.py</tt> to <tt>pong1.py</tt> and change the ball into a paddle by using <tt>Box</tt> instead of the <tt>Circle</tt>. You can look at Appendix A for more information on <tt>Box</tt>. Make the adjustments needed to keep the paddle on the screen.</li> <li> Copy <tt>pong1.py</tt> to <tt>pong2.py</tt>. Replace the <tt>distance</tt> function with a boolean function <tt>hit(bx, by, r, px, py, h)</tt> that returns <tt>True</tt> when the vertical coordinate of the ball (<tt>by</tt>) is between the bottom and top of the paddle, and the horizontal location of the ball (<tt>bx</tt>) is less than or equal to the radius (<tt>r</tt>) away from the front of the paddle. Use <tt>hit</tt> to determine when the ball hits the paddle, and make the ball bounce back in the opposite horizontal direction when <tt>hit</tt> returns <tt>True</tt>. 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.</li> <li> Copy <tt>pong2.py</tt> to <tt>pong3.py</tt>. Add a new paddle on the left side of the screen which moves up when <tt>'a'</tt> is pressed and down when <tt>'s'</tt> 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. </li></ol>