Tuesday, February 25, 2025

Catch the Falling Objects!

import pygame import random # Initialize pygame pygame.init() # Screen dimensions WIDTH, HEIGHT = 800, 600 screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Catch the Falling Objects!") # Colors WHITE = (255, 255, 255) RED = (255, 0, 0) BLUE = (0, 0, 255) # Game Variables basket_width, basket_height = 100, 20 basket_x = WIDTH // 2 - basket_width // 2 basket_y = HEIGHT - 50 basket_speed = 7 apple_size = 20 apple_x = random.randint(0, WIDTH - apple_size) apple_y = 0 apple_speed = 5 score = 0 font = pygame.font.Font(None, 36) clock = pygame.time.Clock() running = True while running: screen.fill(WHITE) # Event handling for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Move basket 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 < WIDTH - basket_width: basket_x += basket_speed # Move apple apple_y += apple_speed if apple_y > HEIGHT: apple_x = random.randint(0, WIDTH - apple_size) apple_y = 0 # Collision detection if (basket_x < apple_x < basket_x + basket_width) and (basket_y < apple_y < basket_y + basket_height): score += 1 apple_x = random.randint(0, WIDTH - apple_size) apple_y = 0 # Draw objects pygame.draw.rect(screen, BLUE, (basket_x, basket_y, basket_width, basket_height)) pygame.draw.circle(screen, RED, (apple_x, apple_y), apple_size) # Display score score_text = font.render(f"Score: {score}", True, (0, 0, 0)) screen.blit(score_text, (10, 10)) pygame.display.flip() clock.tick(30) pygame.quit()

0 comments:

Post a Comment