import pygame import sys import math # Initialize Pygame pygame.init() # Constants WIDTH, HEIGHT = 800, 600 BALL_RADIUS = 20 FPS = 60 # Colors WHITE = (255, 255, 255) BLUE = (0, 0, 255) # Create the screen screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Throw Ball Example") # Clock to control the frame rate clock = pygame.time.Clock() # Class to represent a ball class Ball: def __init__(self, x, y): self.rect = pygame.Rect(x - BALL_RADIUS, y - BALL_RADIUS, BALL_RADIUS * 2, BALL_RADIUS * 2) self.speed = 5 self.direction = (1, 0) def throw(self, angle): self.direction = (math.cos(angle), math.sin(angle)) def move(self): self.rect.x += int(self.speed * self.direction[0]) self.rect.y += int(self.speed * self.direction[1]) def draw(self): pygame.draw.circle(screen, BLUE, self.rect.center, BALL_RADIUS) # Create the ball ball = Ball(WIDTH // 2, HEIGHT // 2) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: # Left mouse button # Calculate angle between the ball and mouse position mouse_x, mouse_y = pygame.mouse.get_pos() angle = math.atan2(mouse_y - ball.rect.centery, mouse_x - ball.rect.centerx) ball.throw(angle) # Move the ball ball.move() # Bounce off the walls if ball.rect.left < 0 or ball.rect.right > WIDTH: ball.direction = (-ball.direction[0], ball.direction[1]) if ball.rect.top < 0 or ball.rect.bottom > HEIGHT: ball.direction = (ball.direction[0], -ball.direction[1]) # Draw everything screen.fill(WHITE) ball.draw() pygame.display.flip() clock.tick(FPS)