Pygame Events

Events in Pygame

The player can interact with the program’s graphical objects through mouse clicks or key presses. These user actions are called Events. The events make the app interactive, meaning that our game or app responds to user inputs from the keyboard and mouse.

We wrote programs to display the image of an object on the previous pages. Now, we will create an app to move that image.

The applications in the next few sections will move the ball we displayed in the previous application.  The program below will move the ball in response to the Events such as key presses, mouse movements, or mouse clicks.  Making the object respond to user actions (keyboard, mouse) makes the app interactive.

Interactive Apps

The essential part of any interactive application is the event loop. Reacting to events is required for all applications and interactive games.

Events are the user actions that occur in a program such as:

  • Key press
  • Mouse clicks
  • Mouse movements

We learned about Events as used with the Tkinter Graphics Programming chapter. Now we will see how events are used in Pygame Graphical Programming.

For more information on Pygame events refer to the link below:

<a href=”https://pygame.org/docs/ref/event.html“>

Events Handling

When Events occur, the program needs to be able to respond to them and take appropriate action. Responding to an Event is referred to as Event Handling.

Responding to the events is done by adding event-handling code to the main loop (event loop). This event-handling code then continuously monitors the user’s inputs and responds to the events, as they occur.

Main Loop (Also Called Event Loop)

As you saw in the ’Display an Image’ app in the Pygame Theory of Operation chapter, the main loop runs continuously.  Since our app needs to respond to the Events (keyboard presses, mouse clicks, or mouse movements), the main loop needs to continuously monitor these user activities (events) so that the event-handling code can respond to these events.

To find what an input device (keyboard, mouse, etc.) is doing, the main loop checks the state of the input device by making a call to the following functions.

  • Pygame.key.get.pressed()
  • Pygame.mouse.get.pos()

Calling the above functions tells the main loop the state of the input device at the moment you call the function. The event-handling code in the event loop will then see the events such as key pressed or mouse click or mouse motion in the events queue and then respond to the events detected.

Since the program’s “event loop” loops continuously and is checking for events in the events queue, the event-handling code will respond appropriately depending on the type of event. 

Events – Theory of Operation

Let us briefly go over the Pygame Events Theory of Operation before we write an application to move the image of an object.

Pygame.event Module

As discussed earlier, when you import pygame, it brings with it many modules. One of these modules is the pygame.event module. 

Note that the module name “event” starts with a lowercase “e”.

Pygame.event.Event Object

When the player presses a keyboard key, clicks the mouse, or moves the mouse, a pygame.event.Event object is created.

Note the upper case “E” in “Event” object.

Note: pygame.event is a module and pygame.event.Event is an object.

Pygame.event.get() Function

The pygame.event module has a function called pygame.event.get(). We can find out which events have happened by calling pygame.event.get() function. This function returns a list of pygame.event.Event objects in the events queue. As the event happens due to the user’s input, they are put in the events queue. Calling the Pygame.event.get() function gets events from the events queue. These events are returned as a list of Event objects.

The following excerpt of code will print all the events on your console.

while True:
    for event in pygame.event.get():
        print(event)

Event type Attributes:

Any user input (keyboard, mouse, or joystick) creates an Event object. All Event objects have properties (or attributes) “type“, which tell the program the type of the Event object.  An Event object contains an event type and a set of member data.

All Event objects contain an event type identifier in the Event.type member.  Here is a list of the Event members that are defined with each event type. Events can have the following type values, with associated attributes:

Event Type and Event Member

EVENT TYPEEVENT MEMBER
QUITnone
KEYDOWNkey, mod
KEYUPkey, mod
MOUSEMOTIONpos, rel, buttons
MOUSEBUTTONUPpos, button
MOUSEBUTTONDOWNpos, button
JOYAXISMOTIONjoy, axis, value
Event Type and Event Member

Pygame Event Types

QUIT TYPE EVENT:

If the type attribute of the event is equal to the constant variable QUIT, it means that the user has closed the window and wants to terminate the program.

Pygame.locals module:

