Menu
CoddyTech

Remove a Star

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

Lists shrink too. stars.pop() removes the last item, the newest one. stars.pop(0) removes the first. stars.remove(item) removes the first item equal to item.

Popping from an empty list is an error, IndexError: pop from empty list, and the program stops. Test the length first:

if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
    if len(stars) > 0:
        stars.pop()

Note the two ifs. The outer one picks the Space press out of the events, the inner one makes sure there is a star to remove.

In an if, an empty list counts as False and a list with items as True, so if stars: means the same as if len(stars) > 0:.

challenge icon

Challenge

Medium

Let Space take a star back:

  1. In the event loop, when a KEYDOWN event for K_SPACE arrives, remove the newest star with stars.pop().
  2. Only pop when the list is not empty, so Space with no stars does nothing.

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 = []
font = pygame.font.Font(None, 36)

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.MOUSEBUTTONDOWN and len(stars) < 10:
            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)
    text = font.render(f"Stars: {len(stars)}", True, (230, 230, 240))
    screen.blit(text, (20, 20))

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

pygame.quit()

All lessons in Python in a Game Window

Practice on your own: Pygame playground