I'm writing a little game, and the game has a State
class to keep track of game state. The State
class is only intended to be modifiable by Command
s (command pattern). The State
class includes lists of other classes - e.g. a Faction
class, which contains members like resources, a list of owned Unit
s, etc.
How can I make the deep innards of State
readable from other classes, without also leaking writable references inside of State
itself?
Currently, I have specialized getters like State.GetOwnerOfUnitAtLocation(x)
, which only return safe values (int factionid
etc.), but I am beginning to need a lot of these, and the class is getting really unwieldy. I would prefer to have those methods in more appropriate locations (Map.Units.GetOwner(x)
or something), but I don't know how to expose the internals of State
to other classes in a safe way.
Relatedly, Command
is an interface that currently lives inside of the State
class, along with all the actual commands that implement it, so that it can modify private members of State
. Is there a better way to implement this?
Edit: A selection of code from State
to illustrate the first issue:
public partial class State
{
public int Turn {get; private set;} = 1;
private Dictionary<Vector2, FactionsMgr.Faction> _unit_map = new Dictionary<Vector2, FactionsMgr.Faction>();
public int GetUnitRemainingMobility(Vector2 pos)
{
if (IsUnitAt(pos))
{
FactionsMgr.Faction owner = _unit_map[pos];
int taken_movement = owner.units[pos]._taken_movement;
int max_mobility = UnitsMgr.GetMaxMobility(owner.units[pos].type);
return max_mobility - taken_movement;
}
else
{
GD.Print("Warning: GetUnitRemainingMobility asked for unknown unit: ", pos);
return -1;
}
}
}