Python / Pygame-如何创建一个程序,以便一旦按下某个键就可以激活其他程序?

时间:2017-06-11 21:33:45

标签: python pygame

我正在进行一个问答游戏,并且遇到了一个循环漏洞。我这样做是为了当用户按下正确的键和空格键时,然后给出这些点。但是循环孔是他们可以按下所有内容然后按空格键。那我该怎么做呢?

 keys = pygame.key.get_pressed()
if keys[pygame.K_w] and (General_knowledge[question_num - 1][5] == "a"):
    test = 1
if keys[pygame.K_d] and (General_knowledge[question_num - 1][5] == "b"):
    test = 1
if keys[pygame.K_s] and (General_knowledge[question_num - 1][5] == "c"):
    test = 1
if keys[pygame.K_a] and (General_knowledge[question_num - 1][5] == "d"):
    test = 1
if keys[pygame.K_SPACE]:
    space_bar = 1

if (test == 1) and (space_bar == 1) and (rect_width > 0):
    test = 0
    space_bar = 0
    player_1_score = rect_width / 30
    player_1_score = round(player_1_score, 0)
    print(player_1_score)

1 个答案:

答案 0 :(得分:0)

如果只按下1个键,您可以在代码中添加一个简单的计数器。试试这样的事情

keys = pygame.key.get_pressed()
keysPressed = 0;
if keys[pygame.K_w] and (General_knowledge[question_num - 1][5] == "a"):
    test = 1
    keysPressed += 1;
if keys[pygame.K_d] and (General_knowledge[question_num - 1][5] == "b"):
    test = 1
    keysPressed += 1;
if keys[pygame.K_s] and (General_knowledge[question_num - 1][5] == "c"):
    test = 1
    keysPressed += 1;
elif keys[pygame.K_a] and (General_knowledge[question_num - 1][5] == "d"):
    test = 1
    keysPressed += 1;
if keys[pygame.K_SPACE]:
    space_bar = 1

if (test == 1) and (space_bar == 1) and (keysPressed == 1) and (rect_width > 0):
    test = 0
    space_bar = 0
    player_1_score = rect_width / 30
    player_1_score = round(player_1_score, 0)
    print(player_1_score)

这样,如果按下超过1个键,那么您的上一个if语句将失败。