pygame KEYDOWN 事件和按键事件 [英] pygame KEYDOWN event and key events
问题描述
有一个问题在使用 pygame 开发游戏时并不重要,但它一直困扰着我一段时间.
Hi there is an issue that doesn't really matter when developing a game with pygame but that kept on bothering me for a while.
while not gameExit:
for event in pygame.event.get():e
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
pass
所以上面是一个工作代码,我相信
so above is a working code and I believe
while not gameExit:
for event in pygame.event.get():e
if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
pass
同样有效.
然而,当我尝试类似event.key == pygame.K_RIGHT:"之类的东西时,python 给我一个错误,说没有属性key".虽然我知道选择以上 2 个代码而不是event.key == pygame.K_RIGHT:"更合理,但我不知道为什么 pygame 会说事件没有属性 'key' 而什么时候我只是检查 event.type == pygame.KEYDOWN pygame 执行event.key == pygame.K_RIGHT"是否没有问题.
However, when I just try something like "event.key == pygame.K_RIGHT:", python gives me an error saying there is no attribute 'key'. While I know it'd be more reasonable to choose above 2 codes over just "event.key == pygame.K_RIGHT:", I don't know why pygame would say the event doesn't have the attribute 'key' while when I simply check if event.type == pygame.KEYDOWN pygame will have no problem executing "event.key == pygame.K_RIGHT".
会不会是检查 event.type == pygame.KEYDOWN 是否真的为事件生成了key"属性?
Could it be that checking if event.type == pygame.KEYDOWN actually generates a 'key' attribute for the event?
推荐答案
并非每个事件都具有所有可能的属性.这就是为什么你必须首先检查事件的类型.
Not every event has all possbile attributes. that's why you have to check the type of the event first.
这里是每个事件类型的所有属性的列表:
Here's a list of all attributes for each event type:
QUIT none
ACTIVEEVENT gain, state
KEYDOWN unicode, key, mod
KEYUP key, mod
MOUSEMOTION pos, rel, buttons
MOUSEBUTTONUP pos, button
MOUSEBUTTONDOWN pos, button
JOYAXISMOTION joy, axis, value
JOYBALLMOTION joy, ball, rel
JOYHATMOTION joy, hat, value
JOYBUTTONUP joy, button
JOYBUTTONDOWN joy, button
VIDEORESIZE size, w, h
VIDEOEXPOSE none
USEREVENT code
如您所见,只有 KEYDOWN
和 KEYUP
事件具有 key
属性.
As you can see, only KEYDOWN
and KEYUP
events have the key
attribute.
这篇关于pygame KEYDOWN 事件和按键事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!