Game Speed in PY Games

Updated: February 17, 2022
No Credit Card Required
ClaimYour
FreeTrialClass

Transcript

In this unit, we're going to be adding some finishing touches, such as making the game playable by slowing down the game speed and adding sounds.

For today's lesson, go ahead and go to www.replit.com and create a new Repl and name it PGD_15_gamespeed.

While testing the game, you've may have noticed that the enemies move a little fast if that, and that's okay, as different machines will see different results at this point. Since all the Sprites move once per frame, they can move hundreds of times each second. The number of frames handled each second is called the FRAME RATE. And getting this right is the difference between a playable game and the forgettable one.

Fortunately, the Module Time contains a clock which is designed exactly for this purpose. Our first step is to create a new clock before the game loop begins. The second line calls “tick” to inform PyGame that the program has reached the end of the frame. The Argument passed to “tick” establishes the desired frame rate, which is the number of milliseconds each frame should take.

Here, we've set the frame rate at 30 milliseconds. Passing in a smaller frame rate will result in more time for each frame for calculations. While, a larger frame rate provides smoother and possibly faster gameplay, experiment a bit and see what happens in the game.

Now, let's explore adding sounds really take it to the next level. PyGame provides a mixer to handle all sound related activities. Using the MUSIC SUB MODULE, you can stream individual sound files in a variety of formats, such as mp3, Ogg, and mod. All playback happens in the background. So when you play sound, the Method returns immediately as the sound plays.

Load your sounds into Repl the same way you did with your images in the earlier lessons. Here are the sound files. After the system is initialized, you can get your sounds and background music setup. The first two lines of code, load a background sound clip and begin playing it. You can tell the sound clip to loop and therefore never end by setting the named Parameters loops equals -1. The next three lines of code load three sounds you'll use for various sound effects. The first two are rising and falling sounds which are played when the player moves up or down. The last is the sound use whenever there is a collision.

You can add other sounds as well such as a sound for whenever an enemy is created or a final sound for when the game ends.

Here's the complete code to add your Repl. Run your code what happens? Go ahead and add other sounds to your game and personalize it.

I'll see you in the next lesson.

Loading...