Table of contents
1.
Introduction
2.
Pygame
3.
Types of Events
3.1.
1) Keyboard event: 
3.2.
2) Mouse events
3.3.
Example 1:
3.4.
Example 2:
4.
Frequently Asked Questions
4.1.
What does an event do in pygame?
4.2.
How do you get events on pygame?
4.3.
Does python have event handling?
4.4.
What is an event in Python?
4.5.
What is pygame Keydown?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Event handling in Pygame

Introduction

Pygame is a multimedia toolkit for Python that may be used to create games and other multimedia applications. We'll use the pygame module to build various forms on the screen while considering their height, width, and position in the pygame window in this lesson.

SDL stands for Simple DirectMedia Layer, and Pygame is a Python wrapper for it. SDL allows you to utilise any platform to access your system's multimedia hardware, including sound, video, mouse, keyboard, and joystick. The pygame project was created to replace the now-defunct PySDL project. Because SDL and pygame are cross-platform, you can create games and rich multimedia Python programs on any platform that supports them!

Pygame

An event is an activity taken by the user to get the desired outcome. A click event, for example, occurs when a user presses a button. All of the user's events are now inserted into an event queue. Because it is a queue, it follows the Initially In First Out rule, which means that the element added first will be the first to be removed. In this scenario, when an event is created, it is placed at the bottom of the queue, and when it is processed, it is moved to the front. Every entry in this queue has an attribute that is nothing more than an integer that indicates the sort of event it is. Let's look at some of the most crucial characteristics of the most frequent event types.

Now that you know what an event in Python is let's delve more into this topic. It is critical to understand that event processing must occur within the primary function. This is because if it is done, there is a potential that input lag would occur, resulting in a poor user experience. pygame.event.get is used to process the data (). This function returns a list of events that can be processed sequentially.

Types of Events

1) Keyboard event: 

An event, as previously stated, is a user-conducted action. So, what kinds of things can be done with the keyboard? Either press or release the key is the basic answer. KEYDOWN refers to pressing the key, while KEYUP refers to releasing it. The legend of the type integer is the attribute associated with these events. Its purpose is to symbolize a keyboard key. A preset integer constant with a capital K represents the standard keys. The letter K is followed by an underscore before the key's name is written. For instance, K s and K F7.

On the other hand, capital letters do not have an integer constant. The solution to this difficulty is a modifier, often known as a mod, which is a modifier such as shift, alt, ctrl, and others that are pressed simultaneously as the key. The integer value of mod is saved in a variable called KMOD_, followed by the key's name. For instance, KMOD RSHIFT, KMOD CTRL, and so on. Let's use a little code to review the topics we learned in the keyboard event topic.

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")
You can also try this code with Online Python Compiler
Run Code

2) Mouse events

Let's look at the various forms of mouse events now. The first two are MOUSEBUTTONDOWN and MOUSEBUTTONUP, similar to KEYDOWN and KEYUP, except that we're using a mouse instead of a keyboard. There is also a mouse event called MOUSEMOTION in addition to these. Let's take a closer look at each of the three mouse events.

1) MOUSEBUTTONDOWN: When the user touches the mouse button, the MOUSEBUTTONDOWN event happens. The following are some of its characteristics:

Button: This is an integer that represents the pressed button. The left mouse button is represented by 1, the mouse wheel is represented by 2, and the right mouse button is represented by 3.

When the user hits the mouse button, the absolute position of the mouse (x, y) is recorded.

2) MOUSEBUTTONUP: When the user releases the mouse button, the MOUSEBUTTONUP event happens. As discussed above, it has the same button and position attributes as the MOUSEBUTTONDOWN.

3) MOUSEMOTION: This event occurs when the user moves his mouse in the display window. The characteristics buttons, pos, and rel are all present.

Buttons: This tuple indicates whether or not the mouse buttons (left, mouse-wheel, and right) are pressed.

pos: This is the cursor's absolute position (x, y) in pixels.

rel: It represents the relative position (rel x, rel y) in pixels to the previous post.

Let's go over the values for each mouse button characteristic again using the table below:


With the help of a tiny code, let us review the ideas we learnt in the mouse event topic.
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")
You can also try this code with Online Python Compiler
Run Code

Let's look at a few pygame programs that deal with event handling.

Example 1:

The following program will determine if we pushed the left or right key and display the appropriate output.
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()
You can also try this code with Online Python Compiler
Run Code

OUTPUT

Example 2:

The following software will detect whether we are moving the mouse, pushing or releasing the mouse button, and display the appropriate output.

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()
You can also try this code with Online Python Compiler
Run Code

OUTPUT

 

Check out this problem - Queue Implementation

Frequently Asked Questions

What does an event do in pygame?

The Pygame event loop comes into play here. Its job is to monitor and process all of the various inputs (keyboard, mouse, joysticks, and so on). You can also program your events depending on time, game logic, or anything else.

How do you get events on pygame?

Pygame will log all user events into an event queue, which may be accessed using the pygame. event. get() function. Every element in this queue is an Event object with the attribute type, a number representing the type of event.

Does python have event handling?

The Python Event Handler class functions similarly to other programming languages. We've realized that the way events work is similar to raising a flag for an event. An event handler is a class that is responsible for handling and monitoring these events.

What is an event in Python?

The constructs that allow a class to alert other types when something interesting happens are known as events. In layman's terms, it's analogous to raising a flag to alert others that something noteworthy has occurred.

What is pygame Keydown?

KEYDOWN and pygame detect if a key is physically pressed down or released. Use pygame. key to creating several pygames. To activate the keyboard repeat, set it to repeat.

Conclusion

So that's the end of the article Event handling in Pygame

After reading about the Event handling in Pygame, are you not feeling excited to read/explore more articles on the topic of pygame? Don't worry; Coding Ninjas has you covered. 

However, you may want to pursue our premium courses to give your job an advantage over the competition!

Upskill yourself in Data Structures and Algorithms, Competitive Programming, JavaScript, System Design, and more with our Coding Ninjas Studio Guided Path! If you want to put your coding skills to the test, check out the mock test series and enter the contests on Coding Ninjas Studio! But if you've only recently started your schooling and are looking for answers to issues presented by digital titans like Amazon, Microsoft, Uber, and others. In this situation, you must consider the obstaclesinterview experiences, and interview package as part of your placement preparations. Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass