Search code examples
pythonpygame

pygame: send custom event with attributes via pygame.time.set_timer()


I am blitting highlightings in a game. Along with that I want to set a timer for firing a custom event which tells the main driver to remove those highlightings after x milliseconds. like so:

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)

and in the main loop:

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

But I am getting AttributeError: 'Event' object has no attribute 'square'.

So apparently I cannot set the attribute this way. I have thought about encoding the coordinates I want to give along in the integer representing the event type, but that seems really unpythonic to me. Is there a better way to pass this information along?

Thanks in advance.


Solution

  • You've misunderstood how pygame.time.set_timer() works. The instruction

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

    doesn't make any sense. In fact, you are creating a temporary event object that goes nowhere. You're trying to invent a feature that doesn't exist.

    You cannot attach a custom pygame.event.Event() object to a timer event. set_timer has 2 arguments, the event id and the time, but nothing else. See Timer in Pygame.
    The only way to post a customer event is pygame.event.post().