Event Handling in Pygame Python
Here in this tutorial, we will look at event handling in Pygame Python.
Anything or everything in pygame is an event and here we will take a look at some of the events present in pygame.
Event Handling in Pygame
import pygame pygame.init() screen = pygame.display.set_mode((500, 450)) while True: for i in pygame.event.get(): if i.type == pygame.QUIT: pygame.quit() exit() if i.type == pygame.KEYDOWN: if i.key == pygame.K_0: print('0 is being pressed') if i.key == pygame.K_a: print('a is being pressed') if i.key == pygame.K_SPACE: print('space bar is being pressed') if i.key == pygame.K_LEFT: print('left arrow is being pressed') if i.type == pygame.MOUSEWHEEL: print(i.x,i.y) if i.type == pygame.MOUSEBUTTONDOWN: print("mouse is pressed") pygame.display.update()
The first event handled in the code written above is to exit the game screen that is being handled by using the quit and exit functions.
Secondly, if any of the mentioned keys are pressed then the text written in the print statement is printed on the output screen.
event.get() function in python takes care of any event happening on the game screen.
Here, when we use the KEYDOWN function, we consider any keys that are pressed. In the above-mentioned code when the number ‘0’ is pressed then the text “0 is being pressed” is printed and so on with the other keys like the alphabet ‘a’ or the spacebar or the left arrow key and the corresponding texts are printed.
Thirdly, we have used the mouse wheel event which will let us know the coordinates according to which the cursor behaves that is it will decrement the y-axis if scrolled upward and increment otherwise.
Next, we used the mouse button event which will let us know if any of the mouse keys are pressed and print the same.
Thus we have seen the use of event function in event handling in pygame Python.