Detect arrow key press in Pygame Python
This tutorial will teach us how to detect the arrow key press in Pygame Python.
Detecting the arrow key press in Pygame
Detecting the moment of arrow keys is easy in Python with the in-built functions that come with Pygame.
import pygame pygame.init() screen = pygame.display.set_mode((500, 450)) x1, y1 = 300, 350 while True: screen.fill((0, 0, 0)) circle1 = pygame.draw.circle(screen, (249, 246, 238), (x1, y1), 35) for i in pygame.event.get(): if i.type == pygame.QUIT: pygame.quit() exit() if i.type == pygame.KEYDOWN: if i.key == pygame.K_LEFT: x1 -= 10 print("Left arrow key is pressed") if i.key == pygame.K_RIGHT: x1 += 10 print("Right arrow key is pressed") if i.key == pygame.K_UP: y1 -= 10 print("Up arrow key is pressed") if i.key == pygame.K_DOWN: y1 += 10 print("Down arrow key is pressed") pygame.display.update()
In the code written above, after importing the Pygame library and initializing the functions using init(); we have drawn a circle that will help in detecting the motion of arrow keys.
We can also use any other figure such as a rectangle, square, triangle, etc or any image to detect if any key is pressed.
Now for detecting the pressed keys we have used the following functions within the while loop:
- pygame.KEYDOWN: This will let us know if any of the keys on the keyboard is pressed.
The four functions mentioned above help us know if any of the arrow keys are pressed by moving the figure accordingly and printing the text onto the console for every key that is pressed.
left arrow key is pressed Right arrow key is pressed Up arrow key is pressed Down arrow key is pressed