Menu
CoddyTech

Methods

Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 11 of 39.

The star's numbers live in the class now, but the rules for them, how it falls and how it is drawn, are still in the loop. Functions written inside a class are methods, and they put the rules next to the data:

class Star:
    # __init__ as before

    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)

Every method's first parameter is self, the object it works on. You call a method on an object with a dot, and pygame's Surface is passed in like any other argument:

star.update()
star.draw(screen)

The main loop now reads as what happens in a frame: update the star, then draw it. Game objects in pygame programs nearly always have these two methods, update and draw.

challenge icon

Challenge

Medium

Give the star its own update and draw methods.

  1. Add update(self) to Star: it adds self.speed to self.y, and puts the star back at y = 0 once self.y is over 480.
  2. Add draw(self, screen): the white circle, radius 4, at (self.x, self.y).
  3. In the loop, call star.update() and, after the fill, star.draw(screen).

Press Play: the star falls as before. Then Check.

Try it yourself

import pygame

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

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


star = Star(320, 0)

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