import pygame import sys # Initialize Pygame pygame.init() # Set screen dimensions WIDTH, HEIGHT = 800, 600 screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Bouncing Ball with Trail") # Colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) # Ball properties ball_radius = 20 ball_color = RED ball_position = [WIDTH // 2, HEIGHT // 2] # Starting position of the ball ball_speed = [5, 5] # Movement speed of the ball trail_length = 20 # Number of previous positions to draw as a trail trail = [] # List to store previous positions of the ball # Main loop while True: # Event handling for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # Update ball position ball_position[0] += ball_speed[0] ball_position[1] += ball_speed[1] # Check for collisions with walls if ball_position[0] + ball_radius >= WIDTH or ball_position[0] - ball_radius <= 0: ball_speed[0] = -ball_speed[0] if ball_position[1] + ball_radius >= HEIGHT or ball_position[1] - ball_radius <= 0: ball_speed[1] = -ball_speed[1] # Add current position to the trail trail.insert(0, (int(ball_position[0]), int(ball_position[1]))) if len(trail) > trail_length: trail.pop() # Clear the screen screen.fill(BLACK) # Draw the trail for i, pos in enumerate(trail): alpha = int(255 * (1 - i / trail_length)) pygame.draw.circle(screen, (ball_color[0], ball_color[1], ball_color[2], alpha), pos, ball_radius) # Draw the ball pygame.draw.circle(screen, ball_color, (int(ball_position[0]), int(ball_position[1])), ball_radius) # Update the display pygame.display.flip() # Control the frame rate pygame.time.Clock().tick(60)