Game Development Reference
In-Depth Information
The colliderect() Method
99. # check if the player has intersected with any food
squares.
100. for food in foods[:]:
101. if player.colliderect(food):
102. foods.remove(food)
In our previous Collision Detection program, we had our own function to check if one
rectangle had collided with another. That function was included in this topic so that you
could understand how the code behind collision detection works. In this program, we can
use the collision detection function that comes with Pygame. The colliderect()
method for pygame.Rect objects is passed another pygame.Rect object as an
argument and returns True if the two rectangles collide and False if they do not. This is
the exact same behavior as the doRectsOverlap() function in our previous Collision
Detection program.
110. mainClock.tick(40)
The rest of the code is similar to the code in the Input program is similar to the earlier
Collision Detection program: draw the food squares and the player squares to the
windowSurface surface, occasionally add a new food square at a random location to the
foods list, check if the player square has collided with any of the food squares, and call
mainClock.tick(40) to make the program run at an appropriate speed.
Summary: Collision Detection and Pygame Input
This chapter introduced the concept of collision detection, which is used in most
graphical games. Detecting collisions between two rectangles is easy: we just check if the
four corners of either rectangle are within the other rectangle. This is such a common thing
to check for that Pygame provides it's own collision detection method named
colliderect() for pygame.Rect objects.
The first several games in this topic were text-based. The program output was text
printed to the screen and the input was text typed by the user on the keyboard. But GUI
programs can accept keyboard and mouse inputs. Furthermore, GUI programs can respond
to single keystrokes when the user pushes down or lets up a single key. The user does not
have to type in an entire response and press Enter. This allows for immediate feedback
when the player presses down any key on the keyboard and much more interactive games.
The Pygame programs we shown so far have drawn rectangles, lines, circles, and even
individual pixels to the screen. These are called drawing primitives. But we also want to
Search WWH ::




Custom Search