Menus and game states
Add a title menu, a pause screen and a game-over screen, with buttons that work with both mouse and keyboard, organised as a simple state machine.
On this page
What you'll learn
- Representing screens as game states
- A reusable
ButtonandMenufor mouse and keyboard - Pausing by skipping the update phase
- Drawing translucent overlays
Prerequisites: Mouse input.
Games are state machines#
At any moment your game is in exactly one state: the title menu, playing, paused, or game over. Each state handles input differently and draws different things. Keeping the current state in a variable and branching on it is the simplest structure that scales to a complete game.
menu ──Play──> playing ──Esc──> paused ──Resume──> playing
^ │ │
└──Main menu─────┴── time up ──> game_over ──Play again──> playingThe example#
"""Menus and game states: a title menu, playing, paused and game over, with mouse and keyboard buttons."""
import pygame
WIDTH, HEIGHT = 640, 480
BG = (20, 26, 46)
WHITE = (230, 236, 247)
YELLOW = (244, 197, 49)
BLUE = (91, 147, 230)
class Button:
def __init__(self, text, center, action):
self.text = text
self.rect = pygame.Rect(0, 0, 240, 52)
self.rect.center = center
self.action = action
def draw(self, surface, font, selected):
pygame.draw.rect(surface, YELLOW if selected else BLUE, self.rect, border_radius=8)
label = font.render(self.text, True, BG)
surface.blit(label, label.get_rect(center=self.rect.center))
class Menu:
"""A vertical list of buttons: arrow keys + Enter, or hover + click."""
def __init__(self, buttons):
self.buttons = buttons
self.selected = 0
def handle(self, event):
if event.type == pygame.KEYDOWN:
if event.key in (pygame.K_DOWN, pygame.K_s):
self.selected = (self.selected + 1) % len(self.buttons)
elif event.key in (pygame.K_UP, pygame.K_w):
self.selected = (self.selected - 1) % len(self.buttons)
elif event.key in (pygame.K_RETURN, pygame.K_SPACE):
return self.buttons[self.selected].action
elif event.type == pygame.MOUSEMOTION:
for i, b in enumerate(self.buttons):
if b.rect.collidepoint(event.pos):
self.selected = i
elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
for b in self.buttons:
if b.rect.collidepoint(event.pos):
return b.action
return None
def draw(self, surface, font):
for i, b in enumerate(self.buttons):
b.draw(surface, font, i == self.selected)
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
title_font = pygame.font.Font(None, 72)
font = pygame.font.Font(None, 36)
state = "menu" # menu | playing | paused | game_over
main_menu = Menu([Button("Play", (WIDTH // 2, 230), "play"), Button("Quit", (WIDTH // 2, 300), "quit")])
pause_menu = Menu([Button("Resume", (WIDTH // 2, 230), "resume"), Button("Main menu", (WIDTH // 2, 300), "menu")])
over_menu = Menu([Button("Play again", (WIDTH // 2, 260), "play"), Button("Main menu", (WIDTH // 2, 330), "menu")])
time_left = 0.0
score = 0
target = pygame.Rect(0, 0, 40, 40)
def start_game():
global time_left, score
time_left, score = 10.0, 0
target.center = (WIDTH // 2, HEIGHT // 2)
running = True
while running:
dt = clock.tick(60) / 1000
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif state == "menu":
action = main_menu.handle(event)
if action == "play":
start_game()
state = "playing"
elif action == "quit":
running = False
elif state == "playing":
if event.type == pygame.KEYDOWN and event.key in (pygame.K_ESCAPE, pygame.K_p):
state = "paused"
elif event.type == pygame.MOUSEBUTTONDOWN and target.collidepoint(event.pos):
score += 1
target.x = (target.x * 7 + 131) % (WIDTH - 40) # move somewhere else
target.y = 60 + (target.y * 5 + 97) % (HEIGHT - 120)
elif state == "paused":
action = pause_menu.handle(event)
if action == "resume" or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
state = "playing"
elif action == "menu":
state = "menu"
elif state == "game_over":
action = over_menu.handle(event)
if action == "play":
start_game()
state = "playing"
elif action == "menu":
state = "menu"
if state == "playing": # only the game updates
time_left -= dt
if time_left <= 0:
state = "game_over"
screen.fill(BG)
if state == "menu":
t = title_font.render("Click Rush", True, YELLOW)
screen.blit(t, t.get_rect(center=(WIDTH // 2, 130)))
main_menu.draw(screen, font)
elif state in ("playing", "paused"):
pygame.draw.rect(screen, YELLOW, target, border_radius=6)
screen.blit(font.render(f"Score {score} Time {max(0, time_left):.1f}", True, WHITE), (16, 12))
if state == "paused":
shade = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
shade.fill((0, 0, 0, 160))
screen.blit(shade, (0, 0))
pause_menu.draw(screen, font)
elif state == "game_over":
t = title_font.render(f"Score: {score}", True, YELLOW)
screen.blit(t, t.get_rect(center=(WIDTH // 2, 150)))
over_menu.draw(screen, font)
pygame.display.flip()
pygame.quit()
How it fits together:
- Events go to the current state only. The menu's buttons can't be clicked while playing, and the target can't be clicked while paused.
- Update runs only while playing. Pausing doesn't need special code inside the game logic; the timer simply stops being updated.
- Draw by state. The pause screen draws the game first, then a translucent black Surface, then the pause menu, so the frozen game stays visible behind it.
Buttons that work for everyone#
The Menu class tracks a selected index. Arrow keys move it, Enter or Space activates it, and the mouse updates it on hover and activates on click. Supporting the keyboard makes menus usable without a mouse, on gamepads (map the D-pad to the same actions) and for players who rely on the keyboard.
Each button returns an action string rather than doing the work itself. The main loop decides what "play" means. This keeps the UI code reusable across games.
Growing the pattern#
When each state's code gets long, move it into classes with the same three methods:
class PlayingState:
def handle(self, event): ...
def update(self, dt): ...
def draw(self, surface): ...
state = MenuState()
while running:
for event in pygame.event.get():
state.handle(event)
state.update(dt)
state.draw(screen)
if state.next is not None: # a state asks to switch
state = state.nextCommon mistakes#
- Restarting by calling the main function again inside the loop nests loops and eventually crashes. Reset your variables (as
start_game()does) and change the state. - Events "leaking" between states: the click that pressed "Play" can also hit something in the first game frame. Handling one state per event, as in the example, prevents that.
- Pausing with
time.sleep()or a nested loop freezes the window. Keep the main loop running and skip updates instead. - Tiny buttons frustrate players. Make them large, with clear hover and focus feedback.
Practice exercises#
- Add a "Settings" button that opens a screen to toggle sound on and off.
- Show a 3-2-1 countdown state before play begins.
- Add mouse-wheel scrolling to a long list of options, such as a level select.
- Combine this with the score system so the game-over screen shows the high score.