224 Chapter 9
in every direction. In the final upgrade to this app, we’ll see an
even more impressive and powerful feature of sprite graphics that
handles detecting collisions.
SmileyPop, Version 1 .0
For our closing example, we’ll add one crucial bit of fun to the
SmileyExplosion.py program: the ability to “pop” the smiley
balloons/bubbles by clicking the right mouse button (or by pressing
the control key and clicking on a Mac). The effect is like a balloon-
popping game or Ant Smasher, Whack-a-Mole, and so on. We’ll be
able to create smiley balloons by dragging the left mouse button,
and we’ll pop them (that is, remove them from the screen) by click-
ing the right mouse button over one or more of the smiley sprites.
Detecting collisions and
removing sprites
The great news is that the Sprite class in Pygame comes with
collision detection built in. We can use the function pygame.sprite
.collide_rect() to check whether the rectangles holding two sprites
have collided; we can use the collide_circle() function to check
whether two round sprites are touching; and if we’re just check-
ing to see whether a sprite has collided with a single point (like
the pixel where the user just clicked the mouse), we can use a
sprite’s rect.collidepoint() function to check whether a sprite
overlaps, or collides with, that point on the screen.
If we’ve determined that the user clicked a point that touches
one or more sprites, we can remove each of those sprites from our
sprite_list group by calling the remove() function. We can handle
all the logic for popping smiley balloons in our MOUSEBUTTONDOWN event
handler code. To turn SmileyExplosion.py into SmileyPop.py, we’ll
just replace these two lines:
if event.type == pygame.MOUSEBUTTONDOWN:
mousedown = True
with the following seven lines of code:
if event.type == pygame.MOUSEBUTTONDOWN:
u if pygame.mouse.get_pressed()[0]: # Regular left mouse button, draw
mousedown = True