Menu
CoddyTech

A List of Objects

Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 13 of 36.

Two named stars is not a sky. Forty need a list: make the objects in a loop and append each one.

stars = []
for i in range(40):
    x = random.randint(0, 639)
    y = random.randint(0, 479)
    speed = random.randint(1, 3)
    stars.append(Star(x, y, speed))

Then one loop updates them all and another draws them all:

for star in stars:
    star.update()

Inside the for, star is each object in turn, so star.update() moves that star by its own speed. Adding a hundred more stars changes one number; the update and draw code stays the same.

Make the list once, before the game loop. A list made inside the loop is a new list of new stars every frame, all back at their starting places, so nothing ever moves.

challenge icon

Challenge

Medium
  1. Add import random at the top.
  2. Before the loop, make stars: a list of 40 Star objects, each with a random x from 0 to 639, a random y from 0 to 479 and a random speed from 1 to 3.
  3. In the loop, update every star in stars, and draw every star after the fill. Remove slow and fast.

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Falling Stars")
clock = pygame.time.Clock()

class Star:
    def __init__(self, x, y, speed):
        self.x = x
        self.y = y
        self.speed = speed

    def update(self):
        self.y += self.speed
        if self.y > 480:
            self.y = 0

    def draw(self, screen):
        pygame.draw.circle(screen, (255, 255, 255), (self.x, self.y), 4)


slow = Star(200, 0, 1)
fast = Star(440, 0, 3)

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    slow.update()
    fast.update()

    screen.fill((20, 22, 40))
    slow.draw(screen)
    fast.draw(screen)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Sprites and Images

Practice on your own: Pygame playground