Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 41 ยท Game Architecture

Game States, Start Menus and Pause Screens

Structure a Pygame game with a state machine: start menu, playing, paused and game over screens, keyboard-navigable menus, state stacks and clean transitions.

Your first Pygame programs are one big loop that draws a game. A real game also needs a title screen, a settings menu, a pause screen, a game-over screen and perhaps a level select. If you handle all of these with a pile of if in_menu: flags the loop quickly becomes unreadable.

The cure is a state machine: at any moment the game is in exactly one state, each state knows how to handle events, update and draw itself, and states decide when to hand control to another. This lesson builds that structure and a menu that works with the keyboard. The Pygame drawing is read-only; the state logic is fully runnable as text simulations.

Game states as a diagram

stateDiagram-v2
  [*] --> Menu
  Menu --> Playing: Start
  Menu --> Options: Options
  Options --> Menu: Back
  Playing --> Paused: Esc
  Paused --> Playing: Esc / Resume
  Paused --> Menu: Quit to menu
  Playing --> GameOver: lives = 0
  GameOver --> Playing: Retry
  GameOver --> Menu: Menu
  Menu --> [*]: Quit

Each box is a state, each arrow a transition triggered by an event.

The flag approach and why it breaks

Python
while running:
    if state == "menu":
        ...handle menu events, draw menu...
    elif state == "playing":
        ...handle game events, update, draw...
    elif state == "paused":
        ...

It works for three states. At ten states, one giant function contains handlers, drawing and transitions for everything, and a bug in the pause screen can break the main game. Moving each state into its own class keeps the code local.

A state class and a manager

Give every state the same three methods and let a small manager call whichever is active:

Python
class State:
    def __init__(self, game):
        self.game = game

    def enter(self):            # called when the state becomes active
        pass

    def handle_event(self, event):
        pass

    def update(self, dt):
        pass

    def draw(self, screen):
        pass


class Game:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((800, 600))
        self.clock = pygame.time.Clock()
        self.running = True
        self.states = {"menu": MenuState(self), "play": PlayState(self),
                       "gameover": GameOverState(self)}
        self.state = self.states["menu"]

    def change_state(self, name):
        self.state = self.states[name]
        self.state.enter()

    def run(self):
        while self.running:
            dt = self.clock.tick(60) / 1000
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.running = False
                else:
                    self.state.handle_event(event)
            self.state.update(dt)
            self.state.draw(self.screen)
            pygame.display.flip()

The main loop never changes again. To add a new screen you write one class, register it and call game.change_state("name") from wherever it should open. This is the State pattern from software design.

Python A state machine you can drive

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at how resume differs from change: coming back from pause must not call enter(), otherwise lives and score would be reset to their starting values.

A menu is a list of options and the index of the selected one. Up and Down change the index (wrapping around), Enter activates it. Mouse support is an extra, using collidepoint as in Buttons and Text Input Boxes.

Python
class MenuState(State):
    OPTIONS = ["Start", "Options", "Quit"]

    def enter(self):
        self.index = 0

    def handle_event(self, event):
        if event.type == pygame.KEYDOWN:
            if event.key in (pygame.K_UP, pygame.K_w):
                self.index = (self.index - 1) % len(self.OPTIONS)
            elif event.key in (pygame.K_DOWN, pygame.K_s):
                self.index = (self.index + 1) % len(self.OPTIONS)
            elif event.key in (pygame.K_RETURN, pygame.K_SPACE):
                self.activate(self.OPTIONS[self.index])

    def activate(self, option):
        if option == "Start":
            self.game.change_state("play")
        elif option == "Quit":
            self.game.running = False

    def draw(self, screen):
        screen.fill((16, 20, 34))
        for i, text in enumerate(self.OPTIONS):
            colour = (255, 220, 90) if i == self.index else (200, 200, 210)
            label = self.game.font.render(("> " if i == self.index else "  ") + text, True, colour)
            screen.blit(label, (300, 220 + i * 50))

The modulo operator makes the selection wrap: from the first item, Up goes to the last.

Python Wrap-around menu navigation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A stack of states for pause screens

With the plain manager, pausing means remembering where to return to. A stack solves that neatly: push the pause screen over the game, and pop it to return. Only the top state receives events and updates, while states below can still draw (so the game freezes visibly behind a translucent pause overlay).

Python
class Game:
    def __init__(self):
        self.stack = [MenuState(self)]

    def push(self, state):  self.stack.append(state)
    def pop(self):          self.stack.pop()

    def run(self):
        while self.running:
            dt = self.clock.tick(60) / 1000
            for event in pygame.event.get():
                self.stack[-1].handle_event(event)
            self.stack[-1].update(dt)
            for state in self.stack:                 # draw bottom to top
                state.draw(self.screen)
            pygame.display.flip()

Menu, then Play pushed on top, then Pause pushed on top of Play: pressing Esc in Pause pops it and Play is right where you left it, with no reset.

Python Push and pop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Passing data between states

States often need to share things: the score for the game-over screen, the chosen level, settings. Put shared information on the Game object (game.score, game.settings) or pass values into change_state("gameover", score=120) and let enter(**kwargs) accept them. Avoid global variables; they make states hard to test.

Fading between states

Abrupt switches feel harsh. A quick fade is easy: draw a black surface with changing alpha over the screen when a transition is running.

Python
overlay = pygame.Surface(screen.get_size())
overlay.fill((0, 0, 0))
overlay.set_alpha(int(255 * progress))    # progress goes 0 -> 1, then switch state, then 1 -> 0
screen.blit(overlay, (0, 0))

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main benefit of putting each screen in its own State class?

    Each state handles its own events, updating and drawing, so adding a screen means adding a class.
  2. 2. Why should resuming from pause not call the playing state's enter() method?

    enter() prepares a fresh state. Returning from pause should continue where the player left off.
  3. 3. How does a menu index wrap from the last item to the first when pressing Down?

    The modulo operator returns to 0 after the last index.
  4. 4. In a state stack, which states receive events?

    Only the top state is active, while states below may still be drawn.

Summary

  • A game is a state machine: menu, playing, paused, game over, each with handle_event, update and draw.
  • A small manager runs the current state, so the main loop never changes when screens are added.
  • Menus keep a selected index that wraps with modulo and activates on Enter.
  • A stack of states makes pause and overlay screens easy to push and pop.
  • Share data through the game object, not globals, and fade between states for polish.

Next: Organizing Game Code