2

I'm coding a chess game in python using pygame. One of the common tasks is the need to handle events, and the only way I know how to do it is like this:

while True:
    for event in pygame.event.get():  
        # handle event

The while loop just keeps spinning, which is inefficient. In embedded programming, you can send the cpu to sleep until there is an interrupt. Is there a way to do something similar in python, having the loop wait for events?

pygame.time.Clock.tick (as covered in "Pygame clock and event loops") can limit the number of frames/iterations per second, which is not what I want to accomplish.

outis
  • 75,655
  • 22
  • 151
  • 221
  • Not sure if there's anything exactly like that but maybe [`pygame.event.pump`](https://www.pygame.org/docs/ref/event.html#pygame.event.pump) comes close? –  Sep 10 '21 at 16:05

2 Answers2

3

It sounds to me like you should use

pygame.event.wait()

Returns a single event from the queue. If the queue is empty this function will wait until one is created...While the program is waiting it will sleep in an idle state.

See this documentation.

La-comadreja
  • 5,627
  • 11
  • 36
  • 64
0

Pygame doesn't support interrupts like that, it requires you to get the events yourself. However they do have a clock that allows you to perform operations in set intervals, e.g. 60 times per second.

Handling events can also be done in the main game loop, which you will need anyway.

You can use a setup like this:

import pygame

class Game():
    def __init__(self):
        pygame.init()
        self.clock = pygame.time.Clock()

    def mainloop(self):
        while True:
            time = self.clock.tick(60)

            for event in pygame.event.get():
                # Handle events
                pass
            
            # Do other game calculations
Jotha
  • 418
  • 2
  • 7
  • Limiting frame rate would not help performance in any way –  Sep 10 '21 at 16:36
  • A quick test suggests that it does reduce CPU load. But the frame rate/tick limit on the game loop is more for game logic than for performance reasons – Jotha Sep 10 '21 at 17:47
  • Well yes, it reduces cpu load because it processes less frames per second. But it does have go through the event loop the same number of times as fps so I don't see how it's improving the performance of the **event processing**. –  Sep 10 '21 at 18:14
  • Less CPU load is a benefit depending on what you do. And your events being tied to your game loop allows you to more easily include events into your game logic. I don't think these are huge benefits for most small projects. But the only benefit for an uncapped loop I can think of is speeding up the response by some milliseconds, which only matters in niche cases – Jotha Sep 10 '21 at 18:20
  • Just saw your edit, and I totally agree the performance of a single event cycle is the same. – Jotha Sep 10 '21 at 18:21