User Interaction: Get into the Game 225
v elif pygame.mouse.get_pressed()[2]: # Right mouse button, pop
w pos = pygame.mouse.get_pos()
x clicked_smileys = [s for s in sprite_list if s.rect.collidepoint(pos)]
y sprite_list.remove(clicked_smileys)
The if statement for MOUSEBUTTONDOWN events remains the same,
but now, we’re interested in which button was pressed. At u, we
check to see if the left mouse button was pressed (the first button,
at index [0]); if so, we turn on the mousedown Boolean flag, and the
game loop will draw new smiley faces. At v, we see if the right
mouse button is pressed, beginning the logic to check whether
the mouse was clicked over one or more smileys in our sprite_list.
First, at w, we get the mouse’s location and store it in the vari-
able pos. At x, we use a programming shortcut to generate a list
of sprites from sprite_list that collide with, or overlap, the point
the user clicked at pos. If a sprite s in the group sprite_list has
a rectangle that collides with the point pos, group it together as a
list [s] and store the list as clicked_smileys. That ability to create
one list, collection, or array from another based on an if condi-
tion is a powerful feature of Python, and it makes our code much
shorter for this app.
Finally, at y, we call the handy remove() function on our Group
of sprites called sprite_list. This remove() function is different
from Python’s regular remove() function, which removes a single
item from a list or collection. The pygame.sprite.Group.remove()
function will remove any number of sprites from a list. In this
case, it will remove all the sprites from our sprite_list that col-
lide with the point the user clicked on the screen. Once these
sprites are removed from sprite_list, when sprite_list is drawn to
the screen in our game loop, the clicked sprites are no longer in the
list, so they don’t get drawn. It’s like they’ve disappeared—or we’ve
popped them like balloons or bubbles!