PyGame Basics
Sound
Other than giving user feedback visually, we can also provide auditory feedback.
To add some sounds, we use the pygame.mixer.Sound()
class Game():
def __init__(self):
pygame.init() # initialise pygame libraries
self.size = WIDTH, HEIGHT
self.display = pygame.display.set_mode(self.size)
self.disp_surf = self.init_display()
self.running = True if self.disp_surf else False
self.font = pygame.font.Font(pygame.font.get_default_font(), 36)
self.ball = Ball()
self.hand = Hand()
self.allsprites = pygame.sprite.RenderPlain((self.ball, self.hand))
self.sound_hit = pygame.mixer.Sound("thump.wav")
self.sound_missed = pygame.mixer.Sound("swish.wav")
And then play the sound when we have a hit:
def check_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
self.running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
if self.hand.hit(self.ball):
self.ball.hit()
self.sound_hit.play()
else:
self.sound_missed.play()
elif event.type == pygame.MOUSEBUTTONUP:
self.hand.unhit()
return
I get my sound files from https://freesound.org/, it requires you to create a free account with the site.
You can download the sounds used above from the github repository: thump.wav, swish.wav