Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...
like image 448
Dr. Programmer Avatar asked Dec 23 '13 17:12

Dr. Programmer


People also ask

How do you wait for a key press in pygame?

In Python 2, use raw_input() : raw_input("Press Enter to continue") This only waits for the user to press enter though. This should wait for a key press.

How do you delay on pygame?

delay() function. This returns the actual number of milliseconds used. Will pause for a given number of milliseconds. This function will use the processor (rather than sleeping) in order to make the delay more accurate than pygame.

How do you pause a program until the key is pressed in Python?

Python wait for user input We can use input() function to achieve this. In this case, the program will wait indefinitely for the user input. Once the user provides the input data and presses the enter key, the program will start executing the next statements.

How do I prompt a user to press Enter in Python?

In Python 3 use input(): input("Press Enter to continue...") In Python 2 use raw_input(): raw_input("Press Enter to continue...")


2 Answers

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

like image 137
cweb Avatar answered Sep 30 '22 12:09

cweb


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
like image 26
Bartlomiej Lewandowski Avatar answered Sep 30 '22 10:09

Bartlomiej Lewandowski