../

Keyboard Input In Pygame

There are 2 different ways of getting keyboard input:

  1. pygame.key
  2. event loop

1. pygame.key

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

  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")

Tags: /python/ /python3/ /pygame/ /gamedev/ /tutorial/ /animation/