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