# Sparsh Pandey
# 18 June 2025
# Sprites Example

# import pygame and sys
import pygame
import sys

# make a ball class (inherit sprite!)
class Ball(pygame.sprite.Sprite):

    # constructor (and we can use super instead of sprite.Sprite
    def __init__(self, color, pos, speedX, speedY):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((50, 50))
        pygame.draw.circle(self.image, color, (25, 25), 25)
        self.rect = self.image.get_rect(center=pos)
        self.speedX = speedX
        self.speedY = speedY

    # update would do nothing if blank, but let's make it move
    def update(self):
        self.rect.x += self.speedX
        self.rect.y += self.speedY
        if self.rect.left < 0 or self.rect.right > 800:
            self.speedX = -self.speedX
        if self.rect.top < 0 or self.rect.bottom > 600:
            self.speedY = -self.speedY    
def main():

    # make our window with caption
    pygame.init()
    screen = pygame.display.set_mode((800, 600))
    pygame.display.set_caption("Sprite Collision Example")

    # make our ball objects (they're sprites too!)
    ball1 = Ball((255, 0, 0), (200, 300), 3, 2)
    ball2 = Ball((0, 0, 255), (600, 300), -3, -2)

    # we can group them together instead of use lists
    balls = pygame.sprite.Group(ball1, ball2)

    # game loop
    while True:

        #check if quit
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        # use OUR update function in the ball class
        balls.update()

        # you don't need to use distance formula or anything fancy to look for collision...
        if pygame.sprite.collide_rect(ball1, ball2):
            ball1.speedX *= -1
            ball1.speedY *= -1
            ball2.speedX *= -1
            ball2.speedY *= -1

        # fill background
        screen.fill("black")

        # draw all balls (no need to draw 1 by 1 or loop, it draws the whole group)
        balls.draw(screen)
        
        # update our display and slow it down a little
        pygame.display.update()
        pygame.time.delay(10)

main()