There are constant variables for each possible type of Event in the pygame.locals module. The pygame.locals module contains 280 constants. One of them QUIT mentioned above.

When we use the statement “pygame.locals import *” in line 1a) of the ’Display an Image’ program example in the Pygame Theory of Operation chapter, we import these constants. As an example, the letter “A” key of the keyboard is the constant variable K_a.  For the left_arrow key, the constant variable is K_LEFT. For the “0” key, the constant variable is K_0, and so on.

Key Module Events

When you import pygame, another module that gets imported is the key module, anlled the pygame.key module.

The pygame.key module has two types of events:

  • KEYUP
  • KEYDOWN 

These event types have an attribute called key.  These key attributes correspond to a constant for each key of the keyboard. These constants start with an uppercase K, followed by an underscore, followed by the name of the key as described in the pygame.locals module above. This is shown in the table below for a few keyboard keys.

Keyboard Key Attributes and Constants

KEYBOARD KEYCONSTANT
ß (LEFT arrow key)K_LEFT
à (RIGHT arrow key)K_RIGHT
0K_0
AK_a
Keyboard KEY Module and Constants

Create an App to Move An Image

Let us now create an app to move an image. The application in the next few sections will move the ball we displayed in the previous application.  The ball is moved as a result of some key presses, mouse movements, or mouse clicks.

Below is an excerpt of a code showing how key event.type KEYDOWN and KEYUP are used.  It also shows the use of key attributes K_LEFT for left arrow key and K_RIGHT for right arrow key.

PROGRAM EXAMPLE: KEYBOARD EVENT TYPES KEYDOWN AND KEYUP
while true:
#  Get the list of events from the queue
    for event in pygame.event.get():	 
        if event.type == pygame.KEYDOWN:        # Check if event type is KEYDOWN (user has pressed a key)
            if event.key == pygame.K_LEFT:      # Check if event.key attribute is constant K_LEFT 
						# User pressed LEFT arrow key
                move = -10			# move an object left by 10 pixels
            elif event.key == pygame.K_RIGHT:	# Check if event.key attribute is K_RIGHT 
						# user pressed right arrow key
                move = 10			# move the object
        if event.type == pygame.KEYUP:		#  Check if event.type is KEYUP
                move = 0			# No move

Pygame.key.get_pressed() Function:

The pygame key module has a function called pygame.key.get_pressed(). This function returns the state of all keyboard buttons. The function returns a Boolean value showing the state of every keyboard key. If a key is pressed, it returns a Boolean value of “1” or “TRUE” meaning that the key is pressed. For all keys that are not pressed, this function returns a Boolean value of “0” or “FALSE”.

Mouse Module Events

Among the modules that are imported on executing the import pygame statement is the mouse module, called pygame.mouse.  The mouse module has three event types. These are:

  • MOUSEBUTTONDOWN
  • MOUSEBUTTONUP
  • MOUSEMOTION

Table: Mouse Event Type

MOUSE ACTIVITYMOUSE EVENT TYPE
The mouse button is pressedevent.type == pygame.MOUSEBUTTONDOWN:
The Mouse button is releasedevent.type == pygame.MOUSEBUTTONUP:
The mouse is movedevent.type == pygame.MOUSEMOTION:
MOUSE EVENT TYPES

Mouse Event Attributes

Each of the above Mouse event types has attributes as described below.

Table: Mouse Button Event Types and Attributes

MOUSE event.typeATTRIBUTEATTRIBUTE DESCRIPTION
MOUSEBUTTONDOWN
OR
MOUSEBUTTONUP
buttonAttribute ‘button’ is an integer.
‘button’ is equal to ‘0’ if mouse left button is pressed.
‘button’ is equal to ‘1’ if the mouse wheel is turned.
‘button’ is equal to ‘2’, if mouse right button is pressed.
 pos‘pos’ is the (x, y) location of the mouse at the moment
the mouse button is pressed
   
Mouse Button Events Types and Attributes

How to use MOUSEBUTTON Event Attribute (button)

