Game Development Reference
In-Depth Information
18 - Collision Detection and Input
A pygame.time.Clock object can do this for us. You can see on line 125 that we
call mainClock.tick(40) inside the game loop. This call to the Clock object's tick
() method will check if we have iterated through the game loop more than 40 times in the
last second. If so, it puts a short sleep into the program for us based on frequently tick()
is being called. This ensures that the game never runs faster than we expect. Be sure to call
tick() only once in the game loop.
Setting Up the Window and Data Structures
30. pygame.display.set_caption('Collision Detection')
31.
32. # set up the bouncer and food data structures
33. foodCounter = 0
34. NEWFOOD = 40
35. FOODSIZE = 20
We are going to set up a few variables for the food blocks that appear on the screen.
foodCounter will start at the value
49. bouncer = {'rect':pygame.Rect(300, 100, 50, 50),
'dir':UPLEFT}
We are going to set up a new data structure called bouncer . bouncer is a dictionary
with two keys. The value stored in the 'rect' key will be a pygame.Rect object that
represents the bouncer's size and position. The value stored in the 'dir' key will be a
direction that the bouncer is currently moving. The bouncer will move the same way the
blocks did in our previous animation program: moving in diagonal directions and bouncing
off of the sides of the window.
50. foods = []
51. for i in range(20):
52. foods.append(pygame.Rect(random.randint(0,
WINDOWWIDTH - FOODSIZE), random.randint(0, WINDOWHEIGHT -
FOODSIZE), FOODSIZE, FOODSIZE))
Our program will keep track of every food square with a list of pygame.Rect objects
called foods . At the start of the program, we want to create twenty food squares randomly
placed around the screen. We can use the random.randint() function to come up with
random XY coordinates.
On line 52, we will call the pygame.Rect() constructor function to return a new
pygame.Rect object that will represent the position and size of the food square. The
Search WWH ::




Custom Search