Game Development Reference
In-Depth Information
20 - Dodger
If the player has closed the window while the program is waiting for the player to press a
key, Pygame will generate a
QUIT
event and we should terminate the program. We will
call our
terminate()
function here, rather than call
pygame.quit()
and
sys.exit
()
themselves.
25. if event.type == KEYDOWN:
26. if event.key == K_ESCAPE: # pressing
escape quits
27. terminate()
28. return
If we receive a
KEYDOWN
event, then we should first check if it is the Esc key that was
pressed. If we are waiting for the player to press a key, and the player presses the Esc key,
we want to terminate the program. If that wasn't the case, then execution will skip the if-
block on line 27 and go straight to the
return
statement, which exits the
waitForPlayerToPressKey()
function.
If a
QUIT
or
KEYDOWN
event is not generated, then this loop will keep looping until it is.
This will freeze the game until the player presses a key or closes the window.
30. def playerHasHitBaddie(playerRect, baddies):
31. for b in baddies:
32. if playerRect.colliderect(b['rect']):
33. return True
34. return False
We will also define a function named
playerHasHitBaddie()
which will return
True
if the player's character has collided with one of the baddies. The
baddies
parameter is a list of baddie data structures. These data structures are just dictionaries, so it
is accurate to say that
baddies
is a list of dictionary objects. Each of these dictionaries
has a
'rect'
key, and the value for that key is a
Rect
object that represents the baddie's
size and location.
playerRect
is also a
Rect
object. Remember that
Rect
objects have a method
named
colliderect()
that returns
True
if the
Rect
object has collided with the Rect
object that is passed to the method. Otherwise,
colliderect()
will return
False
.
We can use this method in our
playerHasHitBaddie()
function. First we iterate
through each baddie data structure in the
baddies
list. If any of these baddies collide with
the player's character, then
playerHasHitBaddie()
will return
True
. If the code
manages to iterate through all the baddies in the
baddies
list without colliding with any
of them, we will return
False
.
36. def drawText(text, font, surface, x, y):