Pygame Tutorial 3: Pong Step 3
Written by Collin Green — Version 1.0.0 — 2010-12-26
Goal
In this tutorial we are going to take our pong game from step 2 and finish it up by adding ball spin and some sounds. At the end you’ll have a fully working Pong clone.
Ball Spin
You may have noticed when you ran the last tutorial that it is actually pretty boring. You can bounce the ball back, but you can’t really affect it in any way to make it harder on your opponent. In real ping pong, you can aim your shots and put spin on them, so we want to add something like that to our little pong game. One way to do this is to simply transfer some of the paddle’s velocity to the ball when they hit. If the paddle is going in the same direction as the ball it will start bouncing faster, if not it will slow it down. By adding this one line we can add a huge amount of depth to the gameplay. Figuring out how you can improve your game with little changes like this will be the difference between a boring game and a fun one. Add this at the end of the manageBall function.
329 330 | # give a little of the paddle's velocity to the ball self.ball.vely += hitpaddle.velocity/3.0 |
Sounds
At this point the game is fun, but where are the characteristic ping and pong sounds? Let’s add them now. I’m going to preload the sounds in the game.__init__ function, then call them inside game.manageBall. Note the above line numbers are going to change as we put code above it and push that code down.
Changes to Game.__init__
Here we create two sounds by loading them with pygame.mixer and storing them as self.pingsound and self.pongsound.
194 195 196 | # create sounds self.pingsound = pygame.mixer.Sound(os.path.join('sound', 'ping.wav')) self.pongsound = pygame.mixer.Sound(os.path.join('sound', 'pong.wav')) |
Changes to Game.manageBall
Now we need to tell the game to play the sounds we just added. We are going to play the pongsound when
the ball hits a wall and the pingsound when the ball hits a paddle. It should make stereotypical (and highly annoying!)
back and forth pong noises.
In the if block where we check if the ball hits the top wall, add this:
296 297 | # play the pong sound self.pongsound.play() |
Similarly add this where we check if the ball hits the bottom wall:
306 307 | # play the pong sound self.pongsound.play() |
Finally, add this to where we check if it hits a paddle:
343 344 | # play the ping sound self.pingsound.play() |
Result and Download:
It’s done! The game is not terribly entertaining but it is playable. It looks the same as before in a screenshot so
run the file and notice the differences.
Tutorial Download:
Pygame Tutorial 3 - Pong (297)