import pygame import random pygame.init() SCREEN_WIDTH = 640 SCREEN_HEIGHT = 480 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("Collect All Coins") clock = pygame.time.Clock() WHITE = (255, 255, 255) BLUE = (50, 100, 200) GOLD = (220, 180, 0) BLACK = (0, 0, 0) RED = (200, 50, 50) GREEN = (50, 180, 50) font_large = pygame.font.SysFont("arial", 48) font_small = pygame.font.SysFont("arial", 24) COIN_COUNT = 5 COIN_RADIUS = 10 TIME_LIMIT = 30 # seconds (30 * 60 = 1800 frames at 60 fps) player = pygame.Rect(300, 220, 30, 30) player_speed = 4 def make_coins(count): coins = [] for _ in range(count): x = random.randint(COIN_RADIUS, SCREEN_WIDTH - COIN_RADIUS) y = random.randint(COIN_RADIUS, SCREEN_HEIGHT - COIN_RADIUS) coins.append([x, y]) return coins def show_end_screen(message, color): screen.fill(WHITE) text = font_large.render(message, True, color) rect = text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)) screen.blit(text, rect) hint = font_small.render("Close the window to exit.", True, BLACK) hrect = hint.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 60)) screen.blit(hint, hrect) pygame.display.flip() waiting = True while waiting: for event in pygame.event.get(): if event.type == pygame.QUIT: waiting = False coins = make_coins(COIN_COUNT) collected = 0 frames_elapsed = 0 running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: player.x -= player_speed if keys[pygame.K_RIGHT]: player.x += player_speed if keys[pygame.K_UP]: player.y -= player_speed if keys[pygame.K_DOWN]: player.y += player_speed player.x = max(0, min(player.x, SCREEN_WIDTH - player.width)) player.y = max(0, min(player.y, SCREEN_HEIGHT - player.height)) # Check coin collection i = 0 while i < len(coins): if player.collidepoint(coins[i][0], coins[i][1]): coins.pop(i) collected += 1 else: i += 1 frames_elapsed += 1 seconds_left = TIME_LIMIT - frames_elapsed // 60 if collected == COIN_COUNT: show_end_screen("You win!", GREEN) running = False if seconds_left <= 0: show_end_screen("Time's up!", RED) running = False screen.fill(WHITE) for coin in coins: pygame.draw.circle(screen, GOLD, (coin[0], coin[1]), COIN_RADIUS) pygame.draw.rect(screen, BLUE, player) coin_text = font_small.render( "Coins: " + str(collected) + " / " + str(COIN_COUNT), True, BLACK ) screen.blit(coin_text, (10, 10)) time_text = font_small.render("Time: " + str(max(0, seconds_left)), True, BLACK) time_rect = time_text.get_rect(topright=(SCREEN_WIDTH - 10, 10)) screen.blit(time_text, time_rect) pygame.display.flip() clock.tick(60) pygame.quit()