Menu
CoddyTech

Count the Stars

Part of the Python in a Game Window section of Coddy's Pygame journey. Lesson 31 of 32.

The player needs to know how close the sky is to full. Show the count out of twenty in the top left corner:

text = font.render(f"Stars: {len(stars)}/20", True, (230, 230, 240))
screen.blit(text, (20, 20))

The f-string mixes a value, len(stars), with plain text, /20. With seven stars it reads Stars: 7/20.

Make the font in the setup part, next to stars = []. Making a font loads it, which takes time, so do it once. Rendering the text is cheap and happens on every frame, so the count is always up to date.

Draw the label last in the draw part, so no star can cover it.

challenge icon

Challenge

Easy

Show the count:

  1. In the setup part, make font = pygame.font.Font(None, 36).
  2. At the end of the draw part, render f"Stars: {len(stars)}/20" in (230, 230, 240) and blit it at (20, 20).

Try it yourself

import random
import pygame

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Night Sky")
clock = pygame.time.Clock()

# Set things up here, before the game loop.
stars = []

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            stars.append(event.pos)

    # Change things here, once a frame.

    screen.fill((20, 24, 48))
    # Draw here, after the fill.
    pygame.draw.circle(screen, (240, 230, 160), (560, 80), 40)
    pygame.draw.rect(screen, (14, 16, 30), (0, 430, 640, 50))
    for star in stars:
        colour = (255, 255, 255)
        if random.randint(1, 30) == 1:
            colour = (110, 120, 170)
        pygame.draw.circle(screen, colour, star, 3)

    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in Python in a Game Window

Practice on your own: Pygame playground