Menu
CoddyTech

A List of Stars

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

A list holds many values in one variable, in order, inside square brackets:

stars = [(100, 80), (220, 160), (360, 100)]

Here each item is a position tuple. stars[0] is the first item, (100, 80), and stars[1] the second. Counting starts at 0, as with range.

A for loop can walk through a list. The loop variable takes each item in turn:

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

A position is a tuple, so star goes straight where the centre goes. Add a position to the list and one more star appears, with no change to the loop. The list is the game's memory of what is on the screen; the loop draws whatever it holds.

challenge icon

Challenge

Easy

Draw a sky of five stars from a list:

  1. Add (360, 100), (480, 200) and (580, 70) to the end of stars.
  2. Replace the line that draws stars[0] with for star in stars:, drawing each as a white (255, 255, 255) circle of radius 5.

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 = [(100, 80), (220, 160)]

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, (255, 255, 255), stars[0], 5)

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

pygame.quit()

All lessons in Python in a Game Window

Practice on your own: Pygame playground