After mentioning MVC a few times, I've stumbled, like many others on Sandy Brown's pygame guide. The guide contains three parts: MVC for single-player games, using Twisted for multiplayer games, and GUI widgets. You can also find the code on github.
Event Manager
The problem: Multiple heterogeneous components, say the network controller and the model, are interested in an event such as a user click from the input controller. The code in the input controller would look like this:
nw_ctrler.send(click)
model.perform(click)
If a new component, say the audio output, becomes interested in user click events, then the input controller code has to be modified. This is not ideal.
Two design patterns exist to help us here: the observer and the mediator. The differences between the two are very subtle , but combining the two allows 1) the possibility to add or remove components from the system without touching the other components, and 2) a component to notify all the others through an intermediate. In our case, an Event Manager is the intermediate receiving events from all components, and notifying those interested in that event. See the diagrams below from Sandy Brown's guide.
Improvements
A
stackoverflow post
remarked that
isinstance()
is not quite
Pythonic
: instead of using isinstance()
, one should appropriately use
duck-typing.
Moreover, listeners should tell the Event Manager which events they are interested in, so that they are not notified for all of the events.