Create a class that represents a circle. The class should have a method that can draw the circle, method that detects if a point is inside the circle and a method that can change the color:
class Circle:
def __init__(self):
self.x = r.randint(1, 1700)
self.y = r.randint(1, 1700)
self.color = (255, 0, 0)
self.r = 10
self.clicked = False
def is_point_in(self, p):
dx = p[0] - self.x
dy = p[1] - self.y
return math.hypot(dx, dy) <= self.r * self.r
def set_color(self, color):
self.color = color
def draw(self):
pygame.draw.circle(screen, self.color, (self.x, self.y), self.r, 0)
Create circles before the application loop and put them in a list:
list_of_circles = []
for i in range(10):
list_of_circles.append(Circle())
When the mouse is clicked, detect if the mouse is in a circle and change color:
for event in pygame.event.get():
# [...]
if event.type == pygame.MOUSEBUTTONDOWN:
for circle in list_of_circles:
if circle.is_point_in(event.pos):
circle.set_color((0, 255, 0))
Draw the circle in a loop in the application loop:
while run:
# [...]
for circle in list_of_circles:
circle.draw()
See alos How do I detect collision in pygame? and Pygame mouse clicking detection.
Minimal example:
import pygame
import random as r
import math
class Circle:
def __init__(self):
self.x = r.randint(1, 1700)
self.y = r.randint(1, 1700)
self.color = (255, 0, 0)
self.r = 10
self.clicked = False
def is_point_in(self, p):
dx = p[0] - self.x
dy = p[1] - self.y
return math.hypot(dx, dy) <= self.r * self.r
def set_color(self, color):
self.color = color
def draw(self):
pygame.draw.circle(screen, self.color, (self.x, self.y), self.r, 0)
pygame.init()
screen = pygame.display.set_mode([1700, 900])
list_of_circles = []
for i in range(10):
list_of_circles.append(Circle())
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
for circle in list_of_circles:
if circle.is_point_in(event.pos):
circle.set_color((0, 255, 0))
screen.fill(0)
for circle in list_of_circles:
circle.draw()
pygame.display.update()
pygame.quit()