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

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

问题描述

我正在搜索一种方法,在该方法中程序停止并等待用户按下特定键.我可以用一个while循环来实现这个吗?我需要最好的算法,如果存在等待的内置功能,以避免循环.我在pygame官方网站上找到了一些信息,但没有任何帮助.>

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

key = "f"而键 != "K_f":键 = pygame.key.get_pressed()如果键[Keys.K_f]:做一点事...

解决方案

你可以用一个 while 循环和一个事件队列来做到:

from pygame.locals import *定义等待():而真:对于 pygame.event.get() 中的事件:如果 event.type == 退出:pygame.quit()系统退出()如果 event.type == KEYDOWN 和 event.key == K_f:返回

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天全站免登陆