The program below illustrates how the MOUSEBUTTON event’s button attribute can be used to find which mouse button was pressed by calling the function pygame.mouse.get_pressed().

The program stores the value returned by the function in a variable named “mouse_button”, which is a tuple.

The index for the left button is “0”, the index for the wheel is “1”, and the index for the right button is “2”.

How to use MOUSEBUTTON Event Attribute (pos)

The MOUSEBUTTON event type has another attribute called pos, as shown in the Table above.

pygame.mouse.get_pos() Function:

To find the position of the mouse, we call the function pygame.mouse.get_pos() and store the returned value in the variable “mouse_pos”. The pos attribute has the mouse (x, y) coordinates in pixels. The variable “mouse_pos” contains the (x, y) coordinates of the mouse position.

The  pygame.mouse.get_pressed()  function and  pygame.mouse.get_pos()  functions’ use is shown in the Program Example “pygameMouseButtonDown.py” below.

PROGRAM EXAMPLE: MOUSE EVENT TYPE MOUSEBUTTONDOWN

Program Name: pygame_event_mousebuttondown.py

# This example code shows the use mouse module's 
# event.type MOUSEBUTTONDOWN
# and its attributes 'button' and 'pos'.
import pygame
pygame.init()
from pygame.locals import *
screen = pygame.display.set_mode((640, 240))

WHITE = (255, 255, 255)
background = WHITE

while True:
    for event in pygame.event.get():
        # Call function pygame.event.get() 
        # to get a list of Event objects.
        mouse_pos = pygame.mouse.get_pos()
        # Call function pygame.mouse.get_pos(x,y) 
        # to get the mouse curser position
        mouse_buttons = pygame.mouse.get_pressed()  # # mouse_buttons is tuple.
#  left button index = 0, wheel index = 1, 
right button index = 2
        if mouse_buttons[0]:  # Mouse left button pressed
            print('Mouse left button pressed')
            print(mouse_pos)
            # print mouse cursor position 
coordinates at the time of mouse button press.
        if mouse_buttons[2]:    # Mouse right button pressed
            print('Mouse right button pressed')
            print(mouse_pos)
        if mouse_buttons[1]:    # Mouse wheel pressed.
            print("Mouse wheel pressed")
            print(mouse_pos)
    
    screen.fill(background)
    pygame.display.update()

MOUSEBUTTONDOWN Event Types

The Table below shows the constants for each Event Type.

EVENT TYPECONSTANTS
If the left button is pressedevent.button == 1 
If the middle button is pressedevent.button == 2
If the right button is pressedelif event.button == 3
If the mouse wheel is turned forwardevent.button == 4
If the wheel is turned backevent.button == 5
MOUSE EVENT TYPE CONSTANTS

The following pseudo-code explains how to use the MOUSEBUTTONDOWN to detect which of the mouse buttons is clicked.

if event.type == pygame.MOUSEBUTTONDOWN:  
# if any mouse button is pressed    
    if event.button == 1:  # if the left button is pressed
	do this
	…..
	…..

Now we introduce the events due to Mouse motion.

Mouse Motion Events

The table below shows the MOUSEMOTION event type and its three attributes.

  • buttons
  • pos
  • rel

Table: Mouse Event Type and Attributes

MOUSE event.typeATTRIBUTEATTRIBUTE DESCRIPTION
MOUSEMOTION Is the user moves the mouse in the displaybuttonsAttribute ‘buttons’ is a tuple (left button pressed = ‘1’, mouse wheel turned = ‘2’, right button pressed = ‘3)’. ‘buttons’ is equal to ‘1’ if mouse button is pressed or mouse wheel turned, else it is ‘0‘.
 pos‘pos’ is the absolute (x, y) location of the mouse in pixels at the moment the mouse button is pressed
 rel‘rel’ is the (rel_x, rel_y) location of the mouse relative to previous position in pixels.
MOUSE MOTION EVENTS AND ATTRIBUTES

Below is an example program that illustrates the meaning of the MOUSEMOTION event.type and its three attributes “buttons”,  “pos”, and “rel”.

