I am making a covid simulation and the balls to bounce off each other, but when it collides with a red ball I need it to become red. However, I'm not entirely sure how to do it. My current code goes as follows:
class Cell(pygame.sprite.Sprite):
def __init__(self, color, speed, width, height):
super().__init__()
self.color = color
self.speed = speed
self.image = pygame.Surface([width, height])
self.image.fill(WHITE)
self.image.set_colorkey(WHITE)
self.radius = width // 2 # 25
center = [width // 2, height // 2]
pygame.draw.circle(self.image, self.color, center, self.radius, width=0)
self.rect = self.image.get_rect()
self.rect.x = random.randint(5, 795)
self.rect.y = random.randint(150, 700)
self.pos = pygame.math.Vector2(self.rect.center)
self.dir = pygame.math.Vector2(1, 0).rotate(random.randrange(360))
def update(self):
self.pos += self.dir * self.speed
if self.pos.x - self.radius < 5 or self.pos.x + self.radius > 790:
self.dir.x *= -1
if self.pos.y - self.radius < 150 or self.pos.y + self.radius > 700:
self.dir.y *= -1
for other_cell in all_cells:
if all_cells != self:
distance_vec = self.pos - other_cell.pos
if 0 < distance_vec.length_squared() < (self.radius * 2) ** 2:
self.dir.reflect_ip(distance_vec)
other_cell.dir.reflect_ip(distance_vec)
self.rect.centerx = round(self.pos.x)
self.rect.centery = round(self.pos.y)
def changeColor(self, newColor):
self.color = newColor
pygame.draw.circle(self.image, self.color, center, self.radius, width=0)
class Infected(Cell):
def __init__(self, color, speed, width, height):
super().__init__('RED', speed, width, height)
self.color = color
self.pos.x = 345
self.pos.y = 295
centre = [self.pos.x, self.pos.y]
pygame.draw.circle(self.image, self.color, centre, self.radius, width=0)
pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE)
pygame.display.set_caption("Covid-19 Simualtion")
all_cells = pygame.sprite.Group()
redcell = Infected('RED', 2, 10, 10)
all_cells.add(redcell)
for _ in range(100):
cell = Cell(GREEN1, 2, 10, 10)
all_cells.add(cell)
This code allows the balls to bounce off each other. Also, I was wondering if it's possible to cast classes, for example, if I have a cell that belongs to a Class healthy(cell) can I cast it into Class infected(cell) upon impact.