Menu
CoddyTech

Your First Class

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

The star is three variables: star_x, star_y and star_speed. Fine for one star; a sky full of them needs a better way to keep each star's numbers together.

A class is a plan for a kind of object. Each object made from it carries its own values, called attributes:

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


star = Star(320, 0)

Star(320, 0) makes a new Star object. Python then runs __init__ on it, the function inside the class that sets up each new object (the name, with two underscores on each side, is one Python looks for), with x = 320 and y = 0. Inside, self is the new object, so self.x = x stores 320 on it. Outside the class you reach the same value as star.x, and change it the same way: star.y += star.speed.

Class names start with a capital letter: Star is the plan, star is one star made from it.

challenge icon

Challenge

Easy
  1. Write a class Star whose __init__(self, x, y) stores self.x, self.y and self.speed = 2.
  2. Replace the three variables with star = Star(320, 0).
  3. In the loop, use star.y, star.speed and star.x where the old variables were.

Try it yourself

import pygame

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

star_x = 320
star_y = 0
star_speed = 2

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

    star_y += star_speed
    if star_y > 480:
        star_y = 0

    screen.fill((20, 22, 40))
    pygame.draw.circle(screen, (255, 255, 255), (star_x, star_y), 4)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in Sprites and Images

Practice on your own: Pygame playground