Game Development Reference
In-Depth Information
20 - Dodger
Line 138 will add the newly created baddie data structure to the list of baddie data
structures. Our program will use this list to check if the player has collided with any of the
baddies and to know where to draw baddies on the window.
Moving the Player's Character
140. # Move the player around.
141. if moveLeft and playerRect.left > 0:
142. playerRect.move_ip(-1 * PLAYERMOVERATE, 0)
The four movement variables
moveLeft
,
moveRight
,
moveUp
and
moveDown
are
set to
True
and
False
when Pygame generates the
KEYDOWN
and
KEYUP
events,
respectively. (This code is from line 86 to line 121.)
If the player's character is moving left and the left edge of the player's character is greater
than
0
(which is the left edge of the window), then we want to move the character's
Rect
object (stored in
playerRect
).
We will always move the
playerRect
object by the number of pixels in
PLAYERMOVERATE
. To get the negative form of an integer, you can simply multiple it by
-1
. So on line 142, since
5
is stored in
PLAYERMOVERATE
, the expression
-1 *
PLAYERMOVERATE
evaluates to
-5
.
This means that calling
playerRect.move_ip(-1 * PLAYERMOVERATE, 0)
will change the location of playerRect by 5 pixels to the left of its current location.
143. if moveRight and playerRect.right < WINDOWWIDTH:
144. playerRect.move_ip(PLAYERMOVERATE, 0)
145. if moveUp and playerRect.top > 0:
146. playerRect.move_ip(0, -1 * PLAYERMOVERATE)
147. if moveDown and playerRect.bottom < WINDOWHEIGHT:
148. playerRect.move_ip(0, PLAYERMOVERATE)
We want to do the same thing for the other three directions: right, up, and down. Each of
the three
if
statements in lines 143 to 148 checks that their movement variable is set to
True
and that the edge of the
Rect
object of the player is inside the window before
calling the
move_ip()
method to move the
Rect
object.
The
pygame.mouse.set_pos()
Function
150. # Move the mouse cursor to match the player.
151. pygame.mouse.set_pos(playerRect.centerx,
playerRect.centery)