Random Color Surface Generator with Pygame

  • Share this:

Code introduction


This function uses the pygame library to create a surface with a randomly generated color, where the color is randomly generated and has a semi-transparent alpha channel.


Technology Stack : pygame

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_color_surface(width, height):
    import pygame
    from pygame.locals import SRCALPHA

    # Initialize Pygame
    pygame.init()

    # Generate a random color
    random_color = (pygame.rand.randint(0, 255), pygame.rand.randint(0, 255), pygame.rand.randint(0, 255), 128)

    # Create a surface with the random color and with alpha transparency
    color_surface = pygame.Surface((width, height), SRCALPHA)
    color_surface.fill(random_color)

    # Return the surface
    return color_surface                
              
Tags: