2

I am working on setting up a game in pygame and I've noticed that there isn't really a lot available for event handling. Basically, pygame has a queue of events that you can pull and iterate through every frame. It's easy enough to do, but I feel like it makes for messy code and a lot of copy-pasted logic.

I created a class that would keep a list of all the event handlers and put a class method on it to iterate through the queue of events and call any relevant handlers. I also made a decorator for my event handlers to register them in a clean way. My problem now is that I don't have a good way of removing my event handlers when they are no longer in scope.

Is there a good way in python to remove my handlers once there is a change in context? It seems like passing the list of events down to every component that's currently active is messy, but keeping track of what handlers are still in scope would also be messy. Is a better way to do this?

1 Answer 1

1

You can maintain a dictionary of event handlers and remove the necessary handlers as context switches. The keys for each context's handlers can be stored in separate lists, which can be used for creating or destroying them in turn.
I use this method to maintain my widgets and sprites.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.