Game Development Reference
In-Depth Information
Line 116 is where our
doRectsOverlap()
function that we defined earlier comes in
handy. We pass two
pygame.Rect
objects to
doRectsOverlap()
: the bouncer and
the current food square. If these two rectangles overlap, then
doRectsOverlap()
will
return
True
and we will remove the overlapping food squares from
foods
list.
Drawing the Food Squares on the Screen
119. # draw the food
120. for i in range(len(foods)):
121. pygame.draw.rect(windowSurface, GREEN, foods[i])
The code on lines 120 and 121 are very similar to how we drew the white square for the
player. We will loop through each food square in the
foods
list, and then draw the
rectangle onto the
windowSurface
surface. This demonstration of collision detection is
fairly easy. This program was very similar to our bouncing program in the previous
chapter, except now the bouncing square will "eat" the other squares as it passes over them.
These past few programs are interesting to watch, but the user does not get to actually
control anything. In this next program, we will learn how to get input from the keyboard.
Keyboard input is handled in Pygame by using events.
The Keyboard Input Program's Source Code
Start a new file and type in the following code, then save it as
pygameInput.py
.
pygameInput.py
This code can be downloaded from http://inventwithpython.com/pygameInput.py
If you get errors after typing this code in, compare it to the topic's code with the online
diff tool at http://inventwithpython.com/diff or email the author at
al@inventwithpython.com
1. import pygame, sys, random
2. from pygame.locals import *
3.
4. # set up pygame
5. pygame.init()
6. mainClock = pygame.time.Clock()
7.
8. # set up the window
9. WINDOWWIDTH = 400
10. WINDOWHEIGHT = 400
11. windowSurface = pygame.display.set_mode((WINDOWWIDTH,
WINDOWHEIGHT), 0, 32)
12. pygame.display.set_caption('Input')
13.
14. # set up the colors