Game Development Reference
In-Depth Information
18 - Collision Detection and Input
72. player.left = random.randint(0,
WINDOWWIDTH - player.width)
We will also add teleportation to our game. If the user presses the "X" key, then we will
set the position of the user's square to a random place on the window. This will give the user
the ability to teleport around the window by pushing the "X" key (though they can't control
where they will teleport: it's completely random).
Handling the
MOUSEBUTTONUP
Event
74. if event.type == MOUSEBUTTONUP:
75. foods.append(pygame.Rect(event.pos[0],
event.pos[1], FOODSIZE, FOODSIZE))
Mouse input is handled by events just like keyboard input is. The
MOUSEBUTTONUP
event occurs when the user clicks a mouse button somewhere in our window, and releases
the mouse button. The
pos
attribute in the
Event
object is set to a tuple of two integers for
the XY coordinates. On line 75, the X-coordinate is stored in
event.pos[0]
and the Y-
coordinate is stored in
event.pos[1]
. We will create a new
Rect
object to represent a
new food and place it where the
MOUSEBUTTONUP
event occurred. By adding a new
Rect
object to the
foods
list, a new food square will be displayed on the screen.
Moving the Bouncer Around the Screen
86. # move the player
87. if moveDown and player.bottom < WINDOWHEIGHT:
88. player.top += MOVESPEED
89. if moveUp and player.top > 0:
90. player.top -= MOVESPEED
91. if moveLeft and player.left > 0:
92. player.left -= MOVESPEED
93. if moveRight and player.right < WINDOWWIDTH:
94. player.right += MOVESPEED
We have set the movement variables (
moveDown
,
moveUp
,
moveLeft
, and
moveRight
) to
True
or
False
depending on what keys the user has pressed. Now we
will actually move the player's square (which is represented by the
pygame.Rect
object
stored in
player
) around by adjusting the XY coordinates of
player
. If
moveDown
is set
to
True
(and the bottom of the player's square is not below the bottom edge of the window),
then we move the player's square down by adding
MOVESPEED
to the player's current
top
attribute. We do the same thing for the other three directions as well.