Home >Backend Development >Python Tutorial >Why Does `pygame.event.get()` Fail to Return Events in a Separate Thread?

Why Does `pygame.event.get()` Fail to Return Events in a Separate Thread?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-01 11:54:13779browse

Why Does `pygame.event.get()` Fail to Return Events in a Separate Thread?

pygame.event.get() Failing to Return Events within a Separate Thread

This query pertains to difficulties encountered when utilizing pygame.event.get() within a separate thread for managing user inputs in a Pac-Man-inspired game. The code snippet responsible for receiving inputs is as follows:

def receiving_inputs(self):
    while True:
        events = pg.event.get()
        for event in events:
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_UP:
                    self.move = 'n'
                elif event.key == pg.K_RIGHT:
                    self.move = 'e'
                elif event.key == pg.K_DOWN:
                    self.move = 's'
                elif event.key == pg.K_LEFT:
                    self.move = 'w'
        time.sleep(1/60)

threading.Thread(target=self.receiving_inputs).start()

When this code is executed, pressing keyboard keys does not trigger any events, while moving the mouse does return events. Intriguingly, the same code functions flawlessly when executed within the program's main loop rather than a separate thread.

The question stems from a desire to minimize the instances of key presses going unregistered in the main loop by employing a separate thread.

Resolution:

The unexpected behavior stems from the fact that events must be managed within the main thread. As stated in thepygame.event documentation:

[...] The event subsystem should be called from the main thread.

While it is feasible to post events from a separate thread, the event queue can only be processed by the main thread. Thus,

  1. Ensure that events are obtained in the main thread:

    def receiving_inputs(self):
        while True:
            events = pg.event.get()
            for event in events:
                ...
  2. Create a thread to modify the game state based on the events:

    def move(self, move):
        ...
    
    thread = threading.Thread(target=self.move, args=(move,))
    thread.start()

The above is the detailed content of Why Does `pygame.event.get()` Fail to Return Events in a Separate Thread?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn