Adding Sounds

I have created a new folder named sounds in my game folder and in it I have placed two sound files, one named eat.mp3 and one named wall.mp3.

We want to play a sound every time the snake eats the food and everytime it hits the wall.

In pygame, loading and playing a sound file is very easy. First we have to load the two sound files, so we go to the Snake class and we are going to load them in the __init__ method. We are going to create two new attributes for the two sounds.

Self.eat_sound = pygame.mixer.Sound()

Now we need to load the first sound file:

with a capital S and inside the parenthesis we need to pass the file path like this “Sounds/eat.mp3).

We do the same for the second sound as well. self.wall_hit_sound = pygame.mixer.Sound(“Sounds/wall.mp3”)

We have loaded the sound files. Now to play the sounds we just have to call the play method of the sound class.

So, in our game class we have to go to the check_collision_with_food() method and add the following line: self.snake.eat_sound.play()

And in the game_over() method we have to add this line of code: self.snake.wall_hit_sound.play().

And with that, our game is complete! Let’s test it out! Perfect, the game works, and we can hear the sounds when the snake eats the food or hits the wall!