Teach Your Kids To Code: A Parent-friendly Guide to Python Programming

(vip2019) #1
Game Programming: Coding for Fun 253

We begin by initializing the mixer (just like we initialize
Pygame with pygame.init()). Then we load our pop.wav sound
effect into a Sound object so we can play it in our program.
The second line loads pop.wav as a pygame.mixer.Sound object
and stores it in the variable pop, which we’ll use later when we
want to hear a popping sound. As with image files, you’ll need
pop.wav saved in the same directory
or folder as your SmileyPop.py pro-
gram for the code to be able to find
the file and use it.
Next we’ll add logic to check
whether a smiley was clicked and
play our pop sound if a smiley was
popped. We’ll do this in the event
handler section of our game loop, in
the same elif statement that pro-
cesses right-mouse-button events (elif
pygame.mouse.get_pressed()[2]). After
the sprite_list.remove(clicked_smileys)
that removes clicked smileys from the
sprite_list, we could check to see if
there were actually any smiley colli-
sions, then play a sound.
The user could right-click the mouse in an area of the screen
with no smiley faces to pop, or they might miss a smiley when try-
ing to click. We’ll check whether any smileys were actually clicked
by seeing if len(clicked_smileys) > 0. The len() function tells us the
length of a list or collection, and if the length is greater than zero,
there were clicked smileys. Remember, clicked_smileys was a list of
the smiley sprites that collided with or were drawn overlapping the
point where the user clicked.
If the clicked_smileys list has smiley sprites in it, then the user
correctly right-clicked at least one smiley, so we play the popping
sound:


if len(clicked_smileys) > 0:
pop.play()


Notice that both lines are indented to align correctly with the
other code in our elif statement for handling right-clicks.
These four lines of added code are all it takes to play the pop-
ping sound when a user successfully right-clicks a smiley. To

Free download pdf