Friday, October 2, 2015

State Machine AI

State machines are the easiest of all AI's to program. They are simple but that also makes their 'intelligence' simple. In a sense they are just glorified switch statements that get told what type of responses they have and then check versus whatever input they receive.

Now lets talk about state machines in a much less abstract form!
What you need to begin is a variable that keeps track of what state the AI is currently in. I prefer an Enum since you can name each state with a unique title, but you could also simply use an Int so long as you can keep track of which state is which number.
Next you have to set up a hierarchy or tree that your AI will check against to tell it what state it should be in. This hierarchy is one way to help define how 'smart' your AI is and how complex its actions are. For ease of an example lets say we're building an AI for capture the flag.
Something like this. Or something much, much bigger. Your choice.
Finally you need to simply set up a switch statement in the AI's update that checks against whichever state it is in and then provide the adequate response.
And that's it. State machine AI's are pretty simple and fun to make (at least I think so).
---
Now for some example code!

void AIUpdate()
{
    CurrentAIState = CheckDemStates();
    
    switch(CurrentAIState)
    {
        case AIState.Attacker:
            //Seek out the flag
            break;
        case AIState.Defender:
            //Cover our flag
            break;
        case AIState.Rescuer:
            //ZOMG, get our flag back!
            break;
    }
}
 
AIState CheckDemStates()
{
    if(//they got the flag)
    {
        if(//Rescuers > X)
        {
            return AIState.Attacker;
        }
        else
        {
            if(//Other teammates are closer)
            {
                return AIState.Attacker;
            }
            else
            {
                return AIState.Rescuer;
            }
        }
    }
    else
    {
        if(//Defenders > X)
        {
            return AIState.Attacker;
        }
        else
        {
            return AIState.Defender;
        }
    }
}

No comments:

Post a Comment