How To Use Pygame Display And Surface Object To Add Figure, Load Image Examples

The pygame.display module is used to create the Pygame app’s main window. And the pygame.surface module is used to create the Pygame app’s sub panel. You can draw figures, text, load images to the sub panel, and then add the sub panel to the Pygame app’s main window or another sub panel. This article will show you how to use pygame.display and pygame.surface with examples.

1. Pygame Display Module Introduction.

  1. PyGame uses the pygame.display module’s set_mode() method to create the game app’s main window, the main window is also a pygame.surface object.
  2. Below is the pygame.display.set_mode() method’s syntax format and parameters introduction.
    main_window_screen = pygame.display.set_mode(size=(),flags=0)
    
    size: a tuple type variable, used to set the game main window's width and height. 
    
    flags: a constants which represents the window style, for example full screen window, etc.
  3. Below are the constant values of the flags parameter.
    pygame.DOUBLEBUF: Create a double buffer window, which is recommended to be used in HWSURFACE or OPENGL.
    
    pygame.FULLSCREEN: Create a full screen window.
    
    pygame.HWSURFACE: Create a hardware acceleration window, which must be used together with FULLSCREEN.
    
    pygame.NOFRAME: Create a window without a border.
    
    pygame.OPENGL: Create an OPENGL rendering window.
    
    pygame.RESIZABLE: Create a window that can be resized.
  4. You can use the method pygame.surface.blit() to draw a surface to another surface object, since the Pygame app’s main window is also a surface object, it also contains the blit() method.
    scrren.blit(source, dest, area=None, special_flags = 0)
    
    source: Represents the surface object to add.
    
    dest: A coordinate in the main window, the value can be a (x, y) tuple, a (x, y, width, height) tuple, or a Rect object.
    
    area: The value can be a Rect object, the default value is None. If this parameter is provided, it is equivalent to image matting operation, that is to display the desired content in the specified area of the screen.
    
    special_flags: This is an optional parameter, which is new to Pygame.1.8. It is used to specify how to mix the colors of the corresponding position. If this parameter is not provided, the color of the source surface object overwrites the color of screen by default. This parameter's value can be BLEND_RGBA_ADD、BLEND_SUB.
  5. pygame.display.flip(): Update the entire Surface object to be displayed on the screen.
  6. pygame.display.get_active(): Returns True if the current surface is displayed on the screen, False if the window is hidden and minimized.
  7. pygame.display.get_surface(): Gets the Surface object currently displayed.
  8. pygame.display.iconify(): Minimize or hide the Surface object ( the main window ) that is displayed.
  9. pygame.display.Info(): Generate a VideoInfo object that contains information about the display surface.
  10. pygame.display.set_icon(): Set the game icon on the game window upper left corner. The icon size is 32 x 32.
  11. pygame.display.update(): Updated portions of the game screen.

2. Pygame Surface Introduction.

  1. Pygame provides different modules for text, images, and colors to generate their own Surface objects.
  2. The Surface module is designed for creating new images in Pygame. You can create a Surface object using the method pygame.Surface(size=(width,height),flags,depth) like below.
    surface_object = pygame.Surface(size=(width,height),flags,depth)
    
    size: Represents the size of the rectangular region of the Surface object.
    
    flags: Function flag bit, there are two optional parameter values HWSURFACE and SPCALPHA, the former represents storing the created Surface object in the video memory, the latter means that each pixel of the image contains an alpha channel.
    
    depth: Specifies the color depth of the pixel, the default is adaptive mode, which is automatically adjusted by Pygame.
  3. pygame.Surface.blit(): Draw an image (Surface object) onto another image.
  4. pygame.Surface.convert(): Modify the pixel format of an image (Surface object).
  5. pygame.Surface.fill(): Fill a Surface object with a solid color.
  6. pygame.Surface.get_at(): Get the color value of a pixel.
  7. pygame.Surface.get_offset(): Get the offset position of the child Surface object in the parent object.
  8. pygame.Surface.get_palette(): Gets the Surface object’s 8-bit index palette.
  9. pygame.Surface.get_size(): Get the dimensions of the Surface object.
  10. pygame.Surface.map_rgb(): Converts an RGBA color to a mapped color value.
  11. pygame.Surface.scroll(): Copy and move Surface objects.
  12. pygame.Surface.set_alpha(): Set the transparency of the entire image.
  13. pygame.Surface.set_at(): Set the color value of a pixel.
  14. pygame.Surface.set_clip(): Sets the current clipping region for this Surface object.
  15. pygame.Surface.subsurface(): Create a new child Surface object based on the parent object.

3. How To Fill Color Rectangle & Load Image In PyGame Examples.

  1. This example contains 2 functions pygame_create_color_rectangle_example() & pygame_load_image_example().

