1

I'm working on a game where pressing space does something, but a lot of the time, the space key is not registered. I have a main function and I run a while loop where at the end, I have this:

for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_SPACE:
            (do this)
    if event.type == pygame.QUIT:
        pygame.quit()
        quit()
        break

    else:
        pass

(Before this, I have a few hundred lines of code)

But I find that a lot of the time, nothing happens when I press space and it takes a lot of tries (usually 7-10) before the game responds to the spacebar. I have tried removing time.sleep(0.05) after pygame.display.update which has helped a bit. I have also tried making this for loop run more often through my while loop, but it still takes many tries before the game responds to the keypress. What am I doing wrong?

John Liu
  • 162
  • 1
  • 9
  • How many times do you invoke `pygame.event.get()` in your application? It is important that you call it only once per frame, because [`pygame.event.get()`](https://www.pygame.org/docs/ref/event.html#pygame.event.get) removes all the pending events from the queue. – Rabbid76 Sep 01 '20 at 21:01
  • Multiple times, so I should remove it? – John Liu Sep 01 '20 at 21:38
  • Please read the answer. – Rabbid76 Sep 02 '20 at 04:27

1 Answers1

0

[...] I have also tried making this for loop run more often through my while loop [...]

No, don't do that. pygame.event.get() removes all the pending events from the queue. If you have more than one event loop and you invoke pygame.event.get() multiple times, only one of the loops will receive the events, all other loops will miss them.

Retrieve the list of events once per frame. You can then go through the list several times:

# application loop
while run:

    # get the events
    events = pygame.event.get()

    # handel QUIT event
    for event in events:
        if evnet.type == pygame.QUIT:
            run = false

    # [...]

    # handle some events
    for event in events:
        # [...]

    # [...]

    # handle some other events
    for event in events:
        # [...]

    # [...]
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • Hey Rabbid, i actually wanted to read how pygame.event.get is implemented but i could only find what is does and not how it is implemented. Can you link to any good article please. Thanks. –  Sep 01 '20 at 21:15
  • 1
    @hippozhipos It depends on the OS. Under the hood pgame uses SDL. So start reading at [`SDL_Event`](https://wiki.libsdl.org/SDL_Event) – Rabbid76 Sep 01 '20 at 21:20