Skip to content
Advertisement

Pygame: how to write event-loop polymorphically

I’m some-what new to pygame, and while trying to get back into it, I found the advice “replace your conditionals with polymorphism.” Most pygame tutorials recommend using the “for event in pygame.event.get()” loop and then using a conditional to determine if any particular event has occured.

1: How do I write that code using a polymorphic function 2: Is it worth it to re-factor the code, or just leave the conditional as-is

Below is what most tutorials recommend

JavaScript

Below is how I want to approach this

JavaScript

Advertisement

Answer

In pygame the event type is an enumerator constant. You have to map this constant to the corresponding class. Use a dictionary:

JavaScript

Of course, the dictionary can be generated or even extended dynamically, too. (e.g.: eventhandler[pygame.MOUSEBUTTONDOWN] = MouseDown)

The events must be delegated to the appropriate actions assigned in the event handler:

JavaScript

Example:

JavaScript

For a more general approach, the handlers can be managed in a list. So multiple actions can be associated to an event type:

JavaScript
JavaScript

Example:

JavaScript

Or even a combination of both answers (see answer of @AKX):

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement