get key pressed pygame code example
Example 1: check key pressed pygame
import pygame
events = pygame.event.get()
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
location -= 1
if event.key == pygame.K_RIGHT:
location += 1
Example 2: pygame key pressed once
# Outside loop
pressed = False
# Inside loop
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a and not pressed: #K_a can be replaced by any key
# Do something
pressed = True
elif event.key != pygame.K_a:
pressed = False
Example 3: pygame.key.get_pressed()
if pygame.mouse.get_pressed()[0]:
# do something when the left mouse button is pressed
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
# do something when the a key is pressed
Example 4: pygame keydown
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
return True