lordmauve / wasabi2d

Cutting-edge 2D game framework for Python
https://wasabi2d.readthedocs.io/
GNU Lesser General Public License v3.0
156 stars 26 forks source link

Question: how to decorate a method with @w2d.event ? #37

Closed shazz closed 4 years ago

shazz commented 4 years ago

Hi,

In my class, I added a method to manipulate my wasabi objects (class variables)

    @w2d.event
    def on_key_down(self, key):
        if key == keys.ESCAPE:
            quit()
        elif key == keys.UP:
            self.bike.pos = (self.bike.pos[0]+1, self.bike.pos[1])

but I got this error: AttributeError: 'Event' object has no attribute 'self'

Thanks!

lordmauve commented 4 years ago

Wasabi2d detects the parameters that a handler function takes and passes the attributes of the Pygame event object. So it cannot handle a method, because it doesn't know about self.

The event mapper could easily be adapted to accept classes and methods. Perhaps a method like

w2d.map_events(MyGameClass())
shazz commented 4 years ago

Yes, it would be great to support methods as a well organized game design will quickly require to define multiple classes of objects.

Else, if there is an explicit way to register a method as a callback for events, that would work too :) Decorators are nice but not mandatory, good to have both in my opinion.

lordmauve commented 4 years ago

The workaround is to create event hooks that dispatch to the current game class instance:

current_game = Game()

@w2d.event
def on_key_down(key):
    current_game.on_key_down(key)