You can download this code by clicking the button below.
This code is now available for download.
This code defines three functions: random_color generates a random color, draw_random_color_rectangle draws a random color rectangle on the screen, and animate_rectangles animates multiple random color rectangles on the screen.
Technology Stack : pygame, random
Code Type : The type of code
Code Difficulty : Intermediate
import pygame
import random
def random_color():
red = random.randint(0, 255)
green = random.randint(0, 255)
blue = random.randint(0, 255)
return (red, green, blue)
def draw_random_color_rectangle(screen, width, height):
color = random_color()
pygame.draw.rect(screen, color, (0, 0, width, height))
def animate_rectangles(screen, width, height, num_rectangles, duration):
start_time = pygame.time.get_ticks()
while pygame.time.get_ticks() - start_time < duration:
screen.fill((0, 0, 0))
for i in range(num_rectangles):
x = random.randint(0, width)
y = random.randint(0, height)
color = random_color()
pygame.draw.rect(screen, color, (x, y, 50, 50))
pygame.display.flip()
pygame.time.delay(50)