语法解释是pygame.event.get()字典?

2024-05-29 07:11:30 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的解释:pygame.event.get()返回排队事件的字典,event是字典中的一个条目。字典中的每个事件都有一个类型和一个键(以及其他属性),这是我们在if语句中比较的

pygame.QUIT和pygame.KEYDOWN是事件类型 pygame.K_RIGHT是一个事件密钥

只有当这些事件在队列中时,才会执行相应的代码

        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    snake.move_snake_right()

这类似于在超市买蔬菜:有一排食品杂货在等着你,每一种都有一种类型、重量、保质期等。你会仔细检查每一种,只有当它是根类蔬菜,叫做防风草时,你才会把它捡起来

有人对字典有更好的解释吗

还有,你为什么把字典叫做

Dictionary[Entry]

但这是你的电话

pygame.event.get().key

?


Tags: keyrightevent类型getif字典属性
2条回答

不,它不是一本字典,而是一个iterable(一个列表、元组或你可以循环使用的东西)

关于词典

字典以键和值对的形式存储

比如说

person = {"name": "Mickey", "age": 44}

访问值

要访问这些值(Mickey或44),您需要指定正确的键:

person["name"]

想象一下,1000间房间都锁着门。要进入某个房间的任何东西,你首先需要一把钥匙(它可以打开门)

获取所有键的列表

您可以像这样检索人员密钥列表

person.keys()

您可以像这样迭代/循环它:

for k in person.keys():
    print(person[k])

想象一下,你有能力拔出所有钥匙并指示每个钥匙打开正确的门

This is my explanation: pygame.event.get() returns a dictionary of queued events and event is an entry in the dictionary.

否。pygame.event.get()返回一个列表。您可以自己检查源代码here

Each event in the dictionary has a type and a key (amongst other attributes), and this is what we compare in the if statements.

每个事件都有一个type,但不是每个事件都有一个key

以下是每个事件类型的所有属性列表:

QUIT              none
ACTIVEEVENT       gain, state
KEYDOWN           key, mod, unicode, scancode
KEYUP             key, mod
MOUSEMOTION       pos, rel, buttons
MOUSEBUTTONUP     pos, button
MOUSEBUTTONDOWN   pos, button
JOYAXISMOTION     joy (deprecated), instance_id, axis, value
JOYBALLMOTION     joy (deprecated), instance_id, ball, rel
JOYHATMOTION      joy (deprecated), instance_id, hat, value
JOYBUTTONUP       joy (deprecated), instance_id, button
JOYBUTTONDOWN     joy (deprecated), instance_id, button
VIDEORESIZE       size, w, h
VIDEOEXPOSE       none
USEREVENT         code

引用docs的话:

All pygame.event.EventType instances contain an event type identifier and attributes specific to that event type. The event type identifier is accessible as the pygame.event.EventType.type property.

我建议您阅读链接文档,因为它解释了您需要了解的所有事件


Only if those events are in the queue will the corresponding code be executed

    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                snake.move_snake_right()

将为pygame.event.get()返回的每个事件执行行if event.type == pygame.KEYDOWN:

下一行(if event.key == pygame.K_RIGHT:)将仅在前一行中的if表达式返回truthy值时执行,这仅在我们当前检查的事件具有等于pygame.KEYDOWNtype属性时才会发生

如果key属性等于pygame.K_RIGHT,则只执行snake.move_snake_right()

那与词典无关。这只是循环使用forif语句的方式

相关问题 更多 >

    热门问题