Search code examples
python-3.xpygamekeypress

Pygame waiting the user to keypress a key


I am searching a method, where the program stops and waiting for a spesific key to be pressed by the user. May I can implement this one with a while loop? I need the best algorithm, if there exist a build-in function of waiting, to avoid the loop. I found several information on the official website of pygame, but nothing help.

Here is a testing algorithms but won't work:

key = "f"
while key != "K_f":
     key = pygame.key.get_pressed()
     if key[Keys.K_f]:
         do something...

Solution

  • You could do it with a while loop and an event queue:

    from pygame.locals import *
    def wait():
        while True:
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == KEYDOWN and event.key == K_f:
                    return