Menu
CoddyTech

Click to Add

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

A list can grow while the game runs. stars.append(item) adds an item to the end.

A mouse click arrives in the event loop as a MOUSEBUTTONDOWN event, and event.pos is where it happened, an (x, y) tuple:

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

Each click adds one position. The draw part already draws every star in the list, so the new star shows on the next frame and stays there, because the list keeps it.

The list starts empty in the setup part: stars = []. Made inside the game loop, it would be emptied on every frame and each star would vanish at once.

challenge icon

Challenge

Easy

In the event loop, when a MOUSEBUTTONDOWN event arrives, append event.pos to stars. Each click then places a white star.

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

    # 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