Okay: I'm fairly new to C++ and static languages on a whole. Coming from years of ruby (and other dynamic languages) I don't know if this is possible.
I've been making a game state system for... well a game. I want to make the system easy for me to cut and paste into other games without any (or very few) changes.
The two things I am wanting to improve are the way in which states switch and the way in which state pointers are held.
There could be any number of states, but there will always be at least 2 to 3 states active in memory.
Ugliness No 1.
Currently I have a state manager class with something like this in it:
void StateManager::changeState(StateID nextStateID)
{
// UNFOCUS THE CURRENT STATE //
if (currentState())
{
currentState()->onUnFocus();
// DESTROY THE STATE IF IT WANTS IT //
if(currentState()->isDestroyedOnUnFocus()) {
destroyCurrentState();
}
}
if (m_GameStates[nextStateID]) {
// SWITCH TO NEXT STATE //
setCurrentState(nextStateID);
}
else
{
// CREATE NEW STATE //
switch (nextStateID)
{
case MainMenuStateID:
m_GameStates[MainMenuStateID] = new MainMenuState;
break;
case GameStateID:
m_GameStates[MainMenuStateID] = new GameStates;
break;
};
setCurrentState(nextStateID);
}
// FOCUS NEXT STATE //
currentState()->onFocus();
}
This approach works but I don't feel it's very nice.
Is it possible to pass a type? And then call new on it?
new NextGameState; // Whatever type that may be.
Can poloymophism help here? All States are derived from a class State
.
Ugliness No 2.
Another thing I think needs some improvement is the way I've been storing the states.
State* m_GameStates[MaxNumberOfStates];
All the states are initialized to NULL, so I can test if a state is there, and if not it creates one when needed.
It works well as I can call the current state:
m_GameStates[m_CurrentState];
However, I don't like this for two reasons. It seems a bit of a waste having an array full of NULL pointers when there will only be 2 or 3 pointers active at any one time. [Editor's note: what is the second reason?]
I thought about shifting this into a vector_ptr
, but didn't as it would create extra complications with checking to see if a state exists. And the vector seems to reinforce Ugliness No 1. as I need to have a list to check each state.
Any advice or direction appreciated.
Thanks, Phil.