PyGame: Economic way of handling game loops

2019-08-09 16:14发布

问题:

I coded a small script using pygame (actually not a video game, but a graphical display for simulation results if that matters) but I'm not really satisfied with it's way of waiting for user events (in my case I'm only interested in a few keys on the keyboard).

It uses a:

running = True
while running:
    for event in pygame.event.get():
        #tests and hypothetical actions

This loops will saturate a CPU core even if the users doesn't do anything, which means useless stress on the CPU, heat, fan noise, maybe lags. Is there a smarter, ie. more economic, way of putting the program in waiting mode for events without using an infinite loop, but still using pygame.

回答1:

The only thing that you can do is to block events that you are not going to use:

pygame.event.set_allowed(None)
pygame.event.set_allowed([pygame.QUIT, pygame.KEYDOWN])

This will only post events such as pygame.QUIT and pygame.KEYDOWN onto the queue.

If there are no new key presses, there is nothing in the event queue, so the loop is not executed.

As sshashhank124 said in the comments, you can also slow the the main loop, by calling

clock.tick(frames)

This will cause pygame to sleep for some time so that the method tick will be called frames times per second.



标签: python pygame