我创建了一个小游戏(目前正在开发中)。我要在屏幕上打印出字典键的位置,并在按空格键后传递到下一个单词。但是,当我完成所有按键的迭代操作并按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作为操作系统。
答案 0 :(得分:1)
pygame.K_q
不是偶数类型(请参见pygame.event.EventType
,它是键,请参见(pygame.key
)。
验证事件类型是否为pygame.KEYDOWN
(或pygame.KEYUP
),然后将event.key
与 k 键(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:
# [...]