← All stepsBobgame: make a Python game

Step 12 of 12

Check it against the finished code

Here is the finished game.py so you can check yours

import pygame

from .player import Bob
from .settings import BG_COLOR, FPS, HEIGHT, WIDTH


class Game:
    def __init__(self) -> None:
        pygame.init()
        self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
        pygame.display.set_caption("Bobgame")
        self.clock = pygame.time.Clock()
        self.bob = Bob()
        self.running = True

    def step(self, dt: float) -> None:
        for event in pygame.event.get():
            if event.type == pygame.QUIT or (
                event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE
            ):
                self.running = False
        self.bob.update(dt, pygame.key.get_pressed(), pygame.mouse.get_pos())
        self.screen.fill(BG_COLOR)
        self.bob.draw(self.screen)
        pygame.display.flip()

    def run(self) -> None:
        while self.running:
            self.step(self.clock.tick(FPS) / 1000)
        pygame.quit()

Every frame the game loop does the same three things: handle input, update the world, then draw it. Almost every game ever made is built on that idea, from this one to the biggest ones you play.

If something isn't working, compare your files with the ones in the bobgame repo. Common culprits are:

  1. Indentation. Python cares about the spaces at the start of a line. Everything inside a class or a def is indented by 4 spaces.
  2. Typos in names. self.pos and self.Pos are different things.
  3. A missing colon at the end of a line starting with def, class, if or while.
  4. Wrong folder. main.py must be in the top bobgame folder, with the inner bobgame folder beside it.

The error message in the terminal tells you the file and the line number. Read it, it's usually trying to help.

Docs: pygame.draw • pygame.math.Vector2 • pygame.time.Clock