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...
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.
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.
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.
In Python 3 use input(): input("Press Enter to continue...") In Python 2 use raw_input(): raw_input("Press Enter to continue...")
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With