Network: WoW Gold | WoW Accounts | MPS Games | FPSowned
MMOwned - World of Warcraft Exploits, Hacks, Bots and Guides
Homepage »      Register »      Hall of Fame »      Ranks And Awards »      Advertise »      Marketplace »
 
Sign up



Do you like this excellent information? Then Donate HERE to remove ads and support the MMOwned community.


Go Back   MMOwned - World of Warcraft Exploits, Hacks, Bots and Guides > Discussions > Programming

Programming Discuss all your programming needs here.

Reply
 
LinkBack Thread Tools
  #1  
Old 05-13-2009
Apoc's Avatar
Apoc is offline.
MMOwned WebDev
Legendary User
  
 
Join Date: Jan 2008
Posts: 2,269
Nominated 8 Times in 4 Posts
Reputation: 1093
Points: 28,488, Level: 24
Points: 28,488, Level: 24 Points: 28,488, Level: 24 Points: 28,488, Level: 24
Level up: 76%, 412 Points needed
Level up: 76% Level up: 76% Level up: 76%
Activity: 26.1%
Activity: 26.1% Activity: 26.1% Activity: 26.1%

[Bot Developers]A simple, but effective FSM for your bots.

First things first; what is an FSM? (Finite State Machine)

Quote:
Originally Posted by Wikipedia
A finite state machine (FSM) or finite state automaton (plural: automata) or simply a state machine, is a model of behavior composed of a finite number of states, transitions between those states, and actions. A finite state machine is an abstract model of a machine with a primitive internal memory.

Finite-state machine - Wikipedia, the free encyclopedia
In other words, it's a way to control logic flow for automated tasks. (E.g; bots)

I'm writing this post for two reasons;

1) People tend to have a hard time implementing an FSM in their bots, or other programs, due to 'complexity', even though it's actually a very simple concept once seen.

2) Hopefully, this will progress current bot writers usage of logic, into something more fluid, and reliable.


An FSM consists of two main parts; The engine, and the states. (All source code will be posted at the bottom)

The Engine

An FSM engine is actually something incredibly simple, but most people make it far too complex, and hard to maintain due to either lack of knowledge on how to properly implement one, or the thought that 'it has to be this way to work properly'. The engine I'm showing you is, by no means, not the only implementation of an FSM. It is however, the most simplistic, and easiest to maintain out of all the ones I've seen. (There may be simpler ones, but I have not come across them.)

In essence, all the engine needs to do is the following:
  1. Determine which states there are to run.
  2. Determine the priority in which the states should run. (E.g; Combat before Resting)
  3. Determine if the state needs to run
  4. If the state needs to run, let the state do it's predefined logic.
  5. Otherwise, move on to the next state.

It's not nearly as complicated as it looks.

The State(s)

A state is just what the name implies. 'The state of the world (or logic system) that we are currently in, and where we would like it to be.'

Ok, so maybe the name isn't quite as 'literal' as it seems.

