How Does Pygame Control Time With Examples

The pygame.time module is mainly used to manage time and game frame rate per second(FPS). This article will tell you how to use it with examples.

1. The pygame.time Module Methods Introduction.

  1. pygame.time.Clock(): Create a clock object to control the FPS of the game.
  2. pygame.time.Clock.tick(FPS): Specify the cycle frequency through the clock object. The code clock.tick(60) will specify to draw up to 60 frames per second.
  3. pygame.time.Clock.get_fps(): Get the frame rate ( frames per second ) of the clock object.
  4. pygame.time.Clock.get_time(): Get the time in the last tick.
  5. pygame.time.get_ticks(): Gets the time in milliseconds. This time refers to the time from the initialization of pygame to the call of this function.
  6. pygame.time.set_timer(): Create a timer to perform some actions at regular intervals.
  7. pygame.time.wait(milliseconds): Pause the program for a period of time.

2. The pygame.time Module Example.

  1. It will show a decreased number in the pygame main window center.
  2. The number will decrease one by one in the specified wait time duration ( implemented by the pygame.time.wait(milliseconds) method or by the pygame.time.Clock.tick(FPS) method).
  3. The python source file name is PygameTime.py, below is the python file source code. If you want to use pygame.time.wait(milliseconds) method to control the frame draw rate, you should uncomment the code pygame.time.wait(1000) in the draw_number() method, otherwise it will use the pygame.time.Clock.tick(FPS) method to control the frame draw rate.
  4. You can see the code comments for the detailed explanation.
    '''
    Created on Feb 22, 2022
    
    @author: Jerry Zhao
    '''
    import pygame, sys
    
    # define the global variables.
    
    # define the maximum frames per second.
    FPS = 2
    
    # define the start number that will be shown on the screen.
    SHOW_NUMBER = 10
    
    # the pygame application main window surface object.
    MAIN_WINDOW_SURFACE = None
    
    # the text surface object where the SHOW_NUMBER value will be rendered on.
    TEXT_SURFACE_OBJECT = None
    
    # the pygame.time.Clock object.
    FPS_CLOCK = None
    
    # initialize the pygame main window and other global objects.
    def initialize_pygame():
        
        pygame.init()
        
        # create the global game main window.
        main_window_size = (300, 300)
        
        global MAIN_WINDOW_SURFACE
        MAIN_WINDOW_SURFACE = pygame.display.set_mode(main_window_size, pygame.RESIZABLE)
        
        # set the window title.
        window_title = 'Pygame Time Module Example.'
        pygame.display.set_caption(window_title)
            
        # create the global pygame.time.Clock object.
        global FPS_CLOCK
        FPS_CLOCK = pygame.time.Clock()
        
    
    # this function will draw the number on the main window's screen.    
    def draw_number():
        
        # create a Font object use the system font 'signpainter'.
        font_object = pygame.font.SysFont('signpainter', 90, bold = True, italic = False)
        
        # define the text color and text background color.
        text_color = pygame.Color('green')
        text_background_color = pygame.Color('blue')
    
        global TEXT_SURFACE_OBJECT
        
        global SHOW_NUMBER
        
        show_number_str = str(SHOW_NUMBER)
        # call the pygame.font.Font's object's render() method to create the text surface object.
        TEXT_SURFACE_OBJECT = font_object.render(show_number_str, True, text_color, text_background_color) 
        
        # if SHOW_NUMBER's value is not the string 'Victory'. 
        if show_number_str != 'Victory!':
            # SHOW_NUMBER value minus 1. 
            SHOW_NUMBER -= 1
        
        # if SHOW_NUMBER's value is 0.
        if show_number_str == '0':
            # assign the string 'Victory!' to the global variable SHOW_NUMBER. 
            SHOW_NUMBER = 'Victory!'
         
        # get the game main window's width & height 
        # to calculate the text surface object's center point coordinates.    
        TEXT_CENTER_X = MAIN_WINDOW_SURFACE.get_width()/2
        TEXT_CENTER_Y = MAIN_WINDOW_SURFACE.get_height()/2
        
        # get the text surface object's pygame.Rect object.
        text_rect_object = TEXT_SURFACE_OBJECT.get_rect()
        # position the text rectangle object' center to coordinate(TEXT_CENTER_X, TEXT_CENTER_Y).
        text_rect_object.center = (TEXT_CENTER_X, TEXT_CENTER_Y)    
        
        # clear the main window screen by drawing white color.
        MAIN_WINDOW_SURFACE.fill(pygame.Color('white'))
        # draw the text surface object to the pygame main window.    
        MAIN_WINDOW_SURFACE.blit(TEXT_SURFACE_OBJECT, text_rect_object)
        
        frames_per_second = FPS_CLOCK.get_fps()
        print('The current frames per second is ', frames_per_second)
        
        time_in_the_last_tick = FPS_CLOCK.get_time()
        print('The time in the last tick is ', time_in_the_last_tick)
        
        time_from_pygame_app_start1 = pygame.time.get_ticks()
        print('The time from the pygame app start is ', time_from_pygame_app_start1)
        
        ''' make the game main thread wait for 1 second.
         if you comment the below source code, 
         the game will use the FPS ( frames per second ) value set by FPS_CLOCK.tick(FPS) 
         to control the frame drawn speed in one second.
         '''
        #pygame.time.wait(1000)
        
        delta_time = pygame.time.get_ticks() - time_from_pygame_app_start1
        print('The delta time is ', delta_time)   
        
        
    def main_loop():
        
       while True:
            
            draw_number()
            
            # Loop to get events and listen for event status.
            for event in pygame.event.get():
                
                # if user click the window close button.
                if event.type == pygame.QUIT: 
                                   
                    # quit pygame.
                    pygame.quit()
                    
                    # quit the application.
                    sys.exit()
                
                elif event.type == pygame.KEYDOWN:
                    
                    if event.key == pygame.K_ESCAPE:
                        
                        print('The Esc key is pressed.')
                        
                        # quit pygame.
                        pygame.quit()
                    
                        # quit the application.
                        sys.exit()
                        
            pygame.display.update()
            
            # set the frame count number that will be drawn in one seconds. 
            FPS_CLOCK.tick(FPS)    
        
        
    if __name__ == '__main__':
    
        initialize_pygame()
        
        main_loop()
  5. When you run the above python source code, you will get the below output in the console.
    The current frames per second is  0.0
    The time in the last tick is  0
    The time from the pygame app start is  384
    The delta time is  0
    The current frames per second is  0.0
    The time in the last tick is  201
    The time from the pygame app start is  581
    The delta time is  0
    The current frames per second is  0.0
    The time in the last tick is  201
    The time from the pygame app start is  782
    The delta time is  0
    The current frames per second is  0.0
    The time in the last tick is  200
    The time from the pygame app start is  982
    The delta time is  0
    The current frames per second is  0.0
    The time in the last tick is  200
    The time from the pygame app start is  1182
    The delta time is  0
    The current frames per second is  0.0
    The time in the last tick is  201
    The time from the pygame app start is  1384
    The delta time is  0
    The current frames per second is  0.0
    The time in the last tick is  201
    The time from the pygame app start is  1584
    The delta time is  0
    The current frames per second is  0.0
    The time in the last tick is  201
    The time from the pygame app start is  1785
    The delta time is  0
    The current frames per second is  0.0
    The time in the last tick is  201
    The time from the pygame app start is  1987
    The delta time is  0
    The current frames per second is  0.0
    The time in the last tick is  200
    The time from the pygame app start is  2187
    The delta time is  0
    The current frames per second is  0.0
    The time in the last tick is  201
    The time from the pygame app start is  2387
    The delta time is  0
    The current frames per second is  4.982561111450195
    The time in the last tick is  201
    The time from the pygame app start is  2588
    The delta time is  0
    The current frames per second is  4.982561111450195
    The time in the last tick is  200
    The time from the pygame app start is  2788
    The delta time is  0

3. The Example Demo Video.

  1. The example demo video URL is https://youtu.be/fWAqFB_nUD0.

4. Why Is The Pygame FPS Return 0 Constantly But I Set It To 60?

4.1 Question.

  1. I set the pygame FPS to 60 using the pygame.time.Clock.tick(60) method.
  2. But when I use the method pygame.time.Clock.get_fps() to get the pygame application’s FPS value, it returns 0 continuously.
  3. The pygame application draws the game frames in the correct FPS as I set (60). But why the get_fps() method return 0 continuously? Can anyone give me some help? Thanks.

4.2 Answer.

  1. The pygame FPS (frames per second) value is the average value of your first 10 times call of the pygame.time.Clock().tick(60) method.
  2. So the pygame.time.Clock.get_fps() method will return a none zero value after you call the method Clock().tick(60) 10 times.
  3. You can see this result from the example console output in this article’s section 2.5.

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Clicky