Open In App

Pygame – Event Handling

Last Updated : 21 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

An event is an action that is performed by the user in order to get the desired result. For instance, if a user clicks a button then it is known as a click event. Now, all the events that are performed by the user are inserted into a queue known as an event queue. Since it is a queue, it follows the First In First Out rule i.e. element inserted first will come out first. In this case, when an event is created it is added to the back of the queue and when the event is processed then it comes out from the front. Every element in this queue is associated with an attribute which is nothing but an integer that represents what type of event it is.  Let us learn a few important attributes of the common event types.

SR No. Event Attributes
1. KEYDOWN   key, mod, unicode
2. KEYUP key, mod
3. MOUSEBUTTONUP  pos, button
4. MOUSEBUTTONDOWN pos, button
5. MOUSEMOTION  pos, rel, buttons
6. QUIT           –

Owing to the fact that you have understood what an event in pygame is now let us dive deep into this topic. It is essential to know that the processing of an event must be done within the main function. This is because if in case if it is done, then there is a chance of having an input lag which can result in a poor user experience. The processing is done using pygame.event.get(). This is a function that will return the list of events that can be processed one after another. 

Types of Events

1) Keyboard event: 

As mentioned above, an event is an action conducted by the user. So let us wonder, what actions can be performed on the keyboard? The simple answer is either pressing the key or releasing it. Pressing the key is known as KEYDOWN and releasing it is known as KEYUP. The attribute associated with these events is known as the key of type integer. Its use is to represent the key of the keyboard. The common keys are represented by a pre-defined integer constant which is a capital K. This K is followed by an underscore and then the name of the key is written. For example K_s, K_F7.

The fact of the matter is that capital letters do not have an integer constant. The solution to this problem is something known as a modifier also known as a mod which is the modifier such as for shift, alt, ctrl, etc. that are being pressed simultaneously as the key.  The integer value of mod is stored in something known as KMOD_  which is followed by the name of the key. For example KMOD_RSHIFT, KMOD_CTRL, etc. Let us revise the concepts that we have learned in the keyboard event topic with the help of a small code.

Python3




for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_w:
            print("Move the character forwards")
        elif event.key == pygame.K_s:
            print("Move the character backwards")
        elif event.key == pygame.K_a:
            print("Move the character left")
        elif event.key == pygame.K_d:
            print("Move the character right")


2) Mouse events

Let us now understand the different types of mouse events. The first two are MOUSEBUTTONDOWN and MOUSEBUTTONUP which are similar to KEYDOWN and KEYUP except for the fact that here we are using a mouse. In addition to them, there is another mouse event known as MOUSEMOTION. Let us understand all 3 mouse events in detail.

i) MOUSEBUTTONDOWN: The MOUSEBUTTONDOWN event occurs when the user presses the mouse button. It has a couple of attributes which are as follows : 

  • button:  It is an integer that represents the button that has been pressed.  The left button of the mouse is represented by 1, for mouse-wheel the integer is 2, and integer 3 is when the right button of the mouse is pressed.
  • pos: It is the absolute position of the mouse (x, y) when the user presses the mouse button. 

ii) MOUSEBUTTONUP: The MOUSEBUTTONUP event occurs when the user releases the mouse button. It has the same button and pos attributes that the MOUSEBUTTONDOWN has which have been mentioned above.

iii) MOUSEMOTION: This event occurs when the user moves his mouse in the display window. It has the attributes buttons, pos, and rel.

  • buttons: It is a tuple that represents whether the mouse buttons (left, mouse-wheel, right) are pressed or not.
  • pos: It is the absolute position (x, y) of the cursor in pixels.
  • rel: It represents the relative position to the previous position (rel_x, rel_y) in pixels.

Let us revise the values for every mouse button attribute with the help of the following table:

SR No. Button Value
1. Left mouse button  1
2. Mouse wheel button 2
3. Right mouse button  3
4. Mouse wheel scroll up 4
5. Mouse wheel scroll down 5

Let us revise the concepts that we have learned in the mouse event topic with the help of a small code. 

Python3




for event in pygame. event.get():
    if event.type == pygame.QUIT:
        raise SystemExit
    elif event.type == pygame.MOUSEMOTION:
        if event.rel[0] > 0:
            print("Mouse moving to the right")
        elif event.rel[1] > 0:
            print("Mouse moving down")
    elif event.type == pygame.MOUSEBUTTONDOWN:
        if event.button == 3:
            print("Right mouse button pressed")
    elif event.type == pygame.MOUSEBUTTONUP:
        print("Mouse button has been released")


Let us now have a look at a couple of pygame programs related to event handling.

Example 1:

 The following program will check whether we have pressed the left key or the right key and display output accordingly.

Python3




import pygame
pygame.init()
  
# Creating window
gameWindow = pygame.display.set_mode((800, 300))
pygame.display.set_caption("Event Handling")
  
  
exit_game = False
game_over = False
  
# Creating a game loop
while not exit_game:
    for event in pygame.event.get():  # For Loop
        if event.type == pygame.QUIT:
            exit_game = True
  
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                print("You have pressed right arrow key")
            elif event.key == pygame.K_LEFT:
                print("You have pressed left arrow key")
  
pygame.quit()
quit()


Output:

Example 2:

The following program will check whether we are moving the mouse or pressing the mouse button or releasing it and display output accordingly.

Python3




import pygame
pygame.init()
  
# Creating window
gameWindow = pygame.display.set_mode((800, 300))
pygame.display.set_caption("Event Handling")
  
  
exit_game = False
game_over = False
  
# Creating a game loop
while not exit_game:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit_game = True
  
        if event.type == pygame.QUIT:
            raise SystemExit
        elif event.type == pygame.MOUSEMOTION:
            if event.rel[0] > 0:
                print("Mouse moving to the right")
            elif event.rel[1] > 0:
                print("Mouse moving down")
        elif event.type == pygame.MOUSEBUTTONDOWN:  # Click event
            if event.button == 3:
                print("Right mouse button pressed")
        elif event.type == pygame.MOUSEBUTTONUP:  # Mouse released
            print("Mouse button has been released")
  
pygame.quit()
quit()


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads