These lines define fonts of different sizes for displaying text in the game.
# Fonts font_large = pygame.font.Font(None, 54) font_medium = pygame.font.Font(None, 26) font_small = pygame.font.Font(None, 14) |
This is the Player class definition. It represents the player-controlled character. The __init__ method initializes the player’s attributes, such as color, position, and score. The update method handles player movement and random color changes.
# Player class class Player(pygame.sprite.Sprite): def __init__(self): super().__init__() self.colors = COLORS.copy() self.image = pygame.Surface((PLAYER_WIDTH, PLAYER_HEIGHT)) self.color = random.choice(self.colors) self.image.fill(self.color) self.rect = self.image.get_rect(center=(WIDTH // 2, HEIGHT – PLAYER_HEIGHT)) self.score = 0 def update(self): keys = pygame.key.get_pressed() if keys[pygame.K_LEFT] and self.rect.left > 0: self.rect.x -= PLAYER_SPEED elif keys[pygame.K_RIGHT] and self.rect.right < WIDTH: self.rect.x += PLAYER_SPEED # Change color randomly if random.random() < 0.01: # Chance of color change self.color = random.choice(self.colors) self.image.fill(self.color) |
This is the Ball class definition. It represents the falling balls. The __init__ method initializes a ball with a specified color and random position/speed. The update method moves the ball downwards and respawns it at the top if it goes off-screen
# Falling ball class class Ball(pygame.sprite.Sprite): def __init__(self, color): super().__init__() self.image = pygame.Surface((BALL_RADIUS * 2, BALL_RADIUS * 2)) self.image.set_colorkey((0, 0, 0)) # Make black color transparent pygame.draw.circle(self.image, color, (BALL_RADIUS, BALL_RADIUS), BALL_RADIUS) self.rect = self.image.get_rect(center=(random.randint(0, WIDTH), -BALL_RADIUS)) self.speed = random.randint(5, 10) def update(self): self.rect.y += self.speed if self.rect.y > HEIGHT: self.rect.y = -BALL_RADIUS self.rect.x = random.randint(0, WIDTH) |