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.
import pygamebrings in the library. The linefrom .settings import ...brings in our own numbers fromsettings.py. The dot means "from the same folder".class Gameis a class, a blueprint. Imagine a blueprint for a house: it isn't a house, but you can build a house from it. Our blueprint describes a game.__init__runs once, the moment the game is built. It starts pygame, makes the window withset_mode, gives it a title, and creates aClock, which keeps time so the game runs at the same speed on every computer.selfjust means "this game".self.running = Trueis a switch that says the game is on.runis the game loop, the heart of every game.while self.running:means "keep repeating this for as long as running is True". Each lap of the loop is one frame, which is one picture of the flipbook. When the switch becomesFalse, the loop ends andpygame.quit()closes everything.self.clock.tick(FPS)waits so we don't go faster than 60 laps a second, and tells us how many milliseconds that lap took. Dividing by 1000 turns it into seconds. We call that number dt (short for "delta time", or "the time since the last frame"). We'll use it soon.stepis what happens on each lap. First it checks the events, things that happened like a key press or clicking the window's close button. If you close the window (QUIT) or pressEscape, we flip the switch toFalse. Then it paints the whole screen with the background colour, anddisplay.flip()shows the finished picture.
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.