In short terms, a state really consists of 3 things.
  1. A priority. (We'll just use a numeric value. int.MinValue - int.MaxValue)
  2. A Boolean statement determining if the state needs to be run. (I.E; execute it's logic.)
  3. Execute the logic that is predefined for that state.

In our example, we'll implement a very simple FSM, including 2-3 states, to give an example of how it will work.

First things first, we need to create the main State class, that all other states will inherit from. (I'll explain why we do this first, rather than the engine, later)

We'll start off with the usual declarations:

Code:
namespace FiniteStateMachine
{
    public abstract class State
    {
    }
}
This is an abstract class for 1 reason: We don't want developers/users creating an instance of the base 'State' class itself, as it will never hold any logic whatsoever. (Also note: We can easily create 'State's as an interface, but I choose not to. You'll see why below.)

Now, we'll 'create' the 3 main pieces of the State class that make it useful for an FSM. (Get ready, this part is really difficult...)

Code:
namespace FiniteStateMachine
{
    public abstract class State
    {
        public abstract int Priority { get; }

        public abstract bool NeedToRun { get; }

        public abstract void Run();
    }
}
Yep. That's pretty much it. We just covered the 3 basic parts of a State in terms of an FSM implementation.

Priority is self explanatory. (You can change it to a uint if you want the lowest priority to be 0, however, it really doesn't matter, unless you like 'high priority' to be low numbers.)

NeedToRun again is self explanatory. Do we need to run this state? If so, return true, if not, return false.

Run() is... well... you get the idea.

The way it is right now, is perfectly viable. However, I'm a lazy programmer, so I tend to avoid doing any messy sorting logic. .NET provides an interface called 'IComparable<T>' and 'IComparer<T>'. It allows us to implement a 'sorting' function in our classes, to make sorting easier. (E.g; List<T>().Sort(); ) We need both interfaces implemented due to how different collections use the comparing methods. (Some use CompareTo, others use Compare.)

Since we only really want to 'sort' based on priority (explained in the engine code section), we'll just compare the Priority properties of the states.

Code:
namespace FiniteStateMachine
{
    public abstract class State : IComparable<State>, IComparer<State>
    {
        public abstract int Priority { get; }

        public abstract bool NeedToRun { get; }

        public abstract void Run();

        public int CompareTo(State other)
        {
            // We want the highest first.
            // int, by default, chooses the lowest to be sorted
            // at the bottom of the list. We want the opposite.
            return -Priority.CompareTo(other.Priority);
        }

        public int Compare(State x, State y)
        {
            return -x.Priority.CompareTo(y.Priority);
        }
    }
}
It really is that simple. Whenever we put a collection of states into a List<T> (as we will later), if we use the .Sort() method, it will sort the states by priority. Highest to lowest.

And that's pretty much it for the State class.

On to the engine!

Code:
namespace FiniteStateMachine
{
    public class Engine
    {
    }
}
Nothing special here, just a normal class. It's not abstract for one main reason: We ARE going to allow developers to override the Pulse() method we'll be creating, however, we also want to be able to use this class itself, as an FSM. This leaves quite a bit of customization.

The following is just some quick and dirty stuff, if you don't understand it, you should go back to the basics.

Code:
using System.Collections.Generic;

namespace FiniteStateMachine
{
    public class Engine
    {
        public List<State> States { get; private set; }

        public Engine()
        {
            States = new List<State>();
        }

        public virtual void Pulse()
        {
            
        }
    }
}
Fairly simple. We just created a List to hold all of our states, and a simple 'Pulse' method that will actually be carrying out our logic system.

Don't be alarmed: This next part is really simple as well.

Code:
namespace FiniteStateMachine
{
    public class Engine
    {
        public List<State> States { get; private set; }

        public Engine()
        {
            States = new List<State>();

            // Remember: We implemented the IComparer, and IComparable
            // interfaces on the State class!
            States.Sort();
        }

        public virtual void Pulse()
        {
            // This starts at the highest priority state,
            // and iterates its way to the lowest priority.
            foreach (State state in States)
            {
                if (state.NeedToRun)
                {
                    state.Run();
                    // Break out of the iteration,
                    // as we found a state that has run.
                    // We don't want to run any more states
                    // this time around.
                    break;
                }
            }
        }
    }
}
That's it. Your whole logic system in a single method. Of course, we're leaving out some basic things, (and some more advanced stuff that I'll show you in a minute) like how to actually 'pulse' the engine, or how to load in the states we want.

Now, lets add a simple method to create a thread, that runs our FSM engine. For shits and giggles, lets base it off of FPS.

Code:
using System.Collections.Generic;
using System.Threading;

namespace FiniteStateMachine
{
    public class Engine
    {
        private Thread _workerThread;

        public Engine()
        {
            States = new List<State>();

            // Remember: We implemented the IComparer, and IComparable
            // interfaces on the State class!
            States.Sort();
        }

        public List<State> States { get; private set; }

        public bool Running { get; private set; }

        public virtual void Pulse()
        {
            // This starts at the highest priority state,
            // and iterates its way to the lowest priority.
            foreach (State state in States)
            {
                if (state.NeedToRun)
                {
                    state.Run();
                    // Break out of the iteration,
                    // as we found a state that has run.
                    // We don't want to run any more states
                    // this time around.
                    break;
                }
            }
        }

        public void StartEngine(byte framesPerSecond)
        {
            // We want to round a bit here.
            int sleepTime = 1000 / framesPerSecond;

            // Leave it as a background thread. This CAN trail off
            // as the program exits, without any issues really.
            _workerThread = new Thread(Run) {IsBackground = true};
            _workerThread.Start(sleepTime);
        }

        private void Run(object sleepTime)
        {
            try
            {
                // This will immitate a games FPS
                // and attempt to 'pulse' each frame
                while (Running)
                {
                    Pulse();
                    // Sleep for a 'frame'
                    Thread.Sleep((int) sleepTime);
                }
            }
            finally
            {
                // If we exit due to some exception,
                // that isn't caught elsewhere,
                // we need to make sure we set the Running
                // property to false, to avoid confusion,
                // and other bugs.
                Running = false;
            }
        }

        public void StopEngine()
        {
            if (!Running)
            {
                // Nothing to do.
                return;
            }
            if (_workerThread.IsAlive)
            {
                _workerThread.Abort();
            }
            // Clear out the thread object.
            _workerThread = null;
            // Make sure we let everyone know, we're not running anymore!
            Running = false;
        }
    }
}
You'll notice; I create a new property 'Running' which is just a flag to let everyone (and ourselves) know if the FSM is actually running or not. I've also created the StartEngine, StopEngine, and Run methods. All of them are self explanatory, and the comments speak for themselves.

Ok, so now we've got a fully working FSM. Our only problem is, how to load the states into our list?

We have two options:
  1. Keep a running list of states we're allowed to load, and add them via States.Add(new StateDescendant());
  2. Load the via reflection, which gives us the ability to load multiple different DLLs, and not have to worry about maintaining a list of states to load.

Obviously we're going with #2.

Now, the following method is far from 'basic' stuff. It actually requires an understand of how late binding works, etc. Which is outside the scope of this tutorial.

Code:
        public void LoadStates(string assemblyPath)
        {
            // Make sure we actually have a path to work with.
            if (string.IsNullOrEmpty(assemblyPath))
            {
                return;
            }

            // Make sure the file exists.
            if (!File.Exists(assemblyPath))
            {
                return;
            }
            try
            {
                // Load the assembly, and get the types contained
                // within it.
                Assembly asm = Assembly.LoadFrom(assemblyPath);
                Type[] types = asm.GetTypes();

                foreach (Type type in types)
                {
                    // Here's some fairly simple stuff.
                    if (type.IsClass && type.IsSubclassOf(typeof(State)))
                    {
                        // Create the State using the Activator class.
                        State tempState = (State) Activator.CreateInstance(type);
                        // Make sure we're not using two of the same state.
                        // (That would be bad!)
                        if (!States.Contains(tempState))
                        {
                            States.Add(tempState);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // Feel free to change this to some other logging method.
                Debug.WriteLine(ex.Message, "Exceptions");
            }
        }
Basically, you pass it a path to a DLL (or exe) and it will attempt to load any States that are defined in it. Keep in mind; it will NOT load any classes that are not public. This is how .NET is, and no, you cannot get around it.

Now that we've added some things, lets make a few simplistic states and give it a go.

Code:
using System;

namespace FiniteStateMachine
{
    public class StateIdle : State
    {
        public override int Priority
        {
            // Idle obviously has the lowest value,
            // it just means we have nothing to do!
            get { return int.MinValue; }
        }

        public override bool NeedToRun
        {
            // Always run this one.
            get { return true; }
        }

        public override void Run()
        {
            Console.WriteLine("Idling....");
        }
    }
}
Code:
using System;

namespace FiniteStateMachine
{
    public class StateNumberToHigh : State
    {
        private int number = 0;

        public override int Priority
        {
            get { return 5; }
        }

        public override bool NeedToRun
        {
            get { return number++ >= 10; }
        }

        public override void Run()
        {
            Console.WriteLine("Lowering the number by 20!");
            number -= 20;
        }
    }
}
And finally, we'll just create a basic console app to do the rest of the work.

Code:
using System;
using FiniteStateMachine;

namespace FSM_Tester
{
    class Program
    {
        static void Main(string[] args)
        {
            Engine engine = new Engine();
            // Just load the actual DLL for now.
            engine.LoadStates("FiniteStateMachine.dll");
            engine.States.Sort();
            Console.WriteLine("Total states: " + engine.States.Count);
            foreach (State state in engine.States)
            {
                Console.WriteLine("State loaded: " + state.GetType().Name);
            }

            // Run the engine! (The very slow engine for now...)
            engine.StartEngine(3);

            Console.ReadLine();
        }
    }
}
Nothing special really. Just prints out the loaded states, and the names.

And there you have it, an incredibly extensible FSM implementation you can use for your bots, or other automated tasks.

Source code download:
Filebeam - Free Fast File Hosting
__________________
[Only registered and activated users can see links. ]

Last edited by Apoc; 05-13-2009 at 06:55 PM.
Reply With Quote


Donate to remove ads, get your "DONATOR title, and get access to the MMOwned community's elite Shoutbawx.

  #2  
Old 05-13-2009
ugkbunb is offline.
Site n00b.. (A leecher if I've been here for more than a month and can't earn 5 rep)
  
 
Join Date: May 2008
Posts: 16
Reputation: 3
Points: 379, Level: 1
Points: 379, Level: 1 Points: 379, Level: 1 Points: 379, Level: 1
Level up: 95%, 21 Points needed
Level up: 95% Level up: 95% Level up: 95%
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%

thank you for the post
Reply With Quote
  #3  
Old 05-14-2009
Nesox's Avatar
Nesox is offline.
MaiN's Biatch
Legendary User
  
 
Join Date: Mar 2007
Location: Managed Heap
Posts: 1,247
Nominated 47 Times in 4 Posts
Nominated TOTM/W Award(s): 2
Reputation: 767
Points: 48,576, Level: 33
Points: 48,576, Level: 33 Points: 48,576, Level: 33 Points: 48,576, Level: 33
Level up: 17%, 2,824 Points needed
Level up: 17% Level up: 17% Level up: 17%
Activity: 5.0%
Activity: 5.0% Activity: 5.0% Activity: 5.0%

Very nice Apoc. Might implement this
__________________
[Only registered and activated users can see links. ]

Warrior 60 | Druid 60 | Shaman 67 | Rogue 68 | Warlock 80 | Mage 80 | Hunter 80 | Death-knight 80 | Priest 80 | Paladin 80
Reply With Quote
  #4  
Old 05-14-2009
BottMaster's Avatar
BottMaster is offline.
Master Sergeant
  
 
Join Date: Jan 2009
Location: Upside Down
Posts: 88
Reputation: 14
Points: 284, Level: 1
Points: 284, Level: 1 Points: 284, Level: 1 Points: 284, Level: 1
Level up: 72%, 116 Points needed
Level up: 72% Level up: 72% Level up: 72%
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
Absolutely a great post. Thank you so much.
Reply With Quote
  #5  
Old 05-14-2009
H4wker is offline.
Sergeant Major
  
 
Join Date: Jan 2009
Posts: 175
Reputation: 13
Points: 898, Level: 1
Points: 898, Level: 1 Points: 898, Level: 1 Points: 898, Level: 1
Level up: 99%, 2 Points needed
Level up: 99% Level up: 99% Level up: 99%
Activity: 3.0%
Activity: 3.0% Activity: 3.0% Activity: 3.0%

Superb. Thanks.
Reply With Quote
  #6  
Old 05-14-2009
SKU's Avatar
SKU is offline.
Contributor
  
 
Join Date: May 2007
Location: Schockiland
Posts: 412
Reputation: 144
Points: 3,529, Level: 5
Points: 3,529, Level: 5 Points: 3,529, Level: 5 Points: 3,529, Level: 5
Level up: 92%, 71 Points needed
Level up: 92% Level up: 92% Level up: 92%
Activity: 1.2%
Activity: 1.2% Activity: 1.2% Activity: 1.2%

Thanks

FILLAR
__________________
Reply With Quote
  #7  
Old 05-14-2009
Robske's Avatar
Robske is offline.
Contributor
  
 
Join Date: May 2007
Location: Dragon Shores
Posts: 773
Reputation: 180
Points: 4,156, Level: 6
Points: 4,156, Level: 6 Points: 4,156, Level: 6 Points: 4,156, Level: 6
Level up: 62%, 344 Points needed
Level up: 62% Level up: 62% Level up: 62%
Activity: 6.1%
Activity: 6.1% Activity: 6.1% Activity: 6.1%

Incredible, thanks
__________________
“First learn computer science and all the theory. Next develop a programming style. Then forget all that and just hack.” -(George Carrette)
Reply With Quote
  #8  
Old 05-14-2009
dekz is offline.
Sergeant
  
 
Join Date: Jan 2008
Location: Brisbane, Australia
Posts: 36
Reputation: 5
Points: 660, Level: 1
Points: 660, Level: 1 Points: 660, Level: 1 Points: 660, Level: 1
Level up: 52%, 240 Points needed
Level up: 52% Level up: 52% Level up: 52%
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%

great read thanks
Reply With Quote
  #9  
Old 05-15-2009
SKU's Avatar
SKU is offline.
Contributor
  
 
Join Date: May 2007
Location: Schockiland
Posts: 412
Reputation: 144
Points: 3,529, Level: 5
Points: 3,529, Level: 5 Points: 3,529, Level: 5 Points: 3,529, Level: 5
Level up: 92%, 71 Points needed
Level up: 92% Level up: 92% Level up: 92%
Activity: 1.2%
Activity: 1.2% Activity: 1.2% Activity: 1.2%

Can't believe how fluent the bot works now with this implementation of a FSM. Pulsing every endscene (yes, overkill 4tw), no lag at all, and a very easy way to add / change the bot logic. Thanks again.
__________________
Reply With Quote
  #10  
Old 05-15-2009
WinRawr's Avatar
WinRawr is offline.
Knight-Lieutenant
  
 
Join Date: Mar 2007
Posts: 293
Reputation: 57
Points: 2,882, Level: 5
Points: 2,882, Level: 5 Points: 2,882, Level: 5 Points: 2,882, Level: 5
Level up: 11%, 718 Points needed
Level up: 11% Level up: 11% Level up: 11%
Activity: 6.4%
Activity: 6.4% Activity: 6.4% Activity: 6.4%

Nice post Apoc, Altho i'm not using it (yet?). Thanks
__________________

Reply With Quote
  #11  
Old 05-16-2009
Apoc's Avatar
Apoc is offline.
MMOwned WebDev
Legendary User
  
 
Join Date: Jan 2008
Posts: 2,269
Nominated 8 Times in 4 Posts
Reputation: 1093
Points: 28,488, Level: 24
Points: 28,488, Level: 24 Points: 28,488, Level: 24 Points: 28,488, Level: 24
Level up: 76%, 412 Points needed
Level up: 76% Level up: 76% Level up: 76%
Activity: 26.1%
Activity: 26.1% Activity: 26.1% Activity: 26.1%

Quote:
Originally Posted by SKU View Post
Can't believe how fluent the bot works now with this implementation of a FSM. Pulsing every endscene (yes, overkill 4tw), no lag at all, and a very easy way to add / change the bot logic. Thanks again.
That's the whole point.

I've seen A LOT of bots implement an FSM assuming they need to use enums to represent what state they're in. There's absolutely no need to, and it really hurts extendability, and much more, maintainability.

Isn't it easier to just go to the class State<name> instead of searching through a function that can easily be 700+ lines long?

Also, if you want to have the FSM pulse only every n frames, it's a simple addition.

Code:
        public Engine(int pulseFrames):this()
        {
            PulseFrames = pulseFrames;
        }

        public ulong FrameCount { get; private set; }
        public int PulseFrames { get; set; }
        public virtual void Pulse()
        {
            FrameCount++;
            if (PulseFrames % (int) FrameCount != 0)
            {
                return;
            }
            // This starts at the highest priority state,
            // and iterates its way to the lowest priority.
            foreach (State state in States)
            {
                if (state.NeedToRun)
                {
                    state.Run();
                    // Break out of the iteration,
                    // as we found a state that has run.
                    // We don't want to run any more states
                    // this time around.
                    break;
                }
            }
        }
__________________
[Only registered and activated users can see links. ]
Reply With Quote
  #12  
Old 05-16-2009
Apoc's Avatar
Apoc is offline.
MMOwned WebDev
Legendary User
  
 
Join Date: Jan 2008
Posts: 2,269
Nominated 8 Times in 4 Posts
Reputation: 1093
Points: 28,488, Level: 24
Points: 28,488, Level: 24 Points: 28,488, Level: 24 Points: 28,488, Level: 24
Level up: 76%, 412 Points needed
Level up: 76% Level up: 76% Level up: 76%
Activity: 26.1%
Activity: 26.1% Activity: 26.1% Activity: 26.1%

Some quick changes since someone requested it. Here's an example on how to run a state based on the same 'frequency' aspect as the engine. (This is useful if you only want to check states once in a blue moon; I.E: new talents to place, etc.)

Code:
// 
// Copyright © ApocDev 2009 <apoc@apocdev.com>
// 
using System;
using System.Collections.Generic;

namespace FiniteStateMachine
{
    public abstract class State : IComparable<State>, IComparer<State>
    {
        public abstract int Priority { get; }

        public abstract bool NeedToRun { get; }

        /// <summary>
        /// Determines the frequency (Frame count) between each attempt
        /// to check, and run, this state.
        /// </summary>
        public virtual int Frequency { get { return 1; } }

        #region IComparable<State> Members

        public int CompareTo(State other)
        {
            // We want the highest first.
            // int, by default, chooses the lowest to be sorted
            // at the bottom of the list. We want the opposite.
            return -Priority.CompareTo(other.Priority);
        }

        #endregion

        #region IComparer<State> Members

        public int Compare(State x, State y)
        {
            return -x.Priority.CompareTo(y.Priority);
        }

        #endregion

        public abstract void Run();
    }
}
Code:
// 
// Copyright © ApocDev 2009 <apoc@apocdev.com>
// 
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading;

namespace FiniteStateMachine
{
    public class Engine
    {
        private Thread _workerThread;

        public Engine()
        {
            States = new List<State>();

            // Remember: We implemented the IComparer, and IComparable
            // interfaces on the State class!
            States.Sort();
        }

        public Engine(int pulseFrames) : this()
        {
            PulseFrames = pulseFrames;
        }

        public List<State> States { get; private set; }
        public bool Running { get; private set; }
        public ulong FrameCount { get; private set; }
        public int PulseFrames { get; set; }

        public virtual void Pulse()
        {
            FrameCount++;
            if (PulseFrames % (int) FrameCount != 0)
            {
                return;
            }
            // This starts at the highest priority state,
            // and iterates its way to the lowest priority.
            foreach (State state in States)
            {
                if (state.Frequency % (int) FrameCount == 0)
                {
                    if (state.NeedToRun)
                    {
                        state.Run();
                        // Break out of the iteration,
                        // as we found a state that has run.
                        // We don't want to run any more states
                        // this time around.
                        break;
                    }
                }
            }
        }

        public void StartEngine(byte framesPerSecond)
        {
            // We want to round a bit here.
            int sleepTime = 1000 / framesPerSecond;

            Running = true;

            // Leave it as a background thread. This CAN trail off
            // as the program exits, without any issues really.
            _workerThread = new Thread(Run) {IsBackground = true};
            _workerThread.Start(sleepTime);
        }

        private void Run(object sleepTime)
        {
            try
            {
                // This will immitate a games FPS
                // and attempt to 'pulse' each frame
                while (Running)
                {
                    Pulse();
                    // Sleep for a 'frame'
                    Thread.Sleep((int) sleepTime);
                }
            }
            finally
            {
                // If we exit due to some exception,
                // that isn't caught elsewhere,
                // we need to make sure we set the Running
                // property to false, to avoid confusion,
                // and other bugs.
                Running = false;
            }
        }

        public void StopEngine()
        {
            if (!Running)
            {
                // Nothing to do.
                return;
            }
            if (_workerThread.IsAlive)
            {
                _workerThread.Abort();
            }
            // Clear out the thread object.
            _workerThread = null;
            // Make sure we let everyone know, we're not running anymore!
            Running = false;
        }

        public void LoadStates(string assemblyPath)
        {
            // Make sure we actually have a path to work with.
            if (string.IsNullOrEmpty(assemblyPath))
            {
                return;
            }

            // Make sure the file exists.
            if (!File.Exists(assemblyPath))
            {
                return;
            }
            try
            {
                // Load the assembly, and get the types contained
                // within it.
                Assembly asm = Assembly.LoadFrom(assemblyPath);
                Type[] types = asm.GetTypes();

                foreach (Type type in types)
                {
                    // Here's some fairly simple stuff.
                    if (type.IsClass && type.IsSubclassOf(typeof(State)))
                    {
                        // Create the State using the Activator class.
                        var tempState = (State) Activator.CreateInstance(type);
                        // Make sure we're not using two of the same state.
                        // (That would be bad!)
                        if (!States.Contains(tempState))
                        {
                            States.Add(tempState);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // Feel free to change this to some other logging method.
                Debug.WriteLine(ex.Message, "Exceptions");
            }
        }
    }
}
Note: Frequency is VIRTUAL. That means, you don't need to override it if you want to run the state every frame. It's really only useful if you run it every 2+ frames.
__________________
[Only registered and activated users can see links. ]
Reply With Quote
  #13  
Old 07-07-2009
vulcanaoc is offline.
Master Sergeant
  
 
Join Date: Jul 2008
Posts: 124
Reputation: 29
Points: 1,393, Level: 2
Points: 1,393, Level: 2 Points: 1,393, Level: 2 Points: 1,393, Level: 2
Level up: 99%, 7 Points needed
Level up: 99% Level up: 99% Level up: 99%
Activity: 1.7%
Activity: 1.7% Activity: 1.7% Activity: 1.7%

wonderful, i am going to implement this into my libraries. +rep
Reply With Quote
  #14  
Old 07-10-2009
Patricker is offline.
Private
  
 
Join Date: Jul 2009
Posts: 4
Reputation: 6
Missing sort?

I was looking through your code (planning on using this beauty) and I noticed something I thought seemed wrong. You are only sorting the states on instantiation, but not on each pulse. So if the priority of a state changes it will stay in the same place instead of moving up or down the list as needed. Shouldn't it be:

Code:
 public virtual void Pulse()
        {
            States.Sort();
            // This starts at the highest priority state,
            // and iterates its way to the lowest priority.
            foreach (State state in States)
            {
                if (state.NeedToRun)
                {
                    state.Run();
                    // Break out of the iteration,
                    // as we found a state that has run.
                    // We don't want to run any more states
                    // this time around.
                    break;
                }
            }
        }
Let me know what you think.

Last edited by Patricker; 07-10-2009 at 12:05 PM. Reason: just typo fix.
Reply With Quote
  #15  
Old 07-10-2009
Patricker is offline.
Private
  
 
Join Date: Jul 2009
Posts: 4
Reputation: 6
Some usefull updates

I would normally just edit my previous post, but this seemed like it was different enough to post separately:

I added some new options to allow for more flexibility without really any added complexity. Basicaly I changed the code so that instead of just calling Run each Pulse it uses an Enter/Update/Exit type cycle. This allows you to run certain code only when the State starts and ends, though you can of course just type return; in the abstract blocks and the behaviour will be just like the original code.

Also I added code to keep track of the current state and to enter/update/exit as needed.

Updated State Code:
Code:
namespace FiniteStateMachine
{
    public abstract class State : IComparable<State>, IComparer<State>
    {
        public abstract int Priority { get; }

        public abstract bool NeedToRun { get; }

        #region IComparable<State> Members

        public int CompareTo(State other)
        {
            // We want the highest first.
            // int, by default, chooses the lowest to be sorted
            // at the bottom of the list. We want the opposite.
            return -Priority.CompareTo(other.Priority);
        }

        #endregion

        #region IComparer<State> Members

        public int Compare(State x, State y)
        {
            return -x.Priority.CompareTo(y.Priority);
        }

        #endregion

        //Changed by Me to allow for more flexible state machine
        public abstract void Enter();

        public abstract void Update();

        public abstract void Exit();
    }
}
Updated Engine Pulse Code:
Code:
       public virtual void Pulse()
        {
            //ADDED: By ME (was missing from original, now re-sorts the list on each pulse)
            States.Sort();

            // This starts at the highest priority state,
            // and iterates its way to the lowest priority.
            foreach (State state in States)
            {
                if (state.NeedToRun)
                {
                    //if we are changing to a new state then exit the old one and enter the new one
                    if (state != CurrentState)
                    {
                        //Exit current state
                        CurrentState.Exit();

                        //track new state
                        CurrentState = state;
                        //enter new state
                        CurrentState.Enter();
                    }

                    //Update State
                    state.Update();

                    // Break out of the iteration,
                    // as we found a state that has run.
                    // We don't want to run any more states
                    // this time around.
                    break;
                }
            }
        }
Let me know what you think.
Reply With Quote
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are On



All times are GMT -4. The time now is 11:21 PM.




Powered by vBulletin® Version 3.8.4
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.2

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524