Search code examples
pythonpygame

Is there a reason why event.key doesn't work halfway through my code?


So, I've been working on a project in PyGame. To test the currency system out, I've decided to increment the money you have when a key is pressed. I've tried moving the if statement out of the game loop. Here's my code:

gameRun = True
while gameRun:
    for event in pygame.event.get():
        if event.key == pygame.K_p:
            print("This Should Work")
            currency.balance.amount += 1
            pygame.display.update()

I have other several other lines of code but I believe that there is something wrong about these lines. Thank you so much!


Solution

  • Is there a reason why event.key doesn't work halfway through my code?

    I guess you have more than 1 event loop, respectively call to pygame.event.get() are there in your code.
    Note pygame.event.get() removes the events from the queue. If you have more than 1 event loop, then just one random loop will get the events, all the other loops go empty-handed. That causes that you'll miss events.

    Get the list of events once in the main application loop and use same list of events in multiple event loops. e.g:

    gameRun = True
    while gameRun:
        events = pygame.event.get()
    
        for event in events:
            if event.key == pygame.K_p:
                print("This Should Work")
                currency.balance.amount += 1
                pygame.display.update()
    
        # [...]
    
        foo(event)
    
        # [...]
    
        for event in events:
            # [...]
    
    def foo(events):
        for event in events:
            # [...]