← All stepsBobgame: make a Python game

Step 7 of 12

Write game.py and open a window

Now the most important file. Open bobgame/game.py

import pygame

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.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.screen.fill(BG_COLOR)
        pygame.display.flip()

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

That's a lot, so here it is piece by piece.

The -> None and : float bits are called type hints. They are notes saying "this gives back nothing" and "this is a decimal number". Python doesn't need them, but they help you and VS Code understand the code.