In pygame how do I draw multiple circles and reduce their radiuses over time without resetting screen?

I’m new to pygame. What I want to do is draw a circle on the screen (I did it successfully), then I want this circle’s radius to decrease over time until it becomes zero and the circle dissappers.
I found that I could reset screen or draw a filled rectangle over the previous circle every time, but I wonder if there’s a more elegant solution, because I want multiple circles appear independently and possibly crossing each other.
Thanks in advance!

This is what I have now:

while running:
    screen = pygame.display.set_mode((1280, 720))

    circle = pygame.draw.circle(screen, pygame.Color(colors[0]), CENTER, radius, width=1)

    pygame.display.update()
    radius -= radius_decrement

    clock.tick(60)

    # poll for events
    # pygame.QUIT event means the user clicked X to close your window
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

>Solution :

I think you can keep a collection of circles along with their positions and radii.

In each frame, you can loop through this collection, adjust the radii, and render the circles accordingly.

Below is an example that illustrates this method:

import pygame

pygame.init()

WIDTH, HEIGHT = 1280, 720
CENTER = (WIDTH // 2, HEIGHT // 2)
radius_decrement = 1
colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255)] 

screen = pygame.display.set_mode((WIDTH, HEIGHT))

# Add title to window
pygame.display.set_caption("Multiple Circles")

clock = pygame.time.Clock()

circles = []

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Create a new circle 
    #and add it to the list
    new_circle = {
        'position': CENTER,
        'radius': 50, 
        'color': colors[len(circles) % len(colors)]  
    }
    circles.append(new_circle)

    # Update and draw circles
    screen.fill((0, 0, 0))  

    for circle in circles:
        # Update the radius
        circle['radius'] -= radius_decrement

        # Draw the circle if it has a positive radius
        if circle['radius'] > 0:
            pygame.draw.circle(screen, circle['color'], circle['position'], circle['radius'], width=1)

    pygame.display.update()
    clock.tick(60)

# Quit 
pygame.quit()

Leave a Reply