Question

I have been trying to get my head around this problem for the last week and can't seem to find a solution that doesn't either require a singleton or tight coupling. I am developing a 3D space game, an early demo of which is here...
www.sugarspook.com/darkmatters/demo.html
... and I'm getting to the point of adding Missions which the player will be able to select from the heads up display (Hud class).

The structure of the game is:
The Game class contains the Hud and the ObjectsList class.
The ObjectsList class contains various game Objects, including the Player, the various kinds of ship, planets, and Orbitals (space stations).
Missions get instantiated when the Player gets to within a certain distance of an Orbital.
Missions are added to a MissionsList class, itself within the ObjectsList.
Missions can become unavailable and expire without warning (as if they are selected by another pilot) so the list displayed on the Hud is dynamic and updated regularly.
Previously I've had the Missions dispatching events up to Game which in turn informs Hud of the change. This seems a little clunky to me, as there are various deeper 'levels' to the Hud that the information needs to be passed down to. I end up with a lot of the same functions all the way down the chain.

The solution I was thinking of involved injecting a reference to the MissionsList class into the Hud, enabling it to listen for updates from the Missonslist. I've heard that it's bad practise to mix the state of something with its display, but I don't see how else to get the 'live' list of Missions to the Hud. In contrast, if the Hud contains only display details without reference to the Mission object that generated those details, when a player selects a Mission from the Hud how can I determine which Mission has been chosen? Is tight coupling in this case OK? Or should I use a singleton to communicate to the Hud? If there is something fundamentally wrong with anything I'm suggesting I welcome being told what that is and what is the best solution. Thanks.

Was it helpful?

Solution

Well the simple answer is why not couple via an intermediate interface?

interface IMissionList
{
    ObservableCollection<IMission> Missions{get;}
}

Then in your Dependency Injection bind that to something that can resolve to a instance, singleton or constant or etc...

then inject it into your Hud's constructor

Hud(IMissionList missionList){}

Now you are loosely coupled to a contract, the implementation of-which can be changed at any point, so long as the implementation adheres to the contract. Also, due to injection your Hud only has to concern it self with using IMissionList rather than also finding it.

[Edit] Sorry, this is C#, but hopefully the idea is of use. See for actionscript interfaces and Dependency Injection for Actionscript

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top