Menu
CoddyTech

Place the Stars

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

The last four lessons build one small game, Night Sky: you click to place stars, they twinkle, a counter shows how many, and at twenty the sky is full. Each lesson starts from your code of the one before.

The game uses what this section taught. The stars are a list of positions, made empty before the game loop. A click appends its position, and a for loop draws every star in the list on every frame:

stars = []

        if event.type == pygame.MOUSEBUTTONDOWN:
            stars.append(event.pos)

    for star in stars:
        pygame.draw.circle(screen, (255, 255, 255), star, 3)

Draw the stars after the moon and the ground, so they show on top. A star placed on the moon then sits in front of it, as if it were closer.

challenge icon

Challenge

Easy

Start Night Sky:

  1. Make stars = [] before the game loop.
  2. On a MOUSEBUTTONDOWN event, append event.pos to stars.
  3. After the moon and the ground, draw every star as a white (255, 255, 255) circle of radius 3.

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.

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.
    pygame.draw.circle(screen, (240, 230, 160), (560, 80), 40)
    pygame.draw.rect(screen, (14, 16, 30), (0, 430, 640, 50))

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

pygame.quit()

All lessons in Python in a Game Window

Practice on your own: Pygame playground