Keyboard Input In Pygame

Vishal Rashmika published on
1 min, 116 words

Categories: Pygame

There are 2 different ways of getting keyboard input:

  1. pygame.key
  2. event loop

1. pygame.key

  • great when using seperate controls inside classes. >pygame.key.get_pressed() -- returns an object that contains all the buttons and their states
keys = pygame.key.get_pressed() # stores the obj in the keys dictionary
# keys[pygame.K_SPACE] --> returns either 0 or 1
if keys[pygame.K_SPACE]: print("jump")

Event Loop

  • have a little bit more control over the controls compared to pygame.key
  1. check if any button was pressed
  2. work with a specific key
if event.type == pygame.KEYDOWN: #triggers when a key is pressed
    print("key Down")

if event.type == pygame.KEYUP: # triggers when a pressed key is released
    print("key Up")
if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_SPACE:
        print("jump")