Add Time in Pygame using Python

In this module, we are going to discuss the usage of time in pygame using Python. It is one of the important concepts in pygame because major aspects like image movement, music, etc. are dependent on this module.

Implement Time using pygame.time in Python

pygame.time.get_ticks()

It gives information regarding time spent by our file in running the code starting from pygame.init(). It returns the output as a number of milliseconds.

The following code gives a complete explanation about this statement

import pygame
pygame.init()
z=1
while z<5:
    ticks=pygame.time.get_ticks()
    print(ticks)
    z+=1

Output:

173
203
206
209

In the output, we printed the time in milliseconds for each iteration time consumed by the pygame file.

pygame.time.wait(milliseconds)

With the help of this, we can stop the program for a specific amount of time mentioned by the user. It takes milliseconds as input and stops the program for the given number of milliseconds and it returns a number of milliseconds used as output.

import pygame
pygame.init()
z=1
while z<5:
    ticks=pygame.time.get_ticks()
    pygame.time.wait(500)
    print(ticks)
    z+=1

Output:

173
704
1207
1710


In the output, we can see the difference between two milliseconds is approximately 500.

To produce more accurate results for the above code we can use this statement.

pygame.time.delay(milliseconds)

Its functionality is the same as wait() but it produces accurate results than wait().

Creating a Clock object

To keep track of the time we create an object as follows

clo_obj=pygame.time.Clock()

clo_obj is a Clock object that can implement functions as follows

  • clo_obj.tick(framerate)

it is used to give information regarding how many milliseconds are passed until the previous call. if we specify frame rate once per frame it will run only that specified number of frames.

Example:

clo_obj.tick(32)

per one frame it doesn’t run more than 32 frames.

  • clo_obj.get_time()

It is used to obtain a number of milliseconds used between two tick()

  • clo_obj.get_fps()

it gives information regarding the clock frame rate. it returns the output in floating-point value.

The following code gives a description of the three functions of Clock

import pygame
pygame.init()
z=1
clo_obj=pygame.time.Clock()
while z<15:
    clo_obj.tick(40)
    print(clo_obj.get_time())
    print(clo_obj.get_fps())
    z+=1

Output:

25
0.0
25
0.0
25
0.0
25
0.0
25
0.0
25
0.0
25
0.0
25
0.0
25
0.0
25
0.0
25
40.0
25
40.0
25
40.0
25
40.0

The values obtained in the result are approximately equal to framerate=40 it produces a result as 0.0 and 40.0. get_time() gives for each interval between tick is 25  because we are not performing any delay or event operations so, it gives constant time.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *