gpt4 book ai didi

python - 无法通过按键盘上的 Q 键来结束游戏

转载 作者:行者123 更新时间:2023-12-01 07:13:51 26 4
gpt4 key购买 nike

我创建了一个小游戏(目前正在开发中)。我想在屏幕上打印出字典的键,并在按空格键后传递到下一个单词。它工作得很好,但是,当我完成所有键的迭代并按 Q 按钮退出游戏时,它不会产生任何结果。

这是我的代码:

import sys 
pygame.init()
pygame.font.init()

keywords = {

'auto': 'gives a local variable a local lifetime',
'break': 'exits out of a compound statement',
'case': 'a branch in a switch-statement',
'char': 'a character data type',
'const': 'makes a variable unmodifiable',
'continue': 'continues to the top of a loop',
'default': 'default branch in a switch-statement',
'do': 'starts a do-while loop',
'double': 'a double floating-point data type',
'else': 'an else branch of an if-statement',
'enum': 'defines a set of int constants',
'extern': 'declares an identifier is defined externally',
'float': 'a floating-point data type',
'for': 'starts a for loop',
'goto': 'jumps to a label',
'if': 'starts an if statement',
'int': 'an integer data type',
'long': 'a long integer data type',
'register': 'declares a variable be stored in a CPU register',
'return': 'returns from a function',
'short': 'a short integer data type',
'signed': 'a signed modifier for integer data types',
'sizeof': 'determines the size of the data',
'static': 'preserves variable value after its scope exits',
'struct': 'combine variables into a single record',
'switch': 'starts a switch-statement',
'typedef': 'creates a new type',
'union': 'starts an union-statement',
'unsigned': 'an unsigned modifier for integer data types',
'void': 'declares a data type empty',
'volatile': 'declares a variable might be modified elsewhere',
'while': 'starts a while loop'

}



counter = 0

size = (500, 700)
screen = pygame.display.set_mode(size)
myfont = pygame.font.SysFont("Comic Sans MS", 30)

while True:

for event in pygame.event.get():

if event.type == pygame.K_q:
sys.exit()

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
try:
counter += 1
list_keys = list(keywords.keys())
screen.fill((255,255,255))
keyword = myfont.render(list_keys[counter], False, (0,0,0))
screen.blit(keyword, (200, 350))

except IndexError:
end_of_game_text = myfont.render("end of flashcards", False,(0,0,0))
screen.blit(end_of_game_text, (175, 325))


pygame.display.flip()

这与 while 循环中设置按键按下事件的位置有关吗?它必须在按键事件之后进行吗?

我正在使用 python 2.7 和 Windows 10 作为操作系统。

最佳答案

pygame.K_q不是偶数类型(请参阅 pygame.event.EventType ,它是关键请参阅( pygame.key )。
验证事件类型是否为 pygame.KEYDOWN (或 pygame.KEYUP ),然后比较 event.keyk 键 ( pygame.K_q )。例如:

while True:

for event in pygame.event.get():

if event.type == pygame.KEYDOWN:

if event.key == pygame.K_q:
sys.exit()

elif event.key == pygame..K_SPACE:
# [...]

关于python - 无法通过按键盘上的 Q 键来结束游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58082164/

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