Menu
CoddyTech

Count with len

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

len(stars) is how many items the list holds. An empty list has length 0. Use it to show a count:

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

An f-string can hold any expression in its curly brackets, a call included.

len can also set a limit. Add a star only while there is room:

if event.type == pygame.MOUSEBUTTONDOWN and len(stars) < 10:
    stars.append(event.pos)

Once the list holds 10 stars the condition is false, so clicks do nothing. The count on screen and the limit read the same list, so they always agree.

The limit sits in the event loop, joined to the click test with and: the append runs only when the event is a click and there is room. len works on strings too: len("Night") is 5.

challenge icon

Challenge

Medium

Count the stars and stop at ten:

  1. In the setup part, make font = pygame.font.Font(None, 36).
  2. In the draw part, show f"Stars: {len(stars)}" in (230, 230, 240) at (20, 20).
  3. Append a star on a click only while len(stars) < 10.

Try it yourself

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.
    for star in stars:
        pygame.draw.circle(screen, (255, 255, 255), star, 5)

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

pygame.quit()

All lessons in Python in a Game Window

Practice on your own: Pygame playground