In this PyGame Tutorial we want to learn that How to Detect Key Presses in Pygame, so Pygame is popular game development library for Python and it offers easy framework for building interactive applications. when you are building games any other type of applications, than you will need an ability to detect key presses in Pygame.
How to Detect Key Presses in Pygame
You can install Pygame using pip command like this:
1 |
pip install pygame |
If you want to detect key presses in Pygame, we need to create a game loop that continually checks for events, including key presses. event loop is fundamental part of any Pygame application, and it is responsible for handling all the events that occurs during runtime.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import pygame pygame.init() # Set dimensions of the screen screen_width, screen_height = 800, 600 screen = pygame.display.set_mode((screen_width, screen_height)) # Set title of the window pygame.display.set_caption("Codeloop.org - Pygame Key Press Demo") # Game loop running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.display.flip() pygame.quit() |
Above code initializes Pygame, after that it creates Pygame window with specific width and height, also it sets window title. after that we have started the game loop and it will continuously checks for events until the user closes the window. pygame.event.get() function returns a list of all events that have occurred since the last time it was called. in this case we are only checking for QUIT event, which occurs when the user clicks the close button on the window.
If you run the code this will be the result
So now we have created our game loop and window, now it is time that we can start detecting key presses. we can detect key presses by checking for KEYDOWN event, KEYDOWN event occurs when a key is pressed, we can also checks which key was pressed by looking at the key attribute of the event object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import pygame pygame.init() # Set dimensions of the screen screen_width, screen_height = 800, 600 screen = pygame.display.set_mode((screen_width, screen_height)) # Set title of the window pygame.display.set_caption("Codeloop.org - Pygame Key Press Demo") # Game loop running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: print("Space key pressed") pygame.display.flip() pygame.quit() |
Subscribe and Get Free Video Courses & Articles in your Email