Paul's Python CoursePPC

The game loop

Not met yet

A game is a loop that goes round many times a second: read the input, update the state by one step, draw the state, wait for the next frame. Speeds in a loop like this are per frame, not per second: 4 pixels a frame at 60 frames a second is 240 pixels a second. Keep update free of drawing and of input, a step from one state to the next, and keep drawing free of changes, and the rules can be tested without a screen, sped up, or replayed exactly from a seed.

Try it

main.py
class Fall:
    def __init__(self):
        self.y = 0

    def update(self):
        self.y += 4                     # pixels per frame

    def draw(self):
        return f"apple at {self.y}"     # reads the state, never changes it


fall = Fall()
for frame in range(3):
    fall.update()
    print(fall.draw())

Output

Press Run and what your program prints shows up here.

Easy to get wrong

  • Thinks a speed added once each time round the game loop is per second. It is per frame, so the frame rate multiplies it.
  • Thinks two rectangles whose edges only touch are overlapping. They share no pixels, so nothing is caught.
  • Thinks it's fine to move things or change scores while drawing. Then the game depends on how often it's drawn, and can't be tested without a screen.

Where it comes up