Random Color Surface Generator with Pygame

  • Share this:

Code introduction


This function uses the pygame library to create a random color rectangle surface with specified width and height. It first initializes pygame, then generates a random color, creates a transparent surface, draws a rectangle to fill the entire surface, and finally returns the surface.


Technology Stack : pygame, random

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import pygame
import random

def create_random_surface(width, height):
    # Initialize Pygame
    pygame.init()
    
    # Create a random color
    color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
    
    # Create a surface with the specified width and height
    surface = pygame.Surface((width, height), pygame.SRCALPHA)
    pygame.draw.rect(surface, color, surface.get_rect())
    
    # Return the created surface
    return surface                
              
Tags: