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'

因此,显然我无法以这种方式设置属性。我曾考虑过要对表示事件类型的整数中的坐标进行编码,但这对我来说似乎很不合逻辑。有没有更好的方法来传递这些信息?

谢谢。

解决方法

您误解了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和时间,但没有其他参数。参见Timer in Pygame
发布客户事件的唯一方法是pygame.event.post()