Random Shape Generator

  • Share this:

Code introduction


This function draws a random shape on the screen, which can be a circle, rectangle, or triangle, and fills it with a specified color.


Technology Stack : pygame

Code Type : Graphics drawing function

Code Difficulty : Intermediate


                
                    
import pygame
import random

def draw_random_shape(screen, color):
    """
    Draws a random shape on the screen with given color.
    """
    shape_type = random.choice(['circle', 'rectangle', 'triangle'])
    if shape_type == 'circle':
        shape = pygame.draw.circle(screen, color, (screen.get_width()//2, screen.get_height()//2), random.randint(50, 100))
    elif shape_type == 'rectangle':
        shape = pygame.draw.rect(screen, color, (random.randint(50, 200), random.randint(50, 200), random.randint(100, 200), random.randint(100, 200)))
    else:
        shape = pygame.draw.polygon(screen, color, [(random.randint(50, 200), random.randint(50, 200)) for _ in range(3)])
    return shape                
              
Tags: