2

I am making a game in which the user has to press a specific key to make the player move. During the handling of this event, which one is the correct code to be written :-

if event.type == pygame.K_E:
      vel_F1_x = 2
      vel_F2_x = 0

OR

   if event.type == pygame.K_e:
       vel_F1_x = 2
       vel_F2_x = 0
Hardyk Mahendru
  • 320
  • 3
  • 11

1 Answers1

1

The enumeration constant for the key e is K_e. However, none of your code snippets is correct.

The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released.
The key that was pressed can be obtained from the key attribute of the pygame.event.Event object:

if event.type == pygame.KEYDOWN:
     if event.key == pygame.K_e:
         vel_F1_x = 2
         vel_F2_x = 0

If you want to evaluate whether a key is being held down, use pygame.key.get_pressed().

The keyboard events (see pygame.event module) occur only once when the state of a key changes. Use the keyboard events for a single action or a step-by-step movement.
pygame.key.get_pressed() returns a list with the state of each key. If a key is held down, the state for the key is True, otherwise False. Use pygame.key.get_pressed() to evaluate the current state of a button and get continuous movement:

keys = pygame.key.get_pressed():
if keys[pygame.K_e]:
    # [...]
Rabbid76
  • 202,892
  • 27
  • 131
  • 174