import pygame import sys import os import random # Initialize Pygame pygame.init() # Screen dimensions SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 # Colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) # Fonts FONT = pygame.font.Font(None, 36) # High score file HIGH_SCORE_FILE = "high_score.txt" def load_high_score(): """Load the high score from a file, if it exists. Return 0 if there is an error or the file doesn't exist.""" if os.path.exists(HIGH_SCORE_FILE): with open(HIGH_SCORE_FILE, 'r') as file: try: return int(file.read().strip()) except ValueError: return 0 return 0 def save_high_score(high_score): """Save the current high score to a file.""" with open(HIGH_SCORE_FILE, 'w') as file: file.write(str(high_score)) # Initial score and high score score = 0 high_score = load_high_score() # Load the high score from the file at the start # Set up the display screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption('High Score Example') # Coin class class Coin(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = pygame.Surface((20, 20)) self.image.fill(WHITE) self.rect = self.image.get_rect() self.rect.x = random.randint(0, SCREEN_WIDTH - self.rect.width) self.rect.y = random.randint(0, SCREEN_HEIGHT - self.rect.height) def update(self): pass # Player class class Player(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = pygame.Surface((50, 50)) self.image.fill(WHITE) self.rect = self.image.get_rect() self.rect.center = (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2) def update(self): keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: self.rect.x -= 5 if keys[pygame.K_RIGHT]: self.rect.x += 5 if keys[pygame.K_UP]: self.rect.y -= 5 if keys[pygame.K_DOWN]: self.rect.y += 5 # Sprite groups all_sprites = pygame.sprite.Group() coins = pygame.sprite.Group() player = Player() all_sprites.add(player) # Create and add coins to the game for _ in range(10): coin = Coin() all_sprites.add(coin) coins.add(coin) # Main game loop running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: print("QUIT event received. Exiting the game loop.") running = False # Update all sprites all_sprites.update() # Check for coin collection coins_collected = pygame.sprite.spritecollide(player, coins, True) if coins_collected: score += len(coins_collected) # Increase the score by the number of coins collected if score > high_score: # Check if the current score is higher than the high score high_score = score # Update the high score save_high_score(high_score) # Save the new high score to the file print(f"Collected {len(coins_collected)} coins. Score: {score}. High Score: {high_score}") # Draw everything on the screen screen.fill(BLACK) all_sprites.draw(screen) # Draw the current score score_text = FONT.render(f"Score: {score}", True, WHITE) screen.blit(score_text, (10, 10)) # Draw the high score high_score_text = FONT.render(f"High Score: {high_score}", True, WHITE) screen.blit(high_score_text, (10, 50)) # Flip the display to update the screen pygame.display.flip() # Cap the frame rate to 60 frames per second pygame.time.Clock().tick(60) # Quit Pygame and exit the script pygame.quit() sys.exit()