3.1 pygame_create_color_rectangle_example()

  1. This function will draw a rectangle in the Pygame main window and fill a special color to it.
  2. Below is the python source code, when you run it, you can press the Esc key to exit the program.
    '''
    Created on Jan 31, 2022
    
    @author: songzhao
    '''
    
    import pygame
    
    import sys
    
    # This function will draw a square figure with specified color on the pygame main window screen. 
    def pygame_create_color_rectangle_example():
        
        # pygame initialization.
        pygame.init()
    
        # create the game main window with provided size and window style.
        main_window_screen_size = (300, 300)
        main_window_screen = pygame.display.set_mode(main_window_screen_size, flags=pygame.RESIZABLE)
    
        # set window title.
        window_title = 'dev2qa.com pygame create figure example'
        pygame.display.set_caption(window_title)
        
        # fill the window color to blue
        main_window_screen.fill('blue')
    
        # create a square surface object with provided size.
        square_size_tuple = (100, 100)
        square_obj = pygame.Surface(square_size_tuple,flags=pygame.HWSURFACE)
    
        # fill red color to the above square object. 
        square_obj.fill(color='red')
    
        main_loop(main_window_screen, square_obj, (100, 100))    
        
        
        
    '''
    The main_loop function is used to listen and handle system and user events.
    
    main_window_screen: The pygame main window screen surface object.
    
    surface_obj: The surface object that will be drawn to the pygame main window screen.
    
    surface_obj_location_cordinates_tuple: The surface_obj upper left point coordinates.
    '''
    def main_loop(main_window_screen, surface_obj, surface_obj_location_coordinates_tuple):
        
        while True:
            # listen and get the system and user triggered event.
            for event in pygame.event.get():
                
                # the variable to save whether user want to exit the program or not.
                exit_flag = False
                
                # if user press the Esc key.
                if event.type == pygame.KEYDOWN:
                    
                    if event.key == pygame.K_ESCAPE:
                        
                        print('The Esc key is pressed.')
                        
                        exit_flag = True
                        
                        
                # if user click the window close button.
                if event.type == pygame.QUIT:
                    
                    print('The close button is clicked.')
                    
                    exit_flag = True        
                
                # if user want to quit the program.
                if exit_flag:
                    
                    # quit pygame framework.
                    pygame.quit()
                    
                    # exit the pygame program.
                    sys.exit()
            
            # draw the surface object to the main window screen at the specified coordinates.
            # the upper left corner point of the main window screen is the (0,0) origin of the coordinate system.
            main_window_screen.blit(surface_obj, surface_obj_location_coordinates_tuple)
            
            # update screen content.
            pygame.display.flip()
            
            
        
    if __name__ == '__main__':
        
        pygame_create_color_rectangle_example()
        
    
  3. Below is the picture when you run the above python source code.
    pygame fill rectangle with color example

3.2 pygame_load_image_example().

  1. This function will load an existing image to Pygame main window screen.
  2. Then scroll ( copy & move ) the image to another location.
  3. Draw a color rectangle on the cloned image.
  4. Below is the python source code, you can click the close button or press the Esc key to exit the program.
    '''
    Created on Jan 31, 2022
    
    @author: songzhao
    '''
    
    import pygame
    
    import sys
    
    # This function will load an existing image, copy & move it, and then draw a color rectangle on it. 
    def pygame_load_image_example():
        
        # initialize the pygame environment.
        pygame.init()
        
        # create the pygame application main window with provided size.
        main_window_size = (500,300)
        main_window_style = pygame.NOFRAME
        # main_window_style = pygame.FULLSCREEN
        main_window_screen = pygame.display.set_mode(main_window_size, main_window_style)
        main_window_screen.fill('green')
    
        # set pygame window title.
        window_title = 'dev2qa.com pygame load image example'
        pygame.display.set_caption(window_title)
    
        # define the image file path.
        image_file_path = '/Users/songzhao/Downloads/configure-tomcat-settings-dialog.webp'
        
        # load the image from the above image file path.
        image_surface = pygame.image.load(image_file_path)
        image_surface = image_surface.convert()
        
        # define a tuple to specify an area of the image (left,top,width,height).
        rect_coordinates = (100,100,100,50)
        
        # define a color tuple to represent the fill rectangle color.
        rect_color = (185, 251, 192)
        
        # special_flags is a function flag bit, which specifies the color mixing mode. 
        # the default value is 0, which means to fill with solid color.
        rect_color_special_flags = pygame.BLEND_MULT
        
        # fill a rectangle in the image with a specified color.
        image_surface.fill(rect_color,rect=rect_coordinates,special_flags = rect_color_special_flags)
        
        # the upper left corner is the coordinate origin.    
        # define the image horizontal direction scroll offset.
        scroll_offset_x = 80
        # define the image vertical direction scroll offset.
        scroll_offset_y = 100
        
        image_surface.scroll(scroll_offset_x,scroll_offset_y)
        
        main_loop(main_window_screen, image_surface, (0, 0))
        
        
        
        
    '''
    The main_loop function is used to listen and handle system and user events.
    
    main_window_screen: The pygame main window screen surface object.
    
    surface_obj: The surface object that will be drawn to the pygame main window screen.
    
    surface_obj_location_cordinates_tuple: The surface_obj upper left point coordinates.
    '''
    def main_loop(main_window_screen, surface_obj, surface_obj_location_coordinates_tuple):
        
        while True:
            # listen and get the system and user triggered event.
            for event in pygame.event.get():
                
                # the variable to save whether user want to exit the program or not.
                exit_flag = False
                
                # if user press the Esc key.
                if event.type == pygame.KEYDOWN:
                    
                    if event.key == pygame.K_ESCAPE:
                        
                        print('The Esc key is pressed.')
                        
                        exit_flag = True
                        
                        
                # if user click the window close button.
                if event.type == pygame.QUIT:
                    
                    print('The close button is clicked.')
                    
                    exit_flag = True        
                
                # if user want to quit the program.
                if exit_flag:
                    
                    # quit pygame framework.
                    pygame.quit()
                    
                    # exit the pygame program.
                    sys.exit()
            
            # draw the surface object to the main window screen at the specified coordinates.
            # the upper left corner point of the main window screen is the (0,0) origin of the coordinate system.
            main_window_screen.blit(surface_obj, surface_obj_location_coordinates_tuple)
            
            # update screen content.
            pygame.display.flip()
            
            
        
    if __name__ == '__main__':
        
        pygame_load_image_example()   
    
  5. When you run the above python source code, you will get the below image.
    pygame load image and scroll example
0 0 votes
Article Rating
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
Clicky
0
Would love your thoughts, please comment.x
()
x