The second part of the program illustrates how the program detects MOUSEBUTTONDOWN event types “left mouse button pressed”, “middle mouse button pressed”, “right mouse button pressed”, “mouse wheel turned forward’, and “mouse wheel turned back”.

PROGRAM EXAMPLE: MOUSE EVENT TYPE MOUSEMOTION and MOUSEBUTTONDOWN

Program name: pygameevent_mousemotion.py

# This example shows how to use mouse module's 
# event.type MOUSEMOTION
# and its attributes 'buttons', 'rel', and 'pos'.
import pygame
pygame.init()
from pygame.locals import *
screen = pygame.display.set_mode((640, 240))
WHITE = (255, 255, 255)
background = WHITE

while True:
    for event in pygame.event.get():
        mouse_pos = pygame.mouse.get_pos()
        # Call function pygame.mouse.get_pos(x,y) 
# to get the mouse curser position.
        # This code checks the MOUSEMOTION attribute 'rel'.
        # and mouse absolute position attribute 'pos'
        if event.type == pygame.MOUSEMOTION:    
# If mouse motion is detected
            if event.rel[0] > 0:
                # 'rel[0]' > 0 means mouse x-position 
# relative to previous x-position is to the right.
                print('Mouse moving to the right')
                print('Mouse position is = ', mouse_pos)    
# print mouse cursor (x,y) position
            elif event.rel[0] < 0:
                # 'rel[0]' < 0 means mouse has moved to 
# left relative to previous position
                print('Mouse moving to the left')
            elif event.rel[1] > 0:
                # 'rel[1]' > 0 means mouse y-position 
# relative to its previous y-position is down.
                print('Mouse moving down')
                print('Mouse position is =', mouse_pos)
            elif event.rel[1] < 0:
                # 'rel[1]' > 0 means mouse y-position 
# relative to its previous y-position is down.
                print('Mouse moving up')
                
# The below code checks and prints the event MOUSEMOTION's
# 'buttons' attribute 'event.button'
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1: 
# '1' corresponds to left mouse button.
        # event.button is a tuple(left, wheel,right).  
# Left = 1, wheel = 2, right=3
                print("Left mouse button pressed")
                print('Mouse button =  ',event.button)
            elif event.button == 2: 
# '2' corresponds to mouse wheel
                print("Mouse wheel turned")
                print('Mouse button = ', event.button)
            elif event.button == 3: 
#'3' corresponds to right mouse button
                print("Right mouse button pressed")
                print('Mouse button = ', event.button)
        elif event.type == pygame.MOUSEBUTTONUP:
            print('Mouse button released')

    screen.fill(background)
    pygame.display.update()

Mouse Module Functions

The mouse module has functions that allow us to check which mouse button is clicked (left, right, or mouse wheel) and allows us to find the position of the mouse.   

One mouse function is pygame.mouse.get_pressed().

Pygame.mouse.get_pressed():

This pygame.mouse.get_pressed() function returns the Boolean value representing the state of the mouse buttons. A True value means the mouse button is being pressed at the time of the function call. This function returns a tuple representing depending on mouse buttons (left, mouse-wheel, right) being pressed.

Note:  Call pygame.event.get() before calling this function.

Pygame.event.wait():

pygame.event.wait() function returns the current event on the queue. If no messages are waiting in the queue, this will not return until one is available.  To get all the mouse events (MOUSEBUTTONDOWN, MOUSEBUTTONUP, MOUSEMOTION), you should use the function pygame.event.wait().

Pygame.mouse.get_pos(x,y):

The function pygame.mouse.get_pos(x, y) gets the mouse curser position. This function returns the mouse x and y cursor position relative to the left-top corner of the display.

In the next two sections, we will learn how to use the above functions to move an image by using:

  1. Keyboard events
  2. Mouse events

The next program example shows the use of the keyboard events and keyboard functions.  The example uses the keyboard arrow keys to move the image on the screen. 

We will write a program to use the mouse functions and mouse events to move an image on the screen in the next section.

Verified by MonsterInsights