Text
Text
import random
import sys
# Initialize Pygame
pygame.init()
# Screen settings
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Bouncing Balls Game")
# Colors
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
# Ball settings
BALL_RADIUS = 20
BALL_COUNT = 5
balls = []
# Button settings
button_rect = pygame.Rect(WIDTH // 2 - 50, HEIGHT // 2 - 20, 100, 40)
def move(self):
self.x += self.vx
self.y += self.vy
def draw(self):
pygame.draw.circle(screen, BLUE, (self.x, self.y), BALL_RADIUS)
# Initialize balls
for _ in range(BALL_COUNT):
x = random.randint(BALL_RADIUS, WIDTH - BALL_RADIUS)
y = random.randint(BALL_RADIUS, HEIGHT - BALL_RADIUS)
balls.append(Ball(x, y))
# Draw button
pygame.draw.rect(screen, RED, button_rect)
pygame.draw.rect(screen, (0, 0, 0), button_rect, 2)
# Event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
running = False # Press 'A' to stop the game
elif event.type == pygame.MOUSEBUTTONDOWN:
mx, my = pygame.mouse.get_pos()
for ball in balls:
if (ball.x - mx) ** 2 + (ball.y - my) ** 2 <= BALL_RADIUS ** 2:
ball.vx = (ball.x - mx) // 2 # Throw in x direction
ball.vy = (ball.y - my) // 2 # Throw in y direction
pygame.display.flip()
pygame.time.delay(30)
pygame.quit()
sys.exit()