gpt4 book ai didi

python - 如何处理 pygame.get_pressed() 来接收输入

转载 作者:行者123 更新时间:2023-11-30 23:31:25 24 4
gpt4 key购买 nike

pygame.get_keypressed() 为每个按下的按键返回一个由 0 和 1 组成的长列表,可以由 pygame 映射。下面的示例,是否有直接的方法来提取按下的按键的字母表示?

我试图避免使用很长的多个 if 语句来测试 K_aK_b... 等是否被单击,有没有办法处理 1 和下面有 0 吗?

(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0)

最佳答案

它看起来像二进制表示形式的数字,因此您可以将其转换为整数并使用按位“AND”将其与某些“掩码”(表示您需要的键)进行比较。我不知道这是否值得做。

<小时/>

要测试更多键(例如 h,e,l,o ),您可以使用

pressed = pygame.get_keypressed()

if all( (pressed[x] for x in (K_h, K_e, K_l, K_o)) ):
print "all keys are pressed: h, e, l, o"

if any( (pressed[x] for x in (K_h, K_e, K_l, K_o)) ):
print "at least one key is pressed: h, e, l, o"

你可以把它变成函数

def test_all_keys( list_of_keys, pressed ):
return all( (pressed[x] for x in list_of_keys) )

if test_all_keys((K_h, K_e, K_l, K_o), pressed):
print "all keys are pressed: h, e, l, o"

如果您需要按键列表:

list_of_pressed = [ i for i in range(len(pressed)) if pressed[i] ]

if K_a in list_of_pressed:
print "key 'a' was pressed"

关于python - 如何处理 pygame.get_pressed() 来接收输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19962598/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com