import pygame import random # Initialize pygame pygame.init() # Set up display screen_width = 600 screen_height = 400 screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption("Catch the Falling Objects") # Define colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) # Set up game variables basket_width = 100 basket_height = 20 basket_x = (screen_width - basket_width) // 2 basket_y = screen_height - basket_height - 10 basket_speed = 10 falling_object_width = 30 falling_object_height = 30 falling_object_x = random.randint(0, screen_width - falling_object_width) falling_object_y = -falling_object_height falling_object_speed = 5 score = 0 font = pygame.font.SysFont("Arial", 25) # Game loop flag running = True while running: screen.fill(WHITE) # Event handling for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Control the basket with arrow keys keys = pygame.key.get_pressed() if keys[pygame.K_LEFT] and basket_x > 0: basket_x -= basket_speed if keys[pygame.K_RIGHT] and basket_x < screen_width - basket_width: basket_x += basket_speed # Move the falling object falling_object_y += falling_object_speed # Check for collision if (falling_object_y + falling_object_height > basket_y and falling_object_x + falling_object_width > basket_x and falling_object_x < basket_x + basket_width): score += 1 falling_object_y = -falling_object_height falling_object_x = random.randint(0, screen_width - falling_object_width) # Reset the falling object if it falls past the basket if falling_object_y > screen_height: falling_object_y = -falling_object_height falling_object_x = random.randint(0, screen_width - falling_object_width) # Draw basket pygame.draw.rect(screen, BLACK, (basket_x, basket_y, basket_width, basket_height)) # Draw falling object pygame.draw.rect(screen, RED, (falling_object_x, falling_object_y, falling_object_width, falling_object_height)) # Display score score_text = font.render(f"Score: {score}", True, BLACK) screen.blit(score_text, (10, 10)) # Update display pygame.display.update() # Control the frame rate pygame.time.Clock().tick(60) # Quit pygame pygame.quit()