Pygame等待用户按键 [英] Pygame waiting the user to keypress a key

查看:379
本文介绍了Pygame等待用户按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法,程序停止并等待用户按下特殊键.我可以用while循环来实现吗?我需要最好的算法,如果存在等待的内置函数,则可以避免循环. 我在 pygame官方网站上找到了一些信息,但是没有帮助.

这是一种测试算法,但不起作用:

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

解决方案

您可以使用while循环和事件队列来实现:

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

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...

解决方案

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

这篇关于Pygame等待用户按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