O'Reilly logo

Raspberry Pi For Dummies by Mike Cook, Sean McManus

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Setting Up the Timings

Before we go into our main game loop, we need to add some instructions for timing. We’re going to use the clock in Pygame to control how fast our game runs. Using this, we can specify the maximum speed we want the game to run at, measured in frames per second. We store that value in a constant called FPS. For a reasonably challenging game of PiBuster, 20 is a good value. Higher values are faster and lower values are slower. During testing, we set it as low as 4 so we could closely watch how the ball was bouncing, and set it as high as 50 to speed up the computer playing itself when we were confirming that gamewon() worked.

By default, keys on the keyboard are set to not repeat, which means if you hold down a key, it only triggers one movement in the game. That’s really annoying because you would have to hammer a key for each step you want to move the bat. We set the keys to repeat so that if you hold down the key, the bat glides for as long as you hold the key down. The two numbers in the pygame.key.set_repeat() command specify the delay before the key starts repeating, and then how often it repeats, so 1,1 is the fastest setting. (If you use 0,0, it turns off the repeat.)

Add these instructions at the end of your program so far:

FPS=20

fpsClock=pygame.time.Clock()

pygame.key.set_repeat(1,1)

Before we enter the game loop, we should make sure we have updated the screen with everything we’ve drawn on it, and give the player a short time to see where the bat ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required