Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
903 views
in Technique[技术] by (71.8m points)

python - pygame KEYDOWN event and key events

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

works as well.

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".

Could it be that checking if event.type == pygame.KEYDOWN actually generates a 'key' attribute for the event?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

As you can see, only KEYDOWN and KEYUP events have the key attribute.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...