Hardware Reference
In-Depth Information
ball to be of the right side of the screen would also trigger the right ball bat collision, so you
must carefully test for collisions in the correct order to avoid a misidentiication of what is
colliding with what. he function takes the irst case that is true from the following list:
A collision with the top of the box
A collision with the bottom of the box
A collision with the left edge of the box (missed ball, computer player)
A collision with the right edge of the box (missed ball, human player)
A collision with the left bat
A collision with the right bat
In the event of any of those conditions being met, the code will take the appropriate action.
In the case of the top or bottom walls, the ball's direction will change appropriately as you
have seen before. If the active player hits the ball, the score will be incremented along with an
elastic collision. If the computer's bat hits it, a new value of the two delta variables will be
chosen from the list deined at the start of the program. All collisions also cause a bounce
sound to be played. Basically, this function controls the action on the screen. he last line
keeps the computer's bat in line with the ball. You can also make the player's bat follow the
ball for testing, but then the game element disappears altogether.
he waitForServe() function is used to restart the rally when the ball has been missed.
Here the computer's bat moves up and down the screen for two seconds before being served
with a new random set of delta values. In the two-player game described in the next section
of this chapter, this will be expanded.
hat leaves us with main() as the only function you have not looked at. As usual, this function
orchestrates the whole program. After a bit of initialisation it enters a while True endless
loop, which initialises the number of balls and score for a game, before entering a while loop
that basically counts down the number of balls in a game. Finally, the third while loop con-
trols the rally and keeps the screen action going until a ball is missed. When it is moveBall()
sets the rally variable to False , and that loop terminates. When all the balls have been
played the inal while loop in this function just checks for any events, one of which could be
the spacebar, which sets the pause variable to False and allows another game to be played.
A Two-Player Game
It doesn't take much to turn this into a two-player game, but there is a subtle change in what the
object of the game is, and that has a few ramiications in the code. In the one-player game the
point was to simply return the ball to the perfect opponent. So there was no need to do anything
about altering the light of the ball when the player hit it back. In a two-player game, however, you
Search WWH ::




Custom Search