Pygame waiting the user to keypress a key

前端 未结 2 1001
遥遥无期
遥遥无期 2021-01-21 04:10

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 algori

相关标签:
2条回答
  • 2021-01-21 04:48

    If you are waiting for a key to be pressed you can use the event.wait() function. This is useful, because it does not require a-lot of processing.

    import pygame
    from pygame.locals import *
    
    pygame.event.clear()
    while True:
        event = pygame.event.wait()
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            if event.key = K_f:
                do something...
    

    Note that event.wait() waits for events to appear in the event cache, the event cache should be cleared first.

    pygame.event documentation

    0 讨论(0)
  • 2021-01-21 05:03

    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
    
    0 讨论(0)
提交回复
热议问题