How To Use The Pygame Event Handler

Introduction To Events

In pygame when working with keyboard or mouse inputs we talk about an event handler, but what is an event handler?

Pygame manages its events through an event queue:

As events are detected, they get added to this queue. We can then use these events to detect mouseclicks, keyboard presses and so on.

There is a limit to how many events the event queue can hold though, so it is important the events are handled every frame to make sure the program works correctly.

There are a few functions associated with events but the one you will use most is pygame.event.get()

This function will grab all the events from the queue and allow us to process them. That is why our event handler typically uses a for loop. We grab all the events, which come back as a list, then we iterate through the list and look at each event. If it’s one that we are interested in then we catch it with an if statement. Otherwise, it gets discarded.

Take another look at the code from the previous tutorial and notice how this structure is applied to check for a QUIT event.

				
					import pygame

pygame.init()

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

run = True
while run:

  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      run = False

pygame.quit()
				
			

Common Event Types

So what other events are there?

The main ones that are used most commonly are (unsurprisingly) the input events:

  • KEYDOWN & KEYUPto detect keyboard buttons being pressed and released
  • MOUSEMOTION to detect mouse movement
  • MOUSEBUTTONDOWN & MOUSEBUTTONUPto detect the mouse being clicked and released

There’s a whole bunch of other events but you will rarely need to use those in a regular pygame project.

To see the events in action, try printing them out by using the print function (see line 14).

Run this code and move the mouse, press keys, reposition the game window and you’ll notice all the events being displayed in the console.

				
					import pygame

pygame.init()

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

run = True
while run:

  for event in pygame.event.get():
    print(event)
    if event.type == pygame.QUIT:
      run = False

pygame.quit()
				
			

This gives an overview of the pygame event handler. In the next couple of tutorial sections, I will look in more detail at the different input events.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *