Random Color Rectangle Drawing with Pygame

  • Share this:

Code introduction


This function uses the pygame library to draw a random rectangle on the screen. The color of the rectangle is randomly selected from a predefined list of colors.


Technology Stack : pygame, Random selection

Code Type : Function

Code Difficulty : Intermediate


                
                    
import pygame
import random

def draw_random_color_rectangle(screen, rect_size):
    # Initialize pygame
    pygame.init()
    
    # Define colors
    colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255), (0, 255, 255)]
    
    # Get a random color from the list
    random_color = random.choice(colors)
    
    # Create a rectangle with the random color
    rectangle = pygame.Rect(0, 0, rect_size, rect_size)
    
    # Fill the rectangle with the random color
    pygame.draw.rect(screen, random_color, rectangle)
    
    # Update the display
    pygame.display.flip()

    # Quit pygame
    pygame.quit()