python游戏开发keydown_pygame KEYDOWN事件和关键事件

本文探讨了使用Pygame处理键盘事件时遇到的一个问题:并非所有事件都有'key'属性。作者对比了不同方式检查按键事件的有效性和语法正确性,并解释了为何需要先检查事件类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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?

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值