1

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

我试图避免长时间的多个 if 语句来测试 if K_a, K_b... ect 是否被点击,有没有办法处理下面的 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)
4

1 回答 1

3

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


要测试更多键(例如 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"
于 2013-11-13T20:06:14.663 回答