Adam
Adam

Reputation: 141

ignore multiple keypresses in PyGame

I have a program where the user is presented with a word and has to make a two key decision based on it.

Every time the word is presented, I have some code below that monitors their key presses. If they've given an acceptable response (1 or 0), it returns that response, but also delays the program for 1000 ms before doing so, at which point the next word is presented:

  pygame.event.clear()
  while True:
    for event in pygame.event.get(): #check for keypresses
      if event.key == pygame.K_1:
        wait(1000) #wait 1000 ms if they make a response before the next word is presented
        return 1
      elif event.key == pygame.K_0:
        wait(1000)
        return 0

The problem I'm having is that if on a given trial, the user gets impatient and starts pressing buttons during the wait(1000) call, those end up getting registered for the next couple of presented words when the above code is called.

The pygame.event.clear() at the beginning is supposed to clear the event queue, such that if the user has already pressed some keys, it clears the queue and only checks for new responses. What am I doing wrong here?

Upvotes: 0

Views: 280

Answers (1)

9000
9000

Reputation: 40894

Do not sleep. Instead, store the time and the key of the previous keypress event.

If the current event is the same key, and the time since the first keypress of this key is below 1 second, blink or beep somehow to indicate that the program is not hung, but does not accept this particular key.

If the key is different from last registered, store the time and the key, then process it as normal.

Always give users instant feedback to their actions, even if the feedback is "this action is not welcome".

Upvotes: 1

Related Questions