StateMachine
George Rowland

George Rowland

Simple AI

This week I started implementing the simplest of AI opponents. This implementation turned out to be more complicated than I had imagined. We will take a look into what scenarios I considered for a functional AI and how I implemented them in this game.

Everything I know about AI comes from the book by Mat Buckland, Programming Game AI by Example (link below). If you wish to know more about programming AI I strongly suggest you purchase this book.

Currently, the two behaviors required to create a functional AI are mining and attacking. I choose to implement my AI using a finite state machine (FSM). I will share my way to do this here, but there are many ways to implement an FSM in your project.

I like to use a class to represent my states. In my opinion, this keeps the logic clean and concise. Here is the base class I use for my state machine.

     public class State
     {
         public virtual void Enter() {}
         public virtual void Update() {}
         public virtual void FixedUpdate() {}
         public virtual void Exit() {}
     }

When creating new behaviors I inherit from this class. I can then override the functions defined in the base class creating unique behaviors. Inheriting from a base in this manner simplifies the AI manager. The manager no longer will need to know about each type of state. It can use the base State class to call the methods on any inherited state.

Here is an example of a class that implements the base State class.


    public class Miner : State
    {
        public override void Enter() 
        {
            //Setup mine specific variables or goals
        }
        public override void Update() 
        {
            //Perform per frame decisions
            //Perform checks to determine if state should change 
        }
        public override void FixedUpdate() 
        {
            //Perform physics operations such as movement 
        }
        public override void Exit() 
        {
            //Clean up state for transition to next state
        }
    }

As you can see the methods defined in the base State class are overridden. Using this logic you can perform per state transitions by checking for certain conditions. Here is a diagram of my state machine.

This is just the beginning of making my AI for this game. Next week we will take a look at managing the states.

Share this post