Using Game Time

From TRCCompSci - AQA Computer Science
Revision as of 09:26, 5 July 2018 by Admin (talk | contribs) (Created page with "=Create a Clock= Pygame has built in functions for game time, you can easily create a clock as below: <syntaxhighlight lang=python> # Create Pygame clock object. clock = py...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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)
pygame.display.set_caption(text)