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

时间:2013-11-13 19:25:37

标签: python input pygame

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)

1 个答案:

答案 0 :(得分:3)

它看起来像二进制表示中的数字,因此您可以将其转换为整数并使用按位' 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"