Using Game Time

From TRCCompSci - AQA Computer Science
Jump to: navigation, search

Create a Clock

Pygame has built in functions for game time, you can easily create a clock as below:

# Create Pygame clock object.  
clock = pygame.time.Clock()

# Desired framerate in frames per second. Try out other values.              
FPS = 30

# How many seconds the "game" is played.
playtime = 0.0

FPS is just a variable to specify the frame rate required, playtime will just record the amount of time passed since the game started.

Updating Clock & Time

In the game loop of your program add the following:

# Do not go faster than this framerate.
milliseconds = clock.tick(FPS) 
playtime += milliseconds / 1000.0

This code will update the playtime and also control the frame rate of the game.

Displaying Frame Rate & Time

The code below will set the game caption to display the current time and frame rate information. You could alternative just blit this to the screen instead:

text = "FPS: {0:.2f}   Playtime: {1:.2f}".format(clock.get_fps(), playtime)

Using Visual Studio seems to limit the frame rate, my laptop will only do 19 frames per second when running through VS however if you run your program in IDLE it runs at 30 frames per second.