首页 > 解决方案 > pygame:通过 pygame.time.set_timer() 发送带有属性的自定义事件

问题描述

我在游戏中突出显示。除此之外,我想设置一个计时器来触发一个自定义事件,该事件告诉主驱动程序在 x 毫秒后删除这些突出显示。像这样:

REMOVE_HIGHLIGHT_EVENT = p.USEREVENT + 1

coords = (3, 5)  # the coordinates of the highlighted square

pygame.time.set_timer(p.event.Event(REMOVE_HIGHLIGHT_EVENT, square=coords).type, milliseconds=2000, once=True)

在主循环中:

while running:
    for e in pygame.event.get():
        ...
        if e.type == REMOVE_HIGHLIGHT_EVENT:
                removeHighlight(e.square)

但我越来越AttributeError: 'Event' object has no attribute 'square'

所以显然我不能以这种方式设置属性。我曾考虑过在表示事件类型的整数中编码我想给出的坐标,但这对我来说似乎真的很不合时宜。有没有更好的方法来传递这些信息?

提前致谢。

标签: pythonpygame

解决方案


你误解了它的pygame.time.set_timer()工作原理。该指令

pygame.time.set_timer(p.event.Event(REMOVE_HIGHLIGHT_EVENT, square=coords).type, milliseconds=2000, once=True)

没有任何意义。事实上,您正在创建一个无处可去的临时事件对象。您正在尝试发明一种不存在的功能。

您不能将自定义pygame.event.Event()对象附加到计时器事件。set_timer有 2 个参数,事件 id 和时间,但没有别的。请参阅Pygame 中的计时器
发布客户事件的唯一方法是pygame.event.post().


推荐阅读