# Using Booleans to Manage State

I'm in the middle of writing my own little bullet shooter game much in the style of Touhou. Everything works fine so far but I'm disliking certain aspects of my code. Take this function for showing and unshowing the title screen:

    private function runIntro() : void
{
if (introFadeInTitle_ && aliceIntroTxt.alpha < 1)
aliceIntroTxt.alpha += 0.02;
{
var timer : Timer = new Timer(1000);
timer.stop();

});
timer.start();

}
else if (introFadeInBtns_ && startBtn.alpha < 1)
{
startBtn.alpha   += 0.02;
optionsBtn.alpha += 0.02;
}
{

}

if (introFadeOutBtns_ && startBtn.alpha > 0)
{
startBtn.alpha   -= 0.02;
optionsBtn.alpha -= 0.02;
}
{
var timer : Timer = new Timer(500);
timer.stop();

});
timer.start();

}
else if (introFadeOutTitle_ && aliceIntroTxt.alpha > 0)
aliceIntroTxt.alpha -= 0.02;
{
var timer : Timer = new Timer(500);
timer.stop();

});
timer.start();

}
else if (introFadeOutBg_ && introBg.alpha > 0)
introBg.alpha -= 0.02;
{

gameState = GameState.RUNNING;
}
}


At a glance, it's just a bunch of if-else-if statements that check whether or not a given object has faded out and what the current state of the animation is. I feel that this if-else-if chain is alright for a rather short function like this, but I do have more complicated states that I wish to show (for example a ready-set-go splash before the fight begins) that would just balloon this kind of structure into an unholy mess.

What is the best way to deal with this code?

If ActionScript supports enums use an enum instead of the many booleans. If not, use a string with one constant for every state. It's also better than the booleans. For example:

...
else if (state == FADE_INT_ASDF) {
state = CODE_OF_NEXT_STATE;
}
...


If the logic was more complicated it would be worth implementing the State pattern.

If the booleans were replaced to an enum/string constants you can create a new setTimer function which could remove some code duplication:

private function setTimer(int timeout, IntroState/String newState) : void {
var timer : Timer = new Timer(timeout);
timer.stop();
state = newState;
});
timer.start();
}

• Wouldn't state pattern be an over kill here .
– NRS
Nov 14, 2011 at 